diff --git a/NNBase.php b/NNBase.php index 25cb9e850..3f37a5603 100644 --- a/NNBase.php +++ b/NNBase.php @@ -1,15 +1,13 @@ 1) { - $constant = $argv[1]; - include_once __DIR__ . DIRECTORY_SEPARATOR . 'nntmux/constants.php'; - if (defined($constant)) { - exit(constant($constant)); - } - + $constant = $argv[1]; + include_once __DIR__.DIRECTORY_SEPARATOR.'nntmux/constants.php'; + if (defined($constant)) { + exit(constant($constant)); + } } -exit(__DIR__ . __FILE__); - -?> +exit(__DIR__.__FILE__); diff --git a/_install/Autoloader_Class.php b/_install/Autoloader_Class.php index 5cea8b2b0..69726bcd5 100755 --- a/_install/Autoloader_Class.php +++ b/_install/Autoloader_Class.php @@ -1,4 +1,5 @@ prefixes[$prefix]) === false) { - $this->prefixes[$prefix] = []; - } + // initialize the namespace prefix array + if (isset($this->prefixes[$prefix]) === false) { + $this->prefixes[$prefix] = []; + } - // retain the base directory for the namespace prefix - if ($prepend) { - array_unshift($this->prefixes[$prefix], $base_dir); - } else { - array_push($this->prefixes[$prefix], $base_dir); - } - } + // retain the base directory for the namespace prefix + if ($prepend) { + array_unshift($this->prefixes[$prefix], $base_dir); + } else { + array_push($this->prefixes[$prefix], $base_dir); + } + } - /** - * Loads the class file for a given class name. - * - * @param string $class The fully-qualified class name. - * - * @return string|false The mapped file name on success, or boolean false on - * failure. - */ - public function loadClass($class) - { - // the current namespace prefix - $prefix = $class; + /** + * Loads the class file for a given class name. + * + * @param string $class The fully-qualified class name. + * + * @return string|false The mapped file name on success, or boolean false on + * failure. + */ + public function loadClass($class) + { + // the current namespace prefix + $prefix = $class; - // work backwards through the namespace names of the fully-qualified - // class name to find a mapped file name - while (false !== $pos = strrpos($prefix, '\\')) { + // work backwards through the namespace names of the fully-qualified + // class name to find a mapped file name + while (false !== $pos = strrpos($prefix, '\\')) { // retain the trailing namespace separator in the prefix - $prefix = substr($class, 0, $pos + 1); + $prefix = substr($class, 0, $pos + 1); - // the rest is the relative class name - $relative_class = substr($class, $pos + 1); + // the rest is the relative class name + $relative_class = substr($class, $pos + 1); - // try to load a mapped file for the prefix and relative class - $mapped_file = $this->loadMappedFile($prefix, $relative_class); - if ($mapped_file) { - return $mapped_file; - } + // try to load a mapped file for the prefix and relative class + $mapped_file = $this->loadMappedFile($prefix, $relative_class); + if ($mapped_file) { + return $mapped_file; + } - // remove the trailing namespace separator for the next iteration - // of strrpos() - $prefix = rtrim($prefix, '\\'); - } + // remove the trailing namespace separator for the next iteration + // of strrpos() + $prefix = rtrim($prefix, '\\'); + } - // never found a mapped file - return false; - } + // never found a mapped file + return false; + } - /** - * Load the mapped file for a namespace prefix and relative class. - * - * @param string $prefix The namespace prefix. - * @param string $relative_class The relative class name. - * - * @return string|false Boolean false if no mapped file can be loaded, or the - * name of the mapped file that was loaded. - */ - protected function loadMappedFile($prefix, $relative_class) - { - // are there any base directories for this namespace prefix? - if (isset($this->prefixes[$prefix]) === false) { - return false; - } + /** + * Load the mapped file for a namespace prefix and relative class. + * + * @param string $prefix The namespace prefix. + * @param string $relative_class The relative class name. + * + * @return string|false Boolean false if no mapped file can be loaded, or the + * name of the mapped file that was loaded. + */ + protected function loadMappedFile($prefix, $relative_class) + { + // are there any base directories for this namespace prefix? + if (isset($this->prefixes[$prefix]) === false) { + return false; + } - // look through base directories for this namespace prefix - foreach ($this->prefixes[$prefix] as $base_dir) { + // look through base directories for this namespace prefix + foreach ($this->prefixes[$prefix] as $base_dir) { // 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'; - $file = $base_dir - . str_replace('\\', '/', $relative_class) - . '.php'; + // replace namespace separators with directory separators + // in the relative class name, append with .php + $file = $base_dir + .str_replace('\\', DIRECTORY_SEPARATOR, $relative_class) + .'.php'; + $file = $base_dir + .str_replace('\\', '/', $relative_class) + .'.php'; - // if the mapped file exists, require it - if ($this->requireFile($file)) { - // yes, we're done - return $file; - } - } + // if the mapped file exists, require it + if ($this->requireFile($file)) { + // yes, we're done + return $file; + } + } - // never found it - return false; - } + // never found it + return false; + } - /** - * If a file exists, require it from the file system. - * - * @param string $file The file to require. - * - * @return bool True if the file exists, false if not. - */ - protected function requireFile($file) - { - if (file_exists($file)) { - require $file; + /** + * If a file exists, require it from the file system. + * + * @param string $file The file to require. + * + * @return bool True if the file exists, false if not. + */ + protected function requireFile($file) + { + if (file_exists($file)) { + require $file; - return true; - } + return true; + } - return false; - } + return false; + } } - -?> diff --git a/_install/install_nntmux.php b/_install/install_nntmux.php index 4fa2885fb..eb72082dd 100644 --- a/_install/install_nntmux.php +++ b/_install/install_nntmux.php @@ -1,17 +1,17 @@ true, 'createDb' => true, @@ -45,13 +45,13 @@ if (env('DB_SYSTEM') !== 'mysql') { 'dbuser' => env('DB_USER'), ] ); - $dbConnCheck = true; - } catch (\PDOException $e) { - ColorCLI::doEcho(ColorCLI::error('Unable to connect to MySQL server.')); - $error = true; - $dbConnCheck = false; - } catch (\RuntimeException $e) { - switch ($e->getCode()) { + $dbConnCheck = true; + } catch (\PDOException $e) { + ColorCLI::doEcho(ColorCLI::error('Unable to connect to MySQL server.')); + $error = true; + $dbConnCheck = false; + } catch (\RuntimeException $e) { + switch ($e->getCode()) { case 1: case 2: case 3: @@ -62,93 +62,93 @@ if (env('DB_SYSTEM') !== 'mysql') { var_dump($e); throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); } - } + } - // Check if the MySQL version is correct. - $goodVersion = false; - if (!$error) { - try { - $goodVersion = $pdo->isDbVersionAtLeast(NN_MINIMUM_MYSQL_VERSION); - } catch (\PDOException $e) { - $goodVersion = false; - $error = true; - ColorCLI::doEcho(ColorCLI::error('Could not get version from MySQL server.')); - } + // Check if the MySQL version is correct. + $goodVersion = false; + if (! $error) { + try { + $goodVersion = $pdo->isDbVersionAtLeast(NN_MINIMUM_MYSQL_VERSION); + } catch (\PDOException $e) { + $goodVersion = false; + $error = true; + ColorCLI::doEcho(ColorCLI::error('Could not get version from MySQL server.')); + } - if ($goodVersion === false) { - $error = true; - ColorCLI::doEcho(ColorCLI::error( - 'You are using an unsupported version of ' . - env('DB_SYSTEM') . - ' the minimum allowed version is ' . + if ($goodVersion === false) { + $error = true; + ColorCLI::doEcho(ColorCLI::error( + 'You are using an unsupported version of '. + env('DB_SYSTEM'). + ' the minimum allowed version is '. NN_MINIMUM_MYSQL_VERSION ) ); - } - } + } + } } // Start inserting data into the DB. -if (!$error) { - $DbSetup = new DbUpdate( +if (! $error) { + $DbSetup = new DbUpdate( [ 'backup' => false, 'db' => $pdo, ] ); - try { - $DbSetup->processSQLFile(); // Setup default schema + try { + $DbSetup->processSQLFile(); // Setup default schema $DbSetup->loadTables(); // Load default data files - } catch (\PDOException $err) { - $error = true; - ColorCLI::doEcho(ColorCLI::error('Error inserting: (' . $err->getMessage() . ')')); - } + } catch (\PDOException $err) { + $error = true; + ColorCLI::doEcho(ColorCLI::error('Error inserting: ('.$err->getMessage().')')); + } - if (!$error) { - // Check one of the standard tables was created and has data. - $dbInstallWorked = false; - $reschk = $pdo->query('SELECT COUNT(id) AS num FROM tmux'); - if ($reschk === false) { - $dbCreateCheck = false; - $error = true; - ColorCLI::doEcho(ColorCLI::warningOver('Could not select data from your database, check that tables and data are properly created/inserted.')); - } else { - foreach ($reschk as $row) { - if ($row['num'] > 0) { - $dbInstallWorked = true; - break; - } - } - } - $ver = new Versions(); - $patch = $ver->getSQLPatchFromFile(); - if ($dbInstallWorked) { - $updateSettings = false; - if ($patch > 0) { - $updateSettings = $pdo->exec( + if (! $error) { + // Check one of the standard tables was created and has data. + $dbInstallWorked = false; + $reschk = $pdo->query('SELECT COUNT(id) AS num FROM tmux'); + if ($reschk === false) { + $dbCreateCheck = false; + $error = true; + ColorCLI::doEcho(ColorCLI::warningOver('Could not select data from your database, check that tables and data are properly created/inserted.')); + } else { + foreach ($reschk as $row) { + if ($row['num'] > 0) { + $dbInstallWorked = true; + break; + } + } + } + $ver = new Versions(); + $patch = $ver->getSQLPatchFromFile(); + if ($dbInstallWorked) { + $updateSettings = false; + if ($patch > 0) { + $updateSettings = $pdo->exec( "UPDATE settings SET value = '$patch' WHERE section = '' AND subsection = '' AND name = 'sqlpatch'" ); - } - // If it all worked, continue the install process. - if ($updateSettings) { - ColorCLI::doEcho(ColorCLI::info('Database updated successfully')); - } else { - $error = true; - ColorCLI::doEcho(ColorCLI::error('Could not update sqlpatch to ' . $patch . ' for your database.')); - } - } else { - $dbCreateCheck = false; - $error = true; - ColorCLI::doEcho(ColorCLI::warning('Could not select data from your database.')); - } - } + } + // If it all worked, continue the install process. + if ($updateSettings) { + ColorCLI::doEcho(ColorCLI::info('Database updated successfully')); + } else { + $error = true; + ColorCLI::doEcho(ColorCLI::error('Could not update sqlpatch to '.$patch.' for your database.')); + } + } else { + $dbCreateCheck = false; + $error = true; + ColorCLI::doEcho(ColorCLI::warning('Could not select data from your database.')); + } + } } //Insert admin user into database if (env('ADMIN_USER') === '' || env('ADMIN_PASS') === '' || env('ADMIN_EMAIL') === '') { - $error = true; - ColorCLI::doEcho(ColorCLI::error('Admin user data cannot be empty! Please edit .env file and fill in admin user details and run this script again!')); - exit(); + $error = true; + ColorCLI::doEcho(ColorCLI::error('Admin user data cannot be empty! Please edit .env file and fill in admin user details and run this script again!')); + exit(); } $capsule = new Capsule; @@ -163,98 +163,96 @@ if (env('ADMIN_USER') === '' || env('ADMIN_PASS') === '' || env('ADMIN_EMAIL') = 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', - 'strict' => false + 'strict' => false, ]); $capsule->bootEloquent(); $user = new Users(); -if (!$user->isValidUsername(env('ADMIN_USER'))) { - $error = true; +if (! $user->isValidUsername(env('ADMIN_USER'))) { + $error = true; } else { - $usrCheck = $user->getByUsername(env('ADMIN_USER')); - if ($usrCheck) { - $error = true; - } + $usrCheck = $user->getByUsername(env('ADMIN_USER')); + if ($usrCheck) { + $error = true; + } } -if (!$user->isValidEmail(env('ADMIN_EMAIL'))) { - $error = true; +if (! $user->isValidEmail(env('ADMIN_EMAIL'))) { + $error = true; } -if (!$error) { - $adminCheck = $user->add(env('ADMIN_USER'), env('ADMIN_PASS'), env('ADMIN_EMAIL'), 2, '', ''); - if (!is_numeric($adminCheck)) { - $error = true; - } +if (! $error) { + $adminCheck = $user->add(env('ADMIN_USER'), env('ADMIN_PASS'), env('ADMIN_EMAIL'), 2, '', ''); + if (! is_numeric($adminCheck)) { + $error = true; + } } -if (!$error) { - $doCheck = true; +if (! $error) { + $doCheck = true; - $covers_path = NN_RES . 'covers' . DS; - $nzb_path = NN_RES . 'nzb' . DS; - $tmp_path = NN_RES . 'tmp' . DS; - $unrar_path = $tmp_path . 'unrar' . DS; + $covers_path = NN_RES.'covers'.DS; + $nzb_path = NN_RES.'nzb'.DS; + $tmp_path = NN_RES.'tmp'.DS; + $unrar_path = $tmp_path.'unrar'.DS; + $nzbPathCheck = is_writable($nzb_path); + if ($nzbPathCheck === false) { + $error = true; + ColorCLI::doEcho(ColorCLI::warning($nzb_path.' is not writable. Please fix folder permissions')); + } - $nzbPathCheck = is_writable($nzb_path); - if ($nzbPathCheck === false) { - $error = true; - ColorCLI::doEcho(ColorCLI::warning($nzb_path . ' is not writable. Please fix folder permissions')); - } + $lastchar = substr($nzb_path, strlen($nzb_path) - 1); + if ($lastchar !== '/') { + $nzb_path .= '/'; + } - $lastchar = substr($nzb_path, strlen($nzb_path) - 1); - if ($lastchar !== '/') { - $nzb_path .= '/'; - } + if (! file_exists($unrar_path)) { + ColorCLI::doEcho(ColorCLI::primary('Creating missing '.$unrar_path.' folder')); + if (! @mkdir($unrar_path) && ! is_dir($unrar_path)) { + throw new RuntimeException('Unable to create '.$unrar_path.' folder'); + } + ColorCLI::doEcho(ColorCLI::primary('Folder '.$unrar_path.' successfully created')); + } + $unrarPathCheck = is_writable($unrar_path); + if ($unrarPathCheck === false) { + $error = true; + ColorCLI::doEcho(ColorCLI::warning($unrar_path.' is not writable. Please fix folder permissions')); + } - if (!file_exists($unrar_path)) { - ColorCLI::doEcho(ColorCLI::primary('Creating missing ' . $unrar_path . ' folder')); - if (!@mkdir($unrar_path) && !is_dir($unrar_path)) { - throw new RuntimeException('Unable to create ' . $unrar_path . ' folder'); - } - ColorCLI::doEcho(ColorCLI::primary('Folder ' . $unrar_path . ' successfully created')); - } - $unrarPathCheck = is_writable($unrar_path); - if ($unrarPathCheck === false) { - $error = true; - ColorCLI::doEcho(ColorCLI::warning($unrar_path . ' is not writable. Please fix folder permissions')); - } + $lastchar = substr($unrar_path, strlen($unrar_path) - 1); + if ($lastchar !== '/') { + $unrar_path .= '/'; + } - $lastchar = substr($unrar_path, strlen($unrar_path) - 1); - if ($lastchar !== '/') { - $unrar_path .= '/'; - } + $coversPathCheck = is_writable($covers_path); + if ($coversPathCheck === false) { + $error = true; + ColorCLI::doEcho(ColorCLI::warning($covers_path.' is not writable. Please fix folder permissions')); + } - $coversPathCheck = is_writable($covers_path); - if ($coversPathCheck === false) { - $error = true; - ColorCLI::doEcho(ColorCLI::warning($covers_path . ' is not writable. Please fix folder permissions')); - } + $lastchar = substr($covers_path, strlen($covers_path) - 1); + if ($lastchar !== '/') { + $covers_path .= '/'; + } - $lastchar = substr($covers_path, strlen($covers_path) - 1); - if ($lastchar !== '/') { - $covers_path .= '/'; - } - - if (!$error) { - - $sql1 = sprintf("UPDATE settings SET value = %s WHERE setting = 'nzbpath'", $pdo->escapeString($nzb_path)); - $sql2 = sprintf("UPDATE settings SET value = %s WHERE setting = 'tmpunrarpath'", $pdo->escapeString($unrar_path)); - $sql3 = sprintf("UPDATE settings SET value = %s WHERE setting = 'coverspath'", $pdo->escapeString($covers_path)); - if ($pdo->queryExec($sql1) === false || $pdo->queryExec($sql2) === false || $pdo->queryExec($sql3) === false) { - $error = true; - } else { - ColorCLI::doEcho(ColorCLI::info('Settings table updated successfully')); - } - } + if (! $error) { + $sql1 = sprintf("UPDATE settings SET value = %s WHERE setting = 'nzbpath'", $pdo->escapeString($nzb_path)); + $sql2 = sprintf("UPDATE settings SET value = %s WHERE setting = 'tmpunrarpath'", $pdo->escapeString($unrar_path)); + $sql3 = sprintf("UPDATE settings SET value = %s WHERE setting = 'coverspath'", $pdo->escapeString($covers_path)); + if ($pdo->queryExec($sql1) === false || $pdo->queryExec($sql2) === false || $pdo->queryExec($sql3) === false) { + $error = true; + } else { + ColorCLI::doEcho(ColorCLI::info('Settings table updated successfully')); + } + } } -if (!$error) { - @file_put_contents(NN_ROOT . '_install/install.lock', ''); - ColorCLI::doEcho(ColorCLI::header('Generating application key')); - passthru('php ' . NN_ROOT . 'tmux key:generate'); - ColorCLI::doEcho(ColorCLI::alternate('NNTmux installation completed successfully')); - exit(); +if (! $error) { + @file_put_contents(NN_ROOT.'_install/install.lock', ''); + ColorCLI::doEcho(ColorCLI::header('Generating application key')); + passthru('php '.NN_ROOT.'tmux key:generate'); + ColorCLI::doEcho(ColorCLI::alternate('NNTmux installation completed successfully')); + exit(); } ColorCLI::doEcho(ColorCLI::error('NNTmux installation failed. Fix reported problems and try again')); diff --git a/app/Console/Commands/TmuxUIStart.php b/app/Console/Commands/TmuxUIStart.php index 8bf5a86fe..190f497d3 100644 --- a/app/Console/Commands/TmuxUIStart.php +++ b/app/Console/Commands/TmuxUIStart.php @@ -32,23 +32,23 @@ class TmuxUIStart extends Command parent::__construct(); } - /** - * Execute the console command. - * - * @return mixed - * @throws \Symfony\Component\Process\Exception\LogicException - * @throws \Symfony\Component\Process\Exception\RuntimeException - */ + /** + * Execute the console command. + * + * @return mixed + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\RuntimeException + */ public function handle() { $process = new Process('php misc/update/nix/tmux/start.php'); $process->setTty(true); - $process->run(function ($type, $buffer) { - if (Process::ERR === $type) { - echo 'ERR > '.$buffer; - } else { - echo $buffer; - } - }); + $process->run(function ($type, $buffer) { + if (Process::ERR === $type) { + echo 'ERR > '.$buffer; + } else { + echo $buffer; + } + }); } } diff --git a/app/Console/Commands/TmuxUIStop.php b/app/Console/Commands/TmuxUIStop.php index 2c394b537..d4a96176d 100644 --- a/app/Console/Commands/TmuxUIStop.php +++ b/app/Console/Commands/TmuxUIStop.php @@ -33,45 +33,44 @@ class TmuxUIStop extends Command parent::__construct(); } - /** - * Execute the console command. - * - * @return mixed - * @throws \Symfony\Component\Process\Exception\InvalidArgumentException - * @throws \Symfony\Component\Process\Exception\LogicException - * @throws \Symfony\Component\Process\Exception\RuntimeException - * @throws \RuntimeException - */ + /** + * Execute the console command. + * + * @return mixed + * @throws \Symfony\Component\Process\Exception\InvalidArgumentException + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\RuntimeException + * @throws \RuntimeException + */ public function handle() { - if ($this->argument('type') === 'false' || $this->argument('type') === 'true') { - $process = new Process('php misc/update/nix/tmux/stop.php'); - $process->setTimeout(600); - $process->run(function ($type, $buffer) { - if (Process::ERR === $type) { - echo 'ERR > ' . $buffer; - } else { - echo $buffer; - } - } + if ($this->argument('type') === 'false' || $this->argument('type') === 'true') { + $process = new Process('php misc/update/nix/tmux/stop.php'); + $process->setTimeout(600); + $process->run(function ($type, $buffer) { + if (Process::ERR === $type) { + echo 'ERR > '.$buffer; + } else { + echo $buffer; + } + } ); - if ($this->argument('type') === 'true') { - - $sessionName = Tmux::value('tmux_session'); - $tmuxSession = new Process('tmux kill-session -t ' . $sessionName); - $this->info('Killing active tmux session: ' . $sessionName); - $tmuxSession->run(function ($type, $buffer) { - if (Process::ERR === $type) { - echo 'ERR > ' . $buffer; - } else { - echo $buffer; - } - } + if ($this->argument('type') === 'true') { + $sessionName = Tmux::value('tmux_session'); + $tmuxSession = new Process('tmux kill-session -t '.$sessionName); + $this->info('Killing active tmux session: '.$sessionName); + $tmuxSession->run(function ($type, $buffer) { + if (Process::ERR === $type) { + echo 'ERR > '.$buffer; + } else { + echo $buffer; + } + } ); - } - }else { - $this->error($this->description); - } + } + } else { + $this->error($this->description); + } } } diff --git a/app/Console/Commands/UpdateNNTmux.php b/app/Console/Commands/UpdateNNTmux.php index 444c8a2aa..7c24cbe56 100644 --- a/app/Console/Commands/UpdateNNTmux.php +++ b/app/Console/Commands/UpdateNNTmux.php @@ -6,9 +6,9 @@ use Illuminate\Console\Command; class UpdateNNTmux extends Command { - const UPDATES_FILE = NN_CONFIGS . 'updates.json'; + const UPDATES_FILE = NN_CONFIGS.'updates.json'; - /** + /** * The name and signature of the console command. * * @var string @@ -22,62 +22,62 @@ class UpdateNNTmux extends Command */ protected $description = 'Update NNTmux installation'; + /** + * @var \app\extensions\util\Git object. + */ + protected $git; - /** - * @var \app\extensions\util\Git object. - */ - protected $git; + /** + * @var array Decoded JSON updates file. + */ + protected $updates = null; - /** - * @var array Decoded JSON updates file. - */ - protected $updates = null; + /** + * Create a new command instance. + */ + public function __construct() + { + parent::__construct(); + } - /** - * Create a new command instance. - * - */ - public function __construct() - { - parent::__construct(); - } + /** + * Execute the console command. + * + * @return mixed + */ + public function handle() + { + try { + $output = $this->call('nntmux:git'); + if ($output === 'Already up-to-date.') { + $this->info($output); + } else { + $status = $this->call('nntmux:composer'); + if ($status) { + $this->error('Composer failed to update!!'); - /** - * Execute the console command. - * - * @return mixed - */ - public function handle() - { - try { - $output = $this->call('nntmux:git'); - if ($output === 'Already up-to-date.') { - $this->info($output); - } else { - $status = $this->call('nntmux:composer'); - if ($status) { - $this->error('Composer failed to update!!'); - return false; - } - $fail = $this->call('nntmux:db'); - if ($fail) { - $this->error('Db updating failed!!'); - return 1; - } - } + return false; + } + $fail = $this->call('nntmux:db'); + if ($fail) { + $this->error('Db updating failed!!'); - $smarty = new \Smarty(); - $smarty->setCompileDir(NN_SMARTY_TEMPLATES); - $cleared = $smarty->clearCompiledTemplate(); - if ($cleared) { - $this->output->writeln('The Smarty compiled template cache has been cleaned for you'); - } else { - $this->output->writeln('You should clear your Smarty compiled template cache at: ' . - NN_RES . 'smarty' . DS . 'templates_c' + return 1; + } + } + + $smarty = new \Smarty(); + $smarty->setCompileDir(NN_SMARTY_TEMPLATES); + $cleared = $smarty->clearCompiledTemplate(); + if ($cleared) { + $this->output->writeln('The Smarty compiled template cache has been cleaned for you'); + } else { + $this->output->writeln('You should clear your Smarty compiled template cache at: '. + NN_RES.'smarty'.DS.'templates_c' ); - } - } catch (\Exception $e) { - $this->error($e->getMessage()); - } - } + } + } catch (\Exception $e) { + $this->error($e->getMessage()); + } + } } diff --git a/app/Console/Commands/UpdateNNTmuxComposer.php b/app/Console/Commands/UpdateNNTmuxComposer.php index 893144813..e4d28ba67 100644 --- a/app/Console/Commands/UpdateNNTmuxComposer.php +++ b/app/Console/Commands/UpdateNNTmuxComposer.php @@ -2,8 +2,8 @@ namespace App\Console\Commands; -use Illuminate\Console\Command; use App\Extensions\util\Git; +use Illuminate\Console\Command; use Symfony\Component\Process\Process; class UpdateNNTmuxComposer extends Command @@ -22,67 +22,66 @@ class UpdateNNTmuxComposer extends Command */ protected $description = 'Update composer libraries for NNTmux'; - /** - * @var \app\extensions\util\Git object. - */ - protected $git; + /** + * @var \app\extensions\util\Git object. + */ + protected $git; - private $gitBranch; + private $gitBranch; - /** - * Create a new command instance. - * - */ + /** + * Create a new command instance. + */ public function __construct() { parent::__construct(); } - /** - * Execute the console command. - * - * @return mixed - * @throws \Symfony\Component\Process\Exception\LogicException - */ + /** + * Execute the console command. + * + * @return mixed + * @throws \Symfony\Component\Process\Exception\LogicException + */ public function handle() { $this->composer(); } - /** - * Issues the command to 'install' the composer package. - * - * It first checks the current branch for stable versions. If found then the '--no-dev' - * option is added to the command to prevent development packages being also downloded. - * - * @return integer Return status from Composer. - * @throws \Symfony\Component\Process\Exception\LogicException - * @throws \Symfony\Component\Process\Exception\RuntimeException - */ - protected function composer() - { - $this->initialiseGit(); - $command = 'composer install'; - if (in_array($this->gitBranch, $this->git->getBranchesStable(), false)) { - $command .= ' --prefer-dist --no-dev'; - } else { - $command .= ' --prefer-source'; - } - $this->output->writeln('Running composer install process...'); - $process = new Process($command); - $process->run(function ($type, $buffer){ - if (Process::ERR === $type) { - echo $buffer; - } - }); + /** + * Issues the command to 'install' the composer package. + * + * It first checks the current branch for stable versions. If found then the '--no-dev' + * option is added to the command to prevent development packages being also downloded. + * + * @return int Return status from Composer. + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\RuntimeException + */ + protected function composer() + { + $this->initialiseGit(); + $command = 'composer install'; + if (in_array($this->gitBranch, $this->git->getBranchesStable(), false)) { + $command .= ' --prefer-dist --no-dev'; + } else { + $command .= ' --prefer-source'; + } + $this->output->writeln('Running composer install process...'); + $process = new Process($command); + $process->run(function ($type, $buffer) { + if (Process::ERR === $type) { + echo $buffer; + } + }); - return $process->getOutput(); - } + return $process->getOutput(); + } - protected function initialiseGit() - { - if (!($this->git instanceof Git)) { - $this->git = new Git(); - } - } + protected function initialiseGit() + { + if (! ($this->git instanceof Git)) { + $this->git = new Git(); + } + } } diff --git a/app/Console/Commands/UpdateNNTmuxDB.php b/app/Console/Commands/UpdateNNTmuxDB.php index 0e7c8d846..c67711b7d 100644 --- a/app/Console/Commands/UpdateNNTmuxDB.php +++ b/app/Console/Commands/UpdateNNTmuxDB.php @@ -2,10 +2,10 @@ namespace App\Console\Commands; +use nntmux\db\DbUpdate; +use App\Extensions\util\Git; use Illuminate\Console\Command; use App\Extensions\util\Versions; -use App\Extensions\util\Git; -use nntmux\db\DbUpdate; class UpdateNNTmuxDB extends Command { @@ -23,15 +23,14 @@ class UpdateNNTmuxDB extends Command */ protected $description = 'Update NNTmux database with new patches'; - /** - * @var \app\extensions\util\Git object. - */ - protected $git; + /** + * @var \app\extensions\util\Git object. + */ + protected $git; - /** - * Create a new command instance. - * - */ + /** + * Create a new command instance. + */ public function __construct() { parent::__construct(); @@ -44,28 +43,28 @@ class UpdateNNTmuxDB extends Command */ public function handle() { - // TODO Add check to determine if the indexer or other scripts are running. Hopefully - // also prevent web access. - $this->output->writeln('Checking database version'); + // TODO Add check to determine if the indexer or other scripts are running. Hopefully + // also prevent web access. + $this->output->writeln('Checking database version'); - $versions = new Versions(['git' => ($this->git instanceof Git) ? $this->git : null]); + $versions = new Versions(['git' => ($this->git instanceof Git) ? $this->git : null]); - try { - $currentDb = $versions->getSQLPatchFromDB(); - $currentXML = $versions->getSQLPatchFromFile(); - } catch (\PDOException $e) { - $this->error('Error fetching patch versions!'); + try { + $currentDb = $versions->getSQLPatchFromDB(); + $currentXML = $versions->getSQLPatchFromFile(); + } catch (\PDOException $e) { + $this->error('Error fetching patch versions!'); - return 1; - } + return 1; + } - $this->info("Db: $currentDb,\tFile: $currentXML"); + $this->info("Db: $currentDb,\tFile: $currentXML"); - if ($currentDb < $currentXML) { - $db = new DbUpdate(['backup' => false]); - $db->processPatches(['safe' => false]); - } else { - $this->info('Up to date.'); - } + if ($currentDb < $currentXML) { + $db = new DbUpdate(['backup' => false]); + $db->processPatches(['safe' => false]); + } else { + $this->info('Up to date.'); + } } } diff --git a/app/Console/Commands/UpdateNNTmuxGit.php b/app/Console/Commands/UpdateNNTmuxGit.php index 63485e54d..5dd9f0867 100644 --- a/app/Console/Commands/UpdateNNTmuxGit.php +++ b/app/Console/Commands/UpdateNNTmuxGit.php @@ -2,8 +2,8 @@ namespace App\Console\Commands; -use Illuminate\Console\Command; use App\Extensions\util\Git; +use Illuminate\Console\Command; class UpdateNNTmuxGit extends Command { @@ -21,15 +21,14 @@ class UpdateNNTmuxGit extends Command */ protected $description = 'Update NNTmux from git repository'; - /** - * @var \app\extensions\util\Git object. - */ - protected $git; + /** + * @var \app\extensions\util\Git object. + */ + protected $git; - /** - * Create a new command instance. - * - */ + /** + * Create a new command instance. + */ public function __construct() { parent::__construct(); @@ -42,22 +41,22 @@ class UpdateNNTmuxGit extends Command */ public function handle() { - // TODO Add check to determine if the indexer or other scripts are running. Hopefully - // also prevent web access. - $this->initialiseGit(); - if (!in_array($this->git->getBranch(), $this->git->getBranchesMain(), false)) { - $this->error('Not on the stable or dev branch! Refusing to update repository'); + // TODO Add check to determine if the indexer or other scripts are running. Hopefully + // also prevent web access. + $this->initialiseGit(); + if (! in_array($this->git->getBranch(), $this->git->getBranchesMain(), false)) { + $this->error('Not on the stable or dev branch! Refusing to update repository'); - return; - } + return; + } - $this->info($this->git->gitPull()); + $this->info($this->git->gitPull()); } - protected function initialiseGit() - { - if (!($this->git instanceof Git)) { - $this->git = new Git(); - } - } + protected function initialiseGit() + { + if (! ($this->git instanceof Git)) { + $this->git = new Git(); + } + } } diff --git a/app/Console/Commands/VerifyNNTmuxSettings.php b/app/Console/Commands/VerifyNNTmuxSettings.php index 0762d0828..52506739c 100644 --- a/app/Console/Commands/VerifyNNTmuxSettings.php +++ b/app/Console/Commands/VerifyNNTmuxSettings.php @@ -2,8 +2,8 @@ namespace App\Console\Commands; -use Illuminate\Console\Command; use App\Models\Settings; +use Illuminate\Console\Command; class VerifyNNTmuxSettings extends Command { @@ -21,23 +21,22 @@ class VerifyNNTmuxSettings extends Command */ protected $description = 'Verify settings table data'; - /** - * Create a new command instance. - * - */ + /** + * Create a new command instance. + */ public function __construct() { parent::__construct(); } - /** - * Execute the console command. - * - * @return mixed - * @throws \Exception - */ + /** + * Execute the console command. + * + * @return mixed + * @throws \Exception + */ public function handle() { - Settings::hasAllEntries($this); + Settings::hasAllEntries($this); } } diff --git a/app/Console/Commands/VerifyNNTmuxVersion.php b/app/Console/Commands/VerifyNNTmuxVersion.php index b04bb1f5c..023faf0e7 100644 --- a/app/Console/Commands/VerifyNNTmuxVersion.php +++ b/app/Console/Commands/VerifyNNTmuxVersion.php @@ -2,8 +2,8 @@ namespace App\Console\Commands; -use App\Extensions\util\Versions; use Illuminate\Console\Command; +use App\Extensions\util\Versions; class VerifyNNTmuxVersion extends Command { @@ -25,16 +25,15 @@ class VerifyNNTmuxVersion extends Command branch Show git branch name. git Show git tag for current version. sql Show SQL patch level'; - private $versions; + private $versions; - /** - * Create a new command instance. - * - */ + /** + * Create a new command instance. + */ public function __construct() { - $this->versions = new Versions(); - parent::__construct(); + $this->versions = new Versions(); + parent::__construct(); } /** @@ -44,61 +43,57 @@ class VerifyNNTmuxVersion extends Command */ public function handle() { - if ($this->argument('type') === 'git') { - $this->git(); - } else if ($this->argument('type') === 'branch') { - $this->branch(); - } else if ($this->argument('type') === 'sql') { - $this->sql(); - } else if($this->argument('type') === 'all') { - $this->all(); - } else { - $this->error($this->description); - } + if ($this->argument('type') === 'git') { + $this->git(); + } elseif ($this->argument('type') === 'branch') { + $this->branch(); + } elseif ($this->argument('type') === 'sql') { + $this->sql(); + } elseif ($this->argument('type') === 'all') { + $this->all(); + } else { + $this->error($this->description); + } } - public function all() - { - $this->git(); - $this->sql(); - } + public function all() + { + $this->git(); + $this->sql(); + } - public function branch() - { - $this->output->writeln('' . 'Git branch: ' . $this->versions->getGitBranch() . ''); - } + public function branch() + { + $this->output->writeln(''.'Git branch: '.$this->versions->getGitBranch().''); + } - /** - * Fetch git tag for latest version. - */ - public function git() - { + /** + * Fetch git tag for latest version. + */ + public function git() + { + $this->output->writeln('Looking up Git tag version(s)'); - $this->output->writeln('Looking up Git tag version(s)'); + $this->info('Hash: '.$this->versions->getGitHeadHash()); + $this->info('XML version: '.$this->versions->getGitTagInFile()); + $this->info('Git version: '.$this->versions->getGitTagInRepo()); + } - $this->info('Hash: ' . $this->versions->getGitHeadHash()); - $this->info('XML version: ' . $this->versions->getGitTagInFile()); - $this->info('Git version: ' . $this->versions->getGitTagInRepo()); - } + /** + * Fetch SQL latest patch version. + */ + public function sql() + { + $this->output->writeln('Looking up SQL patch version(s)'); - /** - * Fetch SQL latest patch version. - */ - public function sql() - { + $latest = $this->versions->getSQLPatchFromFile(); + $this->info("XML version: $latest"); - $this->output->writeln('Looking up SQL patch version(s)'); - - - $latest = $this->versions->getSQLPatchFromFile(); - $this->info("XML version: $latest"); - - try { - $dbVersion = $this->versions->getSQLPatchFromDB(); - $this->info(' DB version: ' . $dbVersion); - } catch (\Exception $e) { - $this->error($e->getMessage()); - } - - } + try { + $dbVersion = $this->versions->getSQLPatchFromDB(); + $this->info(' DB version: '.$dbVersion); + } catch (\Exception $e) { + $this->error($e->getMessage()); + } + } } diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index a444475e4..3c727caf5 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -2,15 +2,15 @@ namespace App\Console; -use App\Console\Commands\TmuxUIStart; use App\Console\Commands\TmuxUIStop; +use App\Console\Commands\TmuxUIStart; use App\Console\Commands\UpdateNNTmux; -use App\Console\Commands\UpdateNNTmuxComposer; use App\Console\Commands\UpdateNNTmuxDB; use App\Console\Commands\UpdateNNTmuxGit; -use App\Console\Commands\VerifyNNTmuxSettings; -use App\Console\Commands\VerifyNNTmuxVersion; use Illuminate\Console\Scheduling\Schedule; +use App\Console\Commands\VerifyNNTmuxVersion; +use App\Console\Commands\UpdateNNTmuxComposer; +use App\Console\Commands\VerifyNNTmuxSettings; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel @@ -28,7 +28,7 @@ class Kernel extends ConsoleKernel VerifyNNTmuxSettings::class, VerifyNNTmuxVersion::class, TmuxUIStart::class, - TmuxUIStop::class + TmuxUIStop::class, ]; /** @@ -44,14 +44,14 @@ class Kernel extends ConsoleKernel } /** - * Register the commands for the application. + * Register the commands for the application. * * @return void */ protected function commands() { - $this->load(__DIR__.'/Commands'); + $this->load(__DIR__.'/Commands'); - require base_path('routes/console.php'); + require base_path('routes/console.php'); } } diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index f0401d839..9b9fb0fb1 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -46,24 +46,24 @@ class Handler extends ExceptionHandler */ public function render($request, Exception $exception) { - // 404 page when a model is not found - if ($exception instanceof ModelNotFoundException) { - return response()->view('errors.404', [], 404); - } + // 404 page when a model is not found + if ($exception instanceof ModelNotFoundException) { + return response()->view('errors.404', [], 404); + } - if ($exception instanceof NotFoundHttpException) - { - return response()->view('errors.404', [], 404); - } + if ($exception instanceof NotFoundHttpException) { + return response()->view('errors.404', [], 404); + } - if ($this->isHttpException($exception)) { - return $this->renderHttpException($exception); - } - // Custom error 500 view on production - if (app()->environment() === 'production') { - return response()->view('errors.503', [], 500); - } - return parent::render($request, $exception); + if ($this->isHttpException($exception)) { + return $this->renderHttpException($exception); + } + // Custom error 500 view on production + if (app()->environment() === 'production') { + return response()->view('errors.503', [], 500); + } + + return parent::render($request, $exception); } /** diff --git a/app/Extensions/helper/helpers.php b/app/Extensions/helper/helpers.php index 8c9cefd1f..e89d3f938 100644 --- a/app/Extensions/helper/helpers.php +++ b/app/Extensions/helper/helpers.php @@ -1,12 +1,12 @@ setCookie(SetCookie::fromString($cookie)); - $client = new Client(['cookies' => $cookieJar]); - } - try { - $response = $client->get($url)->getBody()->getContents(); - } catch (RequestException $e) { - if ($e->hasResponse()) { - if($e->getCode() === 404) { - ColorCLI::doEcho(ColorCLI::notice('Data not available on server')); - } else if ($e->getCode() === 503) { - ColorCLI::doEcho(ColorCLI::notice('Service unavailable')); - } else { - ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from server, http error reported: ' . $e->getCode())); - } - } - } catch (\RuntimeException $e) { - ColorCLI::doEcho(ColorCLI::notice('Runtime error: ' . $e->getCode())); - } + function getRawHtml($url, $cookie = false) + { + $response = false; + $cookiejar = new CookieJar(); + $client = new Client(); + if ($cookie !== false) { + $cookieJar = $cookiejar->setCookie(SetCookie::fromString($cookie)); + $client = new Client(['cookies' => $cookieJar]); + } + try { + $response = $client->get($url)->getBody()->getContents(); + } catch (RequestException $e) { + if ($e->hasResponse()) { + if ($e->getCode() === 404) { + ColorCLI::doEcho(ColorCLI::notice('Data not available on server')); + } elseif ($e->getCode() === 503) { + ColorCLI::doEcho(ColorCLI::notice('Service unavailable')); + } else { + ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from server, http error reported: '.$e->getCode())); + } + } + } catch (\RuntimeException $e) { + ColorCLI::doEcho(ColorCLI::notice('Runtime error: '.$e->getCode())); + } - return $response; - } -} \ No newline at end of file + return $response; + } +} diff --git a/app/Extensions/util/Git.php b/app/Extensions/util/Git.php index 4235d582a..2abb28f5e 100644 --- a/app/Extensions/util/Git.php +++ b/app/Extensions/util/Git.php @@ -10,223 +10,230 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel * @copyright 2016 nZEDb */ + namespace App\Extensions\util; -use \GitRepo; -use Illuminate\Database\Eloquent\Collection; +use GitRepo; use Symfony\Component\Process\Process; +use Illuminate\Database\Eloquent\Collection; class Git extends Collection { - /** - * @var \GitRepo object - */ - protected $repo; + /** + * @var \GitRepo object + */ + protected $repo; - /** - * @var array - */ - public $_config; + /** + * @var array + */ + public $_config; - protected $gitTagLatest = null; + protected $gitTagLatest = null; - private $branch; + private $branch; - public function __construct(array $config = []) - { - $defaults = [ + public function __construct(array $config = []) + { + $defaults = [ 'branches' => [ 'stable' => ['0.x', 'Latest-testing', '\d+\.\d+\.\d+(\.\d+)?'], - 'development' => ['dev', 'dev-test'] + 'development' => ['dev', 'dev-test'], ], 'create' => false, 'initialise' => false, 'filepath' => NN_ROOT, ]; - $config += $defaults; - $this->_config = $config; - parent::__construct($config += $defaults); + $config += $defaults; + $this->_config = $config; + parent::__construct($config += $defaults); - $this->repo = new GitRepo( + $this->repo = new GitRepo( $this->_config['filepath'], $this->_config['create'], $this->_config['initialise'] ); - $this->branch = $this->repo->active_branch(); - } + $this->branch = $this->repo->active_branch(); + } - /** - * Run describe command. - * - * @param string $options - * - * @return string - * @throws \Symfony\Component\Process\Exception\LogicException - * @throws \Symfony\Component\Process\Exception\RuntimeException - */ - public function describe($options = null) - { - $command = new Process('git describe ' . $options); - $command->run(); - return $command->getOutput(); - } + /** + * Run describe command. + * + * @param string $options + * + * @return string + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\RuntimeException + */ + public function describe($options = null) + { + $command = new Process('git describe '.$options); + $command->run(); - /** - * Return the currently active branch - * - * @return string - */ - public function getBranch() - { - return $this->branch; - } + return $command->getOutput(); + } - public function getBranchesDevelop() - { - return $this->_config['branches']['development']; - } + /** + * Return the currently active branch. + * + * @return string + */ + public function getBranch() + { + return $this->branch; + } - /** - * Fetches the array of branch names that are considered to be core. - * - * @return array - */ - public function getBranchesMain() - { - return array_merge($this->getBranchesStable(), $this->getBranchesDevelop()); - } + public function getBranchesDevelop() + { + return $this->_config['branches']['development']; + } - public function getBranchesStable() - { - return $this->_config['branches']['stable']; - } + /** + * Fetches the array of branch names that are considered to be core. + * + * @return array + */ + public function getBranchesMain() + { + return array_merge($this->getBranchesStable(), $this->getBranchesDevelop()); + } - public function getHeadHash() - { - $command = new Process('git rev-parse HEAD'); - $command->run(); - return $command->getOutput(); - } + public function getBranchesStable() + { + return $this->_config['branches']['stable']; + } - /** - * Determine if the supplied object is commited to the repository or not. - * - * @param $gitObject - * - * @return bool - * @throws \Exception - */ - public function isCommited($gitObject) - { - $cmd = "cat-file -e $gitObject"; + public function getHeadHash() + { + $command = new Process('git rev-parse HEAD'); + $command->run(); - try { - $result = new Process($cmd); - $result->run(); - return $result->getOutput(); - } catch (\Exception $e) { - $message = explode("\n", $e->getMessage()); - if ($message[0] === "fatal: Not a valid object name $gitObject") { - $result = false; - } else { - throw new \RuntimeException($message); - } - } + return $command->getOutput(); + } - return ($result === ''); - } + /** + * Determine if the supplied object is commited to the repository or not. + * + * @param $gitObject + * + * @return bool + * @throws \Exception + */ + public function isCommited($gitObject) + { + $cmd = "cat-file -e $gitObject"; - public function isStable($branch) - { - foreach ($this->getBranchesStable() as $pattern) { - if (!preg_match("#$pattern#", $branch)) { - continue; - } - return true; - } + try { + $result = new Process($cmd); + $result->run(); - return false; - } + return $result->getOutput(); + } catch (\Exception $e) { + $message = explode("\n", $e->getMessage()); + if ($message[0] === "fatal: Not a valid object name $gitObject") { + $result = false; + } else { + throw new \RuntimeException($message); + } + } - /** - * Run the log command. - * - * @param null $options - * - * @return string - * @throws \Symfony\Component\Process\Exception\LogicException - * @throws \Symfony\Component\Process\Exception\RuntimeException - */ - public function log($options = null) - { - $command = new Process("git log $options"); - $command->run(); - return $command->getOutput(); - } + return $result === ''; + } - public function gitPull(array $options = []) - { - $default = [ + public function isStable($branch) + { + foreach ($this->getBranchesStable() as $pattern) { + if (! preg_match("#$pattern#", $branch)) { + continue; + } + + return true; + } + + return false; + } + + /** + * Run the log command. + * + * @param null $options + * + * @return string + * @throws \Symfony\Component\Process\Exception\LogicException + * @throws \Symfony\Component\Process\Exception\RuntimeException + */ + public function log($options = null) + { + $command = new Process("git log $options"); + $command->run(); + + return $command->getOutput(); + } + + public function gitPull(array $options = []) + { + $default = [ 'branch' => $this->getBranch(), 'remote' => 'origin', ]; - $options += $default; + $options += $default; - return $this->repo->pull($options['remote'], $options['branch']); - } + return $this->repo->pull($options['remote'], $options['branch']); + } - /** - * Run a git command in the git repository - * Accepts a git command to run - * - * @access public - * - * @param string $command Command to run - * - * @return string - */ - public function gitRun($command) - { - return $this->repo->run($command); - } + /** + * Run a git command in the git repository + * Accepts a git command to run. + * + * + * @param string $command Command to run + * + * @return string + */ + public function gitRun($command) + { + return $this->repo->run($command); + } - /** - * Run the tag command. - * - * @param string $options - * - * @return string - * @throws \Symfony\Component\Process\Exception\RuntimeException - * @throws \Symfony\Component\Process\Exception\LogicException - */ - public function tag($options = null) - { - $command = new Process('git tag' . $options); - $command->run(); - return $command->getOutput(); - } + /** + * Run the tag command. + * + * @param string $options + * + * @return string + * @throws \Symfony\Component\Process\Exception\RuntimeException + * @throws \Symfony\Component\Process\Exception\LogicException + */ + public function tag($options = null) + { + $command = new Process('git tag'.$options); + $command->run(); - /** - * Fetch the most recently added tag. - * - * Be aware this might cause problems if tags are added out of order? - * - * @return string - * @throws \Symfony\Component\Process\Exception\RuntimeException - * @throws \Symfony\Component\Process\Exception\LogicException - */ - public function tagLatest($cached = true) - { - if (empty($this->gitTagLatest) || $cached === false) { - $this->gitTagLatest = trim($this->describe('--tags --abbrev=0 HEAD')); - } - return $this->gitTagLatest; - } + return $command->getOutput(); + } + + /** + * Fetch the most recently added tag. + * + * Be aware this might cause problems if tags are added out of order? + * + * @return string + * @throws \Symfony\Component\Process\Exception\RuntimeException + * @throws \Symfony\Component\Process\Exception\LogicException + */ + public function tagLatest($cached = true) + { + if (empty($this->gitTagLatest) || $cached === false) { + $this->gitTagLatest = trim($this->describe('--tags --abbrev=0 HEAD')); + } + + return $this->gitTagLatest; + } } diff --git a/app/Extensions/util/Versions.php b/app/Extensions/util/Versions.php index f6bf523a5..b03cb5ac1 100644 --- a/app/Extensions/util/Versions.php +++ b/app/Extensions/util/Versions.php @@ -10,326 +10,335 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel * @copyright 2016 nZEDb */ + namespace App\Extensions\util; use App\Models\Settings; -use Illuminate\Database\Eloquent\Collection; use nntmux\utility\Utility; +use Illuminate\Database\Eloquent\Collection; class Versions extends Collection { - /** - * These constants are bitwise for checking what has changed. - */ - const UPDATED_GIT_TAG = 1; - const UPDATED_SQL_DB_PATCH = 2; - const UPDATED_SQL_FILE_LAST = 4; + /** + * These constants are bitwise for checking what has changed. + */ + const UPDATED_GIT_TAG = 1; + const UPDATED_SQL_DB_PATCH = 2; + const UPDATED_SQL_FILE_LAST = 4; - /** - * @var integer Bitwise mask of elements that have been changed. - */ - protected $changes = 0; + /** + * @var int Bitwise mask of elements that have been changed. + */ + protected $changes = 0; - /** - * @var Git object. - */ - protected $git; + /** + * @var Git object. + */ + protected $git; - /** - * @var - */ - protected $_config; + /** + * @var + */ + protected $_config; - /** - * @var \simpleXMLElement object. - */ - protected $versions = null; + /** + * @var \simpleXMLElement object. + */ + protected $versions = null; - /** - * @var \simpleXMLElement object - */ - protected $xml = null; + /** + * @var \simpleXMLElement object + */ + protected $xml = null; - public function __construct(array $config = []) - { - $defaults = [ + public function __construct(array $config = []) + { + $defaults = [ 'git' => null, 'path' => NN_VERSIONS, ]; - $config += $defaults; + $config += $defaults; - $this->_config = $config; - parent::__construct($config+$defaults); - } + $this->_config = $config; + parent::__construct($config + $defaults); + } - public function checkGitTag($update = false) - { - $this->checkGitTagInFile(); - } + public function checkGitTag($update = false) + { + $this->checkGitTagInFile(); + } - /** - * Checks the git's latest version tag against the XML's stored value. Version should be - * Major.Minor.Revision[.fix][-dev|-RCx] - * - * @param bool $update - * - * @return false|string version string if matched or false. - */ - public function checkGitTagInFile($update = false) - { - $this->initialiseGit(); - $result = preg_match(Utility::VERSION_REGEX, $this->git->tagLatest(), $matches) ? $matches['all'] : false; + /** + * Checks the git's latest version tag against the XML's stored value. Version should be + * Major.Minor.Revision[.fix][-dev|-RCx]. + * + * @param bool $update + * + * @return false|string version string if matched or false. + */ + public function checkGitTagInFile($update = false) + { + $this->initialiseGit(); + $result = preg_match(Utility::VERSION_REGEX, $this->git->tagLatest(), $matches) ? $matches['all'] : false; - if ($result !== false) { - if (!$this->git->isStable($this->git->getBranch())) { - $this->loadXMLFile(); - $result = preg_match(Utility::VERSION_REGEX, $this->versions->git->tag->__toString(), + if ($result !== false) { + if (! $this->git->isStable($this->git->getBranch())) { + $this->loadXMLFile(); + $result = preg_match(Utility::VERSION_REGEX, $this->versions->git->tag->__toString(), $matches) ? $matches['digits'] : false; - if ($result !== false) { - if (version_compare($matches['digits'], '0.0.0', '!=')) { - $this->versions->git->tag = '0.0.0-dev'; - $this->changes |= self::UPDATED_GIT_TAG; - } - } + if ($result !== false) { + if (version_compare($matches['digits'], '0.0.0', '!=')) { + $this->versions->git->tag = '0.0.0-dev'; + $this->changes |= self::UPDATED_GIT_TAG; + } + } - $result = $this->versions->git->tag; - } else { - $result = $this->checkGitTagsAreEqual(['update' => $update]); - } - } + $result = $this->versions->git->tag; + } else { + $result = $this->checkGitTagsAreEqual(['update' => $update]); + } + } - return $result; - } + return $result; + } - public function checkGitTagsAreEqual(array $options = []) - { - $options += [ + public function checkGitTagsAreEqual(array $options = []) + { + $options += [ 'update' => true, 'verbose' => true, ]; - $this->loadXMLFile(); - $latestTag = $this->git->tagLatest(); + $this->loadXMLFile(); + $latestTag = $this->git->tagLatest(); - // Check if file's entry is the same as current branch's tag - if (version_compare($this->versions->git->tag, $latestTag, '!=')) { - if ($options['update'] === true) { - if ($options['verbose'] === true) { - echo "Updating tag version to $latestTag" . PHP_EOL; - } - $this->versions->git->tag = $this->git->tagLatest(); - $this->changes |= self::UPDATED_GIT_TAG; + // Check if file's entry is the same as current branch's tag + if (version_compare($this->versions->git->tag, $latestTag, '!=')) { + if ($options['update'] === true) { + if ($options['verbose'] === true) { + echo "Updating tag version to $latestTag".PHP_EOL; + } + $this->versions->git->tag = $this->git->tagLatest(); + $this->changes |= self::UPDATED_GIT_TAG; - return $this->versions->git->tag; - } else { // They're NOT the same but we were told not to update. - if ($options['verbose'] === true) { - echo "Current tag version $latestTag, skipping update!" . PHP_EOL; - } - return false; - } - } else { // They're the same so return true - return true; - } - } + return $this->versions->git->tag; + } else { // They're NOT the same but we were told not to update. + if ($options['verbose'] === true) { + echo "Current tag version $latestTag, skipping update!".PHP_EOL; + } - /** - * Checks the database sqlpatch setting against the XML's stored value. - * - * @param boolean $verbose - * - * @return boolean|string The new database sqlpatch version, or false. - */ - public function checkSQLDb($verbose = true) - { - $this->loadXMLFile(); - $patch = $this->getSQLPatchFromDB(); + return false; + } + } else { // They're the same so return true + return true; + } + } - if ($this->versions->sql->db->__toString() !== $patch) { - if ($verbose) { - echo "Updating Db revision to $patch" . PHP_EOL; - } - $this->versions->sql->db = $patch; - $this->changes |= self::UPDATED_SQL_DB_PATCH; - } + /** + * Checks the database sqlpatch setting against the XML's stored value. + * + * @param bool $verbose + * + * @return bool|string The new database sqlpatch version, or false. + */ + public function checkSQLDb($verbose = true) + { + $this->loadXMLFile(); + $patch = $this->getSQLPatchFromDB(); - return $this->isChanged(self::UPDATED_SQL_DB_PATCH) ? $patch : false; - } + if ($this->versions->sql->db->__toString() !== $patch) { + if ($verbose) { + echo "Updating Db revision to $patch".PHP_EOL; + } + $this->versions->sql->db = $patch; + $this->changes |= self::UPDATED_SQL_DB_PATCH; + } - public function checkSQLFileLatest($verbose = true) - { - $this->loadXMLFile(); - $lastFile = $this->getSQLPatchLast(); + return $this->isChanged(self::UPDATED_SQL_DB_PATCH) ? $patch : false; + } - if ($lastFile !== false && $this->versions->sql->file->__toString() !== $lastFile) { - if ($verbose === true) { - echo "Updating latest patch file to $lastFile" . PHP_EOL; - } - $this->versions->sql->file = $lastFile; - $this->changes |= self::UPDATED_SQL_FILE_LAST; - } - } + public function checkSQLFileLatest($verbose = true) + { + $this->loadXMLFile(); + $lastFile = $this->getSQLPatchLast(); - public function getGitBranch() - { - $this->initialiseGit(); - return $this->git->getBranch(); - } + if ($lastFile !== false && $this->versions->sql->file->__toString() !== $lastFile) { + if ($verbose === true) { + echo "Updating latest patch file to $lastFile".PHP_EOL; + } + $this->versions->sql->file = $lastFile; + $this->changes |= self::UPDATED_SQL_FILE_LAST; + } + } - public function getGitHeadHash() - { - $this->initialiseGit(); - return $this->git->getHeadHash(); - } + public function getGitBranch() + { + $this->initialiseGit(); - public function getGitTagInFile() - { - $this->loadXMLFile(); - return ($this->versions === null) ? null : $this->versions->git->tag->__toString(); - } + return $this->git->getBranch(); + } - public function getGitTagInRepo() - { - $this->initialiseGit(); - return $this->git->tagLatest(); - } + public function getGitHeadHash() + { + $this->initialiseGit(); - public function getSQLPatchFromDB() - { - $dbVersion = Settings::value('..sqlpatch', true); + return $this->git->getHeadHash(); + } - if (!is_numeric($dbVersion)) { - throw new \RuntimeException('Bad sqlpatch value'); - } + public function getGitTagInFile() + { + $this->loadXMLFile(); - return $dbVersion; - } + return ($this->versions === null) ? null : $this->versions->git->tag->__toString(); + } - public function getSQLPatchFromFile() - { - $this->loadXMLFile(); - return ($this->versions === null) ? null : $this->versions->sql->file->__toString(); - } + public function getGitTagInRepo() + { + $this->initialiseGit(); - public function getSQLPatchLast() - { - $options = [ - 'data' => NN_RES . 'db' . DS . 'schema' . DS . 'data' . DS, + return $this->git->tagLatest(); + } + + public function getSQLPatchFromDB() + { + $dbVersion = Settings::value('..sqlpatch', true); + + if (! is_numeric($dbVersion)) { + throw new \RuntimeException('Bad sqlpatch value'); + } + + return $dbVersion; + } + + public function getSQLPatchFromFile() + { + $this->loadXMLFile(); + + return ($this->versions === null) ? null : $this->versions->sql->file->__toString(); + } + + public function getSQLPatchLast() + { + $options = [ + 'data' => NN_RES.'db'.DS.'schema'.DS.'data'.DS, 'ext' => 'sql', - 'path' => NN_RES . 'db' . DS . 'patches' . DS . 'mysql', - 'regex' => '#^' . Utility::PATH_REGEX . '(?P\d{4})~(?P\w+)\.sql$#', + 'path' => NN_RES.'db'.DS.'patches'.DS.'mysql', + 'regex' => '#^'.Utility::PATH_REGEX.'(?P\d{4})~(?P
\w+)\.sql$#', 'safe' => true, ]; - $files = Utility::getDirFiles($options); - natsort($files); + $files = Utility::getDirFiles($options); + natsort($files); - return preg_match($options['regex'], end($files), $matches) ? (int)$matches['patch'] : false; - } + return preg_match($options['regex'], end($files), $matches) ? (int) $matches['patch'] : false; + } - public function getTagVersion() - { - $this->deprecated(__METHOD__, 'getGitTagInRepo'); - return $this->getGitTagInRepo(); - } + public function getTagVersion() + { + $this->deprecated(__METHOD__, 'getGitTagInRepo'); - public function getValidVersionsFile() - { - $this->loadXMLFile(); - return $this->xml; - } + return $this->getGitTagInRepo(); + } - /** - * Check whether the XML has been changed by one of the methods here. - * - * @return boolean True if the XML has been changed. - */ - public function hasChanged() - { - return $this->changes !== 0; - } + public function getValidVersionsFile() + { + $this->loadXMLFile(); - public function save($verbose = true) - { - if ($this->hasChanged()) { - if ($verbose === true && $this->changes > 0) { - if ($this->isChanged(self::UPDATED_GIT_TAG)) { - echo 'Updated git tag version to ' . $this->versions->git->tag . PHP_EOL; - } + return $this->xml; + } - if ($this->isChanged(self::UPDATED_SQL_DB_PATCH)) { - echo 'Updated Db SQL revision to ' . $this->versions->sql->db . PHP_EOL; - } + /** + * Check whether the XML has been changed by one of the methods here. + * + * @return bool True if the XML has been changed. + */ + public function hasChanged() + { + return $this->changes !== 0; + } - if ($this->isChanged(self::UPDATED_SQL_FILE_LAST)) { - echo 'Updated latest SQL file to ' . $this->versions->sql->file . PHP_EOL; - } - } else if ($this->changes === 0) { - echo 'Version file already up to date.' . PHP_EOL; - } - $this->xml->asXML($this->_config['path']); - $this->changes = false; - } - } + public function save($verbose = true) + { + if ($this->hasChanged()) { + if ($verbose === true && $this->changes > 0) { + if ($this->isChanged(self::UPDATED_GIT_TAG)) { + echo 'Updated git tag version to '.$this->versions->git->tag.PHP_EOL; + } - protected function error($message) - { - // TODO handle console error message. - } + if ($this->isChanged(self::UPDATED_SQL_DB_PATCH)) { + echo 'Updated Db SQL revision to '.$this->versions->sql->db.PHP_EOL; + } - protected function initialiseGit() - { - if (!($this->git instanceof Git)) { - $this->git = new Git(); - } - } + if ($this->isChanged(self::UPDATED_SQL_FILE_LAST)) { + echo 'Updated latest SQL file to '.$this->versions->sql->file.PHP_EOL; + } + } elseif ($this->changes === 0) { + echo 'Version file already up to date.'.PHP_EOL; + } + $this->xml->asXML($this->_config['path']); + $this->changes = false; + } + } - protected function isChanged($property) - { - return (($this->changes & $property) === $property); - } + protected function error($message) + { + // TODO handle console error message. + } - protected function loadXMLFile() - { - if (empty($this->versions)) { - $temp = libxml_use_internal_errors(true); - $this->xml = simplexml_load_file($this->_config['path']); - libxml_use_internal_errors($temp); + protected function initialiseGit() + { + if (! ($this->git instanceof Git)) { + $this->git = new Git(); + } + } - if ($this->xml === false) { - $this->error("Your versions XML file ($this->_config['path']) is broken, try updating from git."); - throw new \RuntimeException("Failed to open versions XML file '{$this->_config['path']}'"); - } + protected function isChanged($property) + { + return ($this->changes & $property) === $property; + } - if ($this->xml->count() > 0) { - $vers = $this->xml->xpath('/nntmux/versions'); + protected function loadXMLFile() + { + if (empty($this->versions)) { + $temp = libxml_use_internal_errors(true); + $this->xml = simplexml_load_file($this->_config['path']); + libxml_use_internal_errors($temp); - if ($vers[0]->count() === 0) { - $this->error("Your versions XML file ({$this->_config['path']}) does not contain version info, try updating from git."); - throw new \RuntimeException("Failed to find versions node in XML file '{$this->_config['path']}'"); - } else { - $this->versions = &$this->xml->versions; // Create a convenience shortcut - } - } else { - throw new \RuntimeException("No elements in file!\n"); - } - } - } + if ($this->xml === false) { + $this->error("Your versions XML file ($this->_config['path']) is broken, try updating from git."); + throw new \RuntimeException("Failed to open versions XML file '{$this->_config['path']}'"); + } - protected function _init() - { - if ($this->_config['git'] instanceof Git) { - $this->git =& $this->_config['git']; - } - } + if ($this->xml->count() > 0) { + $vers = $this->xml->xpath('/nntmux/versions'); - private function deprecated($methodOld, $methodUse) - { - trigger_error("This method ($methodOld) is deprecated. Please use '$methodUse' instead.", + if ($vers[0]->count() === 0) { + $this->error("Your versions XML file ({$this->_config['path']}) does not contain version info, try updating from git."); + throw new \RuntimeException("Failed to find versions node in XML file '{$this->_config['path']}'"); + } else { + $this->versions = &$this->xml->versions; // Create a convenience shortcut + } + } else { + throw new \RuntimeException("No elements in file!\n"); + } + } + } + + protected function _init() + { + if ($this->_config['git'] instanceof Git) { + $this->git = &$this->_config['git']; + } + } + + private function deprecated($methodOld, $methodUse) + { + trigger_error("This method ($methodOld) is deprecated. Please use '$methodUse' instead.", E_USER_NOTICE); - } + } } diff --git a/app/Extensions/util/Yenc.php b/app/Extensions/util/Yenc.php index ad6b79f92..78bce9062 100644 --- a/app/Extensions/util/Yenc.php +++ b/app/Extensions/util/Yenc.php @@ -10,7 +10,7 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel @@ -23,55 +23,55 @@ use App\Providers\YencServiceProvider; class Yenc extends YencServiceProvider { - - /** - * @param $text yEncoded text to decode back to an 8 bit form. - * - * @param array $options - * - * @return string 8 bit decoded version of $text. - */ - public static function decode(&$text, array $options = []) - { - $options += [ - 'name' => 'default', - 'file' => true, - ]; - return static::config($options)->decode($text); - } - - /** - * @param $text - * - * @param array $options - * - * @return mixed - */ - public static function decodeIgnore(&$text, array $options = []) - { - $options += [ + /** + * @param $text yEncoded text to decode back to an 8 bit form. + * + * @param array $options + * + * @return string 8 bit decoded version of $text. + */ + public static function decode(&$text, array $options = []) + { + $options += [ 'name' => 'default', 'file' => true, ]; - return static::config($options)->decodeIgnore($text); - } + return static::config($options)->decode($text); + } - /** - * @param $data 8 bit data to convert to yEncoded text. - * @param string $filename Name of file to recreate as. - * @param int $line Maximum number of characters in each line. - * to use. - * - * @param bool $crc32 - * @param array $options - * - * @return \Exception|string The yEncoded version of $data. - */ - public static function encode(&$data, $filename, $line = 128, $crc32 = true, array $options = []) - { - $options += ['name' => 'default']; + /** + * @param $text + * + * @param array $options + * + * @return mixed + */ + public static function decodeIgnore(&$text, array $options = []) + { + $options += [ + 'name' => 'default', + 'file' => true, + ]; - return static::config($options)->encode($data, $filename, $line, $crc32); - } + return static::config($options)->decodeIgnore($text); + } + + /** + * @param $data 8 bit data to convert to yEncoded text. + * @param string $filename Name of file to recreate as. + * @param int $line Maximum number of characters in each line. + * to use. + * + * @param bool $crc32 + * @param array $options + * + * @return \Exception|string The yEncoded version of $data. + */ + public static function encode(&$data, $filename, $line = 128, $crc32 = true, array $options = []) + { + $options += ['name' => 'default']; + + return static::config($options)->encode($data, $filename, $line, $crc32); + } } diff --git a/app/Extensions/util/yenc/adapter/NzedbYenc.php b/app/Extensions/util/yenc/adapter/NzedbYenc.php index 4ede2179a..5a2375bcd 100644 --- a/app/Extensions/util/yenc/adapter/NzedbYenc.php +++ b/app/Extensions/util/yenc/adapter/NzedbYenc.php @@ -10,7 +10,7 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel @@ -21,33 +21,30 @@ namespace App\Extensions\util\yenc\adapter; use yenc\yenc; - class NzedbYenc { - public static function decode(&$text, $ignore = false, array $options = []) - { - return (new yenc())->decode($text); - } + public static function decode(&$text, $ignore = false, array $options = []) + { + return (new yenc())->decode($text); + } - public static function decodeIgnore(&$text, array $options = []) - { - return (new yenc())->decode($text, true); - } + public static function decodeIgnore(&$text, array $options = []) + { + return (new yenc())->decode($text, true); + } - /** - * Determines if this adapter is enabled by checking if the `yenc` extension is loaded. - * - * @return boolean Returns `true` if enabled, otherwise `false`. - */ - public static function enabled() - { - return extension_loaded('yenc'); - } + /** + * Determines if this adapter is enabled by checking if the `yenc` extension is loaded. + * + * @return bool Returns `true` if enabled, otherwise `false`. + */ + public static function enabled() + { + return extension_loaded('yenc'); + } - public static function encode($data, $filename, $lineLength = 128) - { - return (new yenc())->encode($data, $filename, $lineLength); - } + public static function encode($data, $filename, $lineLength = 128) + { + return (new yenc())->encode($data, $filename, $lineLength); + } } - -?> diff --git a/app/Extensions/util/yenc/adapter/Php.php b/app/Extensions/util/yenc/adapter/Php.php index 20d9e0027..503a722ba 100644 --- a/app/Extensions/util/yenc/adapter/Php.php +++ b/app/Extensions/util/yenc/adapter/Php.php @@ -10,7 +10,7 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel @@ -21,92 +21,88 @@ namespace App\Extensions\util\yenc\adapter; use nntmux\Logger; - /** - * Class Php - * - * @package app\extensions\util\yenc\adapter + * Class Php. */ class Php { - public static function decode(&$text, $ignore = false) - { - $crc = ''; - // Extract the yEnc string itself. - if (preg_match("/=ybegin.*size=([^ $]+).*\\r\\n(.*)\\r\\n=yend.*size=([^ $\\r\\n]+)(.*)/ims", + public static function decode(&$text, $ignore = false) + { + $crc = ''; + // Extract the yEnc string itself. + if (preg_match('/=ybegin.*size=([^ $]+).*\\r\\n(.*)\\r\\n=yend.*size=([^ $\\r\\n]+)(.*)/ims', $text, $encoded)) { - if (preg_match('/crc32=([^ $\\r\\n]+)/ims', $encoded[4], $trailer)) { - $crc = trim($trailer[1]); - } + if (preg_match('/crc32=([^ $\\r\\n]+)/ims', $encoded[4], $trailer)) { + $crc = trim($trailer[1]); + } - $headerSize = $encoded[1]; - $trailerSize = $encoded[3]; - $encoded = $encoded[2]; - } else { - return false; - } + $headerSize = $encoded[1]; + $trailerSize = $encoded[3]; + $encoded = $encoded[2]; + } else { + return false; + } - // Remove line breaks from the string. - $encoded = trim(str_replace("\r\n", '', $encoded)); + // Remove line breaks from the string. + $encoded = trim(str_replace("\r\n", '', $encoded)); - // Make sure the header and trailer file sizes match up. - if ($headerSize != $trailerSize) { - $message = 'Header and trailer file sizes do not match. This is a violation of the yEnc specification.'; - if (NN_LOGGING || NN_DEBUG) { - (new Logger())->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); - } + // Make sure the header and trailer file sizes match up. + if ($headerSize != $trailerSize) { + $message = 'Header and trailer file sizes do not match. This is a violation of the yEnc specification.'; + if (NN_LOGGING || NN_DEBUG) { + (new Logger())->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); + } - throw new \RuntimeException($message); - } + throw new \RuntimeException($message); + } - // Decode. - $decoded = ''; - $encodedLength = strlen($encoded); - for ($chr = 0; $chr < $encodedLength; $chr++) { - $decoded .= ( + // Decode. + $decoded = ''; + $encodedLength = strlen($encoded); + for ($chr = 0; $chr < $encodedLength; $chr++) { + $decoded .= ( $encoded[$chr] == '=' ? chr((ord($encoded[$chr]) - 42) % 256) : chr((((ord($encoded[++$chr]) - 64) % 256) - 42) % 256) ); - } + } - // Make sure the decoded file size is the same as the size specified in the header. - if (strlen($decoded) != $headerSize) { - $message = 'Header file size (' . $headerSize . ') and actual file size (' . strlen($decoded) . ') do not match. The file is probably corrupt.'; - if (NN_LOGGING || NN_DEBUG) { - (new Logger())->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); - } + // Make sure the decoded file size is the same as the size specified in the header. + if (strlen($decoded) != $headerSize) { + $message = 'Header file size ('.$headerSize.') and actual file size ('.strlen($decoded).') do not match. The file is probably corrupt.'; + if (NN_LOGGING || NN_DEBUG) { + (new Logger())->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); + } - throw new \RuntimeException($message); - } + throw new \RuntimeException($message); + } - // Check the CRC value - if ($crc !== '' && (strtolower($crc) !== strtolower(sprintf("%04X", crc32($decoded))))) { - $message = 'CRC32 checksums do not match. The file is probably corrupt.'; - if (NN_LOGGING || NN_DEBUG) { - (new Logger())->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); - } + // Check the CRC value + if ($crc !== '' && (strtolower($crc) !== strtolower(sprintf('%04X', crc32($decoded))))) { + $message = 'CRC32 checksums do not match. The file is probably corrupt.'; + if (NN_LOGGING || NN_DEBUG) { + (new Logger())->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); + } - throw new \RuntimeException($message); - } + throw new \RuntimeException($message); + } - return $decoded; - } + return $decoded; + } - /** - * Decode a string of text encoded with yEnc. Ignores all errors. - * - * @param string $text The encoded text to decode. - * - * @return string The decoded yEnc string, or the input string, if it's not yEnc. - * @access protected - */ - public static function decodeIgnore(&$text) - { - if (preg_match('/^(=yBegin.*=yEnd[^$]*)$/ims', $text, $input)) { - $text = ''; - $input = + /** + * Decode a string of text encoded with yEnc. Ignores all errors. + * + * @param string $text The encoded text to decode. + * + * @return string The decoded yEnc string, or the input string, if it's not yEnc. + */ + public static function decodeIgnore(&$text) + { + if (preg_match('/^(=yBegin.*=yEnd[^$]*)$/ims', $text, $input)) { + $text = ''; + $input = trim( preg_replace( '/\r\n/im', @@ -123,79 +119,77 @@ class Php ) ); - $length = strlen($input); - for ($chr = 0; $chr < $length; $chr++) { - $text .= ( + $length = strlen($input); + for ($chr = 0; $chr < $length; $chr++) { + $text .= ( $input[$chr] == '=' ? chr((((ord($input[++$chr]) - 64) % 256) - 42) % 256) : chr((ord($input[$chr]) - 42) % 256) ); - } - } + } + } - return $text; - } + return $text; + } - public static function enabled() - { - return true; - } + public static function enabled() + { + return true; + } - public static function encode($data, $filename, $lineLength = 128, $crc32 = true) - { - // yEnc 1.3 draft doesn't allow line lengths of more than 254 bytes. - if ($lineLength > 254) { - $lineLength = 254; - } + public static function encode($data, $filename, $lineLength = 128, $crc32 = true) + { + // yEnc 1.3 draft doesn't allow line lengths of more than 254 bytes. + if ($lineLength > 254) { + $lineLength = 254; + } - if ($lineLength < 1) { - $message = $lineLength . ' is not a valid line length.'; - if (NN_LOGGING || NN_DEBUG) { - (new Logger())->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); - } + if ($lineLength < 1) { + $message = $lineLength.' is not a valid line length.'; + if (NN_LOGGING || NN_DEBUG) { + (new Logger())->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); + } - throw new \RuntimeException($message); - } + throw new \RuntimeException($message); + } - $encoded = ''; - $stringLength = strlen($data); - // Encode each character of the string one at a time. - for ($i = 0; $i < $stringLength; $i++) { - $value = ((ord($data[$i]) + 42) % 256); + $encoded = ''; + $stringLength = strlen($data); + // Encode each character of the string one at a time. + for ($i = 0; $i < $stringLength; $i++) { + $value = ((ord($data[$i]) + 42) % 256); - // Escape NULL, TAB, LF, CR, space, . and = characters. - switch ($value) { + // Escape NULL, TAB, LF, CR, space, . and = characters. + switch ($value) { case 0: case 10: case 13: case 61: - $encoded .= ('=' . chr(($value + 64) % 256)); + $encoded .= ('='.chr(($value + 64) % 256)); break; default: $encoded .= chr($value); break; } - } + } - $encoded = - '=ybegin line=' . - $lineLength . - ' size=' . - $stringLength . - ' name=' . - trim($filename) . - "\r\n" . - trim(chunk_split($encoded, $lineLength)) . - "\r\n=yend size=" . + $encoded = + '=ybegin line='. + $lineLength. + ' size='. + $stringLength. + ' name='. + trim($filename). + "\r\n". + trim(chunk_split($encoded, $lineLength)). + "\r\n=yend size=". $stringLength; - // Add a CRC32 checksum if desired. - if ($crc32 === true) { - $encoded .= ' crc32=' . strtolower(sprintf("%X", crc32($data))); - } + // Add a CRC32 checksum if desired. + if ($crc32 === true) { + $encoded .= ' crc32='.strtolower(sprintf('%X', crc32($data))); + } - return $encoded; - } + return $encoded; + } } - -?> diff --git a/app/Extensions/util/yenc/adapter/Ydecode.php b/app/Extensions/util/yenc/adapter/Ydecode.php index a8861b32b..bb4054762 100644 --- a/app/Extensions/util/yenc/adapter/Ydecode.php +++ b/app/Extensions/util/yenc/adapter/Ydecode.php @@ -10,7 +10,7 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel @@ -20,68 +20,62 @@ namespace App\Extensions\util\yenc\adapter; use App\Extensions\util\Yenc; -use App\Models\Settings; -use nntmux\utility\Utility; class Ydecode { - /** - * Path to yyDecoder binary. - * - * @var bool|string - * @access protected - */ - protected static $pathBin; + /** + * Path to yyDecoder binary. + * + * @var bool|string + */ + protected static $pathBin; - /** - * If on unix, hide yydecode CLI output. - * - * @var string - * @access protected - */ - protected static $silent; + /** + * If on unix, hide yydecode CLI output. + * + * @var string + */ + protected static $silent; - public static function decode(&$text, $ignore = false) - { - $result = preg_match('/^(=yBegin.*=yEnd[^$]*)$/ims', $text, $input); - switch (true) { - case !$result: + public static function decode(&$text, $ignore = false) + { + $result = preg_match('/^(=yBegin.*=yEnd[^$]*)$/ims', $text, $input); + switch (true) { + case ! $result: throw new \RuntimeException('Text does not look like yEnc.'); case self::$pathBin === false: throw new \InvalidArgumentException('No valid path to yydecoder binary found!'); default: } - $ignoreFlag = $ignore ? '-b ' : ''; - $data = shell_exec( - "echo '{$input[1]}' | {" . self::$pathBin . '} -o - ' . $ignoreFlag . self::$silent + $ignoreFlag = $ignore ? '-b ' : ''; + $data = shell_exec( + "echo '{$input[1]}' | {".self::$pathBin.'} -o - '.$ignoreFlag.self::$silent ); - if ($data === null) { - throw new \RuntimeException('Error getting data from yydecode.'); - } + if ($data === null) { + throw new \RuntimeException('Error getting data from yydecode.'); + } - return $data; - } + return $data; + } - public static function decodeIgnore(&$text) - { - self::decode($text, true); - } + public static function decodeIgnore(&$text) + { + self::decode($text, true); + } - /** - * Determines if this adapter is enabled by checking if the `yydecode` path is enabled. - * - * @return boolean Returns `true` if enabled, otherwise `false`. - */ - public static function enabled() - { - return !empty(self::$pathBin); - } + /** + * Determines if this adapter is enabled by checking if the `yydecode` path is enabled. + * + * @return bool Returns `true` if enabled, otherwise `false`. + */ + public static function enabled() + { + return ! empty(self::$pathBin); + } - public static function encode($data, $filename, $lineLength, $crc32) - { - return Yenc::encode($data, $filename, $lineLength, $crc32, ['name' => 'Php']); - } + public static function encode($data, $filename, $lineLength, $crc32) + { + return Yenc::encode($data, $filename, $lineLength, $crc32, ['name' => 'Php']); + } } - -?> diff --git a/app/Models/AudioData.php b/app/Models/AudioData.php index d9fcc06c3..c9e4bd463 100644 --- a/app/Models/AudioData.php +++ b/app/Models/AudioData.php @@ -6,25 +6,25 @@ use Illuminate\Database\Eloquent\Model; class AudioData extends Model { - /** - * @var string - */ - protected $table = 'audio_data'; + /** + * @var string + */ + protected $table = 'audio_data'; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var array - */ - protected $fillable = [ + /** + * @var array + */ + protected $fillable = [ 'id', 'releases_id', 'audioid', @@ -36,6 +36,6 @@ class AudioData extends Model 'audiosamplerate', 'audiolibrary', 'audiolanguage', - 'audiotitle' + 'audiotitle', ]; } diff --git a/app/Models/BinaryBlacklist.php b/app/Models/BinaryBlacklist.php index 4b911b8eb..c81e3b4c3 100644 --- a/app/Models/BinaryBlacklist.php +++ b/app/Models/BinaryBlacklist.php @@ -6,25 +6,25 @@ use Illuminate\Database\Eloquent\Model; class BinaryBlacklist extends Model { - /** - * @var string - */ - protected $table = 'binaryblacklist'; + /** + * @var string + */ + protected $table = 'binaryblacklist'; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var array - */ - protected $fillable = [ + /** + * @var array + */ + protected $fillable = [ 'id', 'groupname', 'regex', @@ -32,6 +32,6 @@ class BinaryBlacklist extends Model 'optype', 'status', 'description', - 'last_activity' + 'last_activity', ]; } diff --git a/app/Models/BookInfo.php b/app/Models/BookInfo.php index afe4eaa47..b6d42764c 100644 --- a/app/Models/BookInfo.php +++ b/app/Models/BookInfo.php @@ -6,25 +6,25 @@ use Illuminate\Database\Eloquent\Model; class BookInfo extends Model { - /** - * @var string - */ - protected $table = 'bookinfo'; + /** + * @var string + */ + protected $table = 'bookinfo'; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var array - */ - protected $fillable = [ + /** + * @var array + */ + protected $fillable = [ 'title', 'author', 'asin', @@ -39,6 +39,6 @@ class BookInfo extends Model 'genre', 'cover', 'createddate', - 'updateddate' + 'updateddate', ]; } diff --git a/app/Models/DnzbFailure.php b/app/Models/DnzbFailure.php index da4e9c6fb..55f63dde8 100644 --- a/app/Models/DnzbFailure.php +++ b/app/Models/DnzbFailure.php @@ -6,29 +6,28 @@ use Illuminate\Database\Eloquent\Model; class DnzbFailure extends Model { - /** - * @var string - */ - protected $table = 'dnzb_failures'; + /** + * @var string + */ + protected $table = 'dnzb_failures'; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ - public $incrementing = false; - - /** - * @var array - */ - protected $fillable = ['release_id', 'users_id', 'failed']; + /** + * @var bool + */ + public $incrementing = false; + /** + * @var array + */ + protected $fillable = ['release_id', 'users_id', 'failed']; } diff --git a/app/Models/MultigroupPosters.php b/app/Models/MultigroupPosters.php index c45e1b661..673b7e9cf 100644 --- a/app/Models/MultigroupPosters.php +++ b/app/Models/MultigroupPosters.php @@ -10,40 +10,39 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel * @copyright 2016 nZEDb */ + namespace App\Models; use Illuminate\Database\Eloquent\Model; class MultigroupPosters extends Model { - protected $table = 'multigroup_posters'; + protected $table = 'multigroup_posters'; - protected $fillable = ['id', 'poster']; + protected $fillable = ['id', 'poster']; - public $dateFormat = false; + public $dateFormat = false; - public $timestamps = false; + public $timestamps = false; - /** - * @return string - */ - public static function commaSeparatedList(): string - { - $list = []; - $posters = self::all('poster'); + /** + * @return string + */ + public static function commaSeparatedList(): string + { + $list = []; + $posters = self::all('poster'); - foreach ($posters as $poster) { - $list[] = $poster->poster; - } + foreach ($posters as $poster) { + $list[] = $poster->poster; + } - return implode(',', $list); - } + return implode(',', $list); + } } - -?> diff --git a/app/Models/ReleaseExtraFull.php b/app/Models/ReleaseExtraFull.php index 052f417e1..db3f5b90a 100644 --- a/app/Models/ReleaseExtraFull.php +++ b/app/Models/ReleaseExtraFull.php @@ -6,33 +6,33 @@ use Illuminate\Database\Eloquent\Model; class ReleaseExtraFull extends Model { - /** - * @var string - */ - protected $table = 'releaseextrafull'; + /** + * @var string + */ + protected $table = 'releaseextrafull'; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var bool - */ - public $incrementing = false; + /** + * @var bool + */ + public $incrementing = false; - /** - * @var array - */ + /** + * @var array + */ protected $fillable = ['releases_id', 'mediainfo']; - /** - * @var string - */ - protected $primaryKey = 'releases_id'; + /** + * @var string + */ + protected $primaryKey = 'releases_id'; } diff --git a/app/Models/ReleaseRegexes.php b/app/Models/ReleaseRegexes.php index 1795b7ae0..714b27c81 100644 --- a/app/Models/ReleaseRegexes.php +++ b/app/Models/ReleaseRegexes.php @@ -10,30 +10,30 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author DariusIII * @copyright 2017 NNTmux/nZEDb */ -namespace App\Models; +namespace App\Models; use Illuminate\Database\Eloquent\Model; class ReleaseRegexes extends Model { - protected $table = 'release_regexes'; + protected $table = 'release_regexes'; - public $timestamps = false; + public $timestamps = false; - public $dateFormat = false; + public $dateFormat = false; - public $incrementing = false; + public $incrementing = false; - protected $fillable = ['releases_id', 'collection_regex_id', 'naming_regex_id']; + protected $fillable = ['releases_id', 'collection_regex_id', 'naming_regex_id']; - protected $primaryKey = [ - ['releases_id', 'collection_regex_id', 'naming_regex_id'] + protected $primaryKey = [ + ['releases_id', 'collection_regex_id', 'naming_regex_id'], ]; } diff --git a/app/Models/ReleaseSubtitle.php b/app/Models/ReleaseSubtitle.php index a1d4cc24c..f4a8f963c 100644 --- a/app/Models/ReleaseSubtitle.php +++ b/app/Models/ReleaseSubtitle.php @@ -6,28 +6,28 @@ use Illuminate\Database\Eloquent\Model; class ReleaseSubtitle extends Model { - /** - * @var string - */ - protected $table = 'release_subtitles'; + /** + * @var string + */ + protected $table = 'release_subtitles'; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var array - */ - protected $fillable = [ + /** + * @var array + */ + protected $fillable = [ 'id', 'releases_id', 'subsid', - 'subslanguage' + 'subslanguage', ]; } diff --git a/app/Models/ReleasesGroups.php b/app/Models/ReleasesGroups.php index 56c2c861d..8541495ea 100644 --- a/app/Models/ReleasesGroups.php +++ b/app/Models/ReleasesGroups.php @@ -10,26 +10,26 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel * @copyright 2016 nZEDb */ -namespace App\Models; +namespace App\Models; use Illuminate\Database\Eloquent\Model; class ReleasesGroups extends Model { - protected $table = 'releases_groups'; + protected $table = 'releases_groups'; - public $incrementing = false; + public $incrementing = false; - public $timestamps = false; + public $timestamps = false; - public $dateFormat = false; + public $dateFormat = false; - protected $primaryKey = ['releases_id', 'groups_id']; + protected $primaryKey = ['releases_id', 'groups_id']; } diff --git a/app/Models/Settings.php b/app/Models/Settings.php index 1d4305007..81ab67a03 100644 --- a/app/Models/Settings.php +++ b/app/Models/Settings.php @@ -10,7 +10,7 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel @@ -20,242 +20,239 @@ namespace App\Models; -use Illuminate\Database\Eloquent\Model; use nntmux\utility\Utility; use Illuminate\Console\Command; +use Illuminate\Database\Eloquent\Model; /** * Settings - model for settings table. - * - *@package App\Models */ class Settings extends Model { - const REGISTER_STATUS_OPEN = 0; + const REGISTER_STATUS_OPEN = 0; - const REGISTER_STATUS_INVITE = 1; + const REGISTER_STATUS_INVITE = 1; - const REGISTER_STATUS_CLOSED = 2; + const REGISTER_STATUS_CLOSED = 2; - const REGISTER_STATUS_API_ONLY = 3; + const REGISTER_STATUS_API_ONLY = 3; - const ERR_BADUNRARPATH = -1; + const ERR_BADUNRARPATH = -1; - const ERR_BADFFMPEGPATH = -2; + const ERR_BADFFMPEGPATH = -2; - const ERR_BADMEDIAINFOPATH = -3; + const ERR_BADMEDIAINFOPATH = -3; - const ERR_BADNZBPATH = -4; + const ERR_BADNZBPATH = -4; - const ERR_DEEPNOUNRAR = -5; + const ERR_DEEPNOUNRAR = -5; - const ERR_BADTMPUNRARPATH = -6; + const ERR_BADTMPUNRARPATH = -6; - const ERR_BADNZBPATH_UNREADABLE = -7; + const ERR_BADNZBPATH_UNREADABLE = -7; - const ERR_BADNZBPATH_UNSET = -8; + const ERR_BADNZBPATH_UNSET = -8; - const ERR_BAD_COVERS_PATH = -9; + const ERR_BAD_COVERS_PATH = -9; - const ERR_BAD_YYDECODER_PATH = -10; + const ERR_BAD_YYDECODER_PATH = -10; - /** - * @var Command - */ - protected $console; - /** - * @var array - */ - protected $primaryKey = ['section', 'subsection', 'name']; + /** + * @var Command + */ + protected $console; + /** + * @var array + */ + protected $primaryKey = ['section', 'subsection', 'name']; - /** - * @var string - */ - protected $table = 'settings'; + /** + * @var string + */ + protected $table = 'settings'; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ - public $incrementing = false; + /** + * @var bool + */ + public $incrementing = false; - protected $fillable = ['section', 'subsection', 'name', 'value', 'hint', 'setting']; + protected $fillable = ['section', 'subsection', 'name', 'value', 'hint', 'setting']; - /** - * @param Command $console - * - * @return bool - * @throws \Exception - * @throws \InvalidArgumentException - */ - public static function hasAllEntries($console) - { - $filepath = Utility::pathCombine(['db', 'schema', 'data', '10-settings.tsv'], NN_RES); - if (!file_exists($filepath)) { - throw new \InvalidArgumentException("Unable to find {$filepath}"); - } - $settings = file($filepath); + /** + * @param Command $console + * + * @return bool + * @throws \Exception + * @throws \InvalidArgumentException + */ + public static function hasAllEntries($console) + { + $filepath = Utility::pathCombine(['db', 'schema', 'data', '10-settings.tsv'], NN_RES); + if (! file_exists($filepath)) { + throw new \InvalidArgumentException("Unable to find {$filepath}"); + } + $settings = file($filepath); - if (!is_array($settings)) { - var_dump($settings); - throw new \InvalidArgumentException('Settings is not an array!'); - } + if (! is_array($settings)) { + var_dump($settings); + throw new \InvalidArgumentException('Settings is not an array!'); + } - $setting = []; - $dummy = array_shift($settings); - $result = false; - if ($dummy !== null) { - if ($console) { - $console->info('Verifying settings table...'); - $console->info('(section, subsection, name):'); - } - $result = true; - foreach ($settings as $line) { - $message = ''; - list($setting['section'], $setting['subsection'], $setting['name']) = + $setting = []; + $dummy = array_shift($settings); + $result = false; + if ($dummy !== null) { + if ($console) { + $console->info('Verifying settings table...'); + $console->info('(section, subsection, name):'); + } + $result = true; + foreach ($settings as $line) { + $message = ''; + list($setting['section'], $setting['subsection'], $setting['name']) = explode("\t", $line); - $value = Settings::value( + $value = self::value( [ 'section' => $setting['section'], 'subsection' => $setting['subsection'], - 'name' => $setting['name'] + 'name' => $setting['name'], ], true); - if ($value === null) { - $result = false; - $message = 'error'; - } + if ($value === null) { + $result = false; + $message = 'error'; + } - if ($message !== '' && $console !== null) { - $console->error(" {$setting['section']}, {$setting['subsection']}, {$setting['name']}: " - . 'MISSING!'); - } - } - } - $console->info('Settings table has all the required data'); - return $result; - } + if ($message !== '' && $console !== null) { + $console->error(" {$setting['section']}, {$setting['subsection']}, {$setting['name']}: " + .'MISSING!'); + } + } + } + $console->info('Settings table has all the required data'); - /** - * Return a tree-like array of all or selected settings. - * - * @param array $options Options array for Settings::find() i.e. ['conditions' => ...]. - * @param bool $excludeUnsectioned If rows with empty 'section' field should be excluded. - * Note this doesn't prevent empty 'subsection' fields. - * @return array - * @throws \RuntimeException - */ - public static function toTree(array $options = [], $excludeUnsectioned = true) - { - $results = empty($options) ? - Settings::all(): - Settings::all()->find($options); + return $result; + } - $tree = []; - if (is_array($results)) { - foreach ($results as $result) { - if (!empty($result['section']) || !$excludeUnsectioned) { - $tree[$result['section']][$result['subsection']][$result['name']] = + /** + * Return a tree-like array of all or selected settings. + * + * @param array $options Options array for Settings::find() i.e. ['conditions' => ...]. + * @param bool $excludeUnsectioned If rows with empty 'section' field should be excluded. + * Note this doesn't prevent empty 'subsection' fields. + * @return array + * @throws \RuntimeException + */ + public static function toTree(array $options = [], $excludeUnsectioned = true) + { + $results = empty($options) ? + self::all() : + self::all()->find($options); + + $tree = []; + if (is_array($results)) { + foreach ($results as $result) { + if (! empty($result['section']) || ! $excludeUnsectioned) { + $tree[$result['section']][$result['subsection']][$result['name']] = ['value' => $result['value'], 'hint' => $result['hint']]; - } - } - } else { - throw new \RuntimeException( + } + } + } else { + throw new \RuntimeException( 'NO results from Settings table! Check your table has been created and populated.' ); - } + } - return $tree; - } + return $tree; + } - /** - * Checks the supplied parameter is either a string or an array with single element. If - * either the value is passed to Settings::dottedToArray() for conversion. Otherwise the - * value is returned unchanged. - * - * @param $setting array|bool - * - * @return array|bool - */ - public static function settingToArray($setting) - { - if (!is_array($setting)) { - $setting = self::dottedToArray($setting); - } elseif (count($setting) === 1) { - $setting = self::dottedToArray($setting[0]); - } + /** + * Checks the supplied parameter is either a string or an array with single element. If + * either the value is passed to Settings::dottedToArray() for conversion. Otherwise the + * value is returned unchanged. + * + * @param $setting array|bool + * + * @return array|bool + */ + public static function settingToArray($setting) + { + if (! is_array($setting)) { + $setting = self::dottedToArray($setting); + } elseif (count($setting) === 1) { + $setting = self::dottedToArray($setting[0]); + } - return $setting; - } + return $setting; + } - /** - * Return the value of supplied setting. - * The setting can be either a normal condition array for the custom 'setting' finder or a - * dotted string notation setting. Note that dotted notation will be converted to an array, - * so it will be slower: Explicitly use the array format if speed it paramount. - * Be aware that this method only returns the first of any values found, so make sure your - * $setting produces a unique result. - * @param $setting - * @param bool $returnAlways Indicates if the method should throw an exception (false) or return - * null on failure. Defaults to throwing an exception. - * - * @return string|null The setting's value, or null on failure IF 'returnAlways' is true. - * @throws \Exception - */ - public static function value($setting, $returnAlways = false) - { - $setting = self::settingToArray($setting); - $result = Settings::query()->where([ + /** + * Return the value of supplied setting. + * The setting can be either a normal condition array for the custom 'setting' finder or a + * dotted string notation setting. Note that dotted notation will be converted to an array, + * so it will be slower: Explicitly use the array format if speed it paramount. + * Be aware that this method only returns the first of any values found, so make sure your + * $setting produces a unique result. + * @param $setting + * @param bool $returnAlways Indicates if the method should throw an exception (false) or return + * null on failure. Defaults to throwing an exception. + * + * @return string|null The setting's value, or null on failure IF 'returnAlways' is true. + * @throws \Exception + */ + public static function value($setting, $returnAlways = false) + { + $setting = self::settingToArray($setting); + $result = self::query()->where([ ['section', '=', $setting['section']], ['subsection', '=', $setting['subsection']], - ['name', '=', $setting['name']] + ['name', '=', $setting['name']], ])->value('value'); - if ($result !== null) { - $value = $result; - } else if ($returnAlways === false) { - throw new \RuntimeException('Unable to fetch setting from Db!'); - } else { - $value = null; - } + if ($result !== null) { + $value = $result; + } elseif ($returnAlways === false) { + throw new \RuntimeException('Unable to fetch setting from Db!'); + } else { + $value = null; + } - return $value; - } + return $value; + } - protected static function dottedToArray($setting) - { - $result = []; - if (is_string($setting)) { - $array = explode('.', $setting); - $count = count($array); - if ($count > 3) { - return false; - } + protected static function dottedToArray($setting) + { + $result = []; + if (is_string($setting)) { + $array = explode('.', $setting); + $count = count($array); + if ($count > 3) { + return false; + } - while (3 - $count > 0) { - array_unshift($array, ''); - $count++; - } - list( + while (3 - $count > 0) { + array_unshift($array, ''); + $count++; + } + list( $result['section'], $result['subsection'], - $result['name'], - ) = $array; - } else { - return false; - } + $result['name']) = $array; + } else { + return false; + } - return $result; - - } + return $result; + } } diff --git a/app/Models/SteamApps.php b/app/Models/SteamApps.php index 68b2e97ee..add3d3acb 100644 --- a/app/Models/SteamApps.php +++ b/app/Models/SteamApps.php @@ -10,49 +10,48 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author DariusIII * @copyright 2016 NNTmux/nZEDb */ + namespace App\Models; use Illuminate\Database\Eloquent\Model; class SteamApps extends Model { - /** - * @var string - */ - protected $table = 'steam_apps'; + /** + * @var string + */ + protected $table = 'steam_apps'; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ - public $dateFormat = false; + /** + * @var bool + */ + public $dateFormat = false; - /** - * @var array - */ - protected $fillable = ['name', 'appid']; + /** + * @var array + */ + protected $fillable = ['name', 'appid']; - /** - * @var array - */ - protected $primaryKey = 'name'; + /** + * @var array + */ + protected $primaryKey = 'name'; - protected $keyType = 'string'; + protected $keyType = 'string'; - /** - * @var bool - */ - public $incrementing = false; + /** + * @var bool + */ + public $incrementing = false; } - -?> diff --git a/app/Models/Tmux.php b/app/Models/Tmux.php index 95279486a..414b4e64d 100644 --- a/app/Models/Tmux.php +++ b/app/Models/Tmux.php @@ -6,46 +6,46 @@ use Illuminate\Database\Eloquent\Model; class Tmux extends Model { - /** - * @var string - */ - protected $table = 'tmux'; + /** + * @var string + */ + protected $table = 'tmux'; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var array - */ - protected $fillable = ['setting', 'value']; + /** + * @var array + */ + protected $fillable = ['setting', 'value']; - /** - * @param string $setting - * - * @param bool $returnAlways - * - * @return mixed - * @throws \RuntimeException - */ - public static function value($setting, $returnAlways = false) - { - $result = self::query()->where('setting', $setting)->value('value'); + /** + * @param string $setting + * + * @param bool $returnAlways + * + * @return mixed + * @throws \RuntimeException + */ + public static function value($setting, $returnAlways = false) + { + $result = self::query()->where('setting', $setting)->value('value'); - if ($result !== null) { - $value = $result; - } else if ($returnAlways === false) { - throw new \RuntimeException('Unable to fetch setting from Tmux table!'); - } else { - $value = null; - } + if ($result !== null) { + $value = $result; + } elseif ($returnAlways === false) { + throw new \RuntimeException('Unable to fetch setting from Tmux table!'); + } else { + $value = null; + } - return $value; - } + return $value; + } } diff --git a/app/Models/User.php b/app/Models/User.php index 1a31b387b..a81b6500a 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -6,26 +6,25 @@ use Illuminate\Database\Eloquent\Model; class User extends Model { - /** - * @var string - */ - protected $table = 'users'; + /** + * @var string + */ + protected $table = 'users'; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - - /** - * @var array - */ - protected $fillable = [ + /** + * @var array + */ + protected $fillable = [ 'username', 'password', 'email', @@ -36,11 +35,11 @@ class User extends Model 'invites', 'invitedby', 'userseed', - 'notes' + 'notes', ]; - /** - * @var array - */ - protected $hidden = ['password', 'rsstoken']; + /** + * @var array + */ + protected $hidden = ['password', 'rsstoken']; } diff --git a/app/Models/UserRequest.php b/app/Models/UserRequest.php index fc7a96d61..e5aaf7f65 100644 --- a/app/Models/UserRequest.php +++ b/app/Models/UserRequest.php @@ -6,22 +6,20 @@ use Illuminate\Database\Eloquent\Model; class UserRequest extends Model { + /** + * @var string + */ + protected $table = 'user_requests'; - /** - * @var string - */ - protected $table = 'user_requests'; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ - public $timestamps = false; - - - protected $fillable = ['users_id', 'request', 'hosthash', 'timestamp']; + protected $fillable = ['users_id', 'request', 'hosthash', 'timestamp']; } diff --git a/app/Models/UserRole.php b/app/Models/UserRole.php index e61374543..a308ed65b 100644 --- a/app/Models/UserRole.php +++ b/app/Models/UserRole.php @@ -4,27 +4,26 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; - class UserRole extends Model { - /** - * @var string - */ - protected $table = 'user_roles'; + /** + * @var string + */ + protected $table = 'user_roles'; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ + /** + * @var bool + */ protected $dateFormat = false; - /** - * @var array - */ + /** + * @var array + */ protected $fillable = [ 'id', 'name', @@ -33,7 +32,6 @@ class UserRole extends Model 'defaultinvites', 'isdefault', 'canpreview', - 'hideads' + 'hideads', ]; - } diff --git a/app/Models/VideoData.php b/app/Models/VideoData.php index 79bb12294..9ca262701 100644 --- a/app/Models/VideoData.php +++ b/app/Models/VideoData.php @@ -6,35 +6,35 @@ use Illuminate\Database\Eloquent\Model; class VideoData extends Model { - /** - * @var string - */ - protected $table = 'video_data'; + /** + * @var string + */ + protected $table = 'video_data'; - /** - * @var bool - */ - public $timestamps = false; + /** + * @var bool + */ + public $timestamps = false; - /** - * @var bool - */ - protected $dateFormat = false; + /** + * @var bool + */ + protected $dateFormat = false; - /** - * @var bool - */ - public $incrementing = false; + /** + * @var bool + */ + public $incrementing = false; - /** - * @var string - */ - protected $primaryKey = 'releases_id'; + /** + * @var string + */ + protected $primaryKey = 'releases_id'; - /** - * @var array - */ - protected $fillable = [ + /** + * @var array + */ + protected $fillable = [ 'releases_id', 'containerformat', 'overallbitrate', @@ -45,6 +45,6 @@ class VideoData extends Model 'videoheight', 'videoaspect', 'videoframerate', - 'videolibrary' + 'videolibrary', ]; } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 9784b1a30..9e68caa6f 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -2,7 +2,6 @@ namespace App\Providers; -use Illuminate\Support\Facades\Gate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider diff --git a/app/Providers/YencServiceProvider.php b/app/Providers/YencServiceProvider.php index 03eb4ab25..ff13cb026 100644 --- a/app/Providers/YencServiceProvider.php +++ b/app/Providers/YencServiceProvider.php @@ -3,55 +3,49 @@ namespace App\Providers; use Illuminate\Support\ServiceProvider; -use App\Extensions\util\yenc\adapter\NzedbYenc; use App\Extensions\util\yenc\adapter\Php; class YencServiceProvider extends ServiceProvider { + /** + * Bootstrap the application services. + * + * @return void + */ + public function boot() + { + } - /** - * Bootstrap the application services. - * - * @return void - */ - public function boot() - { + /** + * Register the application services. + * + * @return void + */ + public function register() + { + } - } - - /** - * Register the application services. - * - * @return void - */ - public function register() - { - - } - - /** - * @param array $options - * - * @return mixed - * @internal param $option - * - */ - public static function config(array $options = []) - { - $defaults = [ - ['name' => - [ - 'default' => 'Php' - ] - ] + /** + * @param array $options + * + * @return mixed + * @internal param $option + */ + public static function config(array $options = []) + { + $defaults = [ + ['name' => [ + 'default' => 'Php', + ], + ], ]; - $options += $defaults; + $options += $defaults; - $namespace = '\App\Extensions\util\yenc\adapter\\'; + $namespace = '\App\Extensions\util\yenc\adapter\\'; - $class = $namespace . $options[0]['name']['default']; + $class = $namespace.$options[0]['name']['default']; - return new $class; - } + return new $class; + } } diff --git a/bootstrap.php b/bootstrap.php index 6005335f5..2888f4f0d 100644 --- a/bootstrap.php +++ b/bootstrap.php @@ -10,13 +10,10 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel * @copyright 2016 nZEDb */ - -require_once __DIR__ . '/bootstrap/autoload.php'; - -?> +require_once __DIR__.'/bootstrap/autoload.php'; diff --git a/bootstrap/app.php b/bootstrap/app.php index 75c38a65e..15c6b42f6 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -12,7 +12,7 @@ */ $app = new Illuminate\Foundation\Application( - dirname(__DIR__) . '/' + dirname(__DIR__).'/' ); /* diff --git a/bootstrap/autoload.php b/bootstrap/autoload.php index 71358b46f..9454a2638 100644 --- a/bootstrap/autoload.php +++ b/bootstrap/autoload.php @@ -1,11 +1,10 @@ load(); define('NNTMUX_START', microtime(true)); -define('NN_APP_PATH', dirname(__DIR__) . DS . 'app'); +define('NN_APP_PATH', dirname(__DIR__).DS.'app'); -if (!defined('NN_ROOT')) { - define('NN_ROOT', dirname(NN_APP_PATH, 2)); +if (! defined('NN_ROOT')) { + define('NN_ROOT', dirname(NN_APP_PATH, 2)); } -require_once NN_ROOT . DS . 'vendor' . DS . 'autoload.php'; +require_once NN_ROOT.DS.'vendor'.DS.'autoload.php'; $app->make(Kernel::class)->bootstrap(); diff --git a/bootstrap/yenc.php b/bootstrap/yenc.php index 6200085b1..7c9a7078e 100644 --- a/bootstrap/yenc.php +++ b/bootstrap/yenc.php @@ -10,20 +10,18 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel * @copyright 2016 nZEDb */ - - use App\Models\Settings; if (defined('NN_INSTALLER') && NN_INSTALLER !== false) { - $adapter = 'Php'; + $adapter = 'Php'; } else { - switch (true) { + switch (true) { case extension_loaded('yenc'): if (method_exists('yenc\yEnc', 'version') && version_compare( @@ -32,14 +30,14 @@ if (defined('NN_INSTALLER') && NN_INSTALLER !== false) { '>=' ) ) { - $adapter = 'NzedbYenc'; - break; + $adapter = 'NzedbYenc'; + break; } else { - trigger_error('Your version of the php-yenc extension is out of date and will be + trigger_error('Your version of the php-yenc extension is out of date and will be ignored. Please update it to use the extension.', E_USER_WARNING ); } - case !empty(Settings::value('apps..yydecoderpath', true)): + case ! empty(Settings::value('apps..yydecoderpath', true)): $adapter = 'Ydecode'; break; default: @@ -48,12 +46,9 @@ if (defined('NN_INSTALLER') && NN_INSTALLER !== false) { } \App\Providers\YencServiceProvider::config([ - ['name' => - [ - 'default' => $adapter - ] - ] + ['name' => [ + 'default' => $adapter, + ], + ], ] ); - -?> diff --git a/build/NewPatches.php b/build/NewPatches.php index 3d3e02855..264764a03 100644 --- a/build/NewPatches.php +++ b/build/NewPatches.php @@ -18,15 +18,14 @@ * @author niel * @copyright 2015 nZEDb */ - -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\db\DbUpdate; use nntmux\utility\Git; use nntmux\utility\Utility; -if (!Utility::isCLI()) { - exit; +if (! Utility::isCLI()) { + exit; } $error = false; @@ -34,16 +33,16 @@ $git = new Git(); $branch = $git->active_branch(); if (in_array($branch, $git->mainBranches(), false)) { - // Only update patches, etc. on specific branches to lessen conflicts - try { - // Run DbUpdates to make sure we're up to date. - $DbUpdater = new DbUpdate(['git' => $git]); - $DbUpdater->newPatches(['safe' => false]); - } catch (\Exception $e) { - $error = 1; - echo 'Error while checking patches!' . PHP_EOL; - echo $e->getMessage() . PHP_EOL; - } + // Only update patches, etc. on specific branches to lessen conflicts + try { + // Run DbUpdates to make sure we're up to date. + $DbUpdater = new DbUpdate(['git' => $git]); + $DbUpdater->newPatches(['safe' => false]); + } catch (\Exception $e) { + $error = 1; + echo 'Error while checking patches!'.PHP_EOL; + echo $e->getMessage().PHP_EOL; + } } exit($error); diff --git a/build/git-hooks/runHooks.php b/build/git-hooks/runHooks.php index 5c4d56108..21fefb359 100755 --- a/build/git-hooks/runHooks.php +++ b/build/git-hooks/runHooks.php @@ -20,7 +20,7 @@ */ define('GIT_PRE_COMMIT', true); -require_once realpath(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'bootstrap.php'); +require_once realpath(dirname(dirname(__DIR__)).DIRECTORY_SEPARATOR.'bootstrap.php'); use nntmux\utility\Git; use App\Extensions\util\Versions; @@ -35,36 +35,35 @@ $error = false; // echo "Filename: $file\n"; //} -/** +/* * Add all hooks BEFORE the versions are updated so they can be skipped on any errors */ if ($error === false) { - $git = new Git(); - $branch = $git->active_branch(); - if (in_array($branch, $git->mainBranches(), false)) { - // Only update versions, etc. on specific branches to lessen conflicts + $git = new Git(); + $branch = $git->active_branch(); + if (in_array($branch, $git->mainBranches(), false)) { + // Only update versions, etc. on specific branches to lessen conflicts - if ($error === false) { - try { - $vers = new Versions(); - $vers->checkGitTag(true); - $vers->checkSQLFileLatest(false); - $vers->checkSQLDb(false); - $vers->save(); + if ($error === false) { + try { + $vers = new Versions(); + $vers->checkGitTag(true); + $vers->checkSQLFileLatest(false); + $vers->checkSQLDb(false); + $vers->save(); - $git->add(NN_VERSIONS); - } catch (\Exception $e) { - $error = 1; - echo "Error while checking versions!\n"; - echo $e->getMessage() . PHP_EOL; - } - } - } else { - echo "not 'dev' or '0.x' branch, skipping version/patch updates\n"; - } + $git->add(NN_VERSIONS); + } catch (\Exception $e) { + $error = 1; + echo "Error while checking versions!\n"; + echo $e->getMessage().PHP_EOL; + } + } + } else { + echo "not 'dev' or '0.x' branch, skipping version/patch updates\n"; + } } else { - echo "Error in pre-commit hooks!!\n"; + echo "Error in pre-commit hooks!!\n"; } exit($error); -?> diff --git a/build/postInstall.php b/build/postInstall.php index 6ba97bc59..e847c1d52 100644 --- a/build/postInstall.php +++ b/build/postInstall.php @@ -10,19 +10,16 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel * @copyright 2016 nZEDb */ +require_once '..'.DIRECTORY_SEPARATOR.'bootstrap.php'; -require_once '..' . DIRECTORY_SEPARATOR . 'bootstrap.php'; - -$updates = NN_CONFIGS . 'updates.json'; -if (!file_exists($updates)) { - $json = [ 'script' => time()]; - file_put_contents(json_encode($json, JSON_PRETTY_PRINT)); +$updates = NN_CONFIGS.'updates.json'; +if (! file_exists($updates)) { + $json = ['script' => time()]; + file_put_contents(json_encode($json, JSON_PRETTY_PRINT)); } - -?> diff --git a/cli/data/populate_anidb.php b/cli/data/populate_anidb.php index e14154c59..ef9cc989f 100755 --- a/cli/data/populate_anidb.php +++ b/cli/data/populate_anidb.php @@ -2,30 +2,30 @@ /* This script is designed to gather all show data from anidb and add it to the anidb table for nntmux, as part of this process we need the number of PI queries that can be executed max and whether or not we want debuging the first argument if unset will try to do the entire list (a good way to get banned), the second option can be blank or true for debugging. * IF you are using this script then then you also want to edit anidb.php in www/lib and locate "604800" and replace it with 1204400, this will make sure it never tries to connect to anidb as this will fail */ -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; -use nntmux\ColorCLI; use nntmux\db\DB; +use nntmux\ColorCLI; use nntmux\db\populate\AniDB; $pdo = new DB(); if ($argc > 1 && $argv[1] === 'true' && isset($argv[2])) { - if($argv[2] === 'full') { - (new AniDB(['Settings' => $pdo, 'Echo' => true]))->populateTable('full'); - } elseif ($argv[2] === 'info'){ - if ($argv[3] !== null && is_numeric($argv[3])) { - (new AniDB(['Settings' => $pdo, 'Echo' => true]))->populateTable('info', $argv[3]); - } else { - (new AniDB(['Settings' => $pdo, 'Echo' => true]))->populateTable('info'); - } - } + if ($argv[2] === 'full') { + (new AniDB(['Settings' => $pdo, 'Echo' => true]))->populateTable('full'); + } elseif ($argv[2] === 'info') { + if ($argv[3] !== null && is_numeric($argv[3])) { + (new AniDB(['Settings' => $pdo, 'Echo' => true]))->populateTable('info', $argv[3]); + } else { + (new AniDB(['Settings' => $pdo, 'Echo' => true]))->populateTable('info'); + } + } } else { - ColorCLI::doEcho(PHP_EOL . ColorCLI::error( - 'To execute this script you must provide a boolean argument.' . PHP_EOL . - 'Argument1: true|false to run this script or not' . PHP_EOL . - 'Argument2: full|info for what type of data to populate.' . PHP_EOL . - 'Argument3 (optional) anidbid to fetch info for' . PHP_EOL . + ColorCLI::doEcho(PHP_EOL.ColorCLI::error( + 'To execute this script you must provide a boolean argument.'.PHP_EOL. + 'Argument1: true|false to run this script or not'.PHP_EOL. + 'Argument2: full|info for what type of data to populate.'.PHP_EOL. + 'Argument3 (optional) anidbid to fetch info for'.PHP_EOL. 'WARNING: Argument "info" without third argument will get you banned from AniDB almost instantly'), true ); } diff --git a/cli/data/populate_steam_apps.php b/cli/data/populate_steam_apps.php index fbfb67a7c..1057fcfb3 100644 --- a/cli/data/populate_steam_apps.php +++ b/cli/data/populate_steam_apps.php @@ -1,6 +1,6 @@ (?P\d+)_predb_dump\.csv\.gz)'; if (NN_DEBUG) { - echo "Fetching predb_dump directory list from GitHub\n"; + echo "Fetching predb_dump directory list from GitHub\n"; } $result = getDirListing($url); @@ -78,111 +77,110 @@ $dirs = json_decode($result, true); if (is_null($dirs) || (isset($dirs['message']) && substr($dirs['message'], 0, 27) == 'API rate limit exceeded for')) { - exit("Error: $result"); + exit("Error: $result"); } - if (NN_DEBUG) { - echo "Fetching predb_dump lists from GitHub\n"; + echo "Fetching predb_dump lists from GitHub\n"; } foreach ($dirs as $dir) { - if ($dir['name'] == '0README.txt') { - continue; - } + if ($dir['name'] == '0README.txt') { + continue; + } - $result = getDirListing($url . $dir['name'] . '/'); + $result = getDirListing($url.$dir['name'].'/'); - if (NN_DEBUG) { - echo "Extracting filenames from list.\n"; - } + if (NN_DEBUG) { + echo "Extracting filenames from list.\n"; + } - $temp = json_decode($result, true); - if (is_null($temp)) { - exit("Error: $result"); - } + $temp = json_decode($result, true); + if (is_null($temp)) { + exit("Error: $result"); + } - $data[$dir['name']] = $temp; + $data[$dir['name']] = $temp; } $total = 0; foreach ($data as $dir => $files) { - $total += count($files); + $total += count($files); } -$total --; +$total--; $predb = new PreDb(); $progress = $predb->progress(settings_array()); foreach ($data as $dir => $files) { - foreach ($files as $file) { - //var_dump($file); - if (preg_match("#^https://raw\.githubusercontent\.com/nZEDb/nZEDbPre_Dumps/master/dumps/$dir/$filePattern$#", + foreach ($files as $file) { + //var_dump($file); + if (preg_match("#^https://raw\.githubusercontent\.com/nZEDb/nZEDbPre_Dumps/master/dumps/$dir/$filePattern$#", $file['download_url'])) { - if (preg_match("#^$filePattern$#", $file['name'], $match)) { - $timematch = $progress['last']; + if (preg_match("#^$filePattern$#", $file['name'], $match)) { + $timematch = $progress['last']; - // Skip patches the user does not want. - if ($match[1] < $timematch) { - echo 'Skipping dump ' . $match[2] . - ', as your minimum unix time argument is ' . - $timematch . PHP_EOL; - --$total; - continue; - } + // Skip patches the user does not want. + if ($match[1] < $timematch) { + echo 'Skipping dump '.$match[2]. + ', as your minimum unix time argument is '. + $timematch.PHP_EOL; + --$total; + continue; + } - // Download the dump. - $dump = Utility::getUrl(['url' => $file['download_url']]); - echo "Downloading: {$file['download_url']}\n"; + // Download the dump. + $dump = Utility::getUrl(['url' => $file['download_url']]); + echo "Downloading: {$file['download_url']}\n"; - if (!$dump) { - echo "Error downloading dump {$match[2]} you can try manually importing it." . + if (! $dump) { + echo "Error downloading dump {$match[2]} you can try manually importing it.". PHP_EOL; - continue; - } else { - if (NN_DEBUG) { - echo "Dump {$match[2]} downloaded\n"; - } - } + continue; + } else { + if (NN_DEBUG) { + echo "Dump {$match[2]} downloaded\n"; + } + } - // Make sure we didn't get an HTML page. - if (strpos($dump, '') !== false) { - echo "The dump file {$match[2]} might be missing from GitHub." . PHP_EOL; - continue; - } + // Make sure we didn't get an HTML page. + if (strpos($dump, '') !== false) { + echo "The dump file {$match[2]} might be missing from GitHub.".PHP_EOL; + continue; + } - // Decompress. - $dump = gzdecode($dump); + // Decompress. + $dump = gzdecode($dump); - if (!$dump) { - echo "Error decompressing dump {$match[2]}." . PHP_EOL; - continue; - } + if (! $dump) { + echo "Error decompressing dump {$match[2]}.".PHP_EOL; + continue; + } - // Store the dump. - $dumpFile = NN_RES . $match[2] . '_predb_dump.csv'; - $fetched = file_put_contents($dumpFile, $dump); - if (!$fetched) { - echo "Error storing dump file {$match[2]} in (" . NN_RES . ').' . + // Store the dump. + $dumpFile = NN_RES.$match[2].'_predb_dump.csv'; + $fetched = file_put_contents($dumpFile, $dump); + if (! $fetched) { + echo "Error storing dump file {$match[2]} in (".NN_RES.').'. PHP_EOL; - continue; - } + continue; + } - // Make sure it's readable by all. - chmod($dumpFile, 0777); - $local = strtolower($argv[2]) === 'local'; - $verbose = $argv[3] === true; + // Make sure it's readable by all. + chmod($dumpFile, 0777); + $local = strtolower($argv[2]) === 'local'; + $verbose = $argv[3] === true; - if ($verbose) { - echo $predb->log->info('Clearing import table'); - } + if ($verbose) { + echo $predb->log->info('Clearing import table'); + } - // Truncate to clear any old data - $predb->executeTruncate(); + // Truncate to clear any old data + $predb->executeTruncate(); - // Import file into predb_imports - $predb->executeLoadData( + // Import file into predb_imports + $predb->executeLoadData( [ 'fields' => '\\t\\t', 'lines' => '\\r\\n', @@ -190,71 +188,71 @@ foreach ($data as $dir => $files) { 'path' => $dumpFile, ]); - // Remove any titles where length <=8 - if ($verbose === true) { - echo $predb->log->info('Deleting any records where title <=8 from Temporary Table'); - } - $predb->executeDeleteShort(); + // Remove any titles where length <=8 + if ($verbose === true) { + echo $predb->log->info('Deleting any records where title <=8 from Temporary Table'); + } + $predb->executeDeleteShort(); - // Add any groups that do not currently exist - $predb->executeAddGroups(); + // Add any groups that do not currently exist + $predb->executeAddGroups(); - // Fill the groups_id - $predb->executeUpdateGroupID(); + // Fill the groups_id + $predb->executeUpdateGroupID(); - echo $predb->log->info('Inserting records from temporary table into predb table'); - $predb->executeInsert(); + echo $predb->log->info('Inserting records from temporary table into predb table'); + $predb->executeInsert(); - // Delete the dump. - unlink($dumpFile); + // Delete the dump. + unlink($dumpFile); - $progress = $predb->progress(settings_array($match[2] + 1, $progress), + $progress = $predb->progress(settings_array($match[2] + 1, $progress), ['read' => false]); - echo sprintf("Successfully imported PreDB dump %d (%s), %d dumps remaining\n", + echo sprintf("Successfully imported PreDB dump %d (%s), %d dumps remaining\n", $match[2], date('Y-m-d', $match[2]), --$total ); - } else { - echo "Ignoring: {$file['download_url']}\n"; - } - } else { - if (NN_DEBUG) { - echo "^https://raw.githubusercontent.com/nZEDb/nZEDbPre_Dumps/master/dumps/$dir/$filePattern$\n {$file['download_url']}\n"; - } - } - } + } else { + echo "Ignoring: {$file['download_url']}\n"; + } + } else { + if (NN_DEBUG) { + echo "^https://raw.githubusercontent.com/nZEDb/nZEDbPre_Dumps/master/dumps/$dir/$filePattern$\n {$file['download_url']}\n"; + } + } + } } //////////////////////////////////////////////////////////////////////////////////////////////////// function settings_array($last = null, $settings = null) { - if ($settings === null) { - $settings['last'] = 0; - } + if ($settings === null) { + $settings['last'] = 0; + } - if ($last !== null) { - $settings['last'] = $last; - } + if ($last !== null) { + $settings['last'] = $last; + } - return $settings; + return $settings; } function getDirListing($url) { - $result = Utility::getUrl( + $result = Utility::getUrl( [ 'url' => $url, 'requestheaders' => [ 'Content-Type: application/json', - 'User-Agent: nZEDb' - ] + 'User-Agent: nZEDb', + ], ]); - if ($result === false) { - exit('Error connecting to GitHub, try again later?' . PHP_EOL); - } + if ($result === false) { + exit('Error connecting to GitHub, try again later?'.PHP_EOL); + } - return $result; + return $result; } diff --git a/cli/verify_permissions.php b/cli/verify_permissions.php index ddee77779..ff3ecdcda 100644 --- a/cli/verify_permissions.php +++ b/cli/verify_permissions.php @@ -1,19 +1,20 @@ [R], - NN_LIBS . 'smarty' => [R], - NN_LIBS . 'smarty' . DS . 'templates_c' => [R, W], + NN_LIBS.'smarty' => [R], + NN_LIBS.'smarty'.DS.'templates_c' => [R, W], NN_RES => [R, W, E], - NN_RES . 'db' => [R, E], - NN_RES . 'db' . DS . 'patches' => [R, E], - NN_RES . 'nzb' => [R], + NN_RES.'db' => [R, E], + NN_RES.'db'.DS.'patches' => [R, E], + NN_RES.'nzb' => [R], NN_LOGS => [R, W], NN_TMP => [R, W], - NN_TMP . DS . 'unrar' => [R, W, E], - NN_TMP . DS . 'yEnc' => [R, W, E], + NN_TMP.DS.'unrar' => [R, W, E], + NN_TMP.DS.'yEnc' => [R, W, E], NN_VERSIONS => [R], ]; // Add nzb folders. foreach ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'] as $identifier) { - $nzbFolder = NN_RES . 'nzb' . DS . $identifier . DS; - $folders[$nzbFolder] = [R, W]; + $nzbFolder = NN_RES.'nzb'.DS.$identifier.DS; + $folders[$nzbFolder] = [R, W]; } // Add covers paths. foreach (['anime', 'audio', 'audiosample', 'book', 'console', 'games', 'movies', 'music', 'preview', 'sample', 'tvrage', 'video', 'xxx', 'tvshow'] as $identifier) { - $nzbFolder = NN_RES . 'covers' . DS . $identifier . DS; - $folders[$nzbFolder] = [R, W]; + $nzbFolder = NN_RES.'covers'.DS.$identifier.DS; + $folders[$nzbFolder] = [R, W]; } // Set up covers paths. if (env('DB_PASSWORD') !== '') { - $ri = new ReleaseImage(); + $ri = new ReleaseImage(); - $folders[$ri->audSavePath] = [R, W]; - $folders[$ri->imgSavePath] = [R, W]; - $folders[$ri->jpgSavePath] = [R, W]; - $folders[$ri->movieImgSavePath] = [R, W]; - $folders[$ri->vidSavePath] = [R, W]; + $folders[$ri->audSavePath] = [R, W]; + $folders[$ri->imgSavePath] = [R, W]; + $folders[$ri->jpgSavePath] = [R, W]; + $folders[$ri->movieImgSavePath] = [R, W]; + $folders[$ri->vidSavePath] = [R, W]; } else { - echo 'Skipping cover folders check, as you have not set up a database yet. You can rerun this script after running install.' . PHP_EOL; + echo 'Skipping cover folders check, as you have not set up a database yet. You can rerun this script after running install.'.PHP_EOL; } // Check folders. foreach ($folders as $folder => $check) { - exists($folder); - foreach ($check as $type) { - switch ($type) { + exists($folder); + foreach ($check as $type) { + switch ($type) { case R: readable($folder); break; @@ -85,42 +86,42 @@ foreach ($folders as $folder => $check) { executable($folder); break; } - } + } } -echo 'Your permissions seem right for this user. Note, this script does not verify all paths, only the most important ones.' . PHP_EOL; +echo 'Your permissions seem right for this user. Note, this script does not verify all paths, only the most important ones.'.PHP_EOL; -if (!Utility::isWin()) { - $user = posix_getpwuid(posix_geteuid()); - if ($user['name'] !== 'www-data') { - echo 'If you have not already done so, please rerun this script using the www-data user: sudo -u www-data php verify_permissions.php yes' . PHP_EOL; - } +if (! Utility::isWin()) { + $user = posix_getpwuid(posix_geteuid()); + if ($user['name'] !== 'www-data') { + echo 'If you have not already done so, please rerun this script using the www-data user: sudo -u www-data php verify_permissions.php yes'.PHP_EOL; + } } function readable($folder) { - if (!is_readable($folder)) { - exit('Error: This path is not readable: (' . $folder . ') resolve this and rerun the script.' . PHP_EOL); - } + if (! is_readable($folder)) { + exit('Error: This path is not readable: ('.$folder.') resolve this and rerun the script.'.PHP_EOL); + } } function writable($folder) { - if (!is_writable($folder)) { - exit('Error: This path is not writable: (' . $folder . ') resolve this and rerun the script.' . PHP_EOL); - } + if (! is_writable($folder)) { + exit('Error: This path is not writable: ('.$folder.') resolve this and rerun the script.'.PHP_EOL); + } } function executable($folder) { - if (!is_executable($folder)) { - exit('Error: This path is not executable: (' . $folder . ') resolve this and rerun the script.' . PHP_EOL); - } + if (! is_executable($folder)) { + exit('Error: This path is not executable: ('.$folder.') resolve this and rerun the script.'.PHP_EOL); + } } function exists($folder) { - if (!file_exists($folder)) { - exit('Error: This path (' . $folder . ') does not exist or is not readable. Create it or make it readable.' . PHP_EOL); - } + if (! file_exists($folder)) { + exit('Error: This path ('.$folder.') does not exist or is not readable. Create it or make it readable.'.PHP_EOL); + } } diff --git a/cli/versions.php b/cli/versions.php index 0d1504b4b..f9dd6ff11 100644 --- a/cli/versions.php +++ b/cli/versions.php @@ -18,35 +18,35 @@ * @author niel * @copyright 2014 nZEDb */ -require_once realpath(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'bootstrap.php'); +require_once realpath(dirname(__DIR__).DIRECTORY_SEPARATOR.'bootstrap.php'); use nntmux\utility\Utility; use nntmux\utility\Versions; -if (!Utility::isCLI()) { - exit; +if (! Utility::isCLI()) { + exit; } $vers = new Versions(); if (isset($argc) && $argc > 1 && isset($argv[1]) && $argv[1] == true) { - echo $vers->out->header("Checking versions..."); + echo $vers->out->header('Checking versions...'); - if ($vers->checkAll()) { - $vers->save(); - } else { - echo "No changes detected.\n"; - output($vers); - } + if ($vers->checkAll()) { + $vers->save(); + } else { + echo "No changes detected.\n"; + output($vers); + } } else { - $vers->checkAll(false); - echo "Version info in file:\n"; - output($vers); + $vers->checkAll(false); + echo "Version info in file:\n"; + output($vers); } function output($vers) { - echo " Commit: " . $vers->out->primary($vers->getCommit()); - echo "SQL DB: " . $vers->out->primary($vers->getSQLPatchFromDb()); - echo "SQL File: " . $vers->out->primary($vers->getSQLPatchFromFiles()); - echo " Tag: " . $vers->out->primary($vers->getTagVersion()); + echo ' Commit: '.$vers->out->primary($vers->getCommit()); + echo 'SQL DB: '.$vers->out->primary($vers->getSQLPatchFromDb()); + echo 'SQL File: '.$vers->out->primary($vers->getSQLPatchFromFiles()); + echo ' Tag: '.$vers->out->primary($vers->getTagVersion()); } diff --git a/config/database.php b/config/database.php index 67c30c532..0407432e1 100644 --- a/config/database.php +++ b/config/database.php @@ -88,7 +88,7 @@ return [ 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', - 'strict' => false + 'strict' => false, ], ], diff --git a/config/nntmux.php b/config/nntmux.php index 73b15759c..ada701985 100644 --- a/config/nntmux.php +++ b/config/nntmux.php @@ -1,8 +1,9 @@ load(); @@ -19,8 +20,8 @@ $capsule->addConnection([ 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', - 'strict' => false + 'strict' => false, ]); $capsule->setAsGlobal(); -$capsule->bootEloquent(); \ No newline at end of file +$capsule->bootEloquent(); diff --git a/misc/IRCScraper/scrape.php b/misc/IRCScraper/scrape.php index a2ce4101e..4ed8286ac 100644 --- a/misc/IRCScraper/scrape.php +++ b/misc/IRCScraper/scrape.php @@ -1,46 +1,47 @@ /dev/null 2>&1 ; (unix) Scrapes PRE with no text output, in the background (you can close your terminal window).' . PHP_EOL . - 'php ' . $argv[0] . ' true false true ; Scrapes PRE with text output and debug output.' . PHP_EOL . - 'php ' . $argv[0] . ' true true true ; Scrapes PRE with debug but no text output.' . PHP_EOL +if (! isset($argv[1]) || $argv[1] != 'true') { + exit( + 'Argument 1: (required) false|true ; false prints this help screen, true runs the scraper.'.PHP_EOL. + 'Argument 2: (optional) false|true ; true runs in silent mode (no text output)'.PHP_EOL. + 'Argument 3: (optional) false|true ; true turns on debug (shows sent/received messages from the socket)'.PHP_EOL. + 'examples:'.PHP_EOL. + 'php '.$argv[0].' true ; Scrapes PRE with text output.'.PHP_EOL. + 'php '.$argv[0].' true true > /dev/null 2>&1 ; (unix) Scrapes PRE with no text output, in the background (you can close your terminal window).'.PHP_EOL. + 'php '.$argv[0].' true false true ; Scrapes PRE with text output and debug output.'.PHP_EOL. + 'php '.$argv[0].' true true true ; Scrapes PRE with debug but no text output.'.PHP_EOL ); } require_once IRC_SCRAPER_CONFIG; -if (!defined('SCRAPE_IRC_NICKNAME')) { - exit('ERROR! You must update settings.php using settings_example.php.'); +if (! defined('SCRAPE_IRC_NICKNAME')) { + exit('ERROR! You must update settings.php using settings_example.php.'); } if (SCRAPE_IRC_NICKNAME == '') { - exit("ERROR! You must put a username in settings.php" . PHP_EOL); + exit('ERROR! You must put a username in settings.php'.PHP_EOL); } $silent = ((isset($argv[2]) && $argv[2] === 'true') ? true : false); diff --git a/misc/IRCScraper/settings.example.php b/misc/IRCScraper/settings.example.php index 18345d6b2..3fca447dc 100644 --- a/misc/IRCScraper/settings.example.php +++ b/misc/IRCScraper/settings.example.php @@ -1,4 +1,5 @@ false, '#a.b.console.ps3' => false, '#a.b.dvd' => false, @@ -45,7 +46,7 @@ serialize( 'prelist' => false, 'srrdb' => false, 'u4all.eu' => false, - 'zenet' => false - ) + 'zenet' => false, + ] ) -); \ No newline at end of file +); diff --git a/misc/sphinxsearch/create_se_tables.php b/misc/sphinxsearch/create_se_tables.php index 989e566f7..955baeff6 100644 --- a/misc/sphinxsearch/create_se_tables.php +++ b/misc/sphinxsearch/create_se_tables.php @@ -1,30 +1,31 @@ $query) { - $pdo->queryExec(sprintf('DROP TABLE IF EXISTS %s', $table)); - $pdo->queryExec($query); + $pdo->queryExec(sprintf('DROP TABLE IF EXISTS %s', $table)); + $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; diff --git a/misc/sphinxsearch/optimize.php b/misc/sphinxsearch/optimize.php index 0a5aee65d..ac4f0aabf 100644 --- a/misc/sphinxsearch/optimize.php +++ b/misc/sphinxsearch/optimize.php @@ -1,9 +1,10 @@ optimizeRTIndex($argv[1]); diff --git a/misc/sphinxsearch/populate_rt_indexes.php b/misc/sphinxsearch/populate_rt_indexes.php index fb931a69f..f12e30ad8 100644 --- a/misc/sphinxsearch/populate_rt_indexes.php +++ b/misc/sphinxsearch/populate_rt_indexes.php @@ -1,31 +1,32 @@ 0 ? $argv[2] : 10000)); + populate_rt($argv[1], (isset($argv[2]) && is_numeric($argv[2]) && $argv[2] > 0 ? $argv[2] : 10000)); } // Bulk insert releases into sphinx RT index. function populate_rt($table, $max) { - $pdo = new DB(); + $pdo = new DB(); - switch ($table) { + switch ($table) { case 'releases_rt': $pdo->queryDirect('SET SESSION group_concat_max_len=8192'); $query = ( @@ -38,35 +39,34 @@ function populate_rt($table, $max) LIMIT %d' ); $rtvalues = '(id, name, searchname, fromname, filename)'; - $totals = $pdo->queryOneRow("SELECT COUNT(id) AS c, MIN(id) AS min FROM releases"); - if (!$totals) { - exit("Could not get database information for releases table.\n"); + $totals = $pdo->queryOneRow('SELECT COUNT(id) AS c, MIN(id) AS min FROM releases'); + if (! $totals) { + exit("Could not get database information for releases table.\n"); } - $total = $totals["c"]; - $minId = $totals["min"]; + $total = $totals['c']; + $minId = $totals['min']; break; default: exit(); } - $sphinx = new SphinxSearch(); - $string = sprintf('REPLACE INTO %s %s VALUES ', $table, $rtvalues); + $sphinx = new SphinxSearch(); + $string = sprintf('REPLACE INTO %s %s VALUES ', $table, $rtvalues); - $lastId = $minId - 1; - echo "[Starting to populate sphinx RT index $table with $total releases.]\n"; - for ($i = $minId; $i <= ($total + $max + $minId) ; $i += $max) { + $lastId = $minId - 1; + echo "[Starting to populate sphinx RT index $table with $total releases.]\n"; + for ($i = $minId; $i <= ($total + $max + $minId); $i += $max) { + $rows = $pdo->queryDirect(sprintf($query, $lastId, $max)); + if (! $rows) { + continue; + } - $rows = $pdo->queryDirect(sprintf($query, $lastId, $max)); - if (!$rows) { - continue; - } - - $tempString = ''; - foreach ($rows as $row) { - if ($row["id"] > $lastId) { - $lastId = $row["id"]; - } - switch ($table) { + $tempString = ''; + foreach ($rows as $row) { + if ($row['id'] > $lastId) { + $lastId = $row['id']; + } + switch ($table) { case 'releases_rt': $tempString .= sprintf( '(%d,%s,%s,%s,%s),', @@ -78,12 +78,12 @@ function populate_rt($table, $max) ); break; } - } - if (!$tempString) { - continue; - } - $sphinx->sphinxQL->queryExec($string . rtrim($tempString, ',')); - echo "."; - } - echo "\n[Done]\n"; + } + if (! $tempString) { + continue; + } + $sphinx->sphinxQL->queryExec($string.rtrim($tempString, ',')); + echo '.'; + } + echo "\n[Done]\n"; } diff --git a/misc/sphinxsearch/toggle_search_type.php b/misc/sphinxsearch/toggle_search_type.php index 78cc44df9..82a405ec6 100644 --- a/misc/sphinxsearch/toggle_search_type.php +++ b/misc/sphinxsearch/toggle_search_type.php @@ -1,23 +1,23 @@ log->error('Error, NN_RELEASE_SEARCH_TYPE in www/settings.php must be set to SPHINX to optimize for Sphinx!' . PHP_EOL); + 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': @@ -28,23 +28,22 @@ switch ($argv[1]) { // Optimize database usage for Sphinx full-text function optimizeForSphinx($pdo) { - echo PHP_EOL . $pdo->log->info('Dropping search triggers to save CPU and lower QPS. (Quick)' . PHP_EOL); - dropSearchTriggers($pdo); + echo PHP_EOL.$pdo->log->info('Dropping search triggers to save CPU and lower QPS. (Quick)'.PHP_EOL); + dropSearchTriggers($pdo); - echo $pdo->log->info('Truncating release_search_data table to free up memory pools/buffers. (Quick)' . PHP_EOL); - $pdo->queryExec('TRUNCATE TABLE release_search_data'); + echo $pdo->log->info('Truncating release_search_data table to free up memory pools/buffers. (Quick)'.PHP_EOL); + $pdo->queryExec('TRUNCATE TABLE release_search_data'); - echo $pdo->log->header('Optimization for Sphinx process complete!' . PHP_EOL); + echo $pdo->log->header('Optimization for Sphinx process complete!'.PHP_EOL); } //Revert database to standard schema function revertToStandard($pdo) { - $engFormat = ''; + $engFormat = ''; - if (isset($argv[2]) && in_array($argv[2], ['cinnodb', 'dinnodb', 'cmyisam', 'dmyisam'])) { - - switch ($argv[2]) { + if (isset($argv[2]) && in_array($argv[2], ['cinnodb', 'dinnodb', 'cmyisam', 'dmyisam'])) { + switch ($argv[2]) { case 'cinnnodb': $engFormat = 'ENGINE = InnoDB ROW_FORMAT = Compressed'; break; @@ -58,11 +57,11 @@ function revertToStandard($pdo) $engFormat = 'ENGINE = MyISAM ROW_FORMAT = Dynamic'; break; } - } + } - echo PHP_EOL . $pdo->log->info('Dropping old table data and recreating fresh from schema. (Quick)' . PHP_EOL); - $pdo->queryExec('DROP TABLE IF EXISTS release_search_data'); - $pdo->queryExec( + echo PHP_EOL.$pdo->log->info('Dropping old table data and recreating fresh from schema. (Quick)'.PHP_EOL); + $pdo->queryExec('DROP TABLE IF EXISTS release_search_data'); + $pdo->queryExec( sprintf(" CREATE TABLE release_search_data ( id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, @@ -86,15 +85,15 @@ function revertToStandard($pdo) ) ); - echo $pdo->log->info('Populating the releasearch table with initial data. (Slow)' . PHP_EOL); - $pdo->queryInsert('INSERT INTO release_search_data (releases_id, guid, name, searchname, fromname) + echo $pdo->log->info('Populating the releasearch table with initial data. (Slow)'.PHP_EOL); + $pdo->queryInsert('INSERT INTO release_search_data (releases_id, guid, name, searchname, fromname) SELECT id, guid, name, searchname, fromname FROM releases'); - echo $pdo->log->info('Adding the auto-population triggers. (Quick)' . PHP_EOL); + echo $pdo->log->info('Adding the auto-population triggers. (Quick)'.PHP_EOL); - dropSearchTriggers($pdo); + dropSearchTriggers($pdo); - $pdo->exec(' + $pdo->exec(' CREATE TRIGGER insert_search AFTER INSERT ON releases FOR EACH ROW BEGIN INSERT INTO release_search_data (releases_id, guid, name, searchname, fromname) @@ -126,13 +125,13 @@ function revertToStandard($pdo) WHERE releases_id = OLD.id; END;' ); - echo $pdo->log->header('Standard search should once again be available.' . PHP_EOL); + echo $pdo->log->header('Standard search should once again be available.'.PHP_EOL); } //Drops existing triggers 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'); + $pdo->queryExec('DROP TRIGGER IF EXISTS insert_search'); + $pdo->queryExec('DROP TRIGGER IF EXISTS update_search'); + $pdo->queryExec('DROP TRIGGER IF EXISTS delete_search'); } diff --git a/misc/testing/DB/change_USP_provider.php b/misc/testing/DB/change_USP_provider.php index 7f267ffeb..f634ef141 100644 --- a/misc/testing/DB/change_USP_provider.php +++ b/misc/testing/DB/change_USP_provider.php @@ -1,11 +1,11 @@ log->setColor('Yellow') . "This script is used when you have switched UseNet Providers(USP) so you can pickup where you left off, rather than resetting all the groups.\nOnly use this script after you have updated your config.php file with your new USP info!!\nMake sure you " . $pdo->log->setColor('Red', 'Bold') . "DO NOT" . $pdo->log->setcolor('Yellow') . " have any update or postprocess scripts running when running this script!\n\n" . $pdo->log->setColor('Cyan') . "Usage: php change_USP_provider true\n"); - exit(); +if (! isset($argv[1]) || $argv[1] != 'true') { + printf($pdo->log->setColor('Yellow')."This script is used when you have switched UseNet Providers(USP) so you can pickup where you left off, rather than resetting all the groups.\nOnly use this script after you have updated your config.php file with your new USP info!!\nMake sure you ".$pdo->log->setColor('Red', 'Bold').'DO NOT'.$pdo->log->setcolor('Yellow')." have any update or postprocess scripts running when running this script!\n\n".$pdo->log->setColor('Cyan')."Usage: php change_USP_provider true\n"); + exit(); } - -$groups = $pdo->query("SELECT id, name, first_record_postdate, last_record_postdate FROM groups WHERE active = 1"); +$groups = $pdo->query('SELECT id, name, first_record_postdate, last_record_postdate FROM groups WHERE active = 1'); $numofgroups = count($groups); $guesstime = $numofgroups * 2; $totalstart = microtime(true); echo "You have $numofgroups active, it takes about 2 minutes on average to processes each group.\n"; foreach ($groups as $group) { - $starttime = microtime(true); - $nntp = new NNTP(['Settings' => $pdo]); - if ($nntp->doConnect() !== true) { - return; - } - //printf("Updating group ".$group['name']."..\n"); - $bfdays = daysOldstr($group['first_record_postdate']); - $currdays = daysOldstr($group['last_record_postdate']); - $bfartnum = daytopost($nntp, $group['name'], $bfdays, true, true); - echo 'Our Current backfill postdate was: ' . $pdo->log->setColor('Yellow') . date('r', strtotime($group['first_record_postdate'])) . $pdo->log->rsetcolor() . "\n"; - $currartnum = daytopost($nntp, $group['name'], $currdays, true, false); - echo 'Our Current current postdate was: ' . $pdo->log->setColor('Yellow') . date('r', strtotime($group['last_record_postdate'])) . $pdo->log->rsetcolor() . PHP_EOL; - $pdo->queryExec(sprintf('UPDATE groups SET first_record = %s, last_record = %s WHERE id = %d', $pdo->escapeString($bfartnum), $pdo->escapeString($currartnum), $group['id'])); - $endtime = microtime(true); - echo $pdo->log->setColor('Gray', 'Dim') . 'This group took ' . gmdate("H:i:s", $endtime - $starttime) . ' to process.' . PHP_EOL; - $numofgroups--; - echo 'There are ' . $numofgroups . ' left to process.' . PHP_EOL . PHP_EOL . $pdo->log->rsetcolor() . ''; + $starttime = microtime(true); + $nntp = new NNTP(['Settings' => $pdo]); + if ($nntp->doConnect() !== true) { + return; + } + //printf("Updating group ".$group['name']."..\n"); + $bfdays = daysOldstr($group['first_record_postdate']); + $currdays = daysOldstr($group['last_record_postdate']); + $bfartnum = daytopost($nntp, $group['name'], $bfdays, true, true); + echo 'Our Current backfill postdate was: '.$pdo->log->setColor('Yellow').date('r', strtotime($group['first_record_postdate'])).$pdo->log->rsetcolor()."\n"; + $currartnum = daytopost($nntp, $group['name'], $currdays, true, false); + echo 'Our Current current postdate was: '.$pdo->log->setColor('Yellow').date('r', strtotime($group['last_record_postdate'])).$pdo->log->rsetcolor().PHP_EOL; + $pdo->queryExec(sprintf('UPDATE groups SET first_record = %s, last_record = %s WHERE id = %d', $pdo->escapeString($bfartnum), $pdo->escapeString($currartnum), $group['id'])); + $endtime = microtime(true); + echo $pdo->log->setColor('Gray', 'Dim').'This group took '.gmdate('H:i:s', $endtime - $starttime).' to process.'.PHP_EOL; + $numofgroups--; + echo 'There are '.$numofgroups.' left to process.'.PHP_EOL.PHP_EOL.$pdo->log->rsetcolor().''; } $totalend = microtime(true); -echo $pdo->log->header('Total time to update all groups ' . gmdate('H:i:s', $totalend - $totalstart)); +echo $pdo->log->header('Total time to update all groups '.gmdate('H:i:s', $totalend - $totalstart)); // Truncate tables to complete the change to the new USP. $arr = ['parts', 'missed_parts', 'binaries', 'collections', 'multigroup_parts', 'multigroup_missed_parts', 'multigroup_binaries', 'multigroup_collections']; foreach ($arr as &$value) { - $rel = $pdo->queryExec("TRUNCATE TABLE $value"); - if ($rel !== false) { - echo $pdo->log->header("Truncating $value completed."); - } + $rel = $pdo->queryExec("TRUNCATE TABLE $value"); + if ($rel !== false) { + echo $pdo->log->header("Truncating $value completed."); + } } unset($value); function daysOldstr($timestamp) { - return round((time() - strtotime($timestamp)) / 86400, 5); + return round((time() - strtotime($timestamp)) / 86400, 5); } function daysOld($timestamp) { - return round((time() - $timestamp) / 86400, 5); + return round((time() - $timestamp) / 86400, 5); } // This function taken from lib/backfill.php, and modified to fit our needs. function daytopost($nntp, $group, $days, $debug = true, $bfcheck = true) { - global $pdo; + global $pdo; - $st = false; - if ($debug && $bfcheck) { - echo $pdo->log->primary('Finding start and end articles for ' . $group . '.'); - } + $st = false; + if ($debug && $bfcheck) { + echo $pdo->log->primary('Finding start and end articles for '.$group.'.'); + } - if (!isset($nntp)) { - $nntp = new NNTP(['Settings' => $pdo]); - if ($nntp->doConnect(false) !== true) { - return; - } + if (! isset($nntp)) { + $nntp = new NNTP(['Settings' => $pdo]); + if ($nntp->doConnect(false) !== true) { + return; + } - $st = true; - } + $st = true; + } - $binaries = new Binaries(['NNTP' => $nntp, 'Settings' => $pdo]); + $binaries = new Binaries(['NNTP' => $nntp, 'Settings' => $pdo]); - $data = $nntp->selectGroup($group); - if ($nntp->isError($data)) { - $data = $nntp->dataError($nntp, $group, false); - if ($data === false) { - return; - } - } + $data = $nntp->selectGroup($group); + if ($nntp->isError($data)) { + $data = $nntp->dataError($nntp, $group, false); + if ($data === false) { + return; + } + } - // Goal timestamp. - $goaldate = date('U') - (86400 * $days); - $totalnumberofarticles = $data['last'] - $data['first']; - $upperbound = $data['last']; - $lowerbound = $data['first']; + // Goal timestamp. + $goaldate = date('U') - (86400 * $days); + $totalnumberofarticles = $data['last'] - $data['first']; + $upperbound = $data['last']; + $lowerbound = $data['first']; - if ($debug && $bfcheck) { - echo $pdo->log->header('Total Articles: ' . number_format($totalnumberofarticles) . ' Newest: ' . number_format($upperbound) . ' Oldest: ' . number_format($lowerbound)); - } + if ($debug && $bfcheck) { + echo $pdo->log->header('Total Articles: '.number_format($totalnumberofarticles).' Newest: '.number_format($upperbound).' Oldest: '.number_format($lowerbound)); + } - if ($data['last'] == PHP_INT_MAX) { - exit($pdo->log->error("Group data is coming back as php's max value. You should not see this since we use a patched Net_NNTP that fixes this bug.")); - } + if ($data['last'] == PHP_INT_MAX) { + exit($pdo->log->error("Group data is coming back as php's max value. You should not see this since we use a patched Net_NNTP that fixes this bug.")); + } - $firstDate = $binaries->postdate($data['first'], $data); - $lastDate = $binaries->postdate($data['last'], $data); + $firstDate = $binaries->postdate($data['first'], $data); + $lastDate = $binaries->postdate($data['last'], $data); - if ($goaldate < $firstDate && $bfcheck) { - if ($st === true) { - $nntp->doQuit(); - } - echo $pdo->log->warning("The oldest post indexed from $days day(s) ago is older than the first article stored on your news server.\nSetting to First available article of (date('r', $firstDate) or daysOld($firstDate) days)."); - return $data['first']; - } else if ($goaldate > $lastDate && $bfcheck) { - if ($st === true) { - $nntp->doQuit(); - } - echo $pdo->log->error("ERROR: The oldest post indexed from $days day(s) ago is newer than the last article stored on your news server.\nTo backfill this group you need to set Backfill Days to at least ceil(daysOld($lastDate)+1) days (date('r', $lastDate-86400)."); - return ''; - } + if ($goaldate < $firstDate && $bfcheck) { + if ($st === true) { + $nntp->doQuit(); + } + echo $pdo->log->warning("The oldest post indexed from $days day(s) ago is older than the first article stored on your news server.\nSetting to First available article of (date('r', $firstDate) or daysOld($firstDate) days)."); - if ($debug && $bfcheck) { - echo $pdo->log->primary("Searching for postdates.\nGroup's Firstdate: " . $firstDate . ' (' . (is_int($firstDate) ? date('r', $firstDate) : 'n/a') . ").\nGroup's Lastdate: " . $lastDate . ' (' . date('r', $lastDate) . ")."); - } + return $data['first']; + } elseif ($goaldate > $lastDate && $bfcheck) { + if ($st === true) { + $nntp->doQuit(); + } + echo $pdo->log->error("ERROR: The oldest post indexed from $days day(s) ago is newer than the last article stored on your news server.\nTo backfill this group you need to set Backfill Days to at least ceil(daysOld($lastDate)+1) days (date('r', $lastDate-86400)."); - $interval = floor(($upperbound - $lowerbound) * 0.5); - $templowered = ''; - $dateofnextone = $lastDate; - // Match on days not timestamp to speed things up. - while (daysOld($dateofnextone) < $days) { - while (($tmpDate = $binaries->postdate(($upperbound - $interval), $data)) > $goaldate) { - $upperbound -= $interval; - } + return ''; + } - if (!$templowered) { - $interval = ceil($interval / 2); - } - $dateofnextone = $binaries->postdate($upperbound - 1, $data); - while (!$dateofnextone) { - $dateofnextone = $binaries->postdate($upperbound - 1, $data); - } - } - if ($st === true) { - $nntp->doQuit(); - } - if ($bfcheck) { - echo $pdo->log->header("\nBackfill article determined to be " . $upperbound . " " . $pdo->log->setColor('Yellow') . "(" . date('r', $dateofnextone) . ")" . $pdo->log->rsetcolor()); - } // which is '.daysOld($dateofnextone)." days old.\n"; - else { - echo $pdo->log->header('Current article determined to be ' . $upperbound . " " . $pdo->log->setColor('Yellow') . "(" . date('r', $dateofnextone) . ")" . $pdo->log->rsetcolor()); - } // which is '.daysOld($dateofnextone)." days old.\n"; - return $upperbound; + if ($debug && $bfcheck) { + echo $pdo->log->primary("Searching for postdates.\nGroup's Firstdate: ".$firstDate.' ('.(is_int($firstDate) ? date('r', $firstDate) : 'n/a').").\nGroup's Lastdate: ".$lastDate.' ('.date('r', $lastDate).').'); + } + + $interval = floor(($upperbound - $lowerbound) * 0.5); + $templowered = ''; + $dateofnextone = $lastDate; + // Match on days not timestamp to speed things up. + while (daysOld($dateofnextone) < $days) { + while (($tmpDate = $binaries->postdate(($upperbound - $interval), $data)) > $goaldate) { + $upperbound -= $interval; + } + + if (! $templowered) { + $interval = ceil($interval / 2); + } + $dateofnextone = $binaries->postdate($upperbound - 1, $data); + while (! $dateofnextone) { + $dateofnextone = $binaries->postdate($upperbound - 1, $data); + } + } + if ($st === true) { + $nntp->doQuit(); + } + if ($bfcheck) { + echo $pdo->log->header("\nBackfill article determined to be ".$upperbound.' '.$pdo->log->setColor('Yellow').'('.date('r', $dateofnextone).')'.$pdo->log->rsetcolor()); + } // which is '.daysOld($dateofnextone)." days old.\n"; + else { + echo $pdo->log->header('Current article determined to be '.$upperbound.' '.$pdo->log->setColor('Yellow').'('.date('r', $dateofnextone).')'.$pdo->log->rsetcolor()); + } // which is '.daysOld($dateofnextone)." days old.\n"; + return $upperbound; } diff --git a/misc/testing/DB/check_unique_indexes.php b/misc/testing/DB/check_unique_indexes.php index 130e70c2f..f7387ca65 100755 --- a/misc/testing/DB/check_unique_indexes.php +++ b/misc/testing/DB/check_unique_indexes.php @@ -1,121 +1,122 @@ log->error("\nThis script will scan nntmux_fi_schema.sql for all UNIQUE INDEXES.\n" - . "It will verify that you have them. If you do not, you can choose to run manually or allow the script to run them.\n\n" - . "php $argv[0] test ...: To verify all unique indexes.\n" - . "php $argv[0] alter ...: To add missing unique indexes.\n")); - } +if (! isset($argv[1])) { + if ($argv[1] !== 'test' || $argv[1] !== 'alter') { + exit($pdo->log->error("\nThis script will scan nntmux_fi_schema.sql for all UNIQUE INDEXES.\n" + ."It will verify that you have them. If you do not, you can choose to run manually or allow the script to run them.\n\n" + ."php $argv[0] test ...: To verify all unique indexes.\n" + ."php $argv[0] alter ...: To add missing unique indexes.\n")); + } } // Set for Session if (isset($argv[1]) && $argv[1] === 'alter') { - $pdo->queryExec("SET SESSION old_alter_table = 1"); + $pdo->queryExec('SET SESSION old_alter_table = 1'); } function run_query($query, $test) { - global $pdo; + global $pdo; - if ($test === 'alter') { - try { - $qry = $pdo->prepare($query); - $qry->execute(); - echo $pdo->log->alternateOver('SUCCESS: ') . $pdo->log->primary($query); - } catch (\PDOException $e) { - if ($e->errorInfo[1] == 1061) { - // Duplicate key exists - echo $pdo->log->alternateOver('SKIPPED Index name exists: ') . $pdo->log->primary($query); - } else { - echo $pdo->log->alternateOver('FAILED: ') . $pdo->log->primary($query); - } - } - } else { - echo $pdo->log->header($query); - } + if ($test === 'alter') { + try { + $qry = $pdo->prepare($query); + $qry->execute(); + echo $pdo->log->alternateOver('SUCCESS: ').$pdo->log->primary($query); + } catch (\PDOException $e) { + if ($e->errorInfo[1] == 1061) { + // Duplicate key exists + echo $pdo->log->alternateOver('SKIPPED Index name exists: ').$pdo->log->primary($query); + } else { + echo $pdo->log->alternateOver('FAILED: ').$pdo->log->primary($query); + } + } + } else { + echo $pdo->log->header($query); + } } -$path = NN_RES . 'db' . DS . 'schema' . DS . 'nntmux_fi_schema.sql'; -$handle = fopen($path, "r"); +$path = NN_RES.'db'.DS.'schema'.DS.'nntmux_fi_schema.sql'; +$handle = fopen($path, 'r'); if ($handle) { - while (($line = fgets($handle)) !== false) { - if (preg_match('/(?PCREATE UNIQUE INDEX)\s+(?P[\w-]+)\s+ON\s+(?P
[\w-]+)\s*\((?P[\w-]+(?:\s*\((?P\d+)\))?)\);/i', $line, $match)) { - $columns = explode(',', $match['column']); - foreach ($columns as $column) { - $check = $pdo->checkColumnIndex($match['table'], $column); - if (!isset($check['key_name'])) { - if (trim($match['table']) === 'collections') { - $tables = $pdo->query("SHOW TABLES"); - foreach ($tables as $row) { - $tbl = $row['tables_in_' . env('DB_NAME')]; - if (preg_match('/collections_\d+/', $tbl)) { - $check = $pdo->checkColumnIndex($tbl, $column); - if (!isset($check_collections['key_name'])) { - $qry = "ALTER IGNORE TABLE ${tbl} ADD CONSTRAINT {$match['index']} UNIQUE (${match['column']})"; - run_query($qry, $argv[1]); - } - } - } - $qry = "ALTER IGNORE TABLE " . trim($match['table']) . " ADD CONSTRAINT " . trim($match['index']) . " UNIQUE (${match['column']})"; - run_query($qry, $argv[1]); - } else if (trim($match['table']) === 'binaries') { - $tables = $pdo->query("SHOW TABLES"); - foreach ($tables as $row) { - $tbl = $row['tables_in_' . env('DB_NAME')]; - if (preg_match('/binaries_\d+/', $tbl)) { - $checkBinaries = $pdo->checkColumnIndex($tbl, $column); - if (!isset($checkBinaries['key_name'])) { - $qry = "ALTER IGNORE TABLE ${tbl} ADD CONSTRAINT {$match['index']} UNIQUE (${match['column']})"; - run_query($qry, $argv[1]); - } - } - } - $qry = "ALTER IGNORE TABLE " . trim($match['table']) . " ADD CONSTRAINT " . trim($match['index']) . " UNIQUE (${match['column']})"; - run_query($qry, $argv[1]); - } else if (trim($match['table']) === 'parts') { - $tables = $pdo->query("SHOW TABLES"); - foreach ($tables as $row) { - $tbl = $row['tables_in_' . env('DB_NAME')]; - if (preg_match('/parts_\d+/', $tbl)) { - $checkParts = $pdo->checkColumnIndex($tbl, $column); - if (!isset($checkParts['key_name'])) { - $qry = "ALTER IGNORE TABLE ${tbl} ADD CONSTRAINT {$match['index']} UNIQUE (${match['column']})"; - run_query($qry, $argv[1]); - } - } - } - $qry = "ALTER IGNORE TABLE " . trim($match['table']) . " ADD CONSTRAINT " . trim($match['index']) . " UNIQUE (${match['column']})"; - run_query($qry, $argv[1]); - } else if (trim($match['table']) === 'missed_parts') { - $tables = $pdo->query("SHOW TABLES"); - foreach ($tables as $row) { - $tbl = $row['tables_in_' . env('DB_NAME')]; - if (preg_match('/partrepair_\d+/', $tbl)) { - $checkPartRepair = $pdo->checkColumnIndex($tbl, $column); - if (!isset($checkPartRepair['key_name'])) { - $qry = "ALTER IGNORE TABLE ${tbl} ADD CONSTRAINT {$match['index']} UNIQUE (${match['column']})"; - run_query($qry, $argv[1]); - } - } - } - $qry = "ALTER IGNORE TABLE " . trim($match['table']) . " ADD CONSTRAINT " . trim($match['index']) . " UNIQUE (${match['column']})"; - run_query($qry, $argv[1]); - } else { - $qry = "ALTER IGNORE TABLE " . trim($match['table']) . " ADD CONSTRAINT " . trim($match['index']) . " UNIQUE (${match['column']})"; - run_query($qry, $argv[1]); - } - } else { - echo $pdo->log->primary("A Unique Index exists for " . trim($match['table']) . " on " . trim($match['column'])); - } - } - } - } + while (($line = fgets($handle)) !== false) { + if (preg_match('/(?PCREATE UNIQUE INDEX)\s+(?P[\w-]+)\s+ON\s+(?P
[\w-]+)\s*\((?P[\w-]+(?:\s*\((?P\d+)\))?)\);/i', $line, $match)) { + $columns = explode(',', $match['column']); + foreach ($columns as $column) { + $check = $pdo->checkColumnIndex($match['table'], $column); + if (! isset($check['key_name'])) { + if (trim($match['table']) === 'collections') { + $tables = $pdo->query('SHOW TABLES'); + foreach ($tables as $row) { + $tbl = $row['tables_in_'.env('DB_NAME')]; + if (preg_match('/collections_\d+/', $tbl)) { + $check = $pdo->checkColumnIndex($tbl, $column); + if (! isset($check_collections['key_name'])) { + $qry = "ALTER IGNORE TABLE ${tbl} ADD CONSTRAINT {$match['index']} UNIQUE (${match['column']})"; + run_query($qry, $argv[1]); + } + } + } + $qry = 'ALTER IGNORE TABLE '.trim($match['table']).' ADD CONSTRAINT '.trim($match['index'])." UNIQUE (${match['column']})"; + run_query($qry, $argv[1]); + } elseif (trim($match['table']) === 'binaries') { + $tables = $pdo->query('SHOW TABLES'); + foreach ($tables as $row) { + $tbl = $row['tables_in_'.env('DB_NAME')]; + if (preg_match('/binaries_\d+/', $tbl)) { + $checkBinaries = $pdo->checkColumnIndex($tbl, $column); + if (! isset($checkBinaries['key_name'])) { + $qry = "ALTER IGNORE TABLE ${tbl} ADD CONSTRAINT {$match['index']} UNIQUE (${match['column']})"; + run_query($qry, $argv[1]); + } + } + } + $qry = 'ALTER IGNORE TABLE '.trim($match['table']).' ADD CONSTRAINT '.trim($match['index'])." UNIQUE (${match['column']})"; + run_query($qry, $argv[1]); + } elseif (trim($match['table']) === 'parts') { + $tables = $pdo->query('SHOW TABLES'); + foreach ($tables as $row) { + $tbl = $row['tables_in_'.env('DB_NAME')]; + if (preg_match('/parts_\d+/', $tbl)) { + $checkParts = $pdo->checkColumnIndex($tbl, $column); + if (! isset($checkParts['key_name'])) { + $qry = "ALTER IGNORE TABLE ${tbl} ADD CONSTRAINT {$match['index']} UNIQUE (${match['column']})"; + run_query($qry, $argv[1]); + } + } + } + $qry = 'ALTER IGNORE TABLE '.trim($match['table']).' ADD CONSTRAINT '.trim($match['index'])." UNIQUE (${match['column']})"; + run_query($qry, $argv[1]); + } elseif (trim($match['table']) === 'missed_parts') { + $tables = $pdo->query('SHOW TABLES'); + foreach ($tables as $row) { + $tbl = $row['tables_in_'.env('DB_NAME')]; + if (preg_match('/partrepair_\d+/', $tbl)) { + $checkPartRepair = $pdo->checkColumnIndex($tbl, $column); + if (! isset($checkPartRepair['key_name'])) { + $qry = "ALTER IGNORE TABLE ${tbl} ADD CONSTRAINT {$match['index']} UNIQUE (${match['column']})"; + run_query($qry, $argv[1]); + } + } + } + $qry = 'ALTER IGNORE TABLE '.trim($match['table']).' ADD CONSTRAINT '.trim($match['index'])." UNIQUE (${match['column']})"; + run_query($qry, $argv[1]); + } else { + $qry = 'ALTER IGNORE TABLE '.trim($match['table']).' ADD CONSTRAINT '.trim($match['index'])." UNIQUE (${match['column']})"; + run_query($qry, $argv[1]); + } + } else { + echo $pdo->log->primary('A Unique Index exists for '.trim($match['table']).' on '.trim($match['column'])); + } + } + } + } } else { - echo $pdo->log->error("\nCan not open nntmux_fi_schema.sql."); + echo $pdo->log->error("\nCan not open nntmux_fi_schema.sql."); } diff --git a/misc/testing/DB/convert_mysql_tables.php b/misc/testing/DB/convert_mysql_tables.php index b43af3468..a86557ba9 100644 --- a/misc/testing/DB/convert_mysql_tables.php +++ b/misc/testing/DB/convert_mysql_tables.php @@ -1,5 +1,6 @@ true]); $ftinnodb = $pdo->isDbVersionAtLeast('5.6'); -if (isset($argv[1]) && isset($argv[2]) && $argv[2] == "fmyisam") { - $tbl = $argv[1]; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=MYISAM ROW_FORMAT=FIXED"); -} else if (isset($argv[1]) && isset($argv[2]) && $argv[2] == "dmyisam") { - $tbl = $argv[1]; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=MYISAM ROW_FORMAT=DYNAMIC"); -} else if (isset($argv[1]) && isset($argv[2]) && $argv[2] == "cinnodb") { - $tbl = $argv[1]; - if ($ftinnodb || (!$ftinnodb && $tbl !== 'release_search_data' && $tbl !== 'bookinfo' && $tbl !== 'consoleinfo' && $tbl !== 'musicinfo')) { - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=COMPRESSED"); - } else { - printf($cli->header("Not converting bookinfo / consoleinfo / musicinfo / release_search_data as your INNODB version does not support fulltext indexes")); - } -} else if (isset($argv[1]) && isset($argv[2]) && $argv[2] == "dinnodb") { - $tbl = $argv[1]; - if ($ftinnodb || (!$ftinnodb && $tbl !== 'release_search_data' && $tbl !== 'bookinfo' && $tbl !== 'consoleinfo' && $tbl !== 'musicinfo')) { - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=DYNAMIC"); - } else { - printf($cli->header("Not converting bookinfo / consoleinfo / musicinfo / release_search_data as your INNODB version does not support fulltext indexes")); - } -} else if (isset($argv[1]) && $argv[1] == "fmyisam") { - $sql = 'SHOW TABLE STATUS WHERE (Engine != "MyIsam" OR Row_format != "FIXED") AND Engine != "SPHINX"'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=MYISAM ROW_FORMAT=FIXED"); - } -} else if (isset($argv[1]) && $argv[1] == "dmyisam") { - $sql = 'SHOW TABLE STATUS WHERE (Engine != "MyIsam" OR Row_format != "Dynamic") AND Engine != "SPHINX"'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=MYISAM ROW_FORMAT=DYNAMIC"); - } -} else if (isset($argv[1]) && $argv[1] == "dinnodb") { - $sql = 'SHOW TABLE STATUS WHERE (Engine != "InnoDB" OR Row_format != "Dynamic") AND Engine != "SPHINX"'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - if ($tbl !== 'release_search_data' && $tbl !== 'bookinfo' && $tbl !== 'consoleinfo' && $tbl !== 'musicinfo') { - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=DYNAMIC"); - } - } - if ($ftinnodb) { - $sql = 'SHOW TABLE STATUS WHERE Name IN ("release_search_data", "bookinfo", "consoleinfo", "musicinfo") AND (Engine != "InnoDB" || Row_format != "Dynamic")'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=DYNAMIC"); - } - } else { - printf($cli->header("Not converting bookinfo / consoleinfo / musicinfo / release_search_data as your INNODB version does not support fulltext indexes")); - } -} else if (isset($argv[1]) && $argv[1] == "cinnodb") { - $sql = 'SHOW TABLE STATUS WHERE (Engine != "InnoDB" OR Row_format != "Compressed") AND Engine != "SPHINX"'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - if ($tbl !== 'release_nfos' && $tbl !== 'release_search_data' && $tbl !== 'bookinfo' && $tbl !== 'consoleinfo' && $tbl !== 'musicinfo') { - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=COMPRESSED"); - } - } - $sql = 'SHOW TABLE STATUS WHERE Name = "release_nfos" AND (Engine != "InnoDB" || Row_format != "Dynamic")'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=DYNAMIC"); - } - if ($ftinnodb) { - $sql = 'SHOW TABLE STATUS WHERE Name IN ("release_search_data", "bookinfo", "consoleinfo", "musicinfo") AND (Engine != "InnoDB" || Row_format != "Compressed")'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=COMPRESSED"); - } - } else { - printf($cli->header("Not converting bookinfo / consoleinfo / musicinfo / release_search_data as your INNODB version does not support fulltext indexes")); - } -} else if (isset($argv[1]) && $argv[1] == "cinnodb-noparts") { - $sql = 'SHOW TABLE STATUS WHERE (Engine != "InnoDB" OR Row_format != "Compressed") AND Engine != "SPHINX"'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - if ($tbl !== 'release_nfos' && $tbl !== 'release_search_data' && $tbl !== 'bookinfo' && $tbl !== 'consoleinfo' && $tbl !== 'musicinfo' && !preg_match('/parts/', $tbl)) { - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=COMPRESSED"); - } - } - $sql = 'SHOW TABLE STATUS WHERE Name = "release_nfos" AND (Engine != "InnoDB" || Row_format != "Dynamic")'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=DYNAMIC"); - } - $sql = 'SHOW TABLE STATUS WHERE Name LIKE "parts%" AND (Engine != "MyISAM" || Row_format != "Dynamic")'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=MyISAM ROW_FORMAT=DYNAMIC"); - } - if ($ftinnodb) { - $sql = 'SHOW TABLE STATUS WHERE Name IN ("release_search_data", "bookinfo", "consoleinfo", "musicinfo") AND (Engine != "InnoDB" || Row_format != "Compressed")'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=COMPRESSED"); - } - } else { - printf($cli->header("Not converting bookinfo / consoleinfo / musicinfo / release_search_data as your INNODB version does not support fulltext indexes")); - } -} else if (isset($argv[1]) && $argv[1] == "collections") { - $arr = array("parts", "binaries", "collections"); - foreach ($arr as $row) { - $tbl = $row; - printf($cli->header("Converting $tbl")); - $pdo->queryExec("ALTER TABLE $tbl ENGINE=MYISAM ROW_FORMAT=FIXED"); - } -} else if (isset($argv[1]) && $argv[1] == "mariadb-tokudb") { - $tables = $pdo->query('SHOW TABLE STATUS WHERE (Engine != "TokuDB" OR Create_options != "`COMPRESSION`=tokudb_lzma") AND Engine != "SPHINX"'); - foreach ($tables as $row) { - $tbl = $row['name']; - if ($tbl !== 'release_search_data') { - printf($cli->header("Converting $tbl")); - $sql = "ALTER TABLE $tbl ENGINE=TokuDB Compression=tokudb_lzma"; - $pdo->queryExec($sql); - $pdo->queryExec("OPTIMIZE TABLE $tbl"); - } - } -} else if (isset($argv[1]) && $argv[1] == "tokudb") { - $tables = $pdo->query('SHOW TABLE STATUS WHERE (Engine != "TokuDB" OR ROW_FORMAT="tokudb_lzma" OR Create_options != "`COMPRESSION`=tokudb_lzma") AND Engine != "SPHINX"'); - foreach ($tables as $row) { - $tbl = $row['name']; - if ($tbl !== 'release_search_data') { - printf($cli->header("Converting $tbl")); - $sql = "ALTER TABLE $tbl ENGINE=TokuDB row_format=tokudb_lzma"; - $pdo->queryExec($sql); - $pdo->queryExec("OPTIMIZE TABLE $tbl"); - } - } +if (isset($argv[1]) && isset($argv[2]) && $argv[2] == 'fmyisam') { + $tbl = $argv[1]; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=MYISAM ROW_FORMAT=FIXED"); +} elseif (isset($argv[1]) && isset($argv[2]) && $argv[2] == 'dmyisam') { + $tbl = $argv[1]; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=MYISAM ROW_FORMAT=DYNAMIC"); +} elseif (isset($argv[1]) && isset($argv[2]) && $argv[2] == 'cinnodb') { + $tbl = $argv[1]; + if ($ftinnodb || (! $ftinnodb && $tbl !== 'release_search_data' && $tbl !== 'bookinfo' && $tbl !== 'consoleinfo' && $tbl !== 'musicinfo')) { + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=COMPRESSED"); + } else { + printf($cli->header('Not converting bookinfo / consoleinfo / musicinfo / release_search_data as your INNODB version does not support fulltext indexes')); + } +} elseif (isset($argv[1]) && isset($argv[2]) && $argv[2] == 'dinnodb') { + $tbl = $argv[1]; + if ($ftinnodb || (! $ftinnodb && $tbl !== 'release_search_data' && $tbl !== 'bookinfo' && $tbl !== 'consoleinfo' && $tbl !== 'musicinfo')) { + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=DYNAMIC"); + } else { + printf($cli->header('Not converting bookinfo / consoleinfo / musicinfo / release_search_data as your INNODB version does not support fulltext indexes')); + } +} elseif (isset($argv[1]) && $argv[1] == 'fmyisam') { + $sql = 'SHOW TABLE STATUS WHERE (Engine != "MyIsam" OR Row_format != "FIXED") AND Engine != "SPHINX"'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=MYISAM ROW_FORMAT=FIXED"); + } +} elseif (isset($argv[1]) && $argv[1] == 'dmyisam') { + $sql = 'SHOW TABLE STATUS WHERE (Engine != "MyIsam" OR Row_format != "Dynamic") AND Engine != "SPHINX"'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=MYISAM ROW_FORMAT=DYNAMIC"); + } +} elseif (isset($argv[1]) && $argv[1] == 'dinnodb') { + $sql = 'SHOW TABLE STATUS WHERE (Engine != "InnoDB" OR Row_format != "Dynamic") AND Engine != "SPHINX"'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + if ($tbl !== 'release_search_data' && $tbl !== 'bookinfo' && $tbl !== 'consoleinfo' && $tbl !== 'musicinfo') { + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=DYNAMIC"); + } + } + if ($ftinnodb) { + $sql = 'SHOW TABLE STATUS WHERE Name IN ("release_search_data", "bookinfo", "consoleinfo", "musicinfo") AND (Engine != "InnoDB" || Row_format != "Dynamic")'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=DYNAMIC"); + } + } else { + printf($cli->header('Not converting bookinfo / consoleinfo / musicinfo / release_search_data as your INNODB version does not support fulltext indexes')); + } +} elseif (isset($argv[1]) && $argv[1] == 'cinnodb') { + $sql = 'SHOW TABLE STATUS WHERE (Engine != "InnoDB" OR Row_format != "Compressed") AND Engine != "SPHINX"'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + if ($tbl !== 'release_nfos' && $tbl !== 'release_search_data' && $tbl !== 'bookinfo' && $tbl !== 'consoleinfo' && $tbl !== 'musicinfo') { + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=COMPRESSED"); + } + } + $sql = 'SHOW TABLE STATUS WHERE Name = "release_nfos" AND (Engine != "InnoDB" || Row_format != "Dynamic")'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=DYNAMIC"); + } + if ($ftinnodb) { + $sql = 'SHOW TABLE STATUS WHERE Name IN ("release_search_data", "bookinfo", "consoleinfo", "musicinfo") AND (Engine != "InnoDB" || Row_format != "Compressed")'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=COMPRESSED"); + } + } else { + printf($cli->header('Not converting bookinfo / consoleinfo / musicinfo / release_search_data as your INNODB version does not support fulltext indexes')); + } +} elseif (isset($argv[1]) && $argv[1] == 'cinnodb-noparts') { + $sql = 'SHOW TABLE STATUS WHERE (Engine != "InnoDB" OR Row_format != "Compressed") AND Engine != "SPHINX"'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + if ($tbl !== 'release_nfos' && $tbl !== 'release_search_data' && $tbl !== 'bookinfo' && $tbl !== 'consoleinfo' && $tbl !== 'musicinfo' && ! preg_match('/parts/', $tbl)) { + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=COMPRESSED"); + } + } + $sql = 'SHOW TABLE STATUS WHERE Name = "release_nfos" AND (Engine != "InnoDB" || Row_format != "Dynamic")'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=DYNAMIC"); + } + $sql = 'SHOW TABLE STATUS WHERE Name LIKE "parts%" AND (Engine != "MyISAM" || Row_format != "Dynamic")'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=MyISAM ROW_FORMAT=DYNAMIC"); + } + if ($ftinnodb) { + $sql = 'SHOW TABLE STATUS WHERE Name IN ("release_search_data", "bookinfo", "consoleinfo", "musicinfo") AND (Engine != "InnoDB" || Row_format != "Compressed")'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=INNODB ROW_FORMAT=COMPRESSED"); + } + } else { + printf($cli->header('Not converting bookinfo / consoleinfo / musicinfo / release_search_data as your INNODB version does not support fulltext indexes')); + } +} elseif (isset($argv[1]) && $argv[1] == 'collections') { + $arr = ['parts', 'binaries', 'collections']; + foreach ($arr as $row) { + $tbl = $row; + printf($cli->header("Converting $tbl")); + $pdo->queryExec("ALTER TABLE $tbl ENGINE=MYISAM ROW_FORMAT=FIXED"); + } +} elseif (isset($argv[1]) && $argv[1] == 'mariadb-tokudb') { + $tables = $pdo->query('SHOW TABLE STATUS WHERE (Engine != "TokuDB" OR Create_options != "`COMPRESSION`=tokudb_lzma") AND Engine != "SPHINX"'); + foreach ($tables as $row) { + $tbl = $row['name']; + if ($tbl !== 'release_search_data') { + printf($cli->header("Converting $tbl")); + $sql = "ALTER TABLE $tbl ENGINE=TokuDB Compression=tokudb_lzma"; + $pdo->queryExec($sql); + $pdo->queryExec("OPTIMIZE TABLE $tbl"); + } + } +} elseif (isset($argv[1]) && $argv[1] == 'tokudb') { + $tables = $pdo->query('SHOW TABLE STATUS WHERE (Engine != "TokuDB" OR ROW_FORMAT="tokudb_lzma" OR Create_options != "`COMPRESSION`=tokudb_lzma") AND Engine != "SPHINX"'); + foreach ($tables as $row) { + $tbl = $row['name']; + if ($tbl !== 'release_search_data') { + printf($cli->header("Converting $tbl")); + $sql = "ALTER TABLE $tbl ENGINE=TokuDB row_format=tokudb_lzma"; + $pdo->queryExec($sql); + $pdo->queryExec("OPTIMIZE TABLE $tbl"); + } + } } else { - exit($cli->error( + exit($cli->error( "\nThis script will convert your tables to a new engine/format. Only tables not meeting the new engine/format will be converted.\n" - . "A comparison of these, excluding TokuDB, https://github.com/nZEDb/nZEDb/wiki/MySQL-Storage-Engine-Comparison\n\n" - . "php convert_mysql_tables.php dmyisam ...: Converts all the tables to Myisam Dynamic. This is the default and is recommended where ram is limited.\n" - . "php convert_mysql_tables.php fmyisam ...: Converts all the tables to Myisam Fixed. This can be faster, but to fully convert all tables requires changing varchar columns to char.\n" - . " This will use much more space than dynamic.\n" - . "php convert_mysql_tables.php dinnodb ...: Converts all the tables to InnoDB Dynamic. This is recommended when the total data and indexes can fit into the innodb_buffer_pool.\n" - . " NB if your innodb version < 5.6 bookinfo / consoleinfo / musicinfo / release_search_data will not be converted as fulltext indexes are not supported.\n" - . "php convert_mysql_tables.php cinnodb ...: Converts all the tables to InnoDB Compressed. All tables except releasenfo will be converted to Compressed row format.\n" - . " This is recommended when the total data and indexes can not fit into the innodb_buffer_pool using DYNAMIC row format.\n" - . " NB if your innodb version < 5.6 bookinfo / consoleinfo / musicinfo / release_search_data will not be converted as fulltext indexes are not supported.\n" - . "php convert_mysql_tables.php cinnodb-noparts ...: Converts all the tables to InnoDB Compressed. All tables except parts and releasenfo will be converted to Compressed row format.\n" - . " Alls parts* will be converted to MyISAM Dynamic. This is recommended when using Table Per Group.\n" - . " NB if your innodb version < 5.6 bookinfo / consoleinfo / musicinfo / release_search_data will not be converted as fulltext indexes are not supported.\n" - . "php convert_mysql_tables.php collections ...: Converts collections, binaries, parts to MyIsam.\n" - . "php convert_mysql_tables.php mariadb-tokudb ...: Converts all the tables to MariaDB Tokutek DB. Use this is you installed mariadb-tokudb-engine. \n" - . " The TokuDB engine needs to be activated first.\n" - . " https://mariadb.com/kb/en/how-to-enable-tokudb-in-mariadb/\n" - . " NB release_search_data will not be converted as tokudb does not support fulltext indexes.\n" - . "php convert_mysql_tables.php tokudb ...: Converts all the tables to Tokutek DB. Use this if you downloaded and installed the TokuDB binaries.\n" - . " http://www.tokutek.com/resources/support/gadownloads/\n" - . " NB release_search_data will not be converted as tokudb does not support fulltext indexes.\n" - . "php convert_mysql_tables.php table [ fmyisam, dmyisam, dinnodb, cinnodb ] ...: Converts 1 table to Engine, row_format specified.\n" - . " NB if converting to innodb and your innodb version < 5.6 release_search_data will not be converted as fulltext indexes are not supported.\n" + ."A comparison of these, excluding TokuDB, https://github.com/nZEDb/nZEDb/wiki/MySQL-Storage-Engine-Comparison\n\n" + ."php convert_mysql_tables.php dmyisam ...: Converts all the tables to Myisam Dynamic. This is the default and is recommended where ram is limited.\n" + ."php convert_mysql_tables.php fmyisam ...: Converts all the tables to Myisam Fixed. This can be faster, but to fully convert all tables requires changing varchar columns to char.\n" + ." This will use much more space than dynamic.\n" + ."php convert_mysql_tables.php dinnodb ...: Converts all the tables to InnoDB Dynamic. This is recommended when the total data and indexes can fit into the innodb_buffer_pool.\n" + ." NB if your innodb version < 5.6 bookinfo / consoleinfo / musicinfo / release_search_data will not be converted as fulltext indexes are not supported.\n" + ."php convert_mysql_tables.php cinnodb ...: Converts all the tables to InnoDB Compressed. All tables except releasenfo will be converted to Compressed row format.\n" + ." This is recommended when the total data and indexes can not fit into the innodb_buffer_pool using DYNAMIC row format.\n" + ." NB if your innodb version < 5.6 bookinfo / consoleinfo / musicinfo / release_search_data will not be converted as fulltext indexes are not supported.\n" + ."php convert_mysql_tables.php cinnodb-noparts ...: Converts all the tables to InnoDB Compressed. All tables except parts and releasenfo will be converted to Compressed row format.\n" + ." Alls parts* will be converted to MyISAM Dynamic. This is recommended when using Table Per Group.\n" + ." NB if your innodb version < 5.6 bookinfo / consoleinfo / musicinfo / release_search_data will not be converted as fulltext indexes are not supported.\n" + ."php convert_mysql_tables.php collections ...: Converts collections, binaries, parts to MyIsam.\n" + ."php convert_mysql_tables.php mariadb-tokudb ...: Converts all the tables to MariaDB Tokutek DB. Use this is you installed mariadb-tokudb-engine. \n" + ." The TokuDB engine needs to be activated first.\n" + ." https://mariadb.com/kb/en/how-to-enable-tokudb-in-mariadb/\n" + ." NB release_search_data will not be converted as tokudb does not support fulltext indexes.\n" + ."php convert_mysql_tables.php tokudb ...: Converts all the tables to Tokutek DB. Use this if you downloaded and installed the TokuDB binaries.\n" + ." http://www.tokutek.com/resources/support/gadownloads/\n" + ." NB release_search_data will not be converted as tokudb does not support fulltext indexes.\n" + ."php convert_mysql_tables.php table [ fmyisam, dmyisam, dinnodb, cinnodb ] ...: Converts 1 table to Engine, row_format specified.\n" + ." NB if converting to innodb and your innodb version < 5.6 release_search_data will not be converted as fulltext indexes are not supported.\n" )); } diff --git a/misc/testing/DB/convert_to_tpg.php b/misc/testing/DB/convert_to_tpg.php index dcf0a7e8b..7942efb86 100644 --- a/misc/testing/DB/convert_to_tpg.php +++ b/misc/testing/DB/convert_to_tpg.php @@ -1,25 +1,25 @@ $pdo]); $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); $DoPartRepair = (Settings::value('..partrepair') == '0') ? false : true; -if ((!isset($argv[1])) || $argv[1] != 'true') { - exit($pdo->log->error("\nMandatory argument missing\n\n" - . "This script will allow you to move from single collections/binaries/parts tables to TPG without having to run reset_truncate.\n" - . "Please STOP all update scripts before running this script.\n\n" - . "Use the following options to run:\n" - . "php $argv[0] true ...: Convert c/b/p to tpg leaving current collections/binaries/parts tables in-tact.\n" - . "php $argv[0] true delete ...: Convert c/b/p to tpg and TRUNCATE current collections/binaries/parts tables.\n" +if ((! isset($argv[1])) || $argv[1] != 'true') { + exit($pdo->log->error("\nMandatory argument missing\n\n" + ."This script will allow you to move from single collections/binaries/parts tables to TPG without having to run reset_truncate.\n" + ."Please STOP all update scripts before running this script.\n\n" + ."Use the following options to run:\n" + ."php $argv[0] true ...: Convert c/b/p to tpg leaving current collections/binaries/parts tables in-tact.\n" + ."php $argv[0] true delete ...: Convert c/b/p to tpg and TRUNCATE current collections/binaries/parts tables.\n" )); } @@ -35,121 +35,121 @@ $begintime = time(); echo "Creating new collections, binaries, and parts tables for each active group...\n"; foreach ($actgroups as $group) { - if ($groups->createNewTPGTables($group['id']) === false) { - exit($pdo->log->error("There is a problem creating new parts/files tables for group ${group['name']}.")); - } - $consoletools->overWrite("Tables Created: " . $consoletools->percentString($gdone * 3, $newtables)); - $gdone++; + if ($groups->createNewTPGTables($group['id']) === false) { + exit($pdo->log->error("There is a problem creating new parts/files tables for group ${group['name']}.")); + } + $consoletools->overWrite('Tables Created: '.$consoletools->percentString($gdone * 3, $newtables)); + $gdone++; } $endtime = time(); -echo "\nTable creation took " . $consoletools->convertTime($endtime - $begintime) . ".\n"; +echo "\nTable creation took ".$consoletools->convertTime($endtime - $begintime).".\n"; $starttime = time(); echo "\nNew tables created, moving data from old tables to new tables.\nThis will take awhile....\n\n"; while ($cdone < $clen['total']) { - // Only load 1000 collections per loop to not overload memory. - $collections = $pdo->queryAssoc('select * from collections limit ' . $cdone . ',1000;'); + // Only load 1000 collections per loop to not overload memory. + $collections = $pdo->queryAssoc('select * from collections limit '.$cdone.',1000;'); - if ($collections instanceof \Traversable) { - foreach ($collections as $collection) { - $collection['subject'] = $pdo->escapeString($collection['subject']); - $collection['fromname'] = $pdo->escapeString($collection['fromname']); - $collection['date'] = $pdo->escapeString($collection['date']); - $collection['collectionhash'] = $pdo->escapeString($collection['collectionhash']); - $collection['dateadded'] = $pdo->escapeString($collection['dateadded']); - $collection['xref'] = $pdo->escapeString($collection['xref']); - $collection['releaseid'] = $pdo->escapeString($collection['releaseid']); - $oldcid = array_shift($collection); - if ($debug) { - echo "\n\nCollection insert:\n"; - print_r($collection); - echo sprintf("\nINSERT INTO collections_%d (subject, fromname, date, xref, totalfiles, groups_id, collectionhash, dateadded, filecheck, filesize, releaseid) VALUES (%s)\n\n", $collection['groups_id'], implode(', ', $collection)); - } - $newcid = array('collections_id' => $pdo->queryInsert(sprintf('INSERT INTO collections_%d (subject, fromname, date, xref, totalfiles, groups_id, collectionhash, dateadded, filecheck, filesize, releaseid) VALUES (%s);', $collection['groups_id'], implode(', ', $collection)))); - $consoletools->overWrite('Collections Completed: ' . $consoletools->percentString($ccount, $clen['total'])); + if ($collections instanceof \Traversable) { + foreach ($collections as $collection) { + $collection['subject'] = $pdo->escapeString($collection['subject']); + $collection['fromname'] = $pdo->escapeString($collection['fromname']); + $collection['date'] = $pdo->escapeString($collection['date']); + $collection['collectionhash'] = $pdo->escapeString($collection['collectionhash']); + $collection['dateadded'] = $pdo->escapeString($collection['dateadded']); + $collection['xref'] = $pdo->escapeString($collection['xref']); + $collection['releaseid'] = $pdo->escapeString($collection['releaseid']); + $oldcid = array_shift($collection); + if ($debug) { + echo "\n\nCollection insert:\n"; + print_r($collection); + echo sprintf("\nINSERT INTO collections_%d (subject, fromname, date, xref, totalfiles, groups_id, collectionhash, dateadded, filecheck, filesize, releaseid) VALUES (%s)\n\n", $collection['groups_id'], implode(', ', $collection)); + } + $newcid = ['collections_id' => $pdo->queryInsert(sprintf('INSERT INTO collections_%d (subject, fromname, date, xref, totalfiles, groups_id, collectionhash, dateadded, filecheck, filesize, releaseid) VALUES (%s);', $collection['groups_id'], implode(', ', $collection)))]; + $consoletools->overWrite('Collections Completed: '.$consoletools->percentString($ccount, $clen['total'])); - //Get binaries and split to correct group tables. - $binaries = $pdo->queryAssoc('SELECT name, collections_id, filenumber, totalparts, currentparts, HEX(binaryhash) AS binaryhash, partcheck, partsize FROM binaries WHERE collections_id = ' . $oldcid . ';'); + //Get binaries and split to correct group tables. + $binaries = $pdo->queryAssoc('SELECT name, collections_id, filenumber, totalparts, currentparts, HEX(binaryhash) AS binaryhash, partcheck, partsize FROM binaries WHERE collections_id = '.$oldcid.';'); - if ($binaries instanceof \Traversable) { - foreach ($binaries as $binary) { - $binary['name'] = $pdo->escapeString($binary['name']); - $binary['binaryhash'] = "UNHEX(" . $pdo->escapeString($binary['binaryhash']) . ")"; - $oldbid = array_shift($binary); - $binarynew = array_replace($binary, $newcid); - if ($debug) { - echo "\n\nBinary insert:\n"; - print_r($binarynew); - echo sprintf("\nINSERT INTO binaries_%d (name, collections_id, filenumber, totalparts, currentparts, binaryhash, partcheck, partsize) VALUES (%s)\n\n", $collection['groups_id'], implode(', ', $binarynew)); - } - $newbid = array('binaries_id' => $pdo->queryInsert(sprintf('INSERT INTO binaries_%d (name, collections_id, filenumber, totalparts, currentparts, binaryhash, partcheck, partsize) VALUES (%s);', $collection['groups_id'], implode(', ', $binarynew)))); + if ($binaries instanceof \Traversable) { + foreach ($binaries as $binary) { + $binary['name'] = $pdo->escapeString($binary['name']); + $binary['binaryhash'] = 'UNHEX('.$pdo->escapeString($binary['binaryhash']).')'; + $oldbid = array_shift($binary); + $binarynew = array_replace($binary, $newcid); + if ($debug) { + echo "\n\nBinary insert:\n"; + print_r($binarynew); + echo sprintf("\nINSERT INTO binaries_%d (name, collections_id, filenumber, totalparts, currentparts, binaryhash, partcheck, partsize) VALUES (%s)\n\n", $collection['groups_id'], implode(', ', $binarynew)); + } + $newbid = ['binaries_id' => $pdo->queryInsert(sprintf('INSERT INTO binaries_%d (name, collections_id, filenumber, totalparts, currentparts, binaryhash, partcheck, partsize) VALUES (%s);', $collection['groups_id'], implode(', ', $binarynew)))]; - //Get parts and split to correct group tables. - $parts = $pdo->queryAssoc('SELECT * FROM parts WHERE binaryID = ' . $oldbid . ';'); - if ($parts instanceof \Traversable) { - $firstpart = true; - $partsnew = ''; - foreach ($parts as $part) { - $oldpid = array_shift($part); - $partnew = array_replace($part, $newbid); + //Get parts and split to correct group tables. + $parts = $pdo->queryAssoc('SELECT * FROM parts WHERE binaryID = '.$oldbid.';'); + if ($parts instanceof \Traversable) { + $firstpart = true; + $partsnew = ''; + foreach ($parts as $part) { + $oldpid = array_shift($part); + $partnew = array_replace($part, $newbid); - $partsnew .= '(\'' . implode('\', \'', $partnew) . '\'), '; - } - $partsnew = substr($partsnew, 0, -2); - if ($debug) { - echo "\n\nParts insert:\n"; - echo sprintf("\nINSERT INTO parts_%d (binaries_id, messageid, number, partnumber, size, collections_id) VALUES %s;\n\n", $collection['groups_id'], $partsnew); - } - $sql = sprintf('INSERT INTO parts_%d (binaries_id, messageid, number, partnumber, size, collections_id) VALUES %s;', $collection['groups_id'], $partsnew); - $pdo->queryExec($sql); - } - } - } - $ccount++; - } - } - $cdone += 1000; + $partsnew .= '(\''.implode('\', \'', $partnew).'\'), '; + } + $partsnew = substr($partsnew, 0, -2); + if ($debug) { + echo "\n\nParts insert:\n"; + echo sprintf("\nINSERT INTO parts_%d (binaries_id, messageid, number, partnumber, size, collections_id) VALUES %s;\n\n", $collection['groups_id'], $partsnew); + } + $sql = sprintf('INSERT INTO parts_%d (binaries_id, messageid, number, partnumber, size, collections_id) VALUES %s;', $collection['groups_id'], $partsnew); + $pdo->queryExec($sql); + } + } + } + $ccount++; + } + } + $cdone += 1000; } if ($DoPartRepair === true) { - foreach ($actgroups as $group) { - $pcount = 1; - $pdone = 0; - $sql = sprintf('SELECT COUNT(*) AS total FROM missed_parts where groups_id = %d;', $group['id']); - $plen = $pdo->queryOneRow($sql); - while ($pdone < $plen['total']) { - // Only load 10000 partrepair records per loop to not overload memory. - $partrepairs = $pdo->queryAssoc(sprintf('select * from missed_parts where groups_id = %d limit %d, 10000;', $group['id'], $pdone)); - if ($partrepairs instanceof \Traversable) { - foreach ($partrepairs as $partrepair) { - $partrepair['numberid'] = $pdo->escapeString($partrepair['numberid']); - $partrepair['groups_id'] = $pdo->escapeString($partrepair['groups_id']); - $partrepair['attempts'] = $pdo->escapeString($partrepair['attempts']); - if ($debug) { - echo "\n\nPart Repair insert:\n"; - print_r($partrepair); - echo sprintf("\nINSERT INTO partrepair_%d (numberid, groups_id, attempts) VALUES (%s, %s, %s)\n\n", $group['id'], $partrepair['numberid'], $partrepair['groups_id'], $partrepair['attempts']); - } - $pdo->queryExec(sprintf('INSERT INTO partrepair_%d (numberid, groups_id, attempts) VALUES (%s, %s, %s);', $group['id'], $partrepair['numberid'], $partrepair['groups_id'], $partrepair['attempts'])); - $consoletools->overWrite('Part Repairs Completed for ' . $group['name'] . ':' . $consoletools->percentString($pcount, $plen['total'])); - $pcount++; - } - } - $pdone += 10000; - } - } + foreach ($actgroups as $group) { + $pcount = 1; + $pdone = 0; + $sql = sprintf('SELECT COUNT(*) AS total FROM missed_parts where groups_id = %d;', $group['id']); + $plen = $pdo->queryOneRow($sql); + while ($pdone < $plen['total']) { + // Only load 10000 partrepair records per loop to not overload memory. + $partrepairs = $pdo->queryAssoc(sprintf('select * from missed_parts where groups_id = %d limit %d, 10000;', $group['id'], $pdone)); + if ($partrepairs instanceof \Traversable) { + foreach ($partrepairs as $partrepair) { + $partrepair['numberid'] = $pdo->escapeString($partrepair['numberid']); + $partrepair['groups_id'] = $pdo->escapeString($partrepair['groups_id']); + $partrepair['attempts'] = $pdo->escapeString($partrepair['attempts']); + if ($debug) { + echo "\n\nPart Repair insert:\n"; + print_r($partrepair); + echo sprintf("\nINSERT INTO partrepair_%d (numberid, groups_id, attempts) VALUES (%s, %s, %s)\n\n", $group['id'], $partrepair['numberid'], $partrepair['groups_id'], $partrepair['attempts']); + } + $pdo->queryExec(sprintf('INSERT INTO partrepair_%d (numberid, groups_id, attempts) VALUES (%s, %s, %s);', $group['id'], $partrepair['numberid'], $partrepair['groups_id'], $partrepair['attempts'])); + $consoletools->overWrite('Part Repairs Completed for '.$group['name'].':'.$consoletools->percentString($pcount, $plen['total'])); + $pcount++; + } + } + $pdone += 10000; + } + } } $endtime = time(); -echo "\nTable population took " . $consoletools->convertTimer($endtime - $starttime) . ".\n"; +echo "\nTable population took ".$consoletools->convertTimer($endtime - $starttime).".\n"; //Truncate old tables to save space. if (isset($argv[2]) && $argv[2] == 'delete') { - echo "Truncating old tables...\n"; - $pdo->queryDirect('TRUNCATE TABLE collections;'); - $pdo->queryDirect('TRUNCATE TABLE binaries;'); - $pdo->queryDirect('TRUNCATE TABLE parts'); - $pdo->queryDirect('TRUNCATE TABLE missed_parts'); - echo "Complete.\n"; + echo "Truncating old tables...\n"; + $pdo->queryDirect('TRUNCATE TABLE collections;'); + $pdo->queryDirect('TRUNCATE TABLE binaries;'); + $pdo->queryDirect('TRUNCATE TABLE parts'); + $pdo->queryDirect('TRUNCATE TABLE missed_parts'); + echo "Complete.\n"; } // Update TPG setting in site-edit. $pdo->queryExec('UPDATE tmux SET value = 1 where setting = \'releases\';'); @@ -157,17 +157,17 @@ echo "New tables have been created.\nTable Per Group has been set to to \"TRUE\ function multi_implode($array, $glue) { - $ret = ''; + $ret = ''; - foreach ($array as $item) { - if (is_array($item)) { - $ret .= '(' . multi_implode($item, $glue) . '), '; - } else { - $ret .= $item . $glue; - } - } + foreach ($array as $item) { + if (is_array($item)) { + $ret .= '('.multi_implode($item, $glue).'), '; + } else { + $ret .= $item.$glue; + } + } - $ret = substr($ret, 0, 0 - strlen($glue)); + $ret = substr($ret, 0, 0 - strlen($glue)); - return $ret; + return $ret; } diff --git a/misc/testing/DB/convert_to_tpg_alt.php b/misc/testing/DB/convert_to_tpg_alt.php index c5c19cef2..6b03003ba 100644 --- a/misc/testing/DB/convert_to_tpg_alt.php +++ b/misc/testing/DB/convert_to_tpg_alt.php @@ -1,80 +1,80 @@ log->error("\nThis script will move all collections, binaries, parts into tables per group.\n\n" - . "php $argv[0] true ...: To process all parts and leave the parts/binaries/collections tables intact.\n" - . "php $argv[0] true truncate ...: To process all parts and truncate parts/binaries/collections tables after completed.\n")); +if (! isset($argv[1]) || $argv[1] != 'true') { + exit($pdo->log->error("\nThis script will move all collections, binaries, parts into tables per group.\n\n" + ."php $argv[0] true ...: To process all parts and leave the parts/binaries/collections tables intact.\n" + ."php $argv[0] true truncate ...: To process all parts and truncate parts/binaries/collections tables after completed.\n")); } $start = time(); $consoleTools = new ConsoleTools(['ColorCLI' => $pdo->log]); $groups = new Groups(['Settings' => $pdo]); -$actgroups = $pdo->query("SELECT DISTINCT groups_id from collections"); +$actgroups = $pdo->query('SELECT DISTINCT groups_id from collections'); -echo $pdo->log->info("Creating new collections, binaries, and parts tables for each group that has collections."); +echo $pdo->log->info('Creating new collections, binaries, and parts tables for each group that has collections.'); foreach ($actgroups as $group) { - $pdo->queryExec("DROP TABLE IF EXISTS collections_" . $group['groups_id']); - $pdo->queryExec("DROP TABLE IF EXISTS binaries_" . $group['groups_id']); - $pdo->queryExec("DROP TABLE IF EXISTS parts_" . $group['groups_id']); - if ($groups->createNewTPGTables($group['groups_id']) === false) { - exit($pdo->log->error("\nThere is a problem creating new parts/files tables for group ${group['name']}.\n")); - } + $pdo->queryExec('DROP TABLE IF EXISTS collections_'.$group['groups_id']); + $pdo->queryExec('DROP TABLE IF EXISTS binaries_'.$group['groups_id']); + $pdo->queryExec('DROP TABLE IF EXISTS parts_'.$group['groups_id']); + if ($groups->createNewTPGTables($group['groups_id']) === false) { + exit($pdo->log->error("\nThere is a problem creating new parts/files tables for group ${group['name']}.\n")); + } } -$collections_rows = $pdo->queryDirect("SELECT groups_id FROM collections GROUP BY groups_id"); +$collections_rows = $pdo->queryDirect('SELECT groups_id FROM collections GROUP BY groups_id'); -echo $pdo->log->info("Counting parts, this could take a few minutes."); -$parts_count = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM parts"); +echo $pdo->log->info('Counting parts, this could take a few minutes.'); +$parts_count = $pdo->queryOneRow('SELECT COUNT(*) AS cnt FROM parts'); $i = 0; if ($collections_rows instanceof \Traversable) { - foreach ($collections_rows as $row) { - $groupName = $groups->getNameByID($row['groups_id']); - echo $pdo->log->header("Processing ${groupName}"); - //collection - $pdo->queryExec("INSERT IGNORE INTO collections_" . $row['groups_id'] . " (subject, fromname, date, xref, totalfiles, groups_id, collectionhash, dateadded, filecheck, filesize, releaseid) " - . "SELECT subject, fromname, date, xref, totalfiles, groups_id, collectionhash, dateadded, filecheck, filesize, releaseid FROM collections WHERE groups_id = ${row['groups_id']}"); - $collections = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM collections where groups_id = " . $row['groups_id']); - $ncollections = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM collections_" . $row['groups_id']); - echo $pdo->log->primary("Group ${groupName}, Collections = ${collections['cnt']} [${ncollections['cnt']}]"); + foreach ($collections_rows as $row) { + $groupName = $groups->getNameByID($row['groups_id']); + echo $pdo->log->header("Processing ${groupName}"); + //collection + $pdo->queryExec('INSERT IGNORE INTO collections_'.$row['groups_id'].' (subject, fromname, date, xref, totalfiles, groups_id, collectionhash, dateadded, filecheck, filesize, releaseid) ' + ."SELECT subject, fromname, date, xref, totalfiles, groups_id, collectionhash, dateadded, filecheck, filesize, releaseid FROM collections WHERE groups_id = ${row['groups_id']}"); + $collections = $pdo->queryOneRow('SELECT COUNT(*) AS cnt FROM collections where groups_id = '.$row['groups_id']); + $ncollections = $pdo->queryOneRow('SELECT COUNT(*) AS cnt FROM collections_'.$row['groups_id']); + echo $pdo->log->primary("Group ${groupName}, Collections = ${collections['cnt']} [${ncollections['cnt']}]"); - //binaries - $pdo->queryExec("INSERT IGNORE INTO binaries_${row['groups_id']} (name, filenumber, totalparts, currentparts, binaryhash, partcheck, partsize, collections_id) " - . "SELECT name, filenumber, totalparts, currentparts, binaryhash, partcheck, partsize, n.id FROM binaries b " - . "INNER JOIN collections c ON b.collections_id = c.id " - . "INNER JOIN collections_${row['groups_id']} n ON c.collectionhash = n.collectionhash AND c.groups_id = ${row['groups_id']}"); - $binaries = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM binaries b INNER JOIN collections c ON b.collections_id = c.id where c.groups_id = ${row['groups_id']}"); - $nbinaries = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM binaries_${row['groups_id']}"); - echo $pdo->log->primary("Group ${groupName}, Binaries = ${binaries['cnt']} [${nbinaries['cnt']}]"); + //binaries + $pdo->queryExec("INSERT IGNORE INTO binaries_${row['groups_id']} (name, filenumber, totalparts, currentparts, binaryhash, partcheck, partsize, collections_id) " + .'SELECT name, filenumber, totalparts, currentparts, binaryhash, partcheck, partsize, n.id FROM binaries b ' + .'INNER JOIN collections c ON b.collections_id = c.id ' + ."INNER JOIN collections_${row['groups_id']} n ON c.collectionhash = n.collectionhash AND c.groups_id = ${row['groups_id']}"); + $binaries = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM binaries b INNER JOIN collections c ON b.collections_id = c.id where c.groups_id = ${row['groups_id']}"); + $nbinaries = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM binaries_${row['groups_id']}"); + echo $pdo->log->primary("Group ${groupName}, Binaries = ${binaries['cnt']} [${nbinaries['cnt']}]"); - //parts - $pdo->queryExec("INSERT IGNORE INTO parts_${row['groups_id']} (messageid, number, partnumber, size, binaries_id, collections_id) " - . "SELECT messageid, number, partnumber, size, n.id, c.id FROM parts p " - . "INNER JOIN binaries b ON p.binaries_id = b.id " - . "INNER JOIN binaries_${row['groups_id']} n ON b.binaryhash = n.binaryhash " - . "INNER JOIN collections_${row['groups_id']} c on c.id = n.collections_id AND c.groups_id = ${row['groups_id']}"); - $parts = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM parts p INNER JOIN binaries b ON p.binaries_id = b.id INNER JOIN collections c ON b.collections_id = c.id WHERE c.groups_id = ${row['groups_id']}"); - $nparts = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM parts_${row['groups_id']}"); - echo $pdo->log->primary("Group ${groupName}, Parts = ${parts['cnt']} [${nparts['cnt']}]\n"); - $i++; - } + //parts + $pdo->queryExec("INSERT IGNORE INTO parts_${row['groups_id']} (messageid, number, partnumber, size, binaries_id, collections_id) " + .'SELECT messageid, number, partnumber, size, n.id, c.id FROM parts p ' + .'INNER JOIN binaries b ON p.binaries_id = b.id ' + ."INNER JOIN binaries_${row['groups_id']} n ON b.binaryhash = n.binaryhash " + ."INNER JOIN collections_${row['groups_id']} c on c.id = n.collections_id AND c.groups_id = ${row['groups_id']}"); + $parts = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM parts p INNER JOIN binaries b ON p.binaries_id = b.id INNER JOIN collections c ON b.collections_id = c.id WHERE c.groups_id = ${row['groups_id']}"); + $nparts = $pdo->queryOneRow("SELECT COUNT(*) AS cnt FROM parts_${row['groups_id']}"); + echo $pdo->log->primary("Group ${groupName}, Parts = ${parts['cnt']} [${nparts['cnt']}]\n"); + $i++; + } } if (isset($argv[2]) && $argv[2] == 'truncate') { - echo $pdo->log->info("Truncating collections, binaries and parts tables."); - $pdo->queryExec("TRUNCATE TABLE collections"); - $pdo->queryExec("TRUNCATE TABLE binaries"); - $pdo->queryExec("TRUNCATE TABLE parts"); + echo $pdo->log->info('Truncating collections, binaries and parts tables.'); + $pdo->queryExec('TRUNCATE TABLE collections'); + $pdo->queryExec('TRUNCATE TABLE binaries'); + $pdo->queryExec('TRUNCATE TABLE parts'); } -echo $pdo->log->header("Processed: ${i} groups and " . number_format($parts_count['cnt']) . " parts in " . $consoleTools->convertTimer(time() - $start)); +echo $pdo->log->header("Processed: ${i} groups and ".number_format($parts_count['cnt']).' parts in '.$consoleTools->convertTimer(time() - $start)); diff --git a/misc/testing/DB/mysqldump_tables.php b/misc/testing/DB/mysqldump_tables.php index 281635a6f..4582b35aa 100644 --- a/misc/testing/DB/mysqldump_tables.php +++ b/misc/testing/DB/mysqldump_tables.php @@ -1,54 +1,52 @@ 0) { - //Percona only has --innodb-optimize-keys - $exportopts = "--opt --innodb-optimize-keys --complete-insert --skip-quick"; + //Percona only has --innodb-optimize-keys + $exportopts = '--opt --innodb-optimize-keys --complete-insert --skip-quick'; } else { - //generic (or unknown) instance of MySQL - $exportopts = "--opt --complete-insert --skip-quick"; + //generic (or unknown) instance of MySQL + $exportopts = '--opt --complete-insert --skip-quick'; } - function newname($filename) { - rename($filename, dirname($filename)."/".basename($filename,".gz")."_".date("Y_m_d_His", filemtime($filename)).".gz"); + rename($filename, dirname($filename).'/'.basename($filename, '.gz').'_'.date('Y_m_d_His', filemtime($filename)).'.gz'); } function builddefaultsfile() { - //generate file contents - $filetext = "[mysqldump]" + //generate file contents + $filetext = '[mysqldump]' ."\n" - ."user = " . env('DB_USER') + .'user = '.env('DB_USER') ."\n" - ."password = " . env('DB_PASSWORD') + .'password = '.env('DB_PASSWORD') ."\n[mysql]" ."\n" - ."user = " . env('DB_USER') + .'user = '.env('DB_USER') ."\n" - ."password = " . env('DB_PASSWORD'); + .'password = '.env('DB_PASSWORD'); - $filehandle = fopen("mysql-defaults.txt", "w+"); - if(!$filehandle) { - exit("Unable to write mysql defaults file! Exiting"); - } else { - fwrite($filehandle, $filetext); - fclose($filehandle); - chmod("mysql-defaults.txt", 0600); - } + $filehandle = fopen('mysql-defaults.txt', 'w+'); + if (! $filehandle) { + exit('Unable to write mysql defaults file! Exiting'); + } else { + fwrite($filehandle, $filetext); + fclose($filehandle); + chmod('mysql-defaults.txt', 0600); + } } $dbhost = env('DB_HOST'); @@ -59,124 +57,124 @@ $dbpass = env('DB_PASSWORD'); $dbname = env(env('DB_NAME')); if (env('DB_SOCKET') !== '') { - $use = "-S $dbsocket"; + $use = "-S $dbsocket"; } else { - $use = "-P$dbport"; + $use = "-P$dbport"; } //generate defaults file used to store database login information so it is not in cleartext in ps command for mysqldump builddefaultsfile(); -if((isset($argv[1]) && $argv[1] == "db") && (isset($argv[2]) && $argv[2] == "dump") && (isset($argv[3]) && file_exists($argv[3]))) { - $filename = $argv[3]."/".$dbname.".gz"; - echo $pdo->log->header("Dumping $dbname."); - if (file_exists($filename)) { - newname($filename); - } - $command = "mysqldump --defaults-file=mysql-defaults.txt $exportopts -h$dbhost $use "."$dbname | gzip -9 > $filename"; - system($command); -} else if((isset($argv[1]) && $argv[1] == "db") && (isset($argv[2]) && $argv[2] == "restore") && (isset($argv[3]) && file_exists($argv[3]))) { - $filename = $argv[3]."/".$dbname.".gz"; - if (file_exists($filename)) { - echo $pdo->log->header("Restoring $dbname."); - $command = "zcat < $filename | mysql --defaults-file=mysql-defaults.txt -h$dbhost $use $dbname"; - $pdo->queryExec("SET FOREIGN_KEY_CHECKS=0"); - system($command); - $pdo->queryExec("SET FOREIGN_KEY_CHECKS=1"); - } -} else if((isset($argv[1]) && $argv[1] == "all") && (isset($argv[2]) && $argv[2] == "dump") && (isset($argv[3]) && file_exists($argv[3]))) { - $sql = "SHOW tables"; - $tables = $pdo->query($sql); - foreach($tables as $row) { - $tbl = $row['Tables_in_'. env('DB_NAME')]; - $filename = $argv[3]."/".$tbl.".gz"; - echo $pdo->log->header("Dumping $tbl."); - if (file_exists($filename)) { - newname($filename); - } - $command = "mysqldump --defaults-file=mysql-defaults.txt $exportopts -h$dbhost $use "."$dbname $tbl | gzip -9 > $filename"; - system($command); - } -} else if((isset($argv[1]) && $argv[1] == "all") && (isset($argv[2]) && $argv[2] == "restore") && (isset($argv[3]) && file_exists($argv[3]))) { - $sql = "SHOW tables"; - $tables = $pdo->query($sql); - $pdo->queryExec("SET FOREIGN_KEY_CHECKS=0"); - foreach($tables as $row) { - $tbl = $row['Tables_in_'.env('DB_NAME')]; - $filename = $argv[3]."/".$tbl.".gz"; - if (file_exists($filename)) { - echo $pdo->log->header("Restoring $tbl."); - $command = "zcat < $filename | mysql --defaults-file=mysql-defaults.txt -h$dbhost $use $dbname"; - system($command); - } - } - $pdo->queryExec("SET FOREIGN_KEY_CHECKS=1"); -} else if((isset($argv[1]) && $argv[1] == "test") && (isset($argv[2]) && $argv[2] == "dump") && (isset($argv[3]) && file_exists($argv[3]))) { - $arr = array("parts", "binaries", "missed_parts", "groups"); - foreach ($arr as &$tbl) { - $filename = $argv[3]."/".$tbl.".gz"; - echo $pdo->log->header("Dumping $tbl.."); - if (file_exists($filename)) { - newname($filename); - } - $command = "mysqldump --defaults-file=mysql-defaults.txt $exportopts -h$dbhost $use "."$dbname $tbl | gzip -9 > $filename"; - system($command); - } -} else if((isset($argv[1]) && $argv[1] == "test") && (isset($argv[2]) && $argv[2] == "restore") && (isset($argv[3]) && file_exists($argv[3]))) { - $arr = array("parts", "binaries", "missed_parts", "groups"); - $pdo->queryExec("SET FOREIGN_KEY_CHECKS=0"); - foreach ($arr as &$tbl) { - $filename = $argv[3]."/".$tbl.".gz"; - if (file_exists($filename)) { - echo $pdo->log->header("Restoring $tbl."); - $command = "zcat < $filename | mysql --defaults-file=mysql-defaults.txt -h$dbhost $use $dbname"; - system($command); - } - } - $pdo->queryExec("SET FOREIGN_KEY_CHECKS=1"); -} else if((isset($argv[1]) && $argv[1] == "all") && (isset($argv[2]) && $argv[2] == "outfile") && (isset($argv[3]) && file_exists($argv[3]))) { - $sql = "SHOW tables"; - $tables = $pdo->query($sql); - foreach($tables as $row) { - $tbl = $row['Tables_in_'.env('DB_NAME')]; - $filename = $argv[3].$tbl.".csv"; - echo $pdo->log->header("Dumping $tbl."); - if (file_exists($filename)) { - newname($filename); - } - $pdo->queryDirect(sprintf("SELECT * INTO OUTFILE %s FROM %s", $pdo->escapeString($filename), $tbl)); - } -} else if((isset($argv[1]) && $argv[1] == "all") && (isset($argv[2]) && $argv[2] == "infile") && (isset($argv[3]) && is_dir($argv[3]))) { - $sql = "SHOW tables"; - $tables = $pdo->query($sql); - $pdo->queryExec("SET FOREIGN_KEY_CHECKS=0"); - foreach($tables as $row) { - $tbl = $row['Tables_in_'.env('DB_NAME')]; - $filename = $argv[3].$tbl.".csv"; - if (file_exists($filename)) { - echo $pdo->log->header("Restoring $tbl."); - $pdo->queryExec(sprintf("LOAD DATA INFILE %s INTO TABLE %s", $pdo->escapeString($filename), $tbl)); - } - } - $pdo->queryExec("SET FOREIGN_KEY_CHECKS=1"); +if ((isset($argv[1]) && $argv[1] == 'db') && (isset($argv[2]) && $argv[2] == 'dump') && (isset($argv[3]) && file_exists($argv[3]))) { + $filename = $argv[3].'/'.$dbname.'.gz'; + echo $pdo->log->header("Dumping $dbname."); + if (file_exists($filename)) { + newname($filename); + } + $command = "mysqldump --defaults-file=mysql-defaults.txt $exportopts -h$dbhost $use "."$dbname | gzip -9 > $filename"; + system($command); +} elseif ((isset($argv[1]) && $argv[1] == 'db') && (isset($argv[2]) && $argv[2] == 'restore') && (isset($argv[3]) && file_exists($argv[3]))) { + $filename = $argv[3].'/'.$dbname.'.gz'; + if (file_exists($filename)) { + echo $pdo->log->header("Restoring $dbname."); + $command = "zcat < $filename | mysql --defaults-file=mysql-defaults.txt -h$dbhost $use $dbname"; + $pdo->queryExec('SET FOREIGN_KEY_CHECKS=0'); + system($command); + $pdo->queryExec('SET FOREIGN_KEY_CHECKS=1'); + } +} elseif ((isset($argv[1]) && $argv[1] == 'all') && (isset($argv[2]) && $argv[2] == 'dump') && (isset($argv[3]) && file_exists($argv[3]))) { + $sql = 'SHOW tables'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['Tables_in_'.env('DB_NAME')]; + $filename = $argv[3].'/'.$tbl.'.gz'; + echo $pdo->log->header("Dumping $tbl."); + if (file_exists($filename)) { + newname($filename); + } + $command = "mysqldump --defaults-file=mysql-defaults.txt $exportopts -h$dbhost $use "."$dbname $tbl | gzip -9 > $filename"; + system($command); + } +} elseif ((isset($argv[1]) && $argv[1] == 'all') && (isset($argv[2]) && $argv[2] == 'restore') && (isset($argv[3]) && file_exists($argv[3]))) { + $sql = 'SHOW tables'; + $tables = $pdo->query($sql); + $pdo->queryExec('SET FOREIGN_KEY_CHECKS=0'); + foreach ($tables as $row) { + $tbl = $row['Tables_in_'.env('DB_NAME')]; + $filename = $argv[3].'/'.$tbl.'.gz'; + if (file_exists($filename)) { + echo $pdo->log->header("Restoring $tbl."); + $command = "zcat < $filename | mysql --defaults-file=mysql-defaults.txt -h$dbhost $use $dbname"; + system($command); + } + } + $pdo->queryExec('SET FOREIGN_KEY_CHECKS=1'); +} elseif ((isset($argv[1]) && $argv[1] == 'test') && (isset($argv[2]) && $argv[2] == 'dump') && (isset($argv[3]) && file_exists($argv[3]))) { + $arr = ['parts', 'binaries', 'missed_parts', 'groups']; + foreach ($arr as &$tbl) { + $filename = $argv[3].'/'.$tbl.'.gz'; + echo $pdo->log->header("Dumping $tbl.."); + if (file_exists($filename)) { + newname($filename); + } + $command = "mysqldump --defaults-file=mysql-defaults.txt $exportopts -h$dbhost $use "."$dbname $tbl | gzip -9 > $filename"; + system($command); + } +} elseif ((isset($argv[1]) && $argv[1] == 'test') && (isset($argv[2]) && $argv[2] == 'restore') && (isset($argv[3]) && file_exists($argv[3]))) { + $arr = ['parts', 'binaries', 'missed_parts', 'groups']; + $pdo->queryExec('SET FOREIGN_KEY_CHECKS=0'); + foreach ($arr as &$tbl) { + $filename = $argv[3].'/'.$tbl.'.gz'; + if (file_exists($filename)) { + echo $pdo->log->header("Restoring $tbl."); + $command = "zcat < $filename | mysql --defaults-file=mysql-defaults.txt -h$dbhost $use $dbname"; + system($command); + } + } + $pdo->queryExec('SET FOREIGN_KEY_CHECKS=1'); +} elseif ((isset($argv[1]) && $argv[1] == 'all') && (isset($argv[2]) && $argv[2] == 'outfile') && (isset($argv[3]) && file_exists($argv[3]))) { + $sql = 'SHOW tables'; + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['Tables_in_'.env('DB_NAME')]; + $filename = $argv[3].$tbl.'.csv'; + echo $pdo->log->header("Dumping $tbl."); + if (file_exists($filename)) { + newname($filename); + } + $pdo->queryDirect(sprintf('SELECT * INTO OUTFILE %s FROM %s', $pdo->escapeString($filename), $tbl)); + } +} elseif ((isset($argv[1]) && $argv[1] == 'all') && (isset($argv[2]) && $argv[2] == 'infile') && (isset($argv[3]) && is_dir($argv[3]))) { + $sql = 'SHOW tables'; + $tables = $pdo->query($sql); + $pdo->queryExec('SET FOREIGN_KEY_CHECKS=0'); + foreach ($tables as $row) { + $tbl = $row['Tables_in_'.env('DB_NAME')]; + $filename = $argv[3].$tbl.'.csv'; + if (file_exists($filename)) { + echo $pdo->log->header("Restoring $tbl."); + $pdo->queryExec(sprintf('LOAD DATA INFILE %s INTO TABLE %s', $pdo->escapeString($filename), $tbl)); + } + } + $pdo->queryExec('SET FOREIGN_KEY_CHECKS=1'); } else { - passthru("clear"); - echo $pdo->log->error("\nThis script can dump/restore all tables, compressed or OUTFILE/INFILE, or just collections/binaries/parts.\n\n" - . "**Single File\n" - . "php $argv[0] db dump /path/to/save/to ...: To dump the database.\n" - . "php $argv[0] db restore /path/to/restore/from ...: To restore the database.\n\n" - . "**Individual Table Files\n" - . "php $argv[0] all dump /path/to/save/to ...: To dump all tables.\n" - . "php $argv[0] all restore /path/to/restore/from ...: To restore all tables.\n\n" - . "**Three Tables (collections, binaries, parts)\n" - . "php $argv[0] test dump /path/to/save/to ...: To dump binaries and parts tables.\n" - . "php $argv[0] test restore /path/to/restore/from ...: To restore binaries and parts tables.\n\n" - . "**Individal Files - OUTFILE/INFILE - No schema\n" - . "**MySQL MUST have write permissions to this path\n" - . "php $argv[0] all outfile /path/to/save/to ...: To dump all tables, using OUTFILE.\n" - . "php $argv[0] all infile /path/to/restore/from ...: To restore all tables, using INFILE.\n\n"); + passthru('clear'); + echo $pdo->log->error("\nThis script can dump/restore all tables, compressed or OUTFILE/INFILE, or just collections/binaries/parts.\n\n" + ."**Single File\n" + ."php $argv[0] db dump /path/to/save/to ...: To dump the database.\n" + ."php $argv[0] db restore /path/to/restore/from ...: To restore the database.\n\n" + ."**Individual Table Files\n" + ."php $argv[0] all dump /path/to/save/to ...: To dump all tables.\n" + ."php $argv[0] all restore /path/to/restore/from ...: To restore all tables.\n\n" + ."**Three Tables (collections, binaries, parts)\n" + ."php $argv[0] test dump /path/to/save/to ...: To dump binaries and parts tables.\n" + ."php $argv[0] test restore /path/to/restore/from ...: To restore binaries and parts tables.\n\n" + ."**Individal Files - OUTFILE/INFILE - No schema\n" + ."**MySQL MUST have write permissions to this path\n" + ."php $argv[0] all outfile /path/to/save/to ...: To dump all tables, using OUTFILE.\n" + ."php $argv[0] all infile /path/to/restore/from ...: To restore all tables, using INFILE.\n\n"); } -if(file_exists("mysql-defaults.txt")) { - @unlink("mysql-defaults.txt"); +if (file_exists('mysql-defaults.txt')) { + @unlink('mysql-defaults.txt'); } diff --git a/misc/testing/DB/populateTraktID.php b/misc/testing/DB/populateTraktID.php index dff8eb463..af21b7158 100644 --- a/misc/testing/DB/populateTraktID.php +++ b/misc/testing/DB/populateTraktID.php @@ -1,6 +1,7 @@ rowCount(); $ttotal = $treleases->rowCount(); $mcount = 0; if ($mtotal > 0) { - echo $pdo->log->header("Updating Trakt ID for " . number_format($mtotal) . " movies."); - foreach ($mreleases as $rel) { - $mcount++; - $data = $trakt->client->movieSummary('tt' . $rel['imdbid'], 'min'); - if ($data != false) { - if (isset($data['ids']['trakt'])) { - $pdo->queryExec(sprintf('UPDATE releases SET traktid = %s WHERE id = %s', $pdo->escapeString($data['ids']['trakt']), $pdo->escapeString($rel['id']))); - echo $pdo->log->info('Updated ' . $data['title'] . ' with Trakt ID:' . $data['ids']['trakt']); - } - } - } - echo $pdo->log->header('Updated ' . $mcount . ' movie(s).'); + echo $pdo->log->header('Updating Trakt ID for '.number_format($mtotal).' movies.'); + foreach ($mreleases as $rel) { + $mcount++; + $data = $trakt->client->movieSummary('tt'.$rel['imdbid'], 'min'); + if ($data != false) { + if (isset($data['ids']['trakt'])) { + $pdo->queryExec(sprintf('UPDATE releases SET traktid = %s WHERE id = %s', $pdo->escapeString($data['ids']['trakt']), $pdo->escapeString($rel['id']))); + echo $pdo->log->info('Updated '.$data['title'].' with Trakt ID:'.$data['ids']['trakt']); + } + } + } + echo $pdo->log->header('Updated '.$mcount.' movie(s).'); } else { - echo $pdo->log->info('No movies need updating'); + echo $pdo->log->info('No movies need updating'); } $tcount = 0; if ($ttotal > 0) { - echo $pdo->log->header("Updating Trakt ID for " . number_format($ttotal) . " shows."); - foreach ($treleases as $rel) { - $tcount++; - $data = $trakt->client->showSummary($rel['rageid'], 'min'); - if ($data != false) { - if (isset($data['ids']['trakt'])) { - $pdo->queryExec(sprintf('UPDATE releases SET traktid = %s WHERE id = %s', $pdo->escapeString($data['ids']['trakt']), $pdo->escapeString($rel['id']))); - echo $pdo->log->info('Updated ' . $data['title'] . ' with Trakt ID:' . $data['ids']['trakt']); - } - } - } - echo $pdo->log->header('Updated ' . $tcount . ' show(s).'); + echo $pdo->log->header('Updating Trakt ID for '.number_format($ttotal).' shows.'); + foreach ($treleases as $rel) { + $tcount++; + $data = $trakt->client->showSummary($rel['rageid'], 'min'); + if ($data != false) { + if (isset($data['ids']['trakt'])) { + $pdo->queryExec(sprintf('UPDATE releases SET traktid = %s WHERE id = %s', $pdo->escapeString($data['ids']['trakt']), $pdo->escapeString($rel['id']))); + echo $pdo->log->info('Updated '.$data['title'].' with Trakt ID:'.$data['ids']['trakt']); + } + } + } + echo $pdo->log->header('Updated '.$tcount.' show(s).'); } else { - exit($pdo->log->info('No shows need updating')); + exit($pdo->log->info('No shows need updating')); } diff --git a/misc/testing/DB/populate_nzb_guid.php b/misc/testing/DB/populate_nzb_guid.php index 02c5b9498..95b4061ad 100644 --- a/misc/testing/DB/populate_nzb_guid.php +++ b/misc/testing/DB/populate_nzb_guid.php @@ -1,106 +1,107 @@ error("\nThis script updates all releases with the guid (md5 hash of the first message-id) from the nzb file.\n\n" - . "php $argv[0] true ...: To create missing nzb_guids.\n" - . "php $argv[0] true delete ...: To create missing nzb_guids and delete invalid nzbs and releases.\n")); + exit($cli->error("\nThis script updates all releases with the guid (md5 hash of the first message-id) from the nzb file.\n\n" + ."php $argv[0] true ...: To create missing nzb_guids.\n" + ."php $argv[0] true delete ...: To create missing nzb_guids and delete invalid nzbs and releases.\n")); } function create_guids($live, $delete = false) { - $pdo = new DB(); - $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); - $timestart = time(); - $relcount = $deleted = $total = 0; + $pdo = new DB(); + $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); + $timestart = time(); + $relcount = $deleted = $total = 0; - $relrecs = false; - if ($live == "true") { - $relrecs = $pdo->queryDirect(sprintf("SELECT id, guid FROM releases WHERE nzbstatus = 1 AND nzb_guid IS NULL ORDER BY id DESC")); - } else if ($live == "limited") { - $relrecs = $pdo->queryDirect(sprintf("SELECT id, guid FROM releases WHERE nzbstatus = 1 AND nzb_guid IS NULL ORDER BY id DESC LIMIT 10000")); - } - if ($relrecs) { - $total = $relrecs->rowCount(); - } - if ($total > 0) { - echo $pdo->log->header("Creating nzb_guids for " . number_format($total) . " releases."); - $releases = new Releases(['Settings' => $pdo]); - $nzb = new NZB($pdo); - $releaseImage = new ReleaseImage($pdo); - $reccnt = 0; - if ($relrecs instanceof \Traversable) { - foreach ($relrecs as $relrec) { - $reccnt++; - $nzbpath = $nzb->NZBPath($relrec['guid']); - if ($nzbpath !== false) { - $nzbfile = Utility::unzipGzipFile($nzbpath); - if ($nzbfile) { - $nzbfile = @simplexml_load_string($nzbfile); - } - if (!$nzbfile) { - if (isset($delete) && $delete == 'delete') { - //echo "\n".$nzb->NZBPath($relrec['guid'])." is not a valid xml, deleting release.\n"; - $releases->deleteSingle(['g' => $relrec['guid'], 'i' => $relrec['id']], $nzb, $releaseImage); - $deleted++; - } - continue; - } - $binary_names = []; - foreach ($nzbfile->file as $file) { - $binary_names[] = $file["subject"]; - } - if (count($binary_names) == 0) { - if (isset($delete) && $delete == 'delete') { - //echo "\n".$nzb->NZBPath($relrec['guid'])." has no binaries, deleting release.\n"; - $releases->deleteSingle(['g' => $relrec['guid'], 'i' => $relrec['id']], $nzb, $releaseImage); - $deleted++; - } - continue; - } + $relrecs = false; + if ($live == 'true') { + $relrecs = $pdo->queryDirect(sprintf('SELECT id, guid FROM releases WHERE nzbstatus = 1 AND nzb_guid IS NULL ORDER BY id DESC')); + } elseif ($live == 'limited') { + $relrecs = $pdo->queryDirect(sprintf('SELECT id, guid FROM releases WHERE nzbstatus = 1 AND nzb_guid IS NULL ORDER BY id DESC LIMIT 10000')); + } + if ($relrecs) { + $total = $relrecs->rowCount(); + } + if ($total > 0) { + echo $pdo->log->header('Creating nzb_guids for '.number_format($total).' releases.'); + $releases = new Releases(['Settings' => $pdo]); + $nzb = new NZB($pdo); + $releaseImage = new ReleaseImage($pdo); + $reccnt = 0; + if ($relrecs instanceof \Traversable) { + foreach ($relrecs as $relrec) { + $reccnt++; + $nzbpath = $nzb->NZBPath($relrec['guid']); + if ($nzbpath !== false) { + $nzbfile = Utility::unzipGzipFile($nzbpath); + if ($nzbfile) { + $nzbfile = @simplexml_load_string($nzbfile); + } + if (! $nzbfile) { + if (isset($delete) && $delete == 'delete') { + //echo "\n".$nzb->NZBPath($relrec['guid'])." is not a valid xml, deleting release.\n"; + $releases->deleteSingle(['g' => $relrec['guid'], 'i' => $relrec['id']], $nzb, $releaseImage); + $deleted++; + } + continue; + } + $binary_names = []; + foreach ($nzbfile->file as $file) { + $binary_names[] = $file['subject']; + } + if (count($binary_names) == 0) { + if (isset($delete) && $delete == 'delete') { + //echo "\n".$nzb->NZBPath($relrec['guid'])." has no binaries, deleting release.\n"; + $releases->deleteSingle(['g' => $relrec['guid'], 'i' => $relrec['id']], $nzb, $releaseImage); + $deleted++; + } + continue; + } - asort($binary_names); - foreach ($nzbfile->file as $file) { - if ($file["subject"] == $binary_names[0]) { - $segment = $file->segments->segment; - $nzb_guid = md5($segment); + asort($binary_names); + foreach ($nzbfile->file as $file) { + if ($file['subject'] == $binary_names[0]) { + $segment = $file->segments->segment; + $nzb_guid = md5($segment); - $pdo->queryExec("UPDATE releases set nzb_guid = UNHEX(" . $pdo->escapestring($nzb_guid) . ") WHERE id = " . $relrec["id"]); - $relcount++; - $consoletools->overWritePrimary("Created: [" . $deleted . "] " . $consoletools->percentString($reccnt, $total) . " Time:" . $consoletools->convertTimer(time() - $timestart)); - break; - } - } - } else { - if (isset($delete) && $delete == 'delete') { - //echo $pdo->log->primary($nzb->NZBPath($relrec['guid']) . " does not have an nzb, deleting."); - $releases->deleteSingle(['g' => $relrec['guid'], 'i' => $relrec['id']], $nzb, $releaseImage); - } - } - } - } + $pdo->queryExec('UPDATE releases set nzb_guid = UNHEX('.$pdo->escapestring($nzb_guid).') WHERE id = '.$relrec['id']); + $relcount++; + $consoletools->overWritePrimary('Created: ['.$deleted.'] '.$consoletools->percentString($reccnt, $total).' Time:'.$consoletools->convertTimer(time() - $timestart)); + break; + } + } + } else { + if (isset($delete) && $delete == 'delete') { + //echo $pdo->log->primary($nzb->NZBPath($relrec['guid']) . " does not have an nzb, deleting."); + $releases->deleteSingle(['g' => $relrec['guid'], 'i' => $relrec['id']], $nzb, $releaseImage); + } + } + } + } - if ($relcount > 0) { - echo "\n"; - } - echo $pdo->log->header("Updated " . $relcount . " release(s). This script ran for " . $consoletools->convertTime(time() - $timestart)); - } else { - echo $pdo->log->info('Query time: ' . $consoletools->convertTime(time() - $timestart)); - exit($pdo->log->info("No releases are missing the guid.")); - } + if ($relcount > 0) { + echo "\n"; + } + echo $pdo->log->header('Updated '.$relcount.' release(s). This script ran for '.$consoletools->convertTime(time() - $timestart)); + } else { + echo $pdo->log->info('Query time: '.$consoletools->convertTime(time() - $timestart)); + exit($pdo->log->info('No releases are missing the guid.')); + } } diff --git a/misc/testing/DB/rename_to_lower.php b/misc/testing/DB/rename_to_lower.php index 072d1612e..802d71153 100644 --- a/misc/testing/DB/rename_to_lower.php +++ b/misc/testing/DB/rename_to_lower.php @@ -1,64 +1,63 @@ log->error("\nThis script renames all table columns to lowercase, it can be dangerous. Please BACKUP your database before running this script.\n" - . "php rename_to_lower.php true ...: To rename all table columns to lowercase.\n")); +if (! isset($argv[1]) || (isset($argv[1]) && $argv[1] !== 'true')) { + exit($pdo->log->error("\nThis script renames all table columns to lowercase, it can be dangerous. Please BACKUP your database before running this script.\n" + ."php rename_to_lower.php true ...: To rename all table columns to lowercase.\n")); } -echo $pdo->log->warning("This script renames all table colums to lowercase."); +echo $pdo->log->warning('This script renames all table colums to lowercase.'); echo $pdo->log->header("Have you backed up your database? Type 'BACKEDUP' to continue: \n"); echo $pdo->log->warningOver("\n"); $line = fgets(STDIN); if (trim($line) != 'BACKEDUP') { - exit($pdo->log->error("This script is dangerous you must type BACKEDUP for it function.")); + exit($pdo->log->error('This script is dangerous you must type BACKEDUP for it function.')); } echo "\n"; echo $pdo->log->header("Thank you, continuing...\n\n"); - if ($argc == 1 || $argv[1] != 'true') { - exit($pdo->log->error("\nThis script will rename every table column to lowercase that is not already lowercase.\nTo run:\nphp $argv[0] true\n")); + exit($pdo->log->error("\nThis script will rename every table column to lowercase that is not already lowercase.\nTo run:\nphp $argv[0] true\n")); } $database = env('DB_NAME'); $count = 0; -$list = $pdo->query("SELECT TABLE_NAME, COLUMN_NAME, UPPER(COLUMN_TYPE), EXTRA FROM information_schema.columns WHERE table_schema = '" . $database . "'"); +$list = $pdo->query("SELECT TABLE_NAME, COLUMN_NAME, UPPER(COLUMN_TYPE), EXTRA FROM information_schema.columns WHERE table_schema = '".$database."'"); if (count($list) == 0) { - echo $pdo->log->info("No table columns to rename"); + echo $pdo->log->info('No table columns to rename'); } else { - foreach ($list as $column) { - if ($column['column_name'] !== strtolower($column['column_name'])) { - echo $pdo->log->header("Renaming Table " . $column['table_name'] . " Column " . $column['column_name']); - if (isset($column['extra'])) { - $extra = strtoupper($column['extra']); - } else { - $extra = ''; - } - $pdo->queryDirect("ALTER TABLE " . $column['table_name'] . " CHANGE " . $column['column_name'] . " " . strtolower($column['column_name']) . " " . $column['upper(column_type)'] . " " . $extra); - $count++; - } - if (strtolower($column['column_name']) === 'id' && strtolower($column['extra']) !== 'auto_increment') { - echo $pdo->log->header("Renaming Table " . $column['table_name'] . " Column " . $column['column_name']); - $extra = 'AUTO_INCREMENT'; - if ($column['table_name'] != "releases_se") { - $placeholder = $pdo->queryDirect("SELECT MAX(id) FROM " . $column['table_name']); - $pdo->queryDirect("ALTER IGNORE TABLE " . $column['table_name'] . " CHANGE " . $column['column_name'] . " " . strtolower($column['column_name']) . " " . $column['upper(column_type)'] . " " . $extra); - $pdo->queryDirect("ALTER IGNORE TABLE " . $column['table_name'] . " AUTO_INCREMENT = " . $placeholder + 1); - $count++; - } - } - } + foreach ($list as $column) { + if ($column['column_name'] !== strtolower($column['column_name'])) { + echo $pdo->log->header('Renaming Table '.$column['table_name'].' Column '.$column['column_name']); + if (isset($column['extra'])) { + $extra = strtoupper($column['extra']); + } else { + $extra = ''; + } + $pdo->queryDirect('ALTER TABLE '.$column['table_name'].' CHANGE '.$column['column_name'].' '.strtolower($column['column_name']).' '.$column['upper(column_type)'].' '.$extra); + $count++; + } + if (strtolower($column['column_name']) === 'id' && strtolower($column['extra']) !== 'auto_increment') { + echo $pdo->log->header('Renaming Table '.$column['table_name'].' Column '.$column['column_name']); + $extra = 'AUTO_INCREMENT'; + if ($column['table_name'] != 'releases_se') { + $placeholder = $pdo->queryDirect('SELECT MAX(id) FROM '.$column['table_name']); + $pdo->queryDirect('ALTER IGNORE TABLE '.$column['table_name'].' CHANGE '.$column['column_name'].' '.strtolower($column['column_name']).' '.$column['upper(column_type)'].' '.$extra); + $pdo->queryDirect('ALTER IGNORE TABLE '.$column['table_name'].' AUTO_INCREMENT = '.$placeholder + 1); + $count++; + } + } + } } if ($count == 0) { - echo $pdo->log->info("All table column names are already lowercase"); + echo $pdo->log->info('All table column names are already lowercase'); } else { - echo $pdo->log->header($count . " colums renamed"); + echo $pdo->log->header($count.' colums renamed'); } diff --git a/misc/testing/DB/reset_postprocessing.php b/misc/testing/DB/reset_postprocessing.php index 6610ec735..f9db7b68d 100755 --- a/misc/testing/DB/reset_postprocessing.php +++ b/misc/testing/DB/reset_postprocessing.php @@ -1,10 +1,11 @@ $pdo->log]); $ran = false; if (isset($argv[1], $argv[2]) && $argv[1] === 'all' && $argv[2] === 'true') { - $ran = true; - $where = ''; - if (isset($argv[3]) && $argv[3] === 'truncate') { - echo 'Truncating tables\n'; - $pdo->queryExec('TRUNCATE TABLE consoleinfo'); - $pdo->queryExec('TRUNCATE TABLE gamesinfo'); - $pdo->queryExec('TRUNCATE TABLE movieinfo'); - $pdo->queryExec('TRUNCATE TABLE video_data'); - $pdo->queryExec('TRUNCATE TABLE musicinfo'); - $pdo->queryExec('TRUNCATE TABLE bookinfo'); - $pdo->queryExec('TRUNCATE TABLE release_nfos'); - $pdo->queryExec('TRUNCATE TABLE releaseextrafull'); - $pdo->queryExec('TRUNCATE TABLE xxxinfo'); - $pdo->queryExec('TRUNCATE TABLE videos'); - $pdo->queryExec('TRUNCATE TABLE videos_aliases'); - $pdo->queryExec('TRUNCATE TABLE tv_info'); - $pdo->queryExec('TRUNCATE TABLE tv_episodes'); - $pdo->queryExec('TRUNCATE TABLE anidb_info'); - $pdo->queryExec('TRUNCATE TABLE anidb_episodes'); - } - echo ColorCLI::header('Resetting all postprocessing'); - $qry = $pdo->queryDirect('SELECT id FROM releases'); - $affected = 0; - if ($qry instanceof \Traversable) { - $total = $qry->rowCount(); - foreach ($qry as $releases) { - $pdo->queryExec( + $ran = true; + $where = ''; + if (isset($argv[3]) && $argv[3] === 'truncate') { + echo 'Truncating tables\n'; + $pdo->queryExec('TRUNCATE TABLE consoleinfo'); + $pdo->queryExec('TRUNCATE TABLE gamesinfo'); + $pdo->queryExec('TRUNCATE TABLE movieinfo'); + $pdo->queryExec('TRUNCATE TABLE video_data'); + $pdo->queryExec('TRUNCATE TABLE musicinfo'); + $pdo->queryExec('TRUNCATE TABLE bookinfo'); + $pdo->queryExec('TRUNCATE TABLE release_nfos'); + $pdo->queryExec('TRUNCATE TABLE releaseextrafull'); + $pdo->queryExec('TRUNCATE TABLE xxxinfo'); + $pdo->queryExec('TRUNCATE TABLE videos'); + $pdo->queryExec('TRUNCATE TABLE videos_aliases'); + $pdo->queryExec('TRUNCATE TABLE tv_info'); + $pdo->queryExec('TRUNCATE TABLE tv_episodes'); + $pdo->queryExec('TRUNCATE TABLE anidb_info'); + $pdo->queryExec('TRUNCATE TABLE anidb_episodes'); + } + echo ColorCLI::header('Resetting all postprocessing'); + $qry = $pdo->queryDirect('SELECT id FROM releases'); + $affected = 0; + if ($qry instanceof \Traversable) { + $total = $qry->rowCount(); + foreach ($qry as $releases) { + $pdo->queryExec( sprintf(' UPDATE releases SET consoleinfo_id = NULL, gamesinfo_id = 0, imdbid = NULL, musicinfo_id = NULL, @@ -48,299 +49,299 @@ if (isset($argv[1], $argv[2]) && $argv[1] === 'all' && $argv[2] === 'true') { $releases['id'] ) ); - $consoletools->overWritePrimary('Resetting Releases: ' . $consoletools->percentString(++$affected, $total)); - } - } + $consoletools->overWritePrimary('Resetting Releases: '.$consoletools->percentString(++$affected, $total)); + } + } } if (isset($argv[1]) && ($argv[1] === 'consoles' || $argv[1] === 'all')) { - $ran = true; - if (isset($argv[3]) && $argv[3] === 'truncate') { - $pdo->queryExec('TRUNCATE TABLE consoleinfo'); - } - if (isset($argv[2]) && $argv[2] === 'true') { - echo ColorCLI::header('Resetting all Console postprocessing'); - $where = ' WHERE consoleinfo_id IS NOT NULL'; - } else { - echo ColorCLI::header('Resetting all failed Console postprocessing'); - $where = ' WHERE consoleinfo_id IN (-2, 0) AND categories_id BETWEEN ' . Category::GAME_ROOT . ' AND ' . Category::GAME_OTHER; - } + $ran = true; + if (isset($argv[3]) && $argv[3] === 'truncate') { + $pdo->queryExec('TRUNCATE TABLE consoleinfo'); + } + if (isset($argv[2]) && $argv[2] === 'true') { + echo ColorCLI::header('Resetting all Console postprocessing'); + $where = ' WHERE consoleinfo_id IS NOT NULL'; + } else { + echo ColorCLI::header('Resetting all failed Console postprocessing'); + $where = ' WHERE consoleinfo_id IN (-2, 0) AND categories_id BETWEEN '.Category::GAME_ROOT.' AND '.Category::GAME_OTHER; + } - $qry = $pdo->queryDirect('SELECT id FROM releases' . $where); - if ($qry !== false) { - $total = $qry->rowCount(); - } else { - $total = 0; - } - $concount = 0; - if ($qry instanceof \Traversable) { - foreach ($qry as $releases) { - $pdo->queryExec('UPDATE releases SET consoleinfo_id = NULL WHERE id = ' . $releases['id']); - $consoletools->overWritePrimary('Resetting Console Releases: ' . $consoletools->percentString(++$concount, $total)); - } - } - echo ColorCLI::header(PHP_EOL . number_format($concount) . ' consoleinfoIDs reset.'); + $qry = $pdo->queryDirect('SELECT id FROM releases'.$where); + if ($qry !== false) { + $total = $qry->rowCount(); + } else { + $total = 0; + } + $concount = 0; + if ($qry instanceof \Traversable) { + foreach ($qry as $releases) { + $pdo->queryExec('UPDATE releases SET consoleinfo_id = NULL WHERE id = '.$releases['id']); + $consoletools->overWritePrimary('Resetting Console Releases: '.$consoletools->percentString(++$concount, $total)); + } + } + echo ColorCLI::header(PHP_EOL.number_format($concount).' consoleinfoIDs reset.'); } if (isset($argv[1]) && ($argv[1] === 'games' || $argv[1] === 'all')) { - $ran = true; - if (isset($argv[3]) && $argv[3] === 'truncate') { - $pdo->queryExec('TRUNCATE TABLE gamesinfo'); - } - if (isset($argv[2]) && $argv[2] === 'true') { - echo ColorCLI::header('Resetting all Games postprocessing'); - $where = ' WHERE gamesinfo_id != 0'; - } else { - echo ColorCLI::header('Resetting all failed Games postprocessing'); - $where = ' WHERE gamesinfo_id IN (-2, 0) AND categories_id = 4050'; - } + $ran = true; + if (isset($argv[3]) && $argv[3] === 'truncate') { + $pdo->queryExec('TRUNCATE TABLE gamesinfo'); + } + if (isset($argv[2]) && $argv[2] === 'true') { + echo ColorCLI::header('Resetting all Games postprocessing'); + $where = ' WHERE gamesinfo_id != 0'; + } else { + echo ColorCLI::header('Resetting all failed Games postprocessing'); + $where = ' WHERE gamesinfo_id IN (-2, 0) AND categories_id = 4050'; + } - $qry = $pdo->queryDirect('SELECT id FROM releases' . $where); + $qry = $pdo->queryDirect('SELECT id FROM releases'.$where); - $total = 0; - if ($qry !== false) { - $total = $qry->rowCount(); - } + $total = 0; + if ($qry !== false) { + $total = $qry->rowCount(); + } - $concount = 0; - if ($qry instanceof \Traversable) { - foreach ($qry as $releases) { - $pdo->queryExec('UPDATE releases SET gamesinfo_id = 0 WHERE id = ' . $releases['id']); - $consoletools->overWritePrimary('Resetting Games Releases: ' . $consoletools->percentString(++$concount, $total)); - } - echo ColorCLI::header(PHP_EOL . number_format($concount) . ' gameinfo_IDs reset.'); - } + $concount = 0; + if ($qry instanceof \Traversable) { + foreach ($qry as $releases) { + $pdo->queryExec('UPDATE releases SET gamesinfo_id = 0 WHERE id = '.$releases['id']); + $consoletools->overWritePrimary('Resetting Games Releases: '.$consoletools->percentString(++$concount, $total)); + } + echo ColorCLI::header(PHP_EOL.number_format($concount).' gameinfo_IDs reset.'); + } } if (isset($argv[1]) && ($argv[1] === 'movies' || $argv[1] === 'all')) { - $ran = true; - if (isset($argv[3]) && $argv[3] === 'truncate') { - $pdo->queryExec('TRUNCATE TABLE movieinfo'); - } - if (isset($argv[2]) && $argv[2] === 'true') { - echo ColorCLI::header('Resetting all Movie postprocessing'); - $where = ' WHERE imdbid IS NOT NULL'; - } else { - echo ColorCLI::header('Resetting all failed Movie postprocessing'); - $where = ' WHERE imdbid IN (-2, 0) AND categories_id BETWEEN ' . Category::MOVIE_ROOT . ' AND ' . Category::MOVIE_OTHER; - } + $ran = true; + if (isset($argv[3]) && $argv[3] === 'truncate') { + $pdo->queryExec('TRUNCATE TABLE movieinfo'); + } + if (isset($argv[2]) && $argv[2] === 'true') { + echo ColorCLI::header('Resetting all Movie postprocessing'); + $where = ' WHERE imdbid IS NOT NULL'; + } else { + echo ColorCLI::header('Resetting all failed Movie postprocessing'); + $where = ' WHERE imdbid IN (-2, 0) AND categories_id BETWEEN '.Category::MOVIE_ROOT.' AND '.Category::MOVIE_OTHER; + } - $qry = $pdo->queryDirect('SELECT id FROM releases' . $where); - if ($qry !== false) { - $total = $qry->rowCount(); - } else { - $total = 0; - } - $concount = 0; - if ($qry instanceof \Traversable) { - foreach ($qry as $releases) { - $pdo->queryExec('UPDATE releases SET imdbid = NULL WHERE id = ' . $releases['id']); - $consoletools->overWritePrimary('Resetting Movie Releases: ' . $consoletools->percentString(++$concount, $total)); - } - } - echo ColorCLI::header(PHP_EOL . number_format($concount) . ' imdbIDs reset.'); + $qry = $pdo->queryDirect('SELECT id FROM releases'.$where); + if ($qry !== false) { + $total = $qry->rowCount(); + } else { + $total = 0; + } + $concount = 0; + if ($qry instanceof \Traversable) { + foreach ($qry as $releases) { + $pdo->queryExec('UPDATE releases SET imdbid = NULL WHERE id = '.$releases['id']); + $consoletools->overWritePrimary('Resetting Movie Releases: '.$consoletools->percentString(++$concount, $total)); + } + } + echo ColorCLI::header(PHP_EOL.number_format($concount).' imdbIDs reset.'); } if (isset($argv[1]) && ($argv[1] === 'music' || $argv[1] === 'all')) { - $ran = true; - if (isset($argv[3]) && $argv[3] === 'truncate') { - $pdo->queryExec('TRUNCATE TABLE musicinfo'); - } - if (isset($argv[2]) && $argv[2] === 'true') { - echo ColorCLI::header('Resetting all Music postprocessing'); - $where = ' WHERE musicinfo_id IS NOT NULL'; - } else { - echo ColorCLI::header('Resetting all failed Music postprocessing'); - $where = ' WHERE musicinfo_id IN (-2, 0) AND categories_id BETWEEN ' . Category::MUSIC_ROOT . ' AND ' . Category::MUSIC_OTHER; - } + $ran = true; + if (isset($argv[3]) && $argv[3] === 'truncate') { + $pdo->queryExec('TRUNCATE TABLE musicinfo'); + } + if (isset($argv[2]) && $argv[2] === 'true') { + echo ColorCLI::header('Resetting all Music postprocessing'); + $where = ' WHERE musicinfo_id IS NOT NULL'; + } else { + echo ColorCLI::header('Resetting all failed Music postprocessing'); + $where = ' WHERE musicinfo_id IN (-2, 0) AND categories_id BETWEEN '.Category::MUSIC_ROOT.' AND '.Category::MUSIC_OTHER; + } - $qry = $pdo->queryDirect('SELECT id FROM releases' . $where); - $total = $qry->rowCount(); - $concount = 0; - if ($qry instanceof \Traversable) { - foreach ($qry as $releases) { - $pdo->queryExec(sprintf('UPDATE releases SET musicinfo_id = NULL WHERE id = %s ', $releases['id'])); - $consoletools->overWritePrimary('Resetting Music Releases: ' . $consoletools->percentString(++$concount, $total)); - } - } - echo ColorCLI::header(PHP_EOL . number_format($concount) . ' musicinfo_ids reset.'); + $qry = $pdo->queryDirect('SELECT id FROM releases'.$where); + $total = $qry->rowCount(); + $concount = 0; + if ($qry instanceof \Traversable) { + foreach ($qry as $releases) { + $pdo->queryExec(sprintf('UPDATE releases SET musicinfo_id = NULL WHERE id = %s ', $releases['id'])); + $consoletools->overWritePrimary('Resetting Music Releases: '.$consoletools->percentString(++$concount, $total)); + } + } + echo ColorCLI::header(PHP_EOL.number_format($concount).' musicinfo_ids reset.'); } if (isset($argv[1]) && ($argv[1] === 'misc' || $argv[1] === 'all')) { - $ran = true; - if (isset($argv[2]) && $argv[2] === 'true') { - echo ColorCLI::header('Resetting all Additional postprocessing'); - $where = ' WHERE (haspreview != -1 AND haspreview != 0) OR (passwordstatus != -1 AND passwordstatus != 0) OR jpgstatus != 0 OR videostatus != 0 OR audiostatus != 0'; - } else { - echo ColorCLI::header('Resetting all failed Additional postprocessing'); - $where = ' WHERE haspreview < -1 OR haspreview = 0 OR passwordstatus < -1 OR passwordstatus = 0 OR jpgstatus < 0 OR videostatus < 0 OR audiostatus < 0'; - } + $ran = true; + if (isset($argv[2]) && $argv[2] === 'true') { + echo ColorCLI::header('Resetting all Additional postprocessing'); + $where = ' WHERE (haspreview != -1 AND haspreview != 0) OR (passwordstatus != -1 AND passwordstatus != 0) OR jpgstatus != 0 OR videostatus != 0 OR audiostatus != 0'; + } else { + echo ColorCLI::header('Resetting all failed Additional postprocessing'); + $where = ' WHERE haspreview < -1 OR haspreview = 0 OR passwordstatus < -1 OR passwordstatus = 0 OR jpgstatus < 0 OR videostatus < 0 OR audiostatus < 0'; + } - echo ColorCLI::primary('SELECT id FROM releases' . $where); - $qry = $pdo->queryDirect('SELECT id FROM releases' . $where); - if ($qry !== false) { - $total = $qry->rowCount(); - } else { - $total = 0; - } - $concount = 0; - if ($qry instanceof \Traversable) { - foreach ($qry as $releases) { - $pdo->queryExec('UPDATE releases SET passwordstatus = -1, haspreview = -1, jpgstatus = 0, videostatus = 0, audiostatus = 0 WHERE id = ' . $releases['id']); - $consoletools->overWritePrimary('Resetting Releases: ' . $consoletools->percentString(++$concount, $total)); - } - } - echo ColorCLI::header(PHP_EOL . number_format($concount) . ' Releases reset.'); + echo ColorCLI::primary('SELECT id FROM releases'.$where); + $qry = $pdo->queryDirect('SELECT id FROM releases'.$where); + if ($qry !== false) { + $total = $qry->rowCount(); + } else { + $total = 0; + } + $concount = 0; + if ($qry instanceof \Traversable) { + foreach ($qry as $releases) { + $pdo->queryExec('UPDATE releases SET passwordstatus = -1, haspreview = -1, jpgstatus = 0, videostatus = 0, audiostatus = 0 WHERE id = '.$releases['id']); + $consoletools->overWritePrimary('Resetting Releases: '.$consoletools->percentString(++$concount, $total)); + } + } + echo ColorCLI::header(PHP_EOL.number_format($concount).' Releases reset.'); } if (isset($argv[1]) && ($argv[1] === 'tv' || $argv[1] === 'all')) { - $ran = true; - if (isset($argv[3]) && $argv[3] === 'truncate') { - $pdo->queryExec('DELETE v, va FROM videos v INNER JOIN videos_aliases va ON v.id = va.videos_id WHERE type = 0'); - $pdo->queryExec('TRUNCATE TABLE tv_info'); - $pdo->queryExec('TRUNCATE TABLE tv_episodes'); - } - if (isset($argv[2]) && $argv[2] === 'true') { - echo ColorCLI::header('Resetting all TV postprocessing'); - $where = ' WHERE videos_id != 0 AND tv_episodes_id != 0 AND categories_id BETWEEN ' . Category::TV_ROOT . ' AND ' . Category::TV_OTHER; - } else { - echo ColorCLI::header('Resetting all failed TV postprocessing'); - $where = ' WHERE tv_episodes_id < 0 AND categories_id BETWEEN ' . Category::GAME_ROOT . ' AND ' . Category::GAME_OTHER; - } + $ran = true; + if (isset($argv[3]) && $argv[3] === 'truncate') { + $pdo->queryExec('DELETE v, va FROM videos v INNER JOIN videos_aliases va ON v.id = va.videos_id WHERE type = 0'); + $pdo->queryExec('TRUNCATE TABLE tv_info'); + $pdo->queryExec('TRUNCATE TABLE tv_episodes'); + } + if (isset($argv[2]) && $argv[2] === 'true') { + echo ColorCLI::header('Resetting all TV postprocessing'); + $where = ' WHERE videos_id != 0 AND tv_episodes_id != 0 AND categories_id BETWEEN '.Category::TV_ROOT.' AND '.Category::TV_OTHER; + } else { + echo ColorCLI::header('Resetting all failed TV postprocessing'); + $where = ' WHERE tv_episodes_id < 0 AND categories_id BETWEEN '.Category::GAME_ROOT.' AND '.Category::GAME_OTHER; + } - $qry = $pdo->queryDirect('SELECT id FROM releases' . $where); - if ($qry !== false) { - $total = $qry->rowCount(); - } else { - $total = 0; - } - $concount = 0; - if ($qry instanceof \Traversable) { - foreach ($qry as $releases) { - $pdo->queryExec('UPDATE releases SET videos_id = 0, tv_episodes_id = 0 WHERE id = ' . $releases['id']); - $consoletools->overWritePrimary('Resetting TV Releases: ' . $consoletools->percentString(++$concount, $total)); - } - } - echo ColorCLI::header(PHP_EOL . number_format($concount) . ' Video IDs reset.'); + $qry = $pdo->queryDirect('SELECT id FROM releases'.$where); + if ($qry !== false) { + $total = $qry->rowCount(); + } else { + $total = 0; + } + $concount = 0; + if ($qry instanceof \Traversable) { + foreach ($qry as $releases) { + $pdo->queryExec('UPDATE releases SET videos_id = 0, tv_episodes_id = 0 WHERE id = '.$releases['id']); + $consoletools->overWritePrimary('Resetting TV Releases: '.$consoletools->percentString(++$concount, $total)); + } + } + echo ColorCLI::header(PHP_EOL.number_format($concount).' Video IDs reset.'); } if (isset($argv[1]) && ($argv[1] === 'anime' || $argv[1] === 'all')) { - $ran = true; - if (isset($argv[3]) && $argv[3] === 'truncate') { - $pdo->queryExec('TRUNCATE TABLE anidb_info'); - $pdo->queryExec('TRUNCATE TABLE anidb_episodes'); - } - if (isset($argv[2]) && $argv[2] === 'true') { - echo ColorCLI::header('Resetting all Anime postprocessing'); - $where = ' WHERE categories_id = 5070'; - } else { - echo ColorCLI::header('Resetting all failed Anime postprocessing'); - $where = ' WHERE anidbid BETWEEN -2 AND -1 AND categories_id = ' . Category::TV_ANIME; - } + $ran = true; + if (isset($argv[3]) && $argv[3] === 'truncate') { + $pdo->queryExec('TRUNCATE TABLE anidb_info'); + $pdo->queryExec('TRUNCATE TABLE anidb_episodes'); + } + if (isset($argv[2]) && $argv[2] === 'true') { + echo ColorCLI::header('Resetting all Anime postprocessing'); + $where = ' WHERE categories_id = 5070'; + } else { + echo ColorCLI::header('Resetting all failed Anime postprocessing'); + $where = ' WHERE anidbid BETWEEN -2 AND -1 AND categories_id = '.Category::TV_ANIME; + } - $qry = $pdo->queryDirect('SELECT id FROM releases' . $where); - if ($qry !== false) { - $total = $qry->rowCount(); - } else { - $total = 0; - } - $concount = 0; - if ($qry instanceof \Traversable) { - foreach ($qry as $releases) { - $pdo->queryExec('UPDATE releases SET anidbid = NULL WHERE id = ' . $releases['id']); - $consoletools->overWritePrimary('Resetting Anime Releases: ' . $consoletools->percentString(++$concount, $total)); - } - } - echo ColorCLI::header(PHP_EOL . number_format($concount) . ' anidbIDs reset.'); + $qry = $pdo->queryDirect('SELECT id FROM releases'.$where); + if ($qry !== false) { + $total = $qry->rowCount(); + } else { + $total = 0; + } + $concount = 0; + if ($qry instanceof \Traversable) { + foreach ($qry as $releases) { + $pdo->queryExec('UPDATE releases SET anidbid = NULL WHERE id = '.$releases['id']); + $consoletools->overWritePrimary('Resetting Anime Releases: '.$consoletools->percentString(++$concount, $total)); + } + } + echo ColorCLI::header(PHP_EOL.number_format($concount).' anidbIDs reset.'); } if (isset($argv[1]) && ($argv[1] === 'books' || $argv[1] === 'all')) { - $ran = true; - if (isset($argv[3]) && $argv[3] === 'truncate') { - $pdo->queryExec('TRUNCATE TABLE bookinfo'); - } - if (isset($argv[2]) && $argv[2] === 'true') { - echo ColorCLI::header('Resetting all Book postprocessing'); - $where = ' WHERE bookinfo_id IS NOT NULL'; - } else { - echo ColorCLI::header('Resetting all failed Book postprocessing'); - $where = ' WHERE bookinfo_id IN (-2, 0) AND categories_id BETWEEN ' . Category::BOOKS_ROOT . ' AND ' . Category::BOOKS_UNKNOWN; - } + $ran = true; + if (isset($argv[3]) && $argv[3] === 'truncate') { + $pdo->queryExec('TRUNCATE TABLE bookinfo'); + } + if (isset($argv[2]) && $argv[2] === 'true') { + echo ColorCLI::header('Resetting all Book postprocessing'); + $where = ' WHERE bookinfo_id IS NOT NULL'; + } else { + echo ColorCLI::header('Resetting all failed Book postprocessing'); + $where = ' WHERE bookinfo_id IN (-2, 0) AND categories_id BETWEEN '.Category::BOOKS_ROOT.' AND '.Category::BOOKS_UNKNOWN; + } - $qry = $pdo->queryDirect('SELECT id FROM releases' . $where); - $total = $qry->rowCount(); - $concount = 0; - if ($qry instanceof \Traversable) { - foreach ($qry as $releases) { - $pdo->queryExec('UPDATE releases SET bookinfo_id = NULL WHERE id = ' . $releases['id']); - $consoletools->overWritePrimary('Resetting Book Releases: ' . $consoletools->percentString(++$concount, $total)); - } - } - echo ColorCLI::header(PHP_EOL . number_format($concount) . ' bookinfoIDs reset.'); + $qry = $pdo->queryDirect('SELECT id FROM releases'.$where); + $total = $qry->rowCount(); + $concount = 0; + if ($qry instanceof \Traversable) { + foreach ($qry as $releases) { + $pdo->queryExec('UPDATE releases SET bookinfo_id = NULL WHERE id = '.$releases['id']); + $consoletools->overWritePrimary('Resetting Book Releases: '.$consoletools->percentString(++$concount, $total)); + } + } + echo ColorCLI::header(PHP_EOL.number_format($concount).' bookinfoIDs reset.'); } if (isset($argv[1]) && ($argv[1] === 'xxx' || $argv[1] === 'all')) { - $ran = true; - if (isset($argv[3]) && $argv[3] === 'truncate') { - $pdo->queryExec('TRUNCATE TABLE xxxinfo'); - } - if (isset($argv[2]) && $argv[2] === 'true') { - echo ColorCLI::header('Resetting all XXX postprocessing'); - $where = ' WHERE xxxinfo_id != 0'; - } else { - echo ColorCLI::header('Resetting all failed XXX postprocessing'); - $where = ' WHERE xxxinfo_id IN (-2, 0) AND categories_id BETWEEN ' . Category::XXX_ROOT . ' AND ' . Category::XXX_X264; - } + $ran = true; + if (isset($argv[3]) && $argv[3] === 'truncate') { + $pdo->queryExec('TRUNCATE TABLE xxxinfo'); + } + if (isset($argv[2]) && $argv[2] === 'true') { + echo ColorCLI::header('Resetting all XXX postprocessing'); + $where = ' WHERE xxxinfo_id != 0'; + } else { + echo ColorCLI::header('Resetting all failed XXX postprocessing'); + $where = ' WHERE xxxinfo_id IN (-2, 0) AND categories_id BETWEEN '.Category::XXX_ROOT.' AND '.Category::XXX_X264; + } - $qry = $pdo->queryDirect('SELECT id FROM releases' . $where); - $concount = 0; - if ($qry instanceof \Traversable) { - $total = $qry->rowCount(); - foreach ($qry as $releases) { - $pdo->queryExec('UPDATE releases SET xxxinfo_id = 0 WHERE id = ' . $releases['id']); - $consoletools->overWritePrimary('Resetting XXX Releases: ' . $consoletools->percentString(++$concount, + $qry = $pdo->queryDirect('SELECT id FROM releases'.$where); + $concount = 0; + if ($qry instanceof \Traversable) { + $total = $qry->rowCount(); + foreach ($qry as $releases) { + $pdo->queryExec('UPDATE releases SET xxxinfo_id = 0 WHERE id = '.$releases['id']); + $consoletools->overWritePrimary('Resetting XXX Releases: '.$consoletools->percentString(++$concount, $total)); - } - } - echo ColorCLI::header(PHP_EOL . number_format($concount) . ' xxxinfo_IDs reset.'); + } + } + echo ColorCLI::header(PHP_EOL.number_format($concount).' xxxinfo_IDs reset.'); } if (isset($argv[1]) && ($argv[1] === 'nfos' || $argv[1] === 'all')) { - $ran = true; - if (isset($argv[3]) && $argv[3] === 'truncate') { - $pdo->queryExec('TRUNCATE TABLE release_nfos'); - } - if (isset($argv[2]) && $argv[2] === 'true') { - echo ColorCLI::header('Resetting all NFO postprocessing'); - $where = ' WHERE nfostatus != -1'; - } else { - echo ColorCLI::header('Resetting all failed NFO postprocessing'); - $where = ' WHERE nfostatus < -1'; - } + $ran = true; + if (isset($argv[3]) && $argv[3] === 'truncate') { + $pdo->queryExec('TRUNCATE TABLE release_nfos'); + } + if (isset($argv[2]) && $argv[2] === 'true') { + echo ColorCLI::header('Resetting all NFO postprocessing'); + $where = ' WHERE nfostatus != -1'; + } else { + echo ColorCLI::header('Resetting all failed NFO postprocessing'); + $where = ' WHERE nfostatus < -1'; + } - $qry = $pdo->queryDirect('SELECT id FROM releases' . $where); - $concount = 0; - if ($qry instanceof \Traversable) { - $total = $qry->rowCount(); - foreach ($qry as $releases) { - $pdo->queryExec('UPDATE releases SET nfostatus = -1 WHERE id = ' . $releases['id']); - $consoletools->overWritePrimary('Resetting NFO Releases: ' . $consoletools->percentString(++$concount, $total)); - } - } - echo ColorCLI::header(PHP_EOL . number_format($concount) . ' NFOs reset.'); + $qry = $pdo->queryDirect('SELECT id FROM releases'.$where); + $concount = 0; + if ($qry instanceof \Traversable) { + $total = $qry->rowCount(); + foreach ($qry as $releases) { + $pdo->queryExec('UPDATE releases SET nfostatus = -1 WHERE id = '.$releases['id']); + $consoletools->overWritePrimary('Resetting NFO Releases: '.$consoletools->percentString(++$concount, $total)); + } + } + echo ColorCLI::header(PHP_EOL.number_format($concount).' NFOs reset.'); } if ($ran === false) { - exit( + exit( ColorCLI::error( '\nThis script will reset postprocessing per category. It can also truncate the associated tables.' - . '\nTo reset only those that have previously failed, those without covers, samples, previews, etc. use the ' - . 'second argument false.\n' - . 'To reset even those previously post processed, use the second argument true.\n' - . 'To truncate the associated table, use the third argument truncate.\n\n' - . 'php reset_postprocessing.php consoles true ...: To reset all consoles.\n' - . 'php reset_postprocessing.php games true ...: To reset all games.\n' - . 'php reset_postprocessing.php movies true ...: To reset all movies.\n' - . 'php reset_postprocessing.php music true ...: To reset all music.\n' - . 'php reset_postprocessing.php misc true ...: To reset all misc.\n' - . 'php reset_postprocessing.php tv true ...: To reset all tv.\n' - . 'php reset_postprocessing.php anime true ...: To reset all anime.\n' - . 'php reset_postprocessing.php books true ...: To reset all books.\n' - . 'php reset_postprocessing.php xxx true ...: To reset all xxx.\n' - . 'php reset_postprocessing.php nfos true ...: To reset all nfos.\n' - . 'php reset_postprocessing.php all true ...: To reset everything.\n' + .'\nTo reset only those that have previously failed, those without covers, samples, previews, etc. use the ' + .'second argument false.\n' + .'To reset even those previously post processed, use the second argument true.\n' + .'To truncate the associated table, use the third argument truncate.\n\n' + .'php reset_postprocessing.php consoles true ...: To reset all consoles.\n' + .'php reset_postprocessing.php games true ...: To reset all games.\n' + .'php reset_postprocessing.php movies true ...: To reset all movies.\n' + .'php reset_postprocessing.php music true ...: To reset all music.\n' + .'php reset_postprocessing.php misc true ...: To reset all misc.\n' + .'php reset_postprocessing.php tv true ...: To reset all tv.\n' + .'php reset_postprocessing.php anime true ...: To reset all anime.\n' + .'php reset_postprocessing.php books true ...: To reset all books.\n' + .'php reset_postprocessing.php xxx true ...: To reset all xxx.\n' + .'php reset_postprocessing.php nfos true ...: To reset all nfos.\n' + .'php reset_postprocessing.php all true ...: To reset everything.\n' ) ); } else { - echo PHP_EOL; + echo PHP_EOL; } diff --git a/misc/testing/DB/reset_truncate.php b/misc/testing/DB/reset_truncate.php index 985c9b25d..71d614d88 100644 --- a/misc/testing/DB/reset_truncate.php +++ b/misc/testing/DB/reset_truncate.php @@ -1,52 +1,50 @@ queryExec('UPDATE groups SET first_record = 0, first_record_postdate = NULL, last_record = 0, last_record_postdate = NULL, last_updated = NULL'); - echo $pdo->log->primary('Reseting all groups completed.'); + $pdo->queryExec('UPDATE groups SET first_record = 0, first_record_postdate = NULL, last_record = 0, last_record_postdate = NULL, last_updated = NULL'); + echo $pdo->log->primary('Reseting all groups completed.'); - $arr = ['parts', 'missed_parts', 'binaries', 'collections', 'multigroup_parts', 'multigroup_missed_parts', 'multigroup_binaries', 'multigroup_collections']; - foreach ($arr as &$value) { - $rel = $pdo->queryExec("TRUNCATE TABLE $value"); - if ($rel !== false) { - echo $pdo->log->primary("Truncating ${value} completed."); - } - } - unset($value); + $arr = ['parts', 'missed_parts', 'binaries', 'collections', 'multigroup_parts', 'multigroup_missed_parts', 'multigroup_binaries', 'multigroup_collections']; + foreach ($arr as &$value) { + $rel = $pdo->queryExec("TRUNCATE TABLE $value"); + if ($rel !== false) { + echo $pdo->log->primary("Truncating ${value} completed."); + } + } + unset($value); - $sql = 'SHOW table status'; + $sql = 'SHOW table status'; - $tables = $pdo->query($sql); - foreach ($tables as $row) { - $tbl = $row['name']; - if (preg_match('/collections_\d+/', $tbl) || preg_match('/binaries_\d+/', $tbl) || preg_match('/parts_\d+/', $tbl) || preg_match('/missed_parts_\d+/', $tbl) || preg_match('/\d+_collections/', $tbl) || preg_match('/\d+_binaries/', $tbl) || preg_match('/\d+_parts/', $tbl) || preg_match('/\d+_missed_parts_\d+/', $tbl)) { - if ($argv[1] === 'drop') { - $rel = $pdo->queryDirect(sprintf('DROP TABLE %s', $tbl)); - if ($rel !== false) { - echo $pdo->log->primary("Dropping ${tbl} completed."); - } - } else { - $rel = $pdo->queryDirect(sprintf('TRUNCATE TABLE %s', $tbl)); - if ($rel !== false) { - echo $pdo->log->primary("Truncating ${tbl} completed."); - } - } - } - } + $tables = $pdo->query($sql); + foreach ($tables as $row) { + $tbl = $row['name']; + if (preg_match('/collections_\d+/', $tbl) || preg_match('/binaries_\d+/', $tbl) || preg_match('/parts_\d+/', $tbl) || preg_match('/missed_parts_\d+/', $tbl) || preg_match('/\d+_collections/', $tbl) || preg_match('/\d+_binaries/', $tbl) || preg_match('/\d+_parts/', $tbl) || preg_match('/\d+_missed_parts_\d+/', $tbl)) { + if ($argv[1] === 'drop') { + $rel = $pdo->queryDirect(sprintf('DROP TABLE %s', $tbl)); + if ($rel !== false) { + echo $pdo->log->primary("Dropping ${tbl} completed."); + } + } else { + $rel = $pdo->queryDirect(sprintf('TRUNCATE TABLE %s', $tbl)); + if ($rel !== false) { + echo $pdo->log->primary("Truncating ${tbl} completed."); + } + } + } + } - $delcount = $pdo->queryDirect("DELETE FROM releases WHERE nzbstatus = 0"); - echo $pdo->log->primary($delcount->rowCount() . ' releases had no nzb, deleted.'); + $delcount = $pdo->queryDirect('DELETE FROM releases WHERE nzbstatus = 0'); + echo $pdo->log->primary($delcount->rowCount().' releases had no nzb, deleted.'); } else { - exit($pdo->log->error("\nThis script removes releases with no NZBs, resets all groups, truncates or drops(tpg) \n" - . "article tables. All other releases are left alone.\n" - . "php $argv[0] [true, drop] ...: To reset all groups and truncate/drop the tables.\n" + exit($pdo->log->error("\nThis script removes releases with no NZBs, resets all groups, truncates or drops(tpg) \n" + ."article tables. All other releases are left alone.\n" + ."php $argv[0] [true, drop] ...: To reset all groups and truncate/drop the tables.\n" ) ); } - diff --git a/misc/testing/DB/resetdb.php b/misc/testing/DB/resetdb.php index d4eb803c4..cf140f3e9 100644 --- a/misc/testing/DB/resetdb.php +++ b/misc/testing/DB/resetdb.php @@ -1,27 +1,30 @@ queryExec("TRUNCATE TABLE $value"); - if ($rel !== false) { - echo ColorCLI::primary("Truncating ${value} completed."); - } + $rel = $pdo->queryExec("TRUNCATE TABLE $value"); + if ($rel !== false) { + echo ColorCLI::primary("Truncating ${value} completed."); + } } unset($value); @@ -58,28 +61,28 @@ $pdo->optimise(false, 'full'); echo ColorCLI::header('Deleting nzbfiles subfolders.'); try { - $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(Settings::value('..nzbpath'), \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST); - foreach ($files as $file) { - if (basename($file) !== '.gitignore' && basename($file) !== 'tmpunrar') { - $todo = ($file->isDir() ? 'rmdir' : 'unlink'); - @$todo($file); - } - } + $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(Settings::value('..nzbpath'), \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST); + foreach ($files as $file) { + if (basename($file) !== '.gitignore' && basename($file) !== 'tmpunrar') { + $todo = ($file->isDir() ? 'rmdir' : 'unlink'); + @$todo($file); + } + } } catch (UnexpectedValueException $e) { - echo ColorCLI::error($e->getMessage()); + echo ColorCLI::error($e->getMessage()); } echo ColorCLI::header('Deleting all images, previews and samples that still remain.'); try { - $dirItr = new \RecursiveDirectoryIterator(NN_COVERS); - $itr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::LEAVES_ONLY); - foreach ($itr as $filePath) { - if (basename($filePath) !== '.gitignore' && basename($filePath) !== 'no-cover.jpg' && basename($filePath) !== 'no-backdrop.jpg') { - @unlink($filePath); - } - } + $dirItr = new \RecursiveDirectoryIterator(NN_COVERS); + $itr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::LEAVES_ONLY); + foreach ($itr as $filePath) { + if (basename($filePath) !== '.gitignore' && basename($filePath) !== 'no-cover.jpg' && basename($filePath) !== 'no-backdrop.jpg') { + @unlink($filePath); + } + } } catch (UnexpectedValueException $e) { - echo ColorCLI::error($e->getMessage()); + echo ColorCLI::error($e->getMessage()); } -echo ColorCLI::header('Deleted all releases, images, previews and samples. This script ran for ' . $consoletools->convertTime(time() - $timestart)); +echo ColorCLI::header('Deleted all releases, images, previews and samples. This script ran for '.$consoletools->convertTime(time() - $timestart)); diff --git a/misc/testing/DB/setUserPasswordHash.php b/misc/testing/DB/setUserPasswordHash.php index 9acd3e719..dd8cc8e0f 100644 --- a/misc/testing/DB/setUserPasswordHash.php +++ b/misc/testing/DB/setUserPasswordHash.php @@ -6,7 +6,7 @@ * reason, it will allow the password hash on the account to be changed. * Hopefully that will allow admin access to fix any further problems. */ -require_once dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\db\DB; use nntmux\Users; @@ -14,11 +14,11 @@ use nntmux\Users; $pdo = new DB(); if ($argc < 3) { - exit( + exit( $pdo->log->error( - 'Not enough parameters!' . PHP_EOL . - 'Argument 1: New password.' . PHP_EOL . - 'Argument 2: ID or username of the user.' . PHP_EOL + 'Not enough parameters!'.PHP_EOL. + 'Argument 1: New password.'.PHP_EOL. + 'Argument 2: ID or username of the user.'.PHP_EOL ) ); } @@ -26,36 +26,36 @@ if ($argc < 3) { $password = $argv[1]; $identifier = $argv[2]; if (is_numeric($password)) { - exit($pdo->log->error('Password cannot be numbers only!')); + exit($pdo->log->error('Password cannot be numbers only!')); } $field = (is_numeric($identifier) ? 'id' : 'username'); $user = $pdo->queryOneRow( sprintf( - "SELECT id, username FROM users WHERE %s = %s", + 'SELECT id, username FROM users WHERE %s = %s', $field, (is_numeric($identifier) ? $identifier : $pdo->escapeString($identifier)) ) ); if ($user !== false) { - $users = new Users(['Settings' => $pdo]); - $hash = $users->hashPassword($password); - $result = false; - if ($hash !== false) { - $hash = $pdo->queryExec( + $users = new Users(['Settings' => $pdo]); + $hash = $users->hashPassword($password); + $result = false; + if ($hash !== false) { + $hash = $pdo->queryExec( sprintf( 'UPDATE users SET password = %s WHERE id = %d', $hash, $user['id'] ) ); - } + } - if ($result === false || $hash === false) { - $pdo->log->error('An error occured during update attempt.' . PHP_EOL); - } else { - $pdo->log->headerOver("Updated {$user['username']}'s password hash to: ") . $pdo->log->primary("$hash"); - } + if ($result === false || $hash === false) { + $pdo->log->error('An error occured during update attempt.'.PHP_EOL); + } else { + $pdo->log->headerOver("Updated {$user['username']}'s password hash to: ").$pdo->log->primary("$hash"); + } } else { - $pdo->log->error("Unable to find {$field} '{$identifier}' in the users. Cannot change password."); + $pdo->log->error("Unable to find {$field} '{$identifier}' in the users. Cannot change password."); } diff --git a/misc/testing/DB/setUserPasswordHashesToEmail.php b/misc/testing/DB/setUserPasswordHashesToEmail.php index a9b12c0a8..38369d049 100644 --- a/misc/testing/DB/setUserPasswordHashesToEmail.php +++ b/misc/testing/DB/setUserPasswordHashesToEmail.php @@ -1,6 +1,6 @@ . */ -require_once dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\db\DB; -use nntmux\ColorCLI; use nntmux\Users; +use nntmux\ColorCLI; $colorCLI = new ColorCLI(); -$warning = <<warning($warning); if ($argc != 2) { - exit($colorCLI->error("\nWrong number of parameters$usage")); -} else if ($argv[1] !== 1 && $argv[1] != '' && $argv[1] != 'IUnderStandTheRisks' && $argv[1] != 'true') { - exit($colorCLI->error("\nInvalid parameter(s)$usage")); + exit($colorCLI->error("\nWrong number of parameters$usage")); +} elseif ($argv[1] !== 1 && $argv[1] != '' && $argv[1] != 'IUnderStandTheRisks' && $argv[1] != 'true') { + exit($colorCLI->error("\nInvalid parameter(s)$usage")); } $pdo = new DB(); -$users = $pdo->query("SELECT id, username, email, password FROM users"); +$users = $pdo->query('SELECT id, username, email, password FROM users'); $update = $pdo->Prepare('UPDATE users SET password = :password WHERE id = :id'); $Users = new Users(['Settings' => $pdo]); foreach ($users as $user) { - if (needUpdate($user)) { - $hash = $Users->hashPassword($user['email']); - if ($hash !== false) { - $update->execute([':password' => $hash, ':id' => $user['id']]); - echo $colorCLI->primary('Updating hash for user:') . $user['username']; - } else { - echo $colorCLI->error('Error updating hash for user:') . $user['username']; - } - } + if (needUpdate($user)) { + $hash = $Users->hashPassword($user['email']); + if ($hash !== false) { + $update->execute([':password' => $hash, ':id' => $user['id']]); + echo $colorCLI->primary('Updating hash for user:').$user['username']; + } else { + echo $colorCLI->error('Error updating hash for user:').$user['username']; + } + } } function needUpdate($user) { - global $colorCLI; - $status = true; - if (empty($user['email'])) { - $status = false; - echo $colorCLI->error('Cannot update password hash - Email is not set for user: ' . $user['username']); - } else if (preg_match('#^\$.+$#', $user['password'])) { - $status = false; - echo $user['username'] . $colorCLI->primary(' is already using new style hash ;-)'); - } - return $status; + global $colorCLI; + $status = true; + if (empty($user['email'])) { + $status = false; + echo $colorCLI->error('Cannot update password hash - Email is not set for user: '.$user['username']); + } elseif (preg_match('#^\$.+$#', $user['password'])) { + $status = false; + echo $user['username'].$colorCLI->primary(' is already using new style hash ;-)'); + } + + return $status; } diff --git a/misc/testing/DB/show_table_sizes.php b/misc/testing/DB/show_table_sizes.php index e93c09705..0a93af47c 100644 --- a/misc/testing/DB/show_table_sizes.php +++ b/misc/testing/DB/show_table_sizes.php @@ -1,67 +1,68 @@ log->error("\nThis script will show table data, index and free space used. The argument needed is numeric.\n\n" - . "php $argv[0] 1 ...: To show all tables with data + index space used greater than 1MB or free space greater than 1MB.\n" - . "php $argv[0] .01 ...: To show all tables with data + index space used greater than .01MB or free space greater than .01MB.\n")); +if ($argc === 1 || ! is_numeric($argv[1])) { + exit($pdo->log->error("\nThis script will show table data, index and free space used. The argument needed is numeric.\n\n" + ."php $argv[0] 1 ...: To show all tables with data + index space used greater than 1MB or free space greater than 1MB.\n" + ."php $argv[0] .01 ...: To show all tables with data + index space used greater than .01MB or free space greater than .01MB.\n")); } passthru('clear'); $data = $index = $total = $free = 0; $table_data = "SELECT TABLE_NAME AS 'Table', TABLE_ROWS AS 'Rows', " - . "ENGINE AS 'engine', " - . "CREATE_OPTIONS AS 'format', " - . "((DATA_LENGTH) / POWER(1024,2)) AS 'data', " - . "((INDEX_LENGTH) / POWER(1024,2)) AS 'index', " - . "((DATA_FREE) / POWER(1024,2)) AS 'free', " - . "((DATA_LENGTH + INDEX_LENGTH) / POWER(1024,2)) AS 'total' " - . "FROM information_schema.TABLES WHERE information_schema.TABLES.table_schema = '" . env('DB_NAME') . "' " - . "ORDER BY (DATA_LENGTH + INDEX_LENGTH) DESC"; + ."ENGINE AS 'engine', " + ."CREATE_OPTIONS AS 'format', " + ."((DATA_LENGTH) / POWER(1024,2)) AS 'data', " + ."((INDEX_LENGTH) / POWER(1024,2)) AS 'index', " + ."((DATA_FREE) / POWER(1024,2)) AS 'free', " + ."((DATA_LENGTH + INDEX_LENGTH) / POWER(1024,2)) AS 'total' " + ."FROM information_schema.TABLES WHERE information_schema.TABLES.table_schema = '".env('DB_NAME')."' " + .'ORDER BY (DATA_LENGTH + INDEX_LENGTH) DESC'; $run = $pdo->queryDirect($table_data); -$mask = $pdo->log->headerOver("%-25.25s ") . $pdo->log->primaryOver("%7.7s %10.10s %15.15s %15.15s %15.15s %15.15s\n"); +$mask = $pdo->log->headerOver('%-25.25s ').$pdo->log->primaryOver("%7.7s %10.10s %15.15s %15.15s %15.15s %15.15s\n"); printf($mask, 'Table Name', 'Engine', 'Row_Format', 'Data Size', 'Index Size', 'Free Space', 'Total Size'); printf($mask, '=========================', '=======', '==========', '===============', '===============', '===============', '==============='); if ($run instanceof \Traversable) { - foreach ($run as $table) { - if ($table['total'] > $argv[1] || $table['free'] > $argv[1]) { - printf($mask, $table['table'], $table['engine'], str_replace('row_format=', '', $table['format']), number_format($table['data'], 2) . " MB", number_format($table['index'], 2) . " MB", number_format($table['free'], 2) . " MB", number_format($table['total'], 2) . " MB"); - } - $data += $table['data']; - $index += $table['index']; - $free += $table['free']; - $total += $table['total']; - } + foreach ($run as $table) { + if ($table['total'] > $argv[1] || $table['free'] > $argv[1]) { + printf($mask, $table['table'], $table['engine'], str_replace('row_format=', '', $table['format']), number_format($table['data'], 2).' MB', number_format($table['index'], 2).' MB', number_format($table['free'], 2).' MB', number_format($table['total'], 2).' MB'); + } + $data += $table['data']; + $index += $table['index']; + $free += $table['free']; + $total += $table['total']; + } } printf($mask, '=========================', '=======', '==========', '===============', '===============', '===============', '==============='); printf($mask, 'Table Name', 'Engine', 'Row_Format', 'Data Size', 'Index Size', 'Free Space', 'Total Size'); -printf($mask, '', '', '', number_format($data, 2) . " MB", number_format($index, 2) . " MB", number_format($free, 2) . " MB", number_format($total, 2) . " MB"); +printf($mask, '', '', '', number_format($data, 2).' MB', number_format($index, 2).' MB', number_format($free, 2).' MB', number_format($total, 2).' MB'); -$myisam = $pdo->queryOneRow("SELECT CONCAT(ROUND(KBS/POWER(1024,IF(pw<0,0,IF(pw>3,0,pw)))+0.49999), " - . "SUBSTR(' KMG',IF(pw<0,0,IF(pw>3,0,pw))+1,1)) recommended_key_buffer_size " - . "FROM (SELECT SUM(index_length) KBS " - . "FROM information_schema.tables " - . "WHERE engine='MyISAM' AND table_schema NOT IN ('information_schema','mysql')) A, (SELECT 3 pw) B;", false); +$myisam = $pdo->queryOneRow('SELECT CONCAT(ROUND(KBS/POWER(1024,IF(pw<0,0,IF(pw>3,0,pw)))+0.49999), ' + ."SUBSTR(' KMG',IF(pw<0,0,IF(pw>3,0,pw))+1,1)) recommended_key_buffer_size " + .'FROM (SELECT SUM(index_length) KBS ' + .'FROM information_schema.tables ' + ."WHERE engine='MyISAM' AND table_schema NOT IN ('information_schema','mysql')) A, (SELECT 3 pw) B;", false); -$innodb = $pdo->queryOneRow("SELECT CONCAT(ROUND(KBS/POWER(1024,IF(pw<0,0,IF(pw>3,0,pw)))+0.49999), " - . "SUBSTR(' KMG',IF(pw<0,0,IF(pw>3,0,pw))+1,1)) recommended_innodb_buffer_pool_size " - . "FROM (SELECT SUM(index_length) KBS " - . "FROM information_schema.tables " - . "WHERE engine='InnoDB') A,(SELECT 3 pw) B;", false); +$innodb = $pdo->queryOneRow('SELECT CONCAT(ROUND(KBS/POWER(1024,IF(pw<0,0,IF(pw>3,0,pw)))+0.49999), ' + ."SUBSTR(' KMG',IF(pw<0,0,IF(pw>3,0,pw))+1,1)) recommended_innodb_buffer_pool_size " + .'FROM (SELECT SUM(index_length) KBS ' + .'FROM information_schema.tables ' + ."WHERE engine='InnoDB') A,(SELECT 3 pw) B;", false); $a = $myisam['recommended_key_buffer_size']; if ($myisam['recommended_key_buffer_size'] === null) { - $a = '12M'; + $a = '12M'; } $b = $innodb['recommended_innodb_buffer_pool_size']; if ($innodb['recommended_innodb_buffer_pool_size'] === null) { - $b = '12M'; + $b = '12M'; } // Get current variables @@ -69,24 +70,24 @@ $aa = $pdo->queryOneRow("SHOW VARIABLES WHERE Variable_name = 'key_buffer_size'" $bb = $pdo->queryOneRow("SHOW VARIABLES WHERE Variable_name = 'innodb_buffer_pool_size'", false); if ($aa['value'] >= 1073741824) { - $current_a = $aa['value'] / 1024 / 1024 / 1024; - $current_a .= "G"; + $current_a = $aa['value'] / 1024 / 1024 / 1024; + $current_a .= 'G'; } else { - $current_a = $aa['value'] / 1024 / 1024; - $current_a .= "M"; + $current_a = $aa['value'] / 1024 / 1024; + $current_a .= 'M'; } if ($bb['value'] >= 1073741824) { - $current_b = $bb['value'] / 1024 / 1024 / 1024; - $current_b .= "G"; + $current_b = $bb['value'] / 1024 / 1024 / 1024; + $current_b .= 'G'; } else { - $current_b = $bb['value'] / 1024 / 1024; - $current_b .= "M"; + $current_b = $bb['value'] / 1024 / 1024; + $current_b .= 'M'; } echo $pdo->log->headerOver("\n\nThe recommended minimums are:\n"); -echo $pdo->log->primaryOver("MyISAM: key-buffer-size = ") . $pdo->log->alternate($a); -echo $pdo->log->primaryOver("InnoDB: innodb_buffer_pool_size = ") . $pdo->log->alternate($b); +echo $pdo->log->primaryOver('MyISAM: key-buffer-size = ').$pdo->log->alternate($a); +echo $pdo->log->primaryOver('InnoDB: innodb_buffer_pool_size = ').$pdo->log->alternate($b); echo $pdo->log->headerOver("\nYour current setting are:\n"); -echo $pdo->log->primaryOver("MyISAM: key-buffer-size = ") . $pdo->log->alternate($current_a); -echo $pdo->log->primaryOver("InnoDB: innodb_buffer_pool_size = ") . $pdo->log->alternate($current_b); +echo $pdo->log->primaryOver('MyISAM: key-buffer-size = ').$pdo->log->alternate($current_a); +echo $pdo->log->primaryOver('InnoDB: innodb_buffer_pool_size = ').$pdo->log->alternate($current_b); diff --git a/misc/testing/Dev/clean_nzbs.php b/misc/testing/Dev/clean_nzbs.php index 2df205ee3..9b0e6008f 100644 --- a/misc/testing/Dev/clean_nzbs.php +++ b/misc/testing/Dev/clean_nzbs.php @@ -1,34 +1,35 @@ log->error("\nThis script can remove all nzbs not found in the db and all releases with no nzbs found. It can also move invalid nzbs.\n\n" - . "php $argv[0] true ...: For a dry run, to see how many would be moved.\n" - . "php $argv[0] move ...: Move NZBs that are possibly bad or have no release. They are moved into this folder: $dir\n")); +if (! isset($argv[1]) || ! in_array($argv[1], ['true', 'move'])) { + exit($pdo->log->error("\nThis script can remove all nzbs not found in the db and all releases with no nzbs found. It can also move invalid nzbs.\n\n" + ."php $argv[0] true ...: For a dry run, to see how many would be moved.\n" + ."php $argv[0] move ...: Move NZBs that are possibly bad or have no release. They are moved into this folder: $dir\n")); } -if (!is_dir($dir) && !mkdir($dir)) { - exit("ERROR: Could not create folder [$dir]." . PHP_EOL); +if (! is_dir($dir) && ! mkdir($dir)) { + exit("ERROR: Could not create folder [$dir].".PHP_EOL); } $releases = new Releases(['Settings' => $pdo]); $nzb = new NZB($pdo); $releaseImage = new ReleaseImage($pdo); -$timestart = date("r"); +$timestart = date('r'); $checked = $moved = 0; -$couldbe = ($argv[1] === "true") ? "could be " : ""; +$couldbe = ($argv[1] === 'true') ? 'could be ' : ''; echo $pdo->log->header('Getting List of nzbs to check against db.'); echo $pdo->log->header("Checked / {$couldbe}moved\n"); @@ -37,41 +38,41 @@ $dirItr = new \RecursiveDirectoryIterator(Settings::value('..nzbpath')); $itr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::LEAVES_ONLY); foreach ($itr as $filePath) { - $guid = stristr($filePath->getFilename(), '.nzb.gz', true); - if (is_file($filePath) && $guid) { - $nzbfile = Utility::unzipGzipFile($filePath); - $nzbContents = $nzb->nzbFileList($nzbfile, ['no-file-key' => false, 'strip-count' => true]); - if (!$nzbfile || !@simplexml_load_string($nzbfile) || count($nzbContents) === 0) { - if ($argv[1] === "move") { - rename($filePath, $dir . $guid . ".nzb.gz"); - } - $releases->deleteSingle(['g' => $guid, 'i' => false], $nzb, $releaseImage); - $moved++; - } - ++$checked; - echo "$checked / $moved\r"; - } + $guid = stristr($filePath->getFilename(), '.nzb.gz', true); + if (is_file($filePath) && $guid) { + $nzbfile = Utility::unzipGzipFile($filePath); + $nzbContents = $nzb->nzbFileList($nzbfile, ['no-file-key' => false, 'strip-count' => true]); + if (! $nzbfile || ! @simplexml_load_string($nzbfile) || count($nzbContents) === 0) { + if ($argv[1] === 'move') { + rename($filePath, $dir.$guid.'.nzb.gz'); + } + $releases->deleteSingle(['g' => $guid, 'i' => false], $nzb, $releaseImage); + $moved++; + } + ++$checked; + echo "$checked / $moved\r"; + } } -echo $pdo->log->header("\n" . number_format($checked) . ' nzbs checked, ' . number_format($moved) . ' nzbs ' . $couldbe . 'moved.'); -echo $pdo->log->header("Getting List of releases to check against nzbs."); +echo $pdo->log->header("\n".number_format($checked).' nzbs checked, '.number_format($moved).' nzbs '.$couldbe.'moved.'); +echo $pdo->log->header('Getting List of releases to check against nzbs.'); echo $pdo->log->header("Checked / releases deleted\n"); $checked = $deleted = 0; $res = $pdo->queryDirect('SELECT id, guid, nzbstatus FROM releases'); if ($res instanceof \Traversable) { - foreach ($res as $row) { - $nzbpath = $nzb->getNZBPath($row["guid"]); - if (!is_file($nzbpath)) { - ++$deleted; - $releases->deleteSingle(['g' => $row['guid'], 'i' => $row['id']], $nzb, $releaseImage); - } elseif ($row["nzbstatus"] != 1) { - $pdo->queryExec(sprintf("UPDATE releases SET nzbstatus = 1 WHERE id = %d", $row['id'])); - } - ++$checked; - echo "$checked / $deleted\r"; - } + foreach ($res as $row) { + $nzbpath = $nzb->getNZBPath($row['guid']); + if (! is_file($nzbpath)) { + ++$deleted; + $releases->deleteSingle(['g' => $row['guid'], 'i' => $row['id']], $nzb, $releaseImage); + } elseif ($row['nzbstatus'] != 1) { + $pdo->queryExec(sprintf('UPDATE releases SET nzbstatus = 1 WHERE id = %d', $row['id'])); + } + ++$checked; + echo "$checked / $deleted\r"; + } } -echo $pdo->log->header("\n" . number_format($checked) . " releases checked, " . number_format($deleted) . " releases deleted."); -echo $pdo->log->header("Script started at [$timestart], finished at [" . date("r") . "]"); +echo $pdo->log->header("\n".number_format($checked).' releases checked, '.number_format($deleted).' releases deleted.'); +echo $pdo->log->header("Script started at [$timestart], finished at [".date('r').']'); diff --git a/misc/testing/Dev/test-ReleaseCleaner.php b/misc/testing/Dev/test-ReleaseCleaner.php index 4583b7718..0eaf1f0b0 100755 --- a/misc/testing/Dev/test-ReleaseCleaner.php +++ b/misc/testing/Dev/test-ReleaseCleaner.php @@ -1,37 +1,38 @@ queryOneRow(sprintf('SELECT id FROM groups WHERE name = %s', $pdo->escapeString($argv[1]))); if ($group === false) { - exit('No group with name ' . $argv[1] . ' found in the database.'); + exit('No group with name '.$argv[1].' found in the database.'); } $releases = $pdo->query(sprintf('SELECT name, searchname, fromname, size, id FROM releases WHERE groups_id = %d %s ORDER BY postdate LIMIT %d', $group['id'], $category, $argv[2])); if (count($releases) === 0) { - exit('No releases found in your database for group ' . $argv[1] . PHP_EOL); + exit('No releases found in your database for group '.$argv[1].PHP_EOL); } $RC = new ReleaseCleaning($pdo); $sphinx = new SphinxSearch(); foreach ($releases as $release) { - $newName = $RC->releaseCleaner($release['name'], $release['fromname'], $release['size'], $argv[1]); - if (is_array($newName)) { - $newName = $newName['cleansubject']; - } - if ($newName !== $release['searchname']) { - echo 'Old name: ' . $release['searchname'] . PHP_EOL; - echo 'New name: ' . $newName . PHP_EOL . PHP_EOL; + $newName = $RC->releaseCleaner($release['name'], $release['fromname'], $release['size'], $argv[1]); + if (is_array($newName)) { + $newName = $newName['cleansubject']; + } + if ($newName !== $release['searchname']) { + echo 'Old name: '.$release['searchname'].PHP_EOL; + echo 'New name: '.$newName.PHP_EOL.PHP_EOL; - if ($rename === true) { - $newName = $pdo->escapeString($newName); - $pdo->queryExec(sprintf('UPDATE releases SET searchname = %s WHERE id = %d', $newName, $release['id'])); - $sphinx->updateRelease($release['id'], $pdo); - } - } + if ($rename === true) { + $newName = $pdo->escapeString($newName); + $pdo->queryExec(sprintf('UPDATE releases SET searchname = %s WHERE id = %d', $newName, $release['id'])); + $sphinx->updateRelease($release['id'], $pdo); + } + } } diff --git a/misc/testing/Dev/test_hash_algorithms.php b/misc/testing/Dev/test_hash_algorithms.php index e5ef0d4f5..54a653fad 100644 --- a/misc/testing/Dev/test_hash_algorithms.php +++ b/misc/testing/Dev/test_hash_algorithms.php @@ -1,165 +1,162 @@ _inputString = $inputString; - $this->_expectedString = array( + /** + * @param string $inputString + * @param string $expectedString + * @param bool $writeToFile + */ + public function __construct($inputString, $expectedString, $writeToFile) + { + $this->_inputString = $inputString; + $this->_expectedString = [ $expectedString, strtolower($expectedString), strtoupper($expectedString), - strrev($expectedString) - ); - $this->_writeToFile = $writeToFile; - $this->_testStrings(); - } + strrev($expectedString), + ]; + $this->_writeToFile = $writeToFile; + $this->_testStrings(); + } - /** - * Test various hash algorithms on strings. - * - * @access protected - * @void - */ - protected function _testStrings() - { - if ($this->_writeToFile) { - file_put_contents('hash_matches.txt', ''); - } + /** + * Test various hash algorithms on strings. + * + * @void + */ + protected function _testStrings() + { + if ($this->_writeToFile) { + file_put_contents('hash_matches.txt', ''); + } - $firstArray = $this->_hashesToArray($this->_inputString); + $firstArray = $this->_hashesToArray($this->_inputString); - $secondArray = []; - foreach ($firstArray as $key => $value) { - if (!$this->_writeToFile) { - if (in_array($value, $this->_expectedString)) { - exit( - '[' . - $this->_inputString . - ']=>[' . - $key . - ']=>' . - $value . - ']' . + $secondArray = []; + foreach ($firstArray as $key => $value) { + if (! $this->_writeToFile) { + if (in_array($value, $this->_expectedString)) { + exit( + '['. + $this->_inputString. + ']=>['. + $key. + ']=>'. + $value. + ']'. PHP_EOL ); - } - } else { - file_put_contents('hash_matches.txt', $key . "\t\t" . $value . PHP_EOL, FILE_APPEND); - } - $secondArray[$key] = $this->_hashesToArray($value); - } + } + } else { + file_put_contents('hash_matches.txt', $key."\t\t".$value.PHP_EOL, FILE_APPEND); + } + $secondArray[$key] = $this->_hashesToArray($value); + } - $thirdArray = []; - foreach ($secondArray as $key => $value) { - foreach ($value as $key2 => $value2) { - if (!$this->_writeToFile) { - if (in_array($value2, $this->_expectedString)) { - exit( - '[' . - $this->_inputString . - ']=>[' . - $key . - ']=>[' . - $firstArray[$key] . - ']=>[' . - $key2 . - ']=>[' . - $value2 . - ']' . + $thirdArray = []; + foreach ($secondArray as $key => $value) { + foreach ($value as $key2 => $value2) { + if (! $this->_writeToFile) { + if (in_array($value2, $this->_expectedString)) { + exit( + '['. + $this->_inputString. + ']=>['. + $key. + ']=>['. + $firstArray[$key]. + ']=>['. + $key2. + ']=>['. + $value2. + ']'. PHP_EOL ); - } - } else { - file_put_contents('hash_matches.txt', $key . ' => ' . $key2 . "\t\t" . $value2 . PHP_EOL, FILE_APPEND); - } - $thirdArray[$key][$key2] = $this->_hashesToArray($value2); - } - } + } + } else { + file_put_contents('hash_matches.txt', $key.' => '.$key2."\t\t".$value2.PHP_EOL, FILE_APPEND); + } + $thirdArray[$key][$key2] = $this->_hashesToArray($value2); + } + } - foreach ($thirdArray as $key => $value) { - foreach ($value as $key2 => $value2) { - foreach ($value2 as $key3 => $value3) { - if (!$this->_writeToFile) { - if (in_array($value3, $this->_expectedString)) { - exit( - '[' . - $this->_inputString . - ']=>[' . - $key . - ']=>[' . - $firstArray[$key] . - ']=>[' . - $key2 . - ']=>[' . - $value2 . - ']=>[' . - $key3 . - ']=>[' . - $value3 . - ']' . + foreach ($thirdArray as $key => $value) { + foreach ($value as $key2 => $value2) { + foreach ($value2 as $key3 => $value3) { + if (! $this->_writeToFile) { + if (in_array($value3, $this->_expectedString)) { + exit( + '['. + $this->_inputString. + ']=>['. + $key. + ']=>['. + $firstArray[$key]. + ']=>['. + $key2. + ']=>['. + $value2. + ']=>['. + $key3. + ']=>['. + $value3. + ']'. PHP_EOL ); - } - } else { - file_put_contents('hash_matches.txt', - $key . ' => ' . $key2 . ' => ' . $key3 . "\t\t" . $value3 . PHP_EOL, FILE_APPEND + } + } else { + file_put_contents('hash_matches.txt', + $key.' => '.$key2.' => '.$key3."\t\t".$value3.PHP_EOL, FILE_APPEND ); - } - } - } - } - } + } + } + } + } + } - /** - * Return various versions of a input string to hash. - * - * @param string $string - * - * @return array - */ - protected function _hashesToArray($string) - { - $strings = array( + /** + * Return various versions of a input string to hash. + * + * @param string $string + * + * @return array + */ + protected function _hashesToArray($string) + { + $strings = [ 'input' => $string, 'lower' => strtolower($string), 'lower_reverse' => strtolower(strrev($string)), @@ -168,24 +165,24 @@ class HashAlgorithms 'reverse' => strrev($string), 'reverse_upper' => strrev(strtoupper($string)), 'reverse_lower' => strrev(strtolower($string)), - ); + ]; - $hashTypes = array('md5', 'md4', 'sha1', 'sha256', 'sha512'); - $tmpArray = []; - foreach ($hashTypes as $hash) { - foreach ($strings as $key => $value) { - $tmpArray[$hash . '_' . $key] = hash($hash, $value, false); - } - } + $hashTypes = ['md5', 'md4', 'sha1', 'sha256', 'sha512']; + $tmpArray = []; + foreach ($hashTypes as $hash) { + foreach ($strings as $key => $value) { + $tmpArray[$hash.'_'.$key] = hash($hash, $value, false); + } + } - foreach ($strings as $key => $value) { - $tmpArray['input_' . $key] = $value; - $tmpArray['base64_' . $key] = base64_encode($value); - $tmpArray['crc32_' . $key] = crc32($value); - } + foreach ($strings as $key => $value) { + $tmpArray['input_'.$key] = $value; + $tmpArray['base64_'.$key] = base64_encode($value); + $tmpArray['crc32_'.$key] = crc32($value); + } - return $tmpArray; - } + return $tmpArray; + } } new HashAlgorithms($argv[1], $argv[2], ((isset($argv[3]) && strtolower($argv[3]) === 'true') ? true : false)); diff --git a/misc/testing/NZB/nzb-reorg.php b/misc/testing/NZB/nzb-reorg.php index 2ab6bfe30..8ce6be09f 100755 --- a/misc/testing/NZB/nzb-reorg.php +++ b/misc/testing/NZB/nzb-reorg.php @@ -1,12 +1,13 @@ $nzbFile) { - if ($nzbFile->getExtension() != "gz") { - continue; - } + if ($nzbFile->getExtension() != 'gz') { + continue; + } - $newFileName = $nzb->getNZBPath(str_replace(".nzb.gz", "", $nzbFile->getBasename()), + $newFileName = $nzb->getNZBPath(str_replace('.nzb.gz', '', $nzbFile->getBasename()), $newLevel, true); - if ($newFileName != $nzbFile) { - rename($nzbFile, $newFileName); - chmod($newFileName, 0777); - } - $iFilesProcessed++; - if ($iFilesProcessed % 100 == 0) { - $consoleTools->overWrite("Reorganized $iFilesProcessed"); - } + if ($newFileName != $nzbFile) { + rename($nzbFile, $newFileName); + chmod($newFileName, 0777); + } + $iFilesProcessed++; + if ($iFilesProcessed % 100 == 0) { + $consoleTools->overWrite("Reorganized $iFilesProcessed"); + } } $pdo->ping(true); $pdo->queryExec(sprintf("UPDATE settings SET value = %s WHERE setting = 'nzbsplitlevel'", $argv[1])); -$consoleTools->overWrite("Processed $iFilesProcessed nzbs in " . relativeTime($time) . "\n"); +$consoleTools->overWrite("Processed $iFilesProcessed nzbs in ".relativeTime($time)."\n"); function relativeTime($_time) { - $d = array(); - $d[0] = array(1, "sec"); - $d[1] = array(60, "min"); - $d[2] = array(3600, "hr"); - $d[3] = array(86400, "day"); - $d[4] = array(31104000, "yr"); + $d = []; + $d[0] = [1, 'sec']; + $d[1] = [60, 'min']; + $d[2] = [3600, 'hr']; + $d[3] = [86400, 'day']; + $d[4] = [31104000, 'yr']; - $w = array(); + $w = []; - $return = ""; - $now = time(); - $diff = ($now - $_time); - $secondsLeft = $diff; + $return = ''; + $now = time(); + $diff = ($now - $_time); + $secondsLeft = $diff; - for ($i = 4; $i > -1; $i--) { - $w[$i] = intval($secondsLeft / $d[$i][0]); - $secondsLeft -= ($w[$i] * $d[$i][0]); - if ($w[$i] != 0) { - $return .= $w[$i] . " " . $d[$i][1] . (($w[$i] > 1) ? 's' : '') . " "; - } - } - return $return; + for ($i = 4; $i > -1; $i--) { + $w[$i] = intval($secondsLeft / $d[$i][0]); + $secondsLeft -= ($w[$i] * $d[$i][0]); + if ($w[$i] != 0) { + $return .= $w[$i].' '.$d[$i][1].(($w[$i] > 1) ? 's' : '').' '; + } + } + + return $return; } - -?> diff --git a/misc/testing/PostProc/check_covers.php b/misc/testing/PostProc/check_covers.php index a1d4ed69b..86cdf7494 100644 --- a/misc/testing/PostProc/check_covers.php +++ b/misc/testing/PostProc/check_covers.php @@ -1,62 +1,63 @@ true, 'Settings' => $pdo]); $row = $pdo->queryOneRow("SELECT value FROM settings WHERE setting = 'coverspath'"); if ($row !== false) { - Utility::setCoversConstant($row['value']); + Utility::setCoversConstant($row['value']); } else { - die('Unable to determine covers path!' . PHP_EOL); + die('Unable to determine covers path!'.PHP_EOL); } -$path2cover = NN_COVERS . 'movies' . DS; +$path2cover = NN_COVERS.'movies'.DS; if (isset($argv[1]) && ($argv[1] === 'true' || $argv[1] === 'check')) { - $couldbe = $argv[1] === 'true' ? $couldbe = 'had ' : 'could have '; - $limit = $counterfixed = 0; - if (isset($argv[2]) && is_numeric($argv[2])) { - $limit = $argv[2]; - } - echo ColorCLI::header('Scanning for releases missing covers'); - $res = $pdo->queryDirect('SELECT r.id, r.imdbid + $couldbe = $argv[1] === 'true' ? $couldbe = 'had ' : 'could have '; + $limit = $counterfixed = 0; + if (isset($argv[2]) && is_numeric($argv[2])) { + $limit = $argv[2]; + } + echo ColorCLI::header('Scanning for releases missing covers'); + $res = $pdo->queryDirect('SELECT r.id, r.imdbid FROM releases r LEFT JOIN movieinfo m ON m.imdbid = r.imdbid WHERE nzbstatus = 1 AND m.cover = 1 AND adddate > (NOW() - INTERVAL 5 HOUR)'); - if ($res instanceof \Traversable) { - foreach ($res as $row) { - $nzbpath = $path2cover . $row['imdbid'] . '-cover.jpg'; - if (!file_exists($nzbpath)) { - $counterfixed++; - echo ColorCLI::warning('Missing cover ' . $nzbpath); - if ($argv[1] === 'true') { - $cover = $movie->updateMovieInfo($row['imdbid']); - if($cover === false || !file_exists($nzbpath)) { - $pdo->queryExec('UPDATE movieinfo m SET m.cover = 0 WHERE m.imdbid = %d', $row['imdbid']); - } - } - } + if ($res instanceof \Traversable) { + foreach ($res as $row) { + $nzbpath = $path2cover.$row['imdbid'].'-cover.jpg'; + if (! file_exists($nzbpath)) { + $counterfixed++; + echo ColorCLI::warning('Missing cover '.$nzbpath); + if ($argv[1] === 'true') { + $cover = $movie->updateMovieInfo($row['imdbid']); + if ($cover === false || ! file_exists($nzbpath)) { + $pdo->queryExec('UPDATE movieinfo m SET m.cover = 0 WHERE m.imdbid = %d', $row['imdbid']); + } + } + } - if (($limit > 0) && ($counterfixed >= $limit)) { - break; - } - } - } - echo ColorCLI::header('Total releases missing covers that ' . $couldbe . 'their covers fixed = ' . number_format($counterfixed)); + if (($limit > 0) && ($counterfixed >= $limit)) { + break; + } + } + } + echo ColorCLI::header('Total releases missing covers that '.$couldbe.'their covers fixed = '.number_format($counterfixed)); } else { - exit(ColorCLI::header("\nThis script checks if release covers actually exist on disk.\n\n" - . "Releases without covers may be reset for post-processing, thus regenerating them and related meta data.\n\n" - . "Useful for recovery after filesystem corruption, or as an alternative re-postprocessing tool.\n\n" - . "Optional LIMIT parameter restricts number of releases to be reset.\n\n" - . "php $argv[0] check [LIMIT] ...: Dry run, displays missing covers.\n" - . "php $argv[0] true [LIMIT] ...: Re-process releases missing covers.\n")); + exit(ColorCLI::header("\nThis script checks if release covers actually exist on disk.\n\n" + ."Releases without covers may be reset for post-processing, thus regenerating them and related meta data.\n\n" + ."Useful for recovery after filesystem corruption, or as an alternative re-postprocessing tool.\n\n" + ."Optional LIMIT parameter restricts number of releases to be reset.\n\n" + ."php $argv[0] check [LIMIT] ...: Dry run, displays missing covers.\n" + ."php $argv[0] true [LIMIT] ...: Re-process releases missing covers.\n")); } diff --git a/misc/testing/PostProc/check_previews.php b/misc/testing/PostProc/check_previews.php index 871b16907..bf3f4ae6d 100644 --- a/misc/testing/PostProc/check_previews.php +++ b/misc/testing/PostProc/check_previews.php @@ -1,62 +1,63 @@ queryOneRow("SELECT value FROM settings WHERE setting = 'coverspath'"); if ($row !== false) { - Utility::setCoversConstant($row['value']); + Utility::setCoversConstant($row['value']); } else { - die("Unable to determine covers path!\n"); + die("Unable to determine covers path!\n"); } -$path2preview = NN_COVERS . 'preview' . DS; +$path2preview = NN_COVERS.'preview'.DS; -if (isset($argv[1]) && ($argv[1] === "true" || $argv[1] === "check")) { - $releases = new Releases(['Settings' => $pdo]); - $nzb = new NZB($pdo); - $releaseImage = new ReleaseImage($pdo); - $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); - $couldbe = $argv[1] === "true" ? $couldbe = "were " : "could be "; - $limit = $counterfixed = 0; - if (isset($argv[2]) && is_numeric($argv[2])) { - $limit = $argv[2]; - } - echo $pdo->log->header("Scanning for releases missing previews"); - $res = $pdo->queryDirect("SELECT id, guid FROM releases where nzbstatus = 1 AND haspreview = 1"); - if ($res instanceof \Traversable) { - foreach ($res as $row) { - $nzbpath = $path2preview . $row["guid"] . "_thumb.jpg"; - if (!file_exists($nzbpath)) { - $counterfixed++; - echo $pdo->log->warning("Missing preview " . $nzbpath); - if ($argv[1] === "true") { - $pdo->queryExec( - sprintf("UPDATE releases SET consoleinfo_id = NULL, gamesinfo_id = 0, imdbid = NULL, musicinfo_id = NULL, bookinfo_id = NULL, videos_id = 0, xxxinfo_id = 0, passwordstatus = -1, haspreview = -1, jpgstatus = 0, videostatus = 0, audiostatus = 0, nfostatus = -1 WHERE id = %s", $row['id'])); - } - } +if (isset($argv[1]) && ($argv[1] === 'true' || $argv[1] === 'check')) { + $releases = new Releases(['Settings' => $pdo]); + $nzb = new NZB($pdo); + $releaseImage = new ReleaseImage($pdo); + $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); + $couldbe = $argv[1] === 'true' ? $couldbe = 'were ' : 'could be '; + $limit = $counterfixed = 0; + if (isset($argv[2]) && is_numeric($argv[2])) { + $limit = $argv[2]; + } + echo $pdo->log->header('Scanning for releases missing previews'); + $res = $pdo->queryDirect('SELECT id, guid FROM releases where nzbstatus = 1 AND haspreview = 1'); + if ($res instanceof \Traversable) { + foreach ($res as $row) { + $nzbpath = $path2preview.$row['guid'].'_thumb.jpg'; + if (! file_exists($nzbpath)) { + $counterfixed++; + echo $pdo->log->warning('Missing preview '.$nzbpath); + if ($argv[1] === 'true') { + $pdo->queryExec( + sprintf('UPDATE releases SET consoleinfo_id = NULL, gamesinfo_id = 0, imdbid = NULL, musicinfo_id = NULL, bookinfo_id = NULL, videos_id = 0, xxxinfo_id = 0, passwordstatus = -1, haspreview = -1, jpgstatus = 0, videostatus = 0, audiostatus = 0, nfostatus = -1 WHERE id = %s', $row['id'])); + } + } - if (($limit > 0) && ($counterfixed >= $limit)) { - break; - } // QUAD! - } - } - echo $pdo->log->header("Total releases missing previews that " . $couldbe . "reset for reprocessing= " . number_format($counterfixed)); + if (($limit > 0) && ($counterfixed >= $limit)) { + break; + } // QUAD! + } + } + echo $pdo->log->header('Total releases missing previews that '.$couldbe.'reset for reprocessing= '.number_format($counterfixed)); } else { - exit($pdo->log->header("\nThis script checks if release previews actually exist on disk.\n\n" - . "Releases without previews may be reset for post-processing, thus regenerating them and related meta data.\n\n" - . "Useful for recovery after filesystem corruption, or as an alternative re-postprocessing tool.\n\n" - . "Optional LIMIT parameter restricts number of releases to be reset.\n\n" - . "php $argv[0] check [LIMIT] ...: Dry run, displays missing previews.\n" - . "php $argv[0] true [LIMIT] ...: Re-process releases missing previews.\n")); + exit($pdo->log->header("\nThis script checks if release previews actually exist on disk.\n\n" + ."Releases without previews may be reset for post-processing, thus regenerating them and related meta data.\n\n" + ."Useful for recovery after filesystem corruption, or as an alternative re-postprocessing tool.\n\n" + ."Optional LIMIT parameter restricts number of releases to be reset.\n\n" + ."php $argv[0] check [LIMIT] ...: Dry run, displays missing previews.\n" + ."php $argv[0] true [LIMIT] ...: Re-process releases missing previews.\n")); } diff --git a/misc/testing/PostProc/getConsole.php b/misc/testing/PostProc/getConsole.php index 34fa40a1d..b2af8bdfa 100644 --- a/misc/testing/PostProc/getConsole.php +++ b/misc/testing/PostProc/getConsole.php @@ -1,13 +1,12 @@ true, 'Settings' => $pdo]); $res = $pdo->queryDirect( sprintf( - "SELECT searchname, id FROM releases WHERE consoleinfo_id IS NULL AND categories_id - BETWEEN %s AND %s ORDER BY id DESC", + 'SELECT searchname, id FROM releases WHERE consoleinfo_id IS NULL AND categories_id + BETWEEN %s AND %s ORDER BY id DESC', Category::GAME_ROOT, Category::GAME_OTHER )); if ($res instanceof \Traversable) { - echo $pdo->log->header("Updating console info for " . number_format($res->rowCount()) . " releases."); + echo $pdo->log->header('Updating console info for '.number_format($res->rowCount()).' releases.'); - foreach ($res as $arr) { - $starttime = microtime(true); - $gameInfo = $console->parseTitle($arr['searchname']); - if ($gameInfo !== false) { - $game = $console->updateConsoleInfo($gameInfo); - if ($game === false) { - echo $pdo->log->primary($gameInfo['release'] . ' not found'); - } - } + foreach ($res as $arr) { + $starttime = microtime(true); + $gameInfo = $console->parseTitle($arr['searchname']); + if ($gameInfo !== false) { + $game = $console->updateConsoleInfo($gameInfo); + if ($game === false) { + echo $pdo->log->primary($gameInfo['release'].' not found'); + } + } - // amazon limits are 1 per 1 sec - $diff = floor((microtime(true) - $starttime) * 1000000); - if (1000000 - $diff > 0) { - echo $pdo->log->alternate("Sleeping"); - usleep(1000000 - $diff); - } - } + // amazon limits are 1 per 1 sec + $diff = floor((microtime(true) - $starttime) * 1000000); + if (1000000 - $diff > 0) { + echo $pdo->log->alternate('Sleeping'); + usleep(1000000 - $diff); + } + } } diff --git a/misc/testing/PostProc/getGameCovers.php b/misc/testing/PostProc/getGameCovers.php index 5c67f83ec..9d3ecf7b2 100644 --- a/misc/testing/PostProc/getGameCovers.php +++ b/misc/testing/PostProc/getGameCovers.php @@ -1,12 +1,12 @@ true, 'Settings' => $pdo]); @@ -16,28 +16,28 @@ $res = $pdo->query( ); $total = count($res); if ($total > 0) { - echo ColorCLI::header('Updating game covers for ' . number_format($total) . ' releases.'); + echo ColorCLI::header('Updating game covers for '.number_format($total).' releases.'); - foreach ($res as $arr) { - $starttime = microtime(true); - $gameInfo = $game->parseTitle($arr['title']); - if ($gameInfo !== false) { - echo ColorCLI::primary('Looking up: ' . $gameInfo['release']); - $gameData = $game->updateGamesInfo($gameInfo); - if ($gameData === false) { - echo ColorCLI::primary($gameInfo['release'] . ' not found'); - } else { - if (file_exists(NN_COVERS . 'games' . DS . $gameData . '.jpg')) { - $pdo->queryExec(sprintf('UPDATE gamesinfo SET cover = 1 WHERE id = %d', $arr['id'])); - } - } - } + foreach ($res as $arr) { + $starttime = microtime(true); + $gameInfo = $game->parseTitle($arr['title']); + if ($gameInfo !== false) { + echo ColorCLI::primary('Looking up: '.$gameInfo['release']); + $gameData = $game->updateGamesInfo($gameInfo); + if ($gameData === false) { + echo ColorCLI::primary($gameInfo['release'].' not found'); + } else { + if (file_exists(NN_COVERS.'games'.DS.$gameData.'.jpg')) { + $pdo->queryExec(sprintf('UPDATE gamesinfo SET cover = 1 WHERE id = %d', $arr['id'])); + } + } + } - // amazon limits are 1 per 1 sec - $diff = floor((microtime(true) - $starttime) * 1000000); - if (1000000 - $diff > 0) { - echo ColorCLI::alternate('Sleeping'); - usleep(1000000 - $diff); - } - } + // amazon limits are 1 per 1 sec + $diff = floor((microtime(true) - $starttime) * 1000000); + if (1000000 - $diff > 0) { + echo ColorCLI::alternate('Sleeping'); + usleep(1000000 - $diff); + } + } } diff --git a/misc/testing/PostProc/getImdb.php b/misc/testing/PostProc/getImdb.php index 512030247..14478819f 100644 --- a/misc/testing/PostProc/getImdb.php +++ b/misc/testing/PostProc/getImdb.php @@ -1,33 +1,33 @@ true, 'Settings' => $pdo]); - $movies = $pdo->queryDirect('SELECT imdbid FROM movieinfo WHERE tmdbid = 0 ORDER BY id ASC'); if ($movies instanceof \Traversable) { - $count = $movies->rowCount(); - if ($count > 0) { - echo ColorCLI::header('Updating movie info for ' . number_format($count) . ' movies.'); + $count = $movies->rowCount(); + if ($count > 0) { + echo ColorCLI::header('Updating movie info for '.number_format($count).' movies.'); - foreach ($movies as $mov) { - $startTime = microtime(true); - $mov = $movie->updateMovieInfo($mov['imdbid']); + foreach ($movies as $mov) { + $startTime = microtime(true); + $mov = $movie->updateMovieInfo($mov['imdbid']); - // tmdb limits are 30 per 10 sec, not certain for imdb - $diff = floor((microtime(true) - $startTime) * 1000000); - if (333333 - $diff > 0) { - echo "sleeping\n"; - usleep(333333 - $diff); - } - } - } else { - echo ColorCLI::header('No movies to update'); - } + // tmdb limits are 30 per 10 sec, not certain for imdb + $diff = floor((microtime(true) - $startTime) * 1000000); + if (333333 - $diff > 0) { + echo "sleeping\n"; + usleep(333333 - $diff); + } + } + } else { + echo ColorCLI::header('No movies to update'); + } } diff --git a/misc/testing/PostProc/getMovieCovers.php b/misc/testing/PostProc/getMovieCovers.php index 866ff4f45..91bf92f3a 100644 --- a/misc/testing/PostProc/getMovieCovers.php +++ b/misc/testing/PostProc/getMovieCovers.php @@ -1,6 +1,7 @@ true, 'Settings' => $pdo]); $movies = $pdo->queryDirect('SELECT imdbid FROM movieinfo WHERE cover = 0 ORDER BY year ASC, id DESC'); $count = $movies->rowCount(); if ($count > 0) { - if ($movies instanceof \Traversable) { - echo ColorCLI::primary('Updating ' . number_format($count) . ' movie covers.'); - foreach ($movies as $mov) { - $startTime = microtime(true); - $mov = $movie->updateMovieInfo($mov['imdbid']); + if ($movies instanceof \Traversable) { + echo ColorCLI::primary('Updating '.number_format($count).' movie covers.'); + foreach ($movies as $mov) { + $startTime = microtime(true); + $mov = $movie->updateMovieInfo($mov['imdbid']); - // tmdb limits are 30 per 10 sec, not certain for imdb - $diff = floor((microtime(true) - $startTime) * 1000000); - if (333333 - $diff > 0) { - echo "\nsleeping\n"; - usleep(333333 - $diff); - } - } - } + // tmdb limits are 30 per 10 sec, not certain for imdb + $diff = floor((microtime(true) - $startTime) * 1000000); + if (333333 - $diff > 0) { + echo "\nsleeping\n"; + usleep(333333 - $diff); + } + } + } } else { - echo ColorCLI::header('No movie covers to update'); + echo ColorCLI::header('No movie covers to update'); } diff --git a/misc/testing/PostProc/getXXXCovers.php b/misc/testing/PostProc/getXXXCovers.php index ae9da0cca..6fd4a0af9 100644 --- a/misc/testing/PostProc/getXXXCovers.php +++ b/misc/testing/PostProc/getXXXCovers.php @@ -1,29 +1,29 @@ queryDirect("SELECT title FROM xxxinfo WHERE cover = 0"); +$movies = $pdo->queryDirect('SELECT title FROM xxxinfo WHERE cover = 0'); if ($movies instanceof Traversable) { - echo $c->primary("Updating " . number_format($movies->rowCount()) . " XXX movie covers."); - foreach ($movies as $mov) { - $starttime = microtime(true); - $mov = $movie->updateXXXInfo($mov['title']); + echo $c->primary('Updating '.number_format($movies->rowCount()).' XXX movie covers.'); + foreach ($movies as $mov) { + $starttime = microtime(true); + $mov = $movie->updateXXXInfo($mov['title']); - // sleep so that it's not ddos' the site - $diff = floor((microtime(true) - $starttime) * 1000000); - if (333333 - $diff > 0) { - echo "\nsleeping\n"; - usleep(333333 - $diff); - } - } - echo "\n"; + // sleep so that it's not ddos' the site + $diff = floor((microtime(true) - $starttime) * 1000000); + if (333333 - $diff > 0) { + echo "\nsleeping\n"; + usleep(333333 - $diff); + } + } + echo "\n"; } diff --git a/misc/testing/PostProc/getXXXSamples.php b/misc/testing/PostProc/getXXXSamples.php index f2e128bb7..ed9b3b8f8 100644 --- a/misc/testing/PostProc/getXXXSamples.php +++ b/misc/testing/PostProc/getXXXSamples.php @@ -1,5 +1,6 @@ log->header("Scanning for XXX UHD/HD/SD releases missing sample images"); - $res = $pdo->query(sprintf('SELECT r.id, r.guid AS guid, r.searchname AS searchname + echo $pdo->log->header('Scanning for XXX UHD/HD/SD releases missing sample images'); + $res = $pdo->query(sprintf('SELECT r.id, r.guid AS guid, r.searchname AS searchname FROM releases r WHERE r.nzbstatus = 1 AND r.jpgstatus = 0 AND r.categories_id IN (%s, %s, %s) ORDER BY r.adddate DESC', Category::XXX_CLIPHD, Category::XXX_CLIPSD, Category::XXX_UHD)); - foreach ($res as $row) { - $nzbpath = $path2cover . $row["guid"] . "_thumb.jpg"; - if (!file_exists($nzbpath)) { - $counterfixed++; - if ($argv[1] === "true") { - $imgpath = 'http://pic4all.eu/images/' . $row['searchname'] . '_1.jpg'; - //scan pic4all.eu for sample image - if(preg_match('/SDCLiP/i', $row['searchname'])) { - $row['searchname'] = strtolower(preg_replace('/.XXX(.720p|.1080p)?.MP4-SDCLiP/i', '', $row['searchname'])); - $imgpath = 'http://pic4all.eu/images/' . $row['searchname'] . '.jpg'; - } - $sample = $releaseImage->saveImage($row['guid'] . '_thumb', $imgpath, $releaseImage->jpgSavePath, 650, 650); - if($sample !== 0) { - echo $pdo->log->info("Downloaded sample for " . $row['searchname']); - $pdo->queryExec(sprintf('UPDATE releases SET jpgstatus = 1 WHERE id = %d', $row['id'])); - } else { - echo $pdo->log->notice("Sample download failed!"); - $pdo->queryExec(sprintf('UPDATE releases SET jpgstatus = -2 WHERE id = %d', $row['id'])); - } - } - } + foreach ($res as $row) { + $nzbpath = $path2cover.$row['guid'].'_thumb.jpg'; + if (! file_exists($nzbpath)) { + $counterfixed++; + if ($argv[1] === 'true') { + $imgpath = 'http://pic4all.eu/images/'.$row['searchname'].'_1.jpg'; + //scan pic4all.eu for sample image + if (preg_match('/SDCLiP/i', $row['searchname'])) { + $row['searchname'] = strtolower(preg_replace('/.XXX(.720p|.1080p)?.MP4-SDCLiP/i', '', $row['searchname'])); + $imgpath = 'http://pic4all.eu/images/'.$row['searchname'].'.jpg'; + } + $sample = $releaseImage->saveImage($row['guid'].'_thumb', $imgpath, $releaseImage->jpgSavePath, 650, 650); + if ($sample !== 0) { + echo $pdo->log->info('Downloaded sample for '.$row['searchname']); + $pdo->queryExec(sprintf('UPDATE releases SET jpgstatus = 1 WHERE id = %d', $row['id'])); + } else { + echo $pdo->log->notice('Sample download failed!'); + $pdo->queryExec(sprintf('UPDATE releases SET jpgstatus = -2 WHERE id = %d', $row['id'])); + } + } + } - if (($limit > 0) && ($counterfixed >= $limit)) { - break; - } - } - echo $pdo->log->header("Total releases missing samples that " . $couldbe . "their samples updated = " . number_format($counterfixed)); + if (($limit > 0) && ($counterfixed >= $limit)) { + break; + } + } + echo $pdo->log->header('Total releases missing samples that '.$couldbe.'their samples updated = '.number_format($counterfixed)); } else { - exit($pdo->log->header("\nThis script checks if XXX release samples actually exist on disk.\n\n" - . "php $argv[0] check ...: Dry run, displays missing samples.\n" - . "php $argv[0] true ...: Update XXX releases missing samples.\n")); + exit($pdo->log->header("\nThis script checks if XXX release samples actually exist on disk.\n\n" + ."php $argv[0] check ...: Dry run, displays missing samples.\n" + ."php $argv[0] true ...: Update XXX releases missing samples.\n")); } diff --git a/misc/testing/PostProc/updateBookImages.php b/misc/testing/PostProc/updateBookImages.php index 7bbe66600..0f0cc986e 100644 --- a/misc/testing/PostProc/updateBookImages.php +++ b/misc/testing/PostProc/updateBookImages.php @@ -1,9 +1,9 @@ log->error("\nThis script will check all images in covers/book and compare to db->bookinfo.\nTo run:\nphp $argv[0] true\n")); } - -$path2covers = NN_COVERS . 'book' . DS; +$path2covers = NN_COVERS.'book'.DS; $dirItr = new \RecursiveDirectoryIterator($path2covers); $itr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::LEAVES_ONLY); @@ -20,28 +19,28 @@ foreach ($itr as $filePath) { if (is_file($filePath) && preg_match('/\d+\.jpg/', $filePath)) { preg_match('/(\d+)\.jpg/', basename($filePath), $match); if (isset($match[1])) { - $run = $pdo->queryDirect("UPDATE bookinfo SET cover = 1 WHERE cover = 0 AND id = " . $match[1]); + $run = $pdo->queryDirect('UPDATE bookinfo SET cover = 1 WHERE cover = 0 AND id = '.$match[1]); if ($run->rowCount() >= 1) { $covers++; } else { - $run = $pdo->queryDirect("SELECT id FROM bookinfo WHERE id = " . $match[1]); + $run = $pdo->queryDirect('SELECT id FROM bookinfo WHERE id = '.$match[1]); if ($run->rowCount() == 0) { - echo $pdo->log->info($filePath . " not found in db."); + echo $pdo->log->info($filePath.' not found in db.'); } } } } } -$qry = $pdo->queryDirect("SELECT id FROM bookinfo WHERE cover = 1"); +$qry = $pdo->queryDirect('SELECT id FROM bookinfo WHERE cover = 1'); if ($qry instanceof \Traversable) { - foreach ($qry as $rows) { - if (!is_file($path2covers . $rows['id'] . '.jpg')) { - $pdo->queryDirect("UPDATE bookinfo SET cover = 0 WHERE cover = 1 AND id = " . $rows['id']); - echo $pdo->log->info($path2covers . $rows['id'] . ".jpg does not exist."); - $deleted++; - } - } + foreach ($qry as $rows) { + if (! is_file($path2covers.$rows['id'].'.jpg')) { + $pdo->queryDirect('UPDATE bookinfo SET cover = 0 WHERE cover = 1 AND id = '.$rows['id']); + echo $pdo->log->info($path2covers.$rows['id'].'.jpg does not exist.'); + $deleted++; + } + } } -echo $pdo->log->header($covers . " covers set."); -echo $pdo->log->header($deleted . " books unset."); +echo $pdo->log->header($covers.' covers set.'); +echo $pdo->log->header($deleted.' books unset.'); diff --git a/misc/testing/PostProc/updateConsoleImages.php b/misc/testing/PostProc/updateConsoleImages.php index 6016bce12..c6db63d3a 100644 --- a/misc/testing/PostProc/updateConsoleImages.php +++ b/misc/testing/PostProc/updateConsoleImages.php @@ -1,9 +1,9 @@ log->error("\nThis script will check all images in covers/console and compare to db->consoleinfo.\nTo run:\nphp $argv[0] true\n")); } - -$path2covers = NN_COVERS . 'console' . DS; +$path2covers = NN_COVERS.'console'.DS; $dirItr = new \RecursiveDirectoryIterator($path2covers); $itr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::LEAVES_ONLY); @@ -20,28 +19,28 @@ foreach ($itr as $filePath) { if (is_file($filePath) && preg_match('/\d+\.jpg/', $filePath)) { preg_match('/(\d+)\.jpg/', basename($filePath), $match); if (isset($match[1])) { - $run = $pdo->queryDirect("UPDATE consoleinfo SET cover = 1 WHERE cover = 0 AND id = " . $match[1]); + $run = $pdo->queryDirect('UPDATE consoleinfo SET cover = 1 WHERE cover = 0 AND id = '.$match[1]); if ($run->rowCount() >= 1) { $covers++; } else { - $run = $pdo->queryDirect("SELECT id FROM consoleinfo WHERE id = " . $match[1]); + $run = $pdo->queryDirect('SELECT id FROM consoleinfo WHERE id = '.$match[1]); if ($run->rowCount() == 0) { - echo $pdo->log->info($filePath . " not found in db."); + echo $pdo->log->info($filePath.' not found in db.'); } } } } } -$qry = $pdo->queryDirect("SELECT id FROM consoleinfo WHERE cover = 1"); +$qry = $pdo->queryDirect('SELECT id FROM consoleinfo WHERE cover = 1'); if ($qry instanceof \Traversable) { - foreach ($qry as $rows) { - if (!is_file($path2covers . $rows['id'] . '.jpg')) { - $pdo->queryDirect("UPDATE consoleinfo SET cover = 0 WHERE cover = 1 AND id = " . $rows['id']); - echo $pdo->log->info($path2covers . $rows['id'] . ".jpg does not exist."); - $deleted++; - } - } + foreach ($qry as $rows) { + if (! is_file($path2covers.$rows['id'].'.jpg')) { + $pdo->queryDirect('UPDATE consoleinfo SET cover = 0 WHERE cover = 1 AND id = '.$rows['id']); + echo $pdo->log->info($path2covers.$rows['id'].'.jpg does not exist.'); + $deleted++; + } + } } -echo $pdo->log->header($covers . " covers set."); -echo $pdo->log->header($deleted . " consoles unset."); +echo $pdo->log->header($covers.' covers set.'); +echo $pdo->log->header($deleted.' consoles unset.'); diff --git a/misc/testing/PostProc/updateGamesImages.php b/misc/testing/PostProc/updateGamesImages.php index d92b5e08a..f322370ef 100644 --- a/misc/testing/PostProc/updateGamesImages.php +++ b/misc/testing/PostProc/updateGamesImages.php @@ -1,5 +1,6 @@ log->error("\nThis script will check all images in covers/games and compare to db->gamesinfo.\nTo run:\nphp $argv[0] true\n")); + exit($pdo->log->error("\nThis script will check all images in covers/games and compare to db->gamesinfo.\nTo run:\nphp $argv[0] true\n")); } $row = $pdo->queryOneRow("SELECT value FROM settings WHERE setting = 'coverspath'"); if ($row !== false) { - Utility::setCoversConstant($row['value']); + Utility::setCoversConstant($row['value']); } else { - die("Unable to set Covers' constant!\n"); + die("Unable to set Covers' constant!\n"); } -$path2covers = NN_COVERS . 'games' . DS; +$path2covers = NN_COVERS.'games'.DS; $dirItr = new \RecursiveDirectoryIterator($path2covers); $itr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::LEAVES_ONLY); foreach ($itr as $filePath) { - if (is_file($filePath) && preg_match('/\d+\.jpg/', $filePath)) { - preg_match('/(\d+)\.jpg/', basename($filePath), $match); - if (isset($match[1])) { - $run = $pdo->queryDirect("UPDATE gamesinfo SET cover = 1 WHERE cover = 0 AND id = " . $match[1]); - if ($run !== false) { - if ($run->rowCount() >= 1) { - $covers++; - } else { - $run = $pdo->queryDirect("SELECT id FROM gamesinfo WHERE id = " . $match[1]); - if ($run !== false && $run->rowCount() == 0) { - echo $pdo->log->info($filePath . " not found in db."); - } - } - } - } - } + if (is_file($filePath) && preg_match('/\d+\.jpg/', $filePath)) { + preg_match('/(\d+)\.jpg/', basename($filePath), $match); + if (isset($match[1])) { + $run = $pdo->queryDirect('UPDATE gamesinfo SET cover = 1 WHERE cover = 0 AND id = '.$match[1]); + if ($run !== false) { + if ($run->rowCount() >= 1) { + $covers++; + } else { + $run = $pdo->queryDirect('SELECT id FROM gamesinfo WHERE id = '.$match[1]); + if ($run !== false && $run->rowCount() == 0) { + echo $pdo->log->info($filePath.' not found in db.'); + } + } + } + } + } } -$qry = $pdo->queryDirect("SELECT id FROM gamesinfo WHERE cover = 1"); +$qry = $pdo->queryDirect('SELECT id FROM gamesinfo WHERE cover = 1'); if ($qry instanceof \Traversable) { - foreach ($qry as $rows) { - if (!is_file($path2covers . $rows['id'] . '.jpg')) { - $pdo->queryDirect("UPDATE gamesinfo SET cover = 0 WHERE cover = 1 AND id = " . $rows['id']); - echo $pdo->log->info($path2covers . $rows['id'] . ".jpg does not exist."); - $deleted++; - } - } + foreach ($qry as $rows) { + if (! is_file($path2covers.$rows['id'].'.jpg')) { + $pdo->queryDirect('UPDATE gamesinfo SET cover = 0 WHERE cover = 1 AND id = '.$rows['id']); + echo $pdo->log->info($path2covers.$rows['id'].'.jpg does not exist.'); + $deleted++; + } + } } -echo $pdo->log->header($covers . " covers set."); -echo $pdo->log->header($deleted . " games unset."); +echo $pdo->log->header($covers.' covers set.'); +echo $pdo->log->header($deleted.' games unset.'); diff --git a/misc/testing/PostProc/updateMovieImages.php b/misc/testing/PostProc/updateMovieImages.php index 9d2a9ddaf..5c4eda559 100644 --- a/misc/testing/PostProc/updateMovieImages.php +++ b/misc/testing/PostProc/updateMovieImages.php @@ -1,5 +1,6 @@ log->error("\nThis script will check all images in covers/movies and compare to db->movieinfo.\nTo run:\nphp $argv[0] true\n")); + exit($pdo->log->error("\nThis script will check all images in covers/movies and compare to db->movieinfo.\nTo run:\nphp $argv[0] true\n")); } $row = $pdo->queryOneRow("SELECT value FROM settings WHERE setting = 'coverspath'"); if ($row !== false) { - Utility::setCoversConstant($row['value']); + Utility::setCoversConstant($row['value']); } else { - die("Unable to set Covers' constant!\n"); + die("Unable to set Covers' constant!\n"); } -$path2covers = NN_COVERS . 'movies' . DS; +$path2covers = NN_COVERS.'movies'.DS; $dirItr = new \RecursiveDirectoryIterator($path2covers); $itr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::LEAVES_ONLY); foreach ($itr as $filePath) { - if (is_file($filePath) && preg_match('/-cover\.jpg/', $filePath)) { - preg_match('/(\d+)-cover\.jpg/', basename($filePath), $match); - if (isset($match[1])) { - $run = $pdo->queryDirect("UPDATE movieinfo SET cover = 1 WHERE cover = 0 AND imdbid = " . $match[1]); - if ($run->rowCount() >= 1) { - $covers++; - } else { - $run = $pdo->queryDirect("SELECT imdbid FROM movieinfo WHERE imdbid = " . $match[1]); - if ($run->rowCount() == 0) { - echo $pdo->log->info($filePath . " not found in db."); - } - } - } - } - if (is_file($filePath) && preg_match('/-backdrop\.jpg/', $filePath)) { - preg_match('/(\d+)-backdrop\.jpg/', basename($filePath), $match1); - if (isset($match1[1])) { - $run = $pdo->queryDirect("UPDATE movieinfo SET backdrop = 1 WHERE backdrop = 0 AND imdbid = " . $match1[1]); - if ($run->rowCount() >= 1) { - $updated++; - printf("UPDATE movieinfo SET backdrop = 1 WHERE backdrop = 0 AND imdbid = " . $match1[1] . "\n"); - } else { - $run = $pdo->queryDirect("SELECT imdbid FROM movieinfo WHERE imdbid = " . $match1[1]); - if ($run->rowCount() == 0) { - echo $pdo->log->info($filePath . " not found in db."); - } - } - } - } + if (is_file($filePath) && preg_match('/-cover\.jpg/', $filePath)) { + preg_match('/(\d+)-cover\.jpg/', basename($filePath), $match); + if (isset($match[1])) { + $run = $pdo->queryDirect('UPDATE movieinfo SET cover = 1 WHERE cover = 0 AND imdbid = '.$match[1]); + if ($run->rowCount() >= 1) { + $covers++; + } else { + $run = $pdo->queryDirect('SELECT imdbid FROM movieinfo WHERE imdbid = '.$match[1]); + if ($run->rowCount() == 0) { + echo $pdo->log->info($filePath.' not found in db.'); + } + } + } + } + if (is_file($filePath) && preg_match('/-backdrop\.jpg/', $filePath)) { + preg_match('/(\d+)-backdrop\.jpg/', basename($filePath), $match1); + if (isset($match1[1])) { + $run = $pdo->queryDirect('UPDATE movieinfo SET backdrop = 1 WHERE backdrop = 0 AND imdbid = '.$match1[1]); + if ($run->rowCount() >= 1) { + $updated++; + printf('UPDATE movieinfo SET backdrop = 1 WHERE backdrop = 0 AND imdbid = '.$match1[1]."\n"); + } else { + $run = $pdo->queryDirect('SELECT imdbid FROM movieinfo WHERE imdbid = '.$match1[1]); + if ($run->rowCount() == 0) { + echo $pdo->log->info($filePath.' not found in db.'); + } + } + } + } } -$qry = $pdo->queryDirect("SELECT imdbid FROM movieinfo WHERE cover = 1"); +$qry = $pdo->queryDirect('SELECT imdbid FROM movieinfo WHERE cover = 1'); if ($qry instanceof \Traversable) { - foreach ($qry as $rows) { - if (!is_file($path2covers . $rows['imdbid'] . '-cover.jpg')) { - $pdo->queryDirect("UPDATE movieinfo SET cover = 0 WHERE cover = 1 AND imdbid = " . $rows['imdbid']); - echo $pdo->log->info($path2covers . $rows['imdbid'] . "-cover.jpg does not exist."); - $deleted++; - } - } + foreach ($qry as $rows) { + if (! is_file($path2covers.$rows['imdbid'].'-cover.jpg')) { + $pdo->queryDirect('UPDATE movieinfo SET cover = 0 WHERE cover = 1 AND imdbid = '.$rows['imdbid']); + echo $pdo->log->info($path2covers.$rows['imdbid'].'-cover.jpg does not exist.'); + $deleted++; + } + } } -$qry1 = $pdo->queryDirect("SELECT imdbid FROM movieinfo WHERE backdrop = 1"); +$qry1 = $pdo->queryDirect('SELECT imdbid FROM movieinfo WHERE backdrop = 1'); if ($qry1 instanceof \Traversable) { - foreach ($qry1 as $rows) { - if (!is_file($path2covers . $rows['imdbid'] . '-backdrop.jpg')) { - $pdo->queryDirect("UPDATE movieinfo SET backdrop = 0 WHERE backdrop = 1 AND imdbid = " . $rows['imdbid']); - echo $pdo->log->info($path2covers . $rows['imdbid'] . "-backdrop.jpg does not exist."); - $deleted++; - } - } + foreach ($qry1 as $rows) { + if (! is_file($path2covers.$rows['imdbid'].'-backdrop.jpg')) { + $pdo->queryDirect('UPDATE movieinfo SET backdrop = 0 WHERE backdrop = 1 AND imdbid = '.$rows['imdbid']); + echo $pdo->log->info($path2covers.$rows['imdbid'].'-backdrop.jpg does not exist.'); + $deleted++; + } + } } -echo $pdo->log->header($covers . " covers set."); -echo $pdo->log->header($updated . " backdrops set."); -echo $pdo->log->header($deleted . " movies unset."); +echo $pdo->log->header($covers.' covers set.'); +echo $pdo->log->header($updated.' backdrops set.'); +echo $pdo->log->header($deleted.' movies unset.'); diff --git a/misc/testing/PostProc/updateMusicImages.php b/misc/testing/PostProc/updateMusicImages.php index 55403f12d..b63b9798b 100644 --- a/misc/testing/PostProc/updateMusicImages.php +++ b/misc/testing/PostProc/updateMusicImages.php @@ -1,9 +1,9 @@ log->error("\nThis script will check all images in covers/music and compare to db->musicinfo.\nTo run:\nphp $argv[0] true\n")); } -$path2covers = NN_COVERS . 'music' . DS; +$path2covers = NN_COVERS.'music'.DS; $dirItr = new \RecursiveDirectoryIterator($path2covers); $itr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::LEAVES_ONLY); @@ -19,28 +19,28 @@ foreach ($itr as $filePath) { if (is_file($filePath) && preg_match('/\d+\.jpg/', $filePath)) { preg_match('/(\d+)\.jpg/', basename($filePath), $match); if (isset($match[1])) { - $run = $pdo->queryDirect("UPDATE musicinfo SET cover = 1 WHERE cover = 0 AND id = " . $match[1]); + $run = $pdo->queryDirect('UPDATE musicinfo SET cover = 1 WHERE cover = 0 AND id = '.$match[1]); if ($run->rowCount() >= 1) { $covers++; } else { - $run = $pdo->queryDirect("SELECT id FROM musicinfo WHERE id = " . $match[1]); + $run = $pdo->queryDirect('SELECT id FROM musicinfo WHERE id = '.$match[1]); if ($run->rowCount() == 0) { - echo $pdo->log->info($filePath . " not found in db."); + echo $pdo->log->info($filePath.' not found in db.'); } } } } } -$qry = $pdo->queryDirect("SELECT id FROM musicinfo WHERE cover = 1"); +$qry = $pdo->queryDirect('SELECT id FROM musicinfo WHERE cover = 1'); if ($qry instanceof \Traversable) { - foreach ($qry as $rows) { - if (!is_file($path2covers . $rows['id'] . '.jpg')) { - $pdo->queryDirect("UPDATE musicinfo SET cover = 0 WHERE cover = 1 AND id = " . $rows['id']); - echo $pdo->log->info($path2covers . $rows['id'] . ".jpg does not exist."); - $deleted++; - } - } + foreach ($qry as $rows) { + if (! is_file($path2covers.$rows['id'].'.jpg')) { + $pdo->queryDirect('UPDATE musicinfo SET cover = 0 WHERE cover = 1 AND id = '.$rows['id']); + echo $pdo->log->info($path2covers.$rows['id'].'.jpg does not exist.'); + $deleted++; + } + } } -echo $pdo->log->header($covers . " covers set."); -echo $pdo->log->header($deleted . " music unset."); +echo $pdo->log->header($covers.' covers set.'); +echo $pdo->log->header($deleted.' music unset.'); diff --git a/misc/testing/PostProc/updateXXXImages.php b/misc/testing/PostProc/updateXXXImages.php index 1a45f40bb..48b0ac324 100644 --- a/misc/testing/PostProc/updateXXXImages.php +++ b/misc/testing/PostProc/updateXXXImages.php @@ -1,74 +1,74 @@ error("\nThis script will check all images in covers/xxx and compare to db->xxxinfo.\nTo run:\nphp $argv[0] true\n")); + exit($c->error("\nThis script will check all images in covers/xxx and compare to db->xxxinfo.\nTo run:\nphp $argv[0] true\n")); } -$path2covers = NN_COVERS . 'xxx' . DS; +$path2covers = NN_COVERS.'xxx'.DS; $dirItr = new RecursiveDirectoryIterator($path2covers); $itr = new RecursiveIteratorIterator($dirItr, RecursiveIteratorIterator::LEAVES_ONLY); foreach ($itr as $filePath) { - if (is_file($filePath) && preg_match('/-cover\.jpg/', $filePath)) { - preg_match('/(\d+)-cover\.jpg/', basename($filePath), $match); - if (isset($match[1])) { - $run = $pdo->queryDirect("UPDATE xxxinfo SET cover = 1 WHERE cover = 0 AND id = " . $match[1]); - if ($run->rowCount() >= 1) { - $covers++; - } else { - $run = $pdo->queryDirect("SELECT id FROM xxxinfo WHERE id = " . $match[1]); - if ($run->rowCount() == 0) { - echo $c->info($filePath . " not found in db."); - } - } - } - } - if (is_file($filePath) && preg_match('/-backdrop\.jpg/', $filePath)) { - preg_match('/(\d+)-backdrop\.jpg/', basename($filePath), $match1); - if (isset($match1[1])) { - $run = $pdo->queryDirect("UPDATE xxxinfo SET backdrop = 1 WHERE backdrop = 0 AND id = " . $match1[1]); - if ($run->rowCount() >= 1) { - $updated++; - printf("UPDATE xxxinfo SET backdrop = 1 WHERE backdrop = 0 AND id = " . $match1[1] . "\n"); - } else { - $run = $pdo->queryDirect("SELECT id FROM xxxinfo WHERE id = " . $match1[1]); - if ($run->rowCount() == 0) { - echo $c->info($filePath . " not found in db."); - } - } - } - } + if (is_file($filePath) && preg_match('/-cover\.jpg/', $filePath)) { + preg_match('/(\d+)-cover\.jpg/', basename($filePath), $match); + if (isset($match[1])) { + $run = $pdo->queryDirect('UPDATE xxxinfo SET cover = 1 WHERE cover = 0 AND id = '.$match[1]); + if ($run->rowCount() >= 1) { + $covers++; + } else { + $run = $pdo->queryDirect('SELECT id FROM xxxinfo WHERE id = '.$match[1]); + if ($run->rowCount() == 0) { + echo $c->info($filePath.' not found in db.'); + } + } + } + } + if (is_file($filePath) && preg_match('/-backdrop\.jpg/', $filePath)) { + preg_match('/(\d+)-backdrop\.jpg/', basename($filePath), $match1); + if (isset($match1[1])) { + $run = $pdo->queryDirect('UPDATE xxxinfo SET backdrop = 1 WHERE backdrop = 0 AND id = '.$match1[1]); + if ($run->rowCount() >= 1) { + $updated++; + printf('UPDATE xxxinfo SET backdrop = 1 WHERE backdrop = 0 AND id = '.$match1[1]."\n"); + } else { + $run = $pdo->queryDirect('SELECT id FROM xxxinfo WHERE id = '.$match1[1]); + if ($run->rowCount() == 0) { + echo $c->info($filePath.' not found in db.'); + } + } + } + } } -$qry = $pdo->queryDirect("SELECT id FROM xxxinfo WHERE cover = 1"); +$qry = $pdo->queryDirect('SELECT id FROM xxxinfo WHERE cover = 1'); if ($qry instanceof Traversable) { - foreach ($qry as $rows) { - if (!is_file($path2covers . $rows['id'] . '-cover.jpg')) { - $pdo->queryDirect("UPDATE xxxinfo SET cover = 0 WHERE cover = 1 AND id = " . $rows['id']); - echo $c->info($path2covers . $rows['id'] . "-cover.jpg does not exist."); - $deleted++; - } - } + foreach ($qry as $rows) { + if (! is_file($path2covers.$rows['id'].'-cover.jpg')) { + $pdo->queryDirect('UPDATE xxxinfo SET cover = 0 WHERE cover = 1 AND id = '.$rows['id']); + echo $c->info($path2covers.$rows['id'].'-cover.jpg does not exist.'); + $deleted++; + } + } } -$qry1 = $pdo->queryDirect("SELECT id FROM xxxinfo WHERE backdrop = 1"); +$qry1 = $pdo->queryDirect('SELECT id FROM xxxinfo WHERE backdrop = 1'); if ($qry1 instanceof Traversable) { - foreach ($qry1 as $rows) { - if (!is_file($path2covers . $rows['id'] . '-backdrop.jpg')) { - $pdo->queryDirect("UPDATE xxxinfo SET backdrop = 0 WHERE backdrop = 1 AND id = " . $rows['id']); - echo $c->info($path2covers . $rows['id'] . "-backdrop.jpg does not exist."); - $deleted++; - } - } + foreach ($qry1 as $rows) { + if (! is_file($path2covers.$rows['id'].'-backdrop.jpg')) { + $pdo->queryDirect('UPDATE xxxinfo SET backdrop = 0 WHERE backdrop = 1 AND id = '.$rows['id']); + echo $c->info($path2covers.$rows['id'].'-backdrop.jpg does not exist.'); + $deleted++; + } + } } -echo $c->header($covers . " covers set."); -echo $c->header($updated . " backdrops set."); -echo $c->header($deleted . " movies unset."); +echo $c->header($covers.' covers set.'); +echo $c->header($updated.' backdrops set.'); +echo $c->header($deleted.' movies unset.'); diff --git a/misc/testing/PreDB/dump_predb.php b/misc/testing/PreDB/dump_predb.php index 1d59c7429..e8c33dc35 100644 --- a/misc/testing/PreDB/dump_predb.php +++ b/misc/testing/PreDB/dump_predb.php @@ -1,5 +1,6 @@ log->header("SELECT title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, g.name FROM " . $table . " p LEFT OUTER JOIN groups g ON p.groups_id = g.id INTO OUTFILE '" . $path . "' FIELDS TERMINATED BY '\\t\\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\\r\\n';n"); - $pdo->queryExec("SELECT title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, g.name FROM " . $table . " p LEFT OUTER JOIN groups g ON p.groups_id = g.id INTO OUTFILE '" . $path . "' FIELDS TERMINATED BY '\t\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\r\n'"); -} else if (isset($argv[1]) && ($argv[1] == 'local' || $argv[1] == 'remote') && isset($argv[2]) && is_file($argv[2])) { - if (!preg_match('/^\//', $path)) { - $path = require_once getcwd() . '/' . $argv[2]; - } - if (isset($argv[3])) { - $table = $argv[3]; - } else { - $table = 'predb'; - } + if (file_exists($path) && is_file($path)) { + unlink($path); + } + if (isset($argv[3])) { + $table = $argv[3]; + } else { + $table = 'predb'; + } + echo $pdo->log->header('SELECT title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, g.name FROM '.$table." p LEFT OUTER JOIN groups g ON p.groups_id = g.id INTO OUTFILE '".$path."' FIELDS TERMINATED BY '\\t\\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\\r\\n';n"); + $pdo->queryExec('SELECT title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, g.name FROM '.$table." p LEFT OUTER JOIN groups g ON p.groups_id = g.id INTO OUTFILE '".$path."' FIELDS TERMINATED BY '\t\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\r\n'"); +} elseif (isset($argv[1]) && ($argv[1] == 'local' || $argv[1] == 'remote') && isset($argv[2]) && is_file($argv[2])) { + if (! preg_match('/^\//', $path)) { + $path = require_once getcwd().'/'.$argv[2]; + } + if (isset($argv[3])) { + $table = $argv[3]; + } else { + $table = 'predb'; + } - // Truncate predb_imports to clear any old data - $pdo->queryExec("TRUNCATE TABLE predb_imports"); + // Truncate predb_imports to clear any old data + $pdo->queryExec('TRUNCATE TABLE predb_imports'); - // Import file into predb_imports - if ($argv[1] == 'remote') { - echo $pdo->log->header("LOAD DATA LOCAL INFILE '" . $path . "' IGNORE into table predb_imports FIELDS TERMINATED BY '\\t\\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\\r\\n' (title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, groupname);"); - $pdo->queryExec("LOAD DATA LOCAL INFILE '" . $path . "' IGNORE into table predb_imports FIELDS TERMINATED BY '\t\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\r\n' (title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, groupname)"); - } else { - echo $pdo->log->header("LOAD DATA INFILE '" . $path . "' IGNORE into table predb_imports FIELDS TERMINATED BY '\\t\\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\\r\\n' (title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, groupname);"); - $pdo->queryExec("LOAD DATA INFILE '" . $path . "' IGNORE into table predb_imports FIELDS TERMINATED BY '\t\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\r\n' (title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, groupname)"); - } + // Import file into predb_imports + if ($argv[1] == 'remote') { + echo $pdo->log->header("LOAD DATA LOCAL INFILE '".$path."' IGNORE into table predb_imports FIELDS TERMINATED BY '\\t\\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\\r\\n' (title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, groupname);"); + $pdo->queryExec("LOAD DATA LOCAL INFILE '".$path."' IGNORE into table predb_imports FIELDS TERMINATED BY '\t\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\r\n' (title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, groupname)"); + } else { + echo $pdo->log->header("LOAD DATA INFILE '".$path."' IGNORE into table predb_imports FIELDS TERMINATED BY '\\t\\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\\r\\n' (title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, groupname);"); + $pdo->queryExec("LOAD DATA INFILE '".$path."' IGNORE into table predb_imports FIELDS TERMINATED BY '\t\t' ENCLOSED BY \"'\" LINES TERMINATED BY '\r\n' (title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, groupname)"); + } - // Remove any titles where length <=8 - echo $pdo->log->info("Deleting any records where title <=8 from Temporary Table"); - $pdo->queryExec("DELETE FROM predb_imports WHERE LENGTH(title) <= 8"); + // Remove any titles where length <=8 + echo $pdo->log->info('Deleting any records where title <=8 from Temporary Table'); + $pdo->queryExec('DELETE FROM predb_imports WHERE LENGTH(title) <= 8'); - // Add any groups that do not currently exist - $sqlAddGroups = <<queryExec($sqlAddGroups); + $pdo->queryExec($sqlAddGroups); - // Drop triggers on predb - echo $pdo->log->info("Dropping predb_hashes triggers"); - $pdo->queryExec("DROP TRIGGER IF EXISTS insert_hashes"); - $pdo->queryExec("DROP TRIGGER IF EXISTS update_hashes"); - $pdo->queryExec("DROP TRIGGER IF EXISTS delete_hashes"); + // Drop triggers on predb + echo $pdo->log->info('Dropping predb_hashes triggers'); + $pdo->queryExec('DROP TRIGGER IF EXISTS insert_hashes'); + $pdo->queryExec('DROP TRIGGER IF EXISTS update_hashes'); + $pdo->queryExec('DROP TRIGGER IF EXISTS delete_hashes'); - // Insert and update table - $sqlInsert = <<log->primary($sqlInsert); - $pdo->queryExec($sqlInsert); + echo $pdo->log->primary($sqlInsert); + $pdo->queryExec($sqlInsert); - // Add hashes g - echo $pdo->log->info("Adding predb_hashes entries"); - echo $pdo->log->info("Stage 1: UNHEX(MD5(TITLE))"); - $pdo->queryExec("INSERT IGNORE INTO predb_hashes (hash, predb_id) SELECT UNHEX(md5(title)), id from predb;"); - echo $pdo->log->info("Stage 1: UNHEX(MD5(MD5(TITLE)))"); - $pdo->queryExec("INSERT IGNORE INTO predb_hashes (hash, predb_id) SELECT UNHEX(md5(md5(title))), id from predb;"); - echo $pdo->log->info("Stage 1: UNHEX(SHA1(TITLE))"); - $pdo->queryExec("INSERT IGNORE INTO predb_hashes (hash, predb_id) SELECT UNHEX(sha1(title)), id from predb;"); + // Add hashes g + echo $pdo->log->info('Adding predb_hashes entries'); + echo $pdo->log->info('Stage 1: UNHEX(MD5(TITLE))'); + $pdo->queryExec('INSERT IGNORE INTO predb_hashes (hash, predb_id) SELECT UNHEX(md5(title)), id from predb;'); + echo $pdo->log->info('Stage 1: UNHEX(MD5(MD5(TITLE)))'); + $pdo->queryExec('INSERT IGNORE INTO predb_hashes (hash, predb_id) SELECT UNHEX(md5(md5(title))), id from predb;'); + echo $pdo->log->info('Stage 1: UNHEX(SHA1(TITLE))'); + $pdo->queryExec('INSERT IGNORE INTO predb_hashes (hash, predb_id) SELECT UNHEX(sha1(title)), id from predb;'); - // Re-add triggers on predb - echo $pdo->log->info("Adding predb_hashes triggers"); - $pdo->queryExec("CREATE TRIGGER insert_hashes AFTER INSERT ON predb FOR EACH ROW BEGIN INSERT INTO predb_hashes (hash, predb_id) VALUES (UNHEX(MD5(NEW.title)), NEW.id), (UNHEX(MD5(MD5(NEW.title))), NEW.id), ( UNHEX(SHA1(NEW.title)), NEW.id); END;"); - $pdo->queryExec("CREATE TRIGGER update_hashes AFTER UPDATE ON predb FOR EACH ROW BEGIN IF NEW.title != OLD.title THEN DELETE FROM predb_hashes WHERE hash IN ( UNHEX(md5(OLD.title)), UNHEX(md5(md5(OLD.title))), UNHEX(sha1(OLD.title)) ) AND predb_id = OLD.id; INSERT INTO predb_hashes (hash, predb_id) VALUES ( UNHEX(MD5(NEW.title)), NEW.id ), ( UNHEX(MD5(MD5(NEW.title))), NEW.id ), ( UNHEX(SHA1(NEW.title)), NEW.id ); END IF; END;"); - $pdo->queryExec("CREATE TRIGGER delete_hashes BEGIN DELETE FROM predb_hashes WHERE hash IN ( UNHEX(md5(OLD.title)), UNHEX(md5(md5(OLD.title))), UNHEX(sha1(OLD.title)) ) AND predb_id = OLD.id; END;"); + // Re-add triggers on predb + echo $pdo->log->info('Adding predb_hashes triggers'); + $pdo->queryExec('CREATE TRIGGER insert_hashes AFTER INSERT ON predb FOR EACH ROW BEGIN INSERT INTO predb_hashes (hash, predb_id) VALUES (UNHEX(MD5(NEW.title)), NEW.id), (UNHEX(MD5(MD5(NEW.title))), NEW.id), ( UNHEX(SHA1(NEW.title)), NEW.id); END;'); + $pdo->queryExec('CREATE TRIGGER update_hashes AFTER UPDATE ON predb FOR EACH ROW BEGIN IF NEW.title != OLD.title THEN DELETE FROM predb_hashes WHERE hash IN ( UNHEX(md5(OLD.title)), UNHEX(md5(md5(OLD.title))), UNHEX(sha1(OLD.title)) ) AND predb_id = OLD.id; INSERT INTO predb_hashes (hash, predb_id) VALUES ( UNHEX(MD5(NEW.title)), NEW.id ), ( UNHEX(MD5(MD5(NEW.title))), NEW.id ), ( UNHEX(SHA1(NEW.title)), NEW.id ); END IF; END;'); + $pdo->queryExec('CREATE TRIGGER delete_hashes BEGIN DELETE FROM predb_hashes WHERE hash IN ( UNHEX(md5(OLD.title)), UNHEX(md5(md5(OLD.title))), UNHEX(sha1(OLD.title)) ) AND predb_id = OLD.id; END;'); - $pdo->queryExec("TRUNCATE TABLE predb_imports"); + $pdo->queryExec('TRUNCATE TABLE predb_imports'); } else { - exit($pdo->log->error("\nThis script can export or import a predb dump file. You may use the full path, or a relative path.\n" - . "For importing, the script insert new rows and update existing matched rows. For databases not on the local system, use remote, else use local.\n" - . "For exporting, the path must be writeable by mysql, any existing file[predb_dump.csv] will be + exit($pdo->log->error("\nThis script can export or import a predb dump file. You may use the full path, or a relative path.\n" + ."For importing, the script insert new rows and update existing matched rows. For databases not on the local system, use remote, else use local.\n" + ."For exporting, the path must be writeable by mysql, any existing file[predb_dump.csv] will be overwritten.\n\n" - . "php dump_predb.php export /path/to/write/to ...: To export.\n" - . "php dump_predb.php [remote | local] /path/to/filename ...: To import.\n")); + ."php dump_predb.php export /path/to/write/to ...: To export.\n" + ."php dump_predb.php [remote | local] /path/to/filename ...: To import.\n")); } diff --git a/misc/testing/Releases/delete_releases.php b/misc/testing/Releases/delete_releases.php index 843c2675d..f4f5b2ad4 100644 --- a/misc/testing/Releases/delete_releases.php +++ b/misc/testing/Releases/delete_releases.php @@ -1,8 +1,10 @@ info($n . - 'This deletes releases based on a list of criteria you pass.' . $n . - 'Usage:' . $n . $n. - 'List of supported criteria:' . $n . - 'fromname : Look for names of people who posted releases (the poster name). (modifiers: equals, like)' . $n . - 'groupname : Look in groups. (modifiers: equals, like)' . $n . - 'guid : Look for a specific guid. (modifiers: equals)' . $n . - 'name : Look for a name (the usenet name). (modifiers: equals, like)' . $n . - 'searchname : Look for a name (the search name). (modifiers: equals, like)' . $n . - 'size : Release must be (bigger than |smaller than |exactly) this size.(bytes) (modifiers: equals,bigger,smaller)' . $n . - 'adddate : Look for releases added to our DB (older than|newer than) x hours. (modifiers: bigger,smaller)' . $n . - 'postdate : Look for posted to usenet (older than|newer than) x hours. (modifiers: bigger,smaller)' . $n . - 'completion : Look for completion (less than) (modifiers: smaller)' . $n . - 'categories_id : Look for releases within specified category (modifiers: equals)' . $n . - 'imdbid : Look for releases with imdbid (modifiers: equals)' . $n . - 'rageid : Look for releases with rageid (modifiers: equals)' . $n . - 'totalpart : Look for releases with certain number of parts (modifiers: equals,bigger,smaller)' . $n . - 'nzbstatus : Look for releases with nzbstatus (modifiers: equals)' . $n . $n . - 'List of Modifiers:' . $n . - 'equals : Match must be exactly this. (fromname=equals="john" will only look for "john", not "johndoe")' . $n . - 'like : Match can be similar to this. Separate words using spaces(ie:"cars hdtv x264").' . $n . - ' (fromname=like="john" will look for any posters with john in it (ie:john@smith.com)' . $n . - 'bigger : Match must be bigger than this. (postdate=bigger="3" means older than 3 hours ago)' . $n . - 'smaller : Match must be smaller than this (postdate=smaller="3" means between now and 3 hours ago.' . $n . $n . - 'Extra:' . $n . - 'ignore : Ignore the user check. (before running we ask you if you want to run the query to delete)' . $n . $n . - 'Examples:' . $n . - $_SERVER['_'] . ' ' . $argv[0] . ' groupname=equals="alt.binaries.teevee" searchname=like="olympics 2014" postdate=bigger="5"' . $n . - $_SERVER['_'] . ' ' . $argv[0] . ' guid=equals="8fb5956bae3de4fb94edcc69da44d6883d586fd0"' . $n . - $_SERVER['_'] . ' ' . $argv[0] . ' size=smaller="104857600" size=bigger="2048" groupname=like="movies"' . $n . - $_SERVER['_'] . ' ' . $argv[0] . ' fromname=like="@XviD.net" groupname=equals="alt.binaries.movies.divx" ignore' .$n . - $_SERVER['_'] . ' ' . $argv[0] . ' imdbid=equals=NULL categories_id=equals=2999 nzbstatus=equals=1 adddate=bigger=2880 # Remove other movie releases with non-cleaned names added > 120 days ago' + exit($cli->info($n. + 'This deletes releases based on a list of criteria you pass.'.$n. + 'Usage:'.$n.$n. + 'List of supported criteria:'.$n. + 'fromname : Look for names of people who posted releases (the poster name). (modifiers: equals, like)'.$n. + 'groupname : Look in groups. (modifiers: equals, like)'.$n. + 'guid : Look for a specific guid. (modifiers: equals)'.$n. + 'name : Look for a name (the usenet name). (modifiers: equals, like)'.$n. + 'searchname : Look for a name (the search name). (modifiers: equals, like)'.$n. + 'size : Release must be (bigger than |smaller than |exactly) this size.(bytes) (modifiers: equals,bigger,smaller)'.$n. + 'adddate : Look for releases added to our DB (older than|newer than) x hours. (modifiers: bigger,smaller)'.$n. + 'postdate : Look for posted to usenet (older than|newer than) x hours. (modifiers: bigger,smaller)'.$n. + 'completion : Look for completion (less than) (modifiers: smaller)'.$n. + 'categories_id : Look for releases within specified category (modifiers: equals)'.$n. + 'imdbid : Look for releases with imdbid (modifiers: equals)'.$n. + 'rageid : Look for releases with rageid (modifiers: equals)'.$n. + 'totalpart : Look for releases with certain number of parts (modifiers: equals,bigger,smaller)'.$n. + 'nzbstatus : Look for releases with nzbstatus (modifiers: equals)'.$n.$n. + 'List of Modifiers:'.$n. + 'equals : Match must be exactly this. (fromname=equals="john" will only look for "john", not "johndoe")'.$n. + 'like : Match can be similar to this. Separate words using spaces(ie:"cars hdtv x264").'.$n. + ' (fromname=like="john" will look for any posters with john in it (ie:john@smith.com)'.$n. + 'bigger : Match must be bigger than this. (postdate=bigger="3" means older than 3 hours ago)'.$n. + 'smaller : Match must be smaller than this (postdate=smaller="3" means between now and 3 hours ago.'.$n.$n. + 'Extra:'.$n. + 'ignore : Ignore the user check. (before running we ask you if you want to run the query to delete)'.$n.$n. + 'Examples:'.$n. + $_SERVER['_'].' '.$argv[0].' groupname=equals="alt.binaries.teevee" searchname=like="olympics 2014" postdate=bigger="5"'.$n. + $_SERVER['_'].' '.$argv[0].' guid=equals="8fb5956bae3de4fb94edcc69da44d6883d586fd0"'.$n. + $_SERVER['_'].' '.$argv[0].' size=smaller="104857600" size=bigger="2048" groupname=like="movies"'.$n. + $_SERVER['_'].' '.$argv[0].' fromname=like="@XviD.net" groupname=equals="alt.binaries.movies.divx" ignore'.$n. + $_SERVER['_'].' '.$argv[0].' imdbid=equals=NULL categories_id=equals=2999 nzbstatus=equals=1 adddate=bigger=2880 # Remove other movie releases with non-cleaned names added > 120 days ago' )); } $RR = new ReleaseRemover(); // Remove argv[0] and send the array. -$RR->removeByCriteria(array_slice($argv, 1, $totalArgs-1)); +$RR->removeByCriteria(array_slice($argv, 1, $totalArgs - 1)); diff --git a/misc/testing/Releases/fixReleaseNames.php b/misc/testing/Releases/fixReleaseNames.php index 1eb203abf..f28db8c8b 100755 --- a/misc/testing/Releases/fixReleaseNames.php +++ b/misc/testing/Releases/fixReleaseNames.php @@ -7,41 +7,42 @@ * there is another script called resetRelnameStatus.php */ -require_once dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'bootstrap.php'; -use App\Models\Settings; +use nntmux\NNTP; +use nntmux\db\DB; +use nntmux\PreDb; use nntmux\ColorCLI; use nntmux\NameFixer; -use nntmux\NNTP; -use nntmux\PreDb; -use nntmux\db\DB; +use App\Models\Settings; $pdo = new DB(); $namefixer = new NameFixer(['Settings' => $pdo]); $predb = new PreDb(['Echo' => true, 'Settings' => $pdo]); if (isset($argv[1], $argv[2], $argv[3], $argv[4])) { - $update = $argv[2] === 'true' ? true : false; - $other = 1; - if ($argv[3] === 'all') { - $other = 2; - } else if ($argv[3] === 'predb_id') { - $other = 3; - } - $setStatus = $argv[4] === 'yes' ? 1 : 2; + $update = $argv[2] === 'true' ? true : false; + $other = 1; + if ($argv[3] === 'all') { + $other = 2; + } elseif ($argv[3] === 'predb_id') { + $other = 3; + } + $setStatus = $argv[4] === 'yes' ? 1 : 2; - $show = isset($argv[5]) && $argv[5] === 'show' ? 1 : 2; + $show = isset($argv[5]) && $argv[5] === 'show' ? 1 : 2; - $nntp = null; - if ($argv[1] === 7 || $argv[1] === 8) { - $nntp = new NNTP(['Settings' => $pdo]); - if ((Settings::value('..alternate_nntp') === 1 ? $nntp->doConnect(true, true) : $nntp->doConnect()) !== true) { - echo ColorCLI::error('Unable to connect to usenet.'. PHP_EOL); - return; - } - } + $nntp = null; + if ($argv[1] === 7 || $argv[1] === 8) { + $nntp = new NNTP(['Settings' => $pdo]); + if ((Settings::value('..alternate_nntp') === 1 ? $nntp->doConnect(true, true) : $nntp->doConnect()) !== true) { + echo ColorCLI::error('Unable to connect to usenet.'.PHP_EOL); - switch ($argv[1]) { + return; + } + } + + switch ($argv[1]) { case 1: $predb->parseTitles(1, $update, $other, $setStatus, $show); break; @@ -90,30 +91,30 @@ if (isset($argv[1], $argv[2], $argv[3], $argv[4])) { case 16: $namefixer->fixNamesWithParHash(2, $update, $other, $setStatus, $show); break; - default : - exit(ColorCLI::error(PHP_EOL . 'ERROR: Wrong argument, type php $argv[0] to see a list of valid arguments.' . PHP_EOL)); + default: + exit(ColorCLI::error(PHP_EOL.'ERROR: Wrong argument, type php $argv[0] to see a list of valid arguments.'.PHP_EOL)); break; } } else { - exit(ColorCLI::error(PHP_EOL . 'You must supply 4 arguments.' . PHP_EOL - . 'The 2nd argument, false, will display the results, but not change the name, type true to have the names changed.' . PHP_EOL - . 'The 3rd argument, other, will only do against other categories, to do against all categories use all, or predb_id to process all not matched to predb.' . PHP_EOL - . 'The 4th argument, yes, will set the release as checked, so the next time you run it will not be processed, to not set as checked type no.' . PHP_EOL - . 'The 5th argument (optional), show, will display the release changes or only show a counter.\n' . PHP_EOL - . 'php ' . $argv[0] . ' 1 false other no ...: Fix release names using the usenet subject in the past 3 hours with predb information.' . PHP_EOL - . 'php ' . $argv[0] . ' 2 false other no ...: Fix release names using the usenet subject with predb information.' . PHP_EOL - . 'php ' . $argv[0] . ' 3 false other no ...: Fix release names using NFO in the past 6 hours.' . PHP_EOL - . 'php ' . $argv[0] . ' 4 false other no ...: Fix release names using NFO.' . PHP_EOL - . 'php ' . $argv[0] . ' 5 false other no ...: Fix release names in misc categories using File Name in the past 6 hours.' . PHP_EOL - . 'php ' . $argv[0] . ' 6 false other no ...: Fix release names in misc categories using File Name.' . PHP_EOL - . 'php ' . $argv[0] . ' 7 false other no ...: Fix release names in misc categories using Par2 Files in the past 6 hours.' . PHP_EOL - . 'php ' . $argv[0] . ' 8 false other no ...: Fix release names in misc categories using Par2 Files.' . PHP_EOL - . 'php ' . $argv[0] . ' 9 false other no ...: Fix release names in misc categories using UID in the past 6 hours.' . PHP_EOL - . 'php ' . $argv[0] . ' 10 false other no ...: Fix release names in misc categories using UID.' . PHP_EOL - . 'php ' . $argv[0] . ' 11 false other no ...: Fix SDPORN XXX release names in misc categories using specific File Name in the past 6 hours.' . PHP_EOL - . 'php ' . $argv[0] . ' 12 false other no ...: Fix SDPORN XXX release names in misc categories using specific File Name.' . PHP_EOL - . 'php ' . $argv[0] . ' 13 false other no ...: Fix release names in misc categories using SRR files in the past 6 hours.' . PHP_EOL - . 'php ' . $argv[0] . ' 14 false other no ...: Fix release names in misc categories using SRR files.' . PHP_EOL - . 'php ' . $argv[0] . ' 15 false other no ...: Fix release names in misc categories using PAR2 hash_16K block in the past 6 hours.' . PHP_EOL - . 'php ' . $argv[0] . ' 16 false other no ...: Fix release names in misc categories using PAR2 hash_16K block.' . PHP_EOL)); + exit(ColorCLI::error(PHP_EOL.'You must supply 4 arguments.'.PHP_EOL + .'The 2nd argument, false, will display the results, but not change the name, type true to have the names changed.'.PHP_EOL + .'The 3rd argument, other, will only do against other categories, to do against all categories use all, or predb_id to process all not matched to predb.'.PHP_EOL + .'The 4th argument, yes, will set the release as checked, so the next time you run it will not be processed, to not set as checked type no.'.PHP_EOL + .'The 5th argument (optional), show, will display the release changes or only show a counter.\n'.PHP_EOL + .'php '.$argv[0].' 1 false other no ...: Fix release names using the usenet subject in the past 3 hours with predb information.'.PHP_EOL + .'php '.$argv[0].' 2 false other no ...: Fix release names using the usenet subject with predb information.'.PHP_EOL + .'php '.$argv[0].' 3 false other no ...: Fix release names using NFO in the past 6 hours.'.PHP_EOL + .'php '.$argv[0].' 4 false other no ...: Fix release names using NFO.'.PHP_EOL + .'php '.$argv[0].' 5 false other no ...: Fix release names in misc categories using File Name in the past 6 hours.'.PHP_EOL + .'php '.$argv[0].' 6 false other no ...: Fix release names in misc categories using File Name.'.PHP_EOL + .'php '.$argv[0].' 7 false other no ...: Fix release names in misc categories using Par2 Files in the past 6 hours.'.PHP_EOL + .'php '.$argv[0].' 8 false other no ...: Fix release names in misc categories using Par2 Files.'.PHP_EOL + .'php '.$argv[0].' 9 false other no ...: Fix release names in misc categories using UID in the past 6 hours.'.PHP_EOL + .'php '.$argv[0].' 10 false other no ...: Fix release names in misc categories using UID.'.PHP_EOL + .'php '.$argv[0].' 11 false other no ...: Fix SDPORN XXX release names in misc categories using specific File Name in the past 6 hours.'.PHP_EOL + .'php '.$argv[0].' 12 false other no ...: Fix SDPORN XXX release names in misc categories using specific File Name.'.PHP_EOL + .'php '.$argv[0].' 13 false other no ...: Fix release names in misc categories using SRR files in the past 6 hours.'.PHP_EOL + .'php '.$argv[0].' 14 false other no ...: Fix release names in misc categories using SRR files.'.PHP_EOL + .'php '.$argv[0].' 15 false other no ...: Fix release names in misc categories using PAR2 hash_16K block in the past 6 hours.'.PHP_EOL + .'php '.$argv[0].' 16 false other no ...: Fix release names in misc categories using PAR2 hash_16K block.'.PHP_EOL)); } diff --git a/misc/testing/Releases/recategorize.php b/misc/testing/Releases/recategorize.php index 308a0769e..0c0a4e391 100644 --- a/misc/testing/Releases/recategorize.php +++ b/misc/testing/Releases/recategorize.php @@ -1,24 +1,25 @@ $pdo->log]); - $time = $consoletools->convertTime(time() - $timestart); - if ($update === true) { - echo ColorCLI::header('Finished re-categorizing ' . number_format($chgcount) . ' releases in ' . $time . ' , using the searchname.' . PHP_EOL); - } else { - echo ColorCLI::header('Finished re-categorizing in ' . $time . ' , using the searchname.' . PHP_EOL - . 'This would have changed ' . number_format($chgcount) . ' releases but no updates were done.' . PHP_EOL); - } + if (isset($argv[1]) && (is_numeric($argv[1]) || preg_match('/\([\d, ]+\)/', $argv[1]))) { + echo ColorCLI::header('Categorizing all releases in '.$argv[1].' using searchname. This can take a while, be patient.'); + } elseif (isset($argv[1]) && $argv[1] === 'misc') { + echo ColorCLI::header('Categorizing all releases in misc categories using searchname. This can take a while, be patient.'); + } else { + echo ColorCLI::header('Categorizing all releases using searchname. This can take a while, be patient.'); + } + $timestart = time(); + if (isset($argv[1]) && (is_numeric($argv[1]) || $argv[1] === 'misc')) { + $chgcount = categorizeRelease(str_replace(' AND', 'WHERE', $where), $update, true); + } else { + $chgcount = categorizeRelease('', $update, true); + } + $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); + $time = $consoletools->convertTime(time() - $timestart); + if ($update === true) { + echo ColorCLI::header('Finished re-categorizing '.number_format($chgcount).' releases in '.$time.' , using the searchname.'.PHP_EOL); + } else { + echo ColorCLI::header('Finished re-categorizing in '.$time.' , using the searchname.'.PHP_EOL + .'This would have changed '.number_format($chgcount).' releases but no updates were done.'.PHP_EOL); + } } // Categorizes releases. // Returns the quantity of categorized releases. function categorizeRelease($where, $update = true, $echooutput = false) { - global $pdo; - $cat = new Categorize(['Settings' => $pdo]); - $pdo->log = new ColorCLI(); - $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); - $relcount = $chgcount = 0; - echo ColorCLI::primary('SELECT id, searchname, fromname, groups_id, categories_id FROM releases ' . $where); - $resrel = $pdo->queryDirect('SELECT id, searchname, fromname, groups_id, categories_id FROM releases ' . $where); - $total = $resrel->rowCount(); - if ($total > 0) { - foreach ($resrel as $rowrel) { - $catId = $cat->determineCategory($rowrel['groups_id'], $rowrel['searchname'], $rowrel['fromname']); - if ((int)$rowrel['categories_id'] !== $catId) { - if ($update === true) { - $pdo->queryExec( + global $pdo; + $cat = new Categorize(['Settings' => $pdo]); + $pdo->log = new ColorCLI(); + $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); + $relcount = $chgcount = 0; + echo ColorCLI::primary('SELECT id, searchname, fromname, groups_id, categories_id FROM releases '.$where); + $resrel = $pdo->queryDirect('SELECT id, searchname, fromname, groups_id, categories_id FROM releases '.$where); + $total = $resrel->rowCount(); + if ($total > 0) { + foreach ($resrel as $rowrel) { + $catId = $cat->determineCategory($rowrel['groups_id'], $rowrel['searchname'], $rowrel['fromname']); + if ((int) $rowrel['categories_id'] !== $catId) { + if ($update === true) { + $pdo->queryExec( sprintf(' UPDATE releases SET iscategorized = 1, @@ -100,17 +101,18 @@ function categorizeRelease($where, $update = true, $echooutput = false) $rowrel['id'] ) ); - } - $chgcount++; - } - $relcount++; - if ($echooutput) { - $consoletools->overWritePrimary('Re-Categorized: [' . number_format($chgcount) . '] ' . $consoletools->percentString($relcount, $total)); - } - } - } - if ($echooutput !== false && $relcount > 0) { - echo PHP_EOL; - } - return $chgcount; + } + $chgcount++; + } + $relcount++; + if ($echooutput) { + $consoletools->overWritePrimary('Re-Categorized: ['.number_format($chgcount).'] '.$consoletools->percentString($relcount, $total)); + } + } + } + if ($echooutput !== false && $relcount > 0) { + echo PHP_EOL; + } + + return $chgcount; } diff --git a/misc/testing/Releases/removeCrapReleases.php b/misc/testing/Releases/removeCrapReleases.php index 4c84c2605..6cd3a870b 100755 --- a/misc/testing/Releases/removeCrapReleases.php +++ b/misc/testing/Releases/removeCrapReleases.php @@ -1,6 +1,7 @@ error( - $n . - 'Run fixReleaseNames.php first to attempt to fix release names.' . $n . - 'This will miss some releases if you have not set fixReleaseNames to set the release as checked.' . $n . $n . - "php $argv[0] false Display full usage of this script." . $n . + $n. + 'Run fixReleaseNames.php first to attempt to fix release names.'.$n. + 'This will miss some releases if you have not set fixReleaseNames to set the release as checked.'.$n.$n. + "php $argv[0] false Display full usage of this script.".$n. "php $argv[0] true full Run this script with all options." ) ); } if ($argCnt === 2) { - if ($argv[1] === 'false') { - exit( - "php $argv[0] arg1 arg2 arg3 arg4" . $n . $n . - 'arg1 (Required) = true/false' . $n . - ' true = Run this script and delete releases.' . $n . - ' false = Run this script and show what could be deleted.' . $n . $n . - 'arg2 (Required) = full/number' . $n . - ' full = Run without a time limit.' . $n . - ' number = Run on releases up to this old.' . $n . $n . - 'arg3 (Optional) = blacklist | blfiles | codec | executable | gibberish | hashed | huge | nzb | installbin | passworded | passwordurl | sample | scr | short | size | wmv_all' . $n . - ' blfiles = Remove releases using the enabled blacklists in admin section of site against filenames.' . $n . - ' codec = Remove releases where the release contains AVI or WMV file and is in x264 category (the spammer).' . $n . - ' executable = Remove releases containing an exe file.' . $n . - ' gibberish = Remove releases where the name is letters/numbers only and 15 characters or longer.' . $n . - ' hashed = Remove releases where the name is letters/numbers only and 25 characters or longer.' . $n . - ' huge = Remove releases with single file with size of over 200 megabytes.' . $n . - ' nzb = Remove releases having 1 file that is an nzb file.' . $n . - ' installbin = Remove releases which contain an install.bin file.' . $n . - ' passworded = Remove releases which contain the word password in the title.' . $n . - ' passwordurl = Remove releases which contain a password.url file.' . $n . - ' sample = Remove releases that are smaller than 40MB more than 1 file and have sample in the title' . $n . - ' scr = Remove releases where .scr extension is found in the files or subject.' . $n . - ' short = Remove releases where the name is only numbers or letters and is 5 characters or less.' . $n . - ' wmv_all = Remove releases where the release contains WMV file in any group!!.' . $n . - ' size = Remove releases smaller than 1MB and have only 1 file and not in books or mp3 section.' . $n . $n . - 'examples:' . $n . - "php $argv[0] true 12 blacklist = Remove releases up to 12 hours old using site blacklists." . $n . - "php $argv[0] false full = Show what releases could have been removed." . $n . - "php $argv[0] true full installbin = Remove releases which containing an install.bin file." . $n . - "php $argv[0] true full blacklist 1 = Remove releases matching blacklist id 1." . $n + if ($argv[1] === 'false') { + exit( + "php $argv[0] arg1 arg2 arg3 arg4".$n.$n. + 'arg1 (Required) = true/false'.$n. + ' true = Run this script and delete releases.'.$n. + ' false = Run this script and show what could be deleted.'.$n.$n. + 'arg2 (Required) = full/number'.$n. + ' full = Run without a time limit.'.$n. + ' number = Run on releases up to this old.'.$n.$n. + 'arg3 (Optional) = blacklist | blfiles | codec | executable | gibberish | hashed | huge | nzb | installbin | passworded | passwordurl | sample | scr | short | size | wmv_all'.$n. + ' blfiles = Remove releases using the enabled blacklists in admin section of site against filenames.'.$n. + ' codec = Remove releases where the release contains AVI or WMV file and is in x264 category (the spammer).'.$n. + ' executable = Remove releases containing an exe file.'.$n. + ' gibberish = Remove releases where the name is letters/numbers only and 15 characters or longer.'.$n. + ' hashed = Remove releases where the name is letters/numbers only and 25 characters or longer.'.$n. + ' huge = Remove releases with single file with size of over 200 megabytes.'.$n. + ' nzb = Remove releases having 1 file that is an nzb file.'.$n. + ' installbin = Remove releases which contain an install.bin file.'.$n. + ' passworded = Remove releases which contain the word password in the title.'.$n. + ' passwordurl = Remove releases which contain a password.url file.'.$n. + ' sample = Remove releases that are smaller than 40MB more than 1 file and have sample in the title'.$n. + ' scr = Remove releases where .scr extension is found in the files or subject.'.$n. + ' short = Remove releases where the name is only numbers or letters and is 5 characters or less.'.$n. + ' wmv_all = Remove releases where the release contains WMV file in any group!!.'.$n. + ' size = Remove releases smaller than 1MB and have only 1 file and not in books or mp3 section.'.$n.$n. + 'examples:'.$n. + "php $argv[0] true 12 blacklist = Remove releases up to 12 hours old using site blacklists.".$n. + "php $argv[0] false full = Show what releases could have been removed.".$n. + "php $argv[0] true full installbin = Remove releases which containing an install.bin file.".$n. + "php $argv[0] true full blacklist 1 = Remove releases matching blacklist id 1.".$n ); - } else { - exit ($cli->error("Wrong usage! Type php $argv[0] false")); - } + } else { + exit($cli->error("Wrong usage! Type php $argv[0] false")); + } } if ($argCnt < 3) { - exit ($cli->error("Wrong usage! Type php $argv[0] false")); + exit($cli->error("Wrong usage! Type php $argv[0] false")); } if (isset($argv[3]) && $argv[3] === 'blacklist' && isset($argv[4])) { - $blacklistID = $argv[4]; + $blacklistID = $argv[4]; } $RR = new ReleaseRemover(); diff --git a/misc/testing/Tests/memcache.php b/misc/testing/Tests/memcache.php index 9189460ec..034847fc6 100644 --- a/misc/testing/Tests/memcache.php +++ b/misc/testing/Tests/memcache.php @@ -4,14 +4,15 @@ // apt-get install php5-memcache // -$memcache_enabled = extension_loaded("memcached"); +$memcache_enabled = extension_loaded('memcached'); -if ($memcache_enabled) - echo "extension loaded"; -else - echo "extension not loaded"; +if ($memcache_enabled) { + echo 'extension loaded'; +} else { + echo 'extension not loaded'; +} $mc = new Memcached(); -$mc->connect("localhost", 11211) ; +$mc->connect('localhost', 11211); print_r($mc->getStats()); diff --git a/misc/testing/Tests/regexverify.php b/misc/testing/Tests/regexverify.php index 76e49e94e..d45e5d5ff 100644 --- a/misc/testing/Tests/regexverify.php +++ b/misc/testing/Tests/regexverify.php @@ -1,15 +1,15 @@ "", - "illformed" => "[](9()))))))))) [34543/34]", - "simple" => '"data.mp3', - ); +$regs = [ + '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"; +// fetch enabled regular expression +$catsql = 'select ID,groupname,regex from releaseregex where status = 1'; $res = $db->query($catsql); -$total=count($res); -$errcnt=0; +$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; - } - } +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); +exit(($errcnt > 0) ? 1 : 0); diff --git a/misc/testing/Tests/test_amazon_API.php b/misc/testing/Tests/test_amazon_API.php index 648d29f57..bda8c6b5f 100644 --- a/misc/testing/Tests/test_amazon_API.php +++ b/misc/testing/Tests/test_amazon_API.php @@ -1,11 +1,11 @@ getMessage() . PHP_EOL); + exit($error->getMessage().PHP_EOL); } print_r($cache->serverStatistics()); diff --git a/misc/testing/Tests/test_fanarttv_API.php b/misc/testing/Tests/test_fanarttv_API.php index 5e4e9895c..fb71ba6e2 100644 --- a/misc/testing/Tests/test_fanarttv_API.php +++ b/misc/testing/Tests/test_fanarttv_API.php @@ -1,26 +1,24 @@ getMovieFanart((string)$argv[1]); - if ($moviefanart) { - - print_r($moviefanart); - - } else { - exit(ColorCLI::error('Error retrieving Fanart.TV data.')); - } + // Search for a movie/tv + $moviefanart = $fanart->getMovieFanart((string) $argv[1]); + if ($moviefanart) { + print_r($moviefanart); + } else { + exit(ColorCLI::error('Error retrieving Fanart.TV data.')); + } } else { - exit(ColorCLI::error('Invalid arguments. This script requires a number or string (TMDB or IMDb ID.')); + exit(ColorCLI::error('Invalid arguments. This script requires a number or string (TMDB or IMDb ID.')); } diff --git a/misc/testing/Tests/test_giantbomb_API.php b/misc/testing/Tests/test_giantbomb_API.php index e9142abcc..83962f75f 100755 --- a/misc/testing/Tests/test_giantbomb_API.php +++ b/misc/testing/Tests/test_giantbomb_API.php @@ -1,44 +1,45 @@ getSetting('giantbombkey'); $cli = new ColorCLI(); -$obj = new GiantBomb($giantbombkey, $resp = "json"); +$obj = new GiantBomb($giantbombkey, $resp = 'json'); -$searchgame = "South Park The Stick of Truth"; +$searchgame = 'South Park The Stick of Truth'; $resultsfound = 0; $e = null; try { - $fields = array( - "deck", "description", "original_game_rating", "api_detail_url", "image", "genres", "name", - "platforms", "publishers", "original_release_date", "reviews", "site_detail_url" - ); - $result = $obj->search($searchgame, $fields, 1); - $result = json_decode(json_encode($result), true); - if ($result['number_of_total_results'] != 0) { - $resultsfound = count($result['results']); - for ($i = 0; $i <= $resultsfound; $i++) { - similar_text($result['results'][$i]['name'], $searchgame, $p); - if ($p > 90) { - $result = $result['results'][$i]; - break; - } - } - } + $fields = [ + 'deck', 'description', 'original_game_rating', 'api_detail_url', 'image', 'genres', 'name', + 'platforms', 'publishers', 'original_release_date', 'reviews', 'site_detail_url', + ]; + $result = $obj->search($searchgame, $fields, 1); + $result = json_decode(json_encode($result), true); + if ($result['number_of_total_results'] != 0) { + $resultsfound = count($result['results']); + for ($i = 0; $i <= $resultsfound; $i++) { + similar_text($result['results'][$i]['name'], $searchgame, $p); + if ($p > 90) { + $result = $result['results'][$i]; + break; + } + } + } } catch (\Exception $e) { - $result = false; + $result = false; } -if ($result !== false && !empty($result)) { - print_r($result); - exit($cli->header("\nLooks like it is working alright.")); +if ($result !== false && ! empty($result)) { + print_r($result); + exit($cli->header("\nLooks like it is working alright.")); } else { - print_r($e); - exit($cli->error("\nThere was a problem attempting to query giantbomb. Maybe your key is wrong, or you are being throttled.\n")); + print_r($e); + exit($cli->error("\nThere was a problem attempting to query giantbomb. Maybe your key is wrong, or you are being throttled.\n")); } diff --git a/misc/testing/Tests/test_nntp_server.php b/misc/testing/Tests/test_nntp_server.php index 290a5b52c..b5c9b57ed 100755 --- a/misc/testing/Tests/test_nntp_server.php +++ b/misc/testing/Tests/test_nntp_server.php @@ -1,20 +1,21 @@ error("\nTest your nntp connection, get group information and postdate for specific article.\n\n" - . "php $argv[0] alt.binaries.teevee 595751142 ...: To test nntp on alt.binaries.teevee with artivle 595751142.\n")); +if (! isset($argv[2]) || ! is_numeric($argv[2])) { + exit($cli->error("\nTest your nntp connection, get group information and postdate for specific article.\n\n" + ."php $argv[0] alt.binaries.teevee 595751142 ...: To test nntp on alt.binaries.teevee with artivle 595751142.\n")); } $nntp = new NNTP(); if ($nntp->doConnect() !== true) { - exit(); + exit(); } $first = $argv[2]; @@ -25,7 +26,7 @@ $groupArr = $nntp->selectGroup($group); print_r($groupArr); // Insert actual local part numbers here. -$msg = $nntp->getXOVER($first . '-' . $first); +$msg = $nntp->getXOVER($first.'-'.$first); // Print out the array of headers. print_r($msg); @@ -33,4 +34,4 @@ print_r($msg); // get postdate for an article $binaries = new Binaries(['NNTP' => $nntp]); $newdate = $binaries->postdate($first, $groupArr); -echo $cli->primary("The posted date for " . $group . ", article " . $first . " is " . date('Y-m-d H:i:s', $newdate)); +echo $cli->primary('The posted date for '.$group.', article '.$first.' is '.date('Y-m-d H:i:s', $newdate)); diff --git a/misc/testing/Tests/test_omdb_API.php b/misc/testing/Tests/test_omdb_API.php index 0868fe42c..d7b411127 100644 --- a/misc/testing/Tests/test_omdb_API.php +++ b/misc/testing/Tests/test_omdb_API.php @@ -1,34 +1,31 @@ search((string)$argv[1], (string)$argv[2]); - if (is_object($search) && $search->data->Response !== 'False' ) { - print_r($search->data->Search[0]->Title. PHP_EOL); - } + // Search for a show + $search = $omdb->search((string) $argv[1], (string) $argv[2]); + if (is_object($search) && $search->data->Response !== 'False') { + print_r($search->data->Search[0]->Title.PHP_EOL); + } - // Use the first show found (highest match) and get the requested season/episode from $argv - if (is_object($search) && $search->data->Response !== 'False') { + // Use the first show found (highest match) and get the requested season/episode from $argv + if (is_object($search) && $search->data->Response !== 'False') { + $search = $omdb->fetch('i', $search->data->Search[0]->imdbID); - $search = $omdb->fetch('i', $search->data->Search[0]->imdbID); - - print_r($search); - - - } else { - exit(ColorCLI::error('Error retrieving OMDb API data.')); - } + print_r($search); + } else { + exit(ColorCLI::error('Error retrieving OMDb API data.')); + } } else { - exit(ColorCLI::error('Invalid arguments. This script requires a text string (show name), and a second argument, movie or series.')); + exit(ColorCLI::error('Invalid arguments. This script requires a text string (show name), and a second argument, movie or series.')); } diff --git a/misc/testing/Tests/test_regex.php b/misc/testing/Tests/test_regex.php index 9359e72ef..f67c2f07a 100644 --- a/misc/testing/Tests/test_regex.php +++ b/misc/testing/Tests/test_regex.php @@ -1,11 +1,12 @@ "", - "illformed" => "[](9()))))))))) [34543/34]", - "simple" => '"data.mp3', - ); +$regs = [ + '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"; +// fetch enabled regular expression +$catsql = 'select ID,groupname,regex from releaseregex where status = 1'; $res = $db->query($catsql); -$total=count($res); -$errcnt=0; +$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; - } - } +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); +exit(($errcnt > 0) ? 1 : 0); diff --git a/misc/testing/Tests/test_tmdb_API.php b/misc/testing/Tests/test_tmdb_API.php index a6897efaa..22d739a7e 100755 --- a/misc/testing/Tests/test_tmdb_API.php +++ b/misc/testing/Tests/test_tmdb_API.php @@ -1,59 +1,57 @@ client->getSearchApi()->searchTv((string)$argv[1]); - print_r($series); + // Search for a show + $series = $tmdb->client->getSearchApi()->searchTv((string) $argv[1]); + print_r($series); - // Use the first show found (highest match) and get the requested season/episode from $argv - if (!empty($series) && $series['total_results'] > 0) { - $seriesAppends = [ + // Use the first show found (highest match) and get the requested season/episode from $argv + if (! empty($series) && $series['total_results'] > 0) { + $seriesAppends = [ 'networks' => $tmdb->client->getTvApi()->getTvshow($series['results'][0]['id'])['networks'], 'alternative_titles' => $tmdb->client->getTvApi()->getAlternativeTitles($series['results'][0]['id']), - 'external_ids' => $tmdb->client->getTvApi()->getExternalIds($series['results'][0]['id']) + 'external_ids' => $tmdb->client->getTvApi()->getExternalIds($series['results'][0]['id']), ]; - print_r($seriesAppends); - if ($seriesAppends) { - $series['results'][0]['networks'] = $seriesAppends['networks']; - $series['results'][0]['alternative_titles'] = $seriesAppends['alternative_titles']; - $series['results'][0]['external_ids'] = $seriesAppends['external_ids']; - } + print_r($seriesAppends); + if ($seriesAppends) { + $series['results'][0]['networks'] = $seriesAppends['networks']; + $series['results'][0]['alternative_titles'] = $seriesAppends['alternative_titles']; + $series['results'][0]['external_ids'] = $seriesAppends['external_ids']; + } - print_r($series['results'][0]); - - if ($season > 0 && $episode > 0) { - $episodeObj = $tmdb->client->getTvEpisodeApi()->getEpisode($series['results'][0]['id'], $season, $episode); - if ($episodeObj) { - print_r($episodeObj); - } - } else if ($season === 0 && $episode === 0) { - $episodeObj = $tmdb->client->getTvApi()->getTvshow($series['results'][0]['id']); - if (is_array($episodeObj)) { - foreach ($episodeObj AS $ep) { - print_r($ep); - } - } - } else { - exit(\nntmux\ColorCLI::error('Invalid episode data returned from TMDB API.')); - } - - } else { - exit(\nntmux\ColorCLI::error('Invalid show data returned from TMDB API.')); - } + print_r($series['results'][0]); + if ($season > 0 && $episode > 0) { + $episodeObj = $tmdb->client->getTvEpisodeApi()->getEpisode($series['results'][0]['id'], $season, $episode); + if ($episodeObj) { + print_r($episodeObj); + } + } elseif ($season === 0 && $episode === 0) { + $episodeObj = $tmdb->client->getTvApi()->getTvshow($series['results'][0]['id']); + if (is_array($episodeObj)) { + foreach ($episodeObj as $ep) { + print_r($ep); + } + } + } else { + exit(\nntmux\ColorCLI::error('Invalid episode data returned from TMDB API.')); + } + } else { + exit(\nntmux\ColorCLI::error('Invalid show data returned from TMDB API.')); + } } else { - exit(\nntmux\ColorCLI::error('Invalid arguments. This script requires a text string (show name) followed by a season and episode number.')); + exit(\nntmux\ColorCLI::error('Invalid arguments. This script requires a text string (show name) followed by a season and episode number.')); } diff --git a/misc/testing/Tests/test_trakt_API.php b/misc/testing/Tests/test_trakt_API.php index a791afb45..e0844bc0e 100755 --- a/misc/testing/Tests/test_trakt_API.php +++ b/misc/testing/Tests/test_trakt_API.php @@ -1,32 +1,30 @@ client->showSearch((string)$argv[1], 'show'); + // Search for a show + $series = $trakt->client->showSearch((string) $argv[1], 'show'); - // Use the first show found (highest match) and get the requested season/episode from $argv - if (is_array($series)) { + // Use the first show found (highest match) and get the requested season/episode from $argv + if (is_array($series)) { + $series = $trakt->client->showSummary($series[0]['show']['ids']['trakt'], 'full,images'); + $episode = $trakt->client->episodeSummary($series['ids']['trakt'], (int) $argv[2], (int) $argv[3], 'full'); - $series = $trakt->client->showSummary($series[0]['show']['ids']['trakt'], 'full,images'); - $episode = $trakt->client->episodeSummary($series['ids']['trakt'], (int)$argv[2], (int)$argv[3], 'full'); - - print_r($series); - print_r($episode); - - } else { - exit($c->error("Error retrieving Trakt data.")); - } + print_r($series); + print_r($episode); + } else { + exit($c->error('Error retrieving Trakt data.')); + } } else { - exit($c->error("Invalid arguments. This script requires a text string (show name) followed by a season and episode number.")); + exit($c->error('Invalid arguments. This script requires a text string (show name) followed by a season and episode number.')); } diff --git a/misc/testing/Tests/test_tvdb_API.php b/misc/testing/Tests/test_tvdb_API.php index 03c52d777..9ffd9790f 100755 --- a/misc/testing/Tests/test_tvdb_API.php +++ b/misc/testing/Tests/test_tvdb_API.php @@ -1,77 +1,75 @@ client->search()->seriesByName((string)$argv[1]); + // Search for a show + $series = $tvdb->client->search()->seriesByName((string) $argv[1]); - // Use the first show found (highest match) and get the requested season/episode from $argv - if ($series) { - $serie = $series->getData(); - print_r($serie); + // Use the first show found (highest match) and get the requested season/episode from $argv + if ($series) { + $serie = $series->getData(); + print_r($serie); + if ($season > 0 && $episode > 0 && $day === '') { + try { + $episodeObj = $tvdb->client->series()->getEpisodesWithQuery($serie[0]->getid(), ['airedSeason' => $season, 'airedEpisode' => $episode]); + } catch (InvalidArgumentException $error) { + echo 'Invalid argument(s) used'.PHP_EOL; - if ($season > 0 && $episode > 0 && $day === '') { - try { - $episodeObj = $tvdb->client->series()->getEpisodesWithQuery($serie[0]->getid(), ['airedSeason' => $season, 'airedEpisode' => $episode]); - } catch (InvalidArgumentException $error) { - echo 'Invalid argument(s) used' . PHP_EOL; - return false; - } catch (InvalidJsonInResponseException $error) { - if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { - return false; - } - } catch (RequestFailedException $error) { - return false; - } catch (UnauthorizedException $error) { - if (strpos($error->getMessage(), 'Unauthorized') === 0) { - return false; - } - } - - if ($episodeObj) { - print_r($episodeObj); - } - } else if ($season === 0 && $episode === 0) { - $episodeObj = $tvdb->client->series()->getEpisodes($serie[0]->getid()); - if (is_object($episodeObj)) { - foreach ($episodeObj->getData() AS $ep) { - print_r($ep); - } - } - } else if (preg_match('#^(19|20)\d{2}\/\d{2}\/\d{2}$#', $season . '/' . $episode . '/' . $day, $airdate)) { - $episodeObj = $tvdb->client->series()->getEpisodesWithQuery($series[0]->id, ['firstAired' => (string)$airdate[0]]); - if ($episodeObj) { - print_r($episodeObj); - } - } else { - exit($c->error('Invalid episode data returned from TVDB API.')); - } - - } else { - exit($c->error('Invalid show data returned from TVDB API.')); - } + return false; + } catch (InvalidJsonInResponseException $error) { + if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { + return false; + } + } catch (RequestFailedException $error) { + return false; + } catch (UnauthorizedException $error) { + if (strpos($error->getMessage(), 'Unauthorized') === 0) { + return false; + } + } + if ($episodeObj) { + print_r($episodeObj); + } + } elseif ($season === 0 && $episode === 0) { + $episodeObj = $tvdb->client->series()->getEpisodes($serie[0]->getid()); + if (is_object($episodeObj)) { + foreach ($episodeObj->getData() as $ep) { + print_r($ep); + } + } + } elseif (preg_match('#^(19|20)\d{2}\/\d{2}\/\d{2}$#', $season.'/'.$episode.'/'.$day, $airdate)) { + $episodeObj = $tvdb->client->series()->getEpisodesWithQuery($series[0]->id, ['firstAired' => (string) $airdate[0]]); + if ($episodeObj) { + print_r($episodeObj); + } + } else { + exit($c->error('Invalid episode data returned from TVDB API.')); + } + } else { + exit($c->error('Invalid show data returned from TVDB API.')); + } } else { - exit($c->error('Invalid arguments. This script requires a text string (show name) followed by a season and episode number.' . PHP_EOL . + exit($c->error('Invalid arguments. This script requires a text string (show name) followed by a season and episode number.'.PHP_EOL. 'You can also optionally supply "YYYY" "MM" "DD" arguments instead of season/episode for an airdate lookup.') ); } diff --git a/misc/testing/Tests/test_tvmaze_API.php b/misc/testing/Tests/test_tvmaze_API.php index 14adfa132..6a251b480 100755 --- a/misc/testing/Tests/test_tvmaze_API.php +++ b/misc/testing/Tests/test_tvmaze_API.php @@ -1,50 +1,47 @@ client->search((string)$argv[1]); + // Search for a show + $series = $tvmaze->client->search((string) $argv[1]); - // Use the first show found (highest match) and get the requested season/episode from $argv - if ($series) { - - echo PHP_EOL . $c->info("Server Time: " . $serverTime) . PHP_EOL; - print_r($series[0]); - - if ($season > 0 AND $episode > 0) { - $episodeObj = $tvmaze->client->getEpisodeByNumber($series[0]->id, $season, $episode); - if ($episodeObj) { - print_r($episodeObj); - } - } else if ($season == 0 && $episode == 0) { - $episodeObj = $tvmaze->client->getEpisodesByShowID($series[0]->id); - if (is_array($episodeObj)) { - echo '*'; - foreach ($episodeObj AS $ep) { - print_r($ep); - } - } - } else { - exit($c->error("Invalid episode data returned from TVMaze API.")); - } - - } else { - exit($c->error("Invalid show data returned from TVMaze API.")); - } + // Use the first show found (highest match) and get the requested season/episode from $argv + if ($series) { + echo PHP_EOL.$c->info('Server Time: '.$serverTime).PHP_EOL; + print_r($series[0]); + if ($season > 0 and $episode > 0) { + $episodeObj = $tvmaze->client->getEpisodeByNumber($series[0]->id, $season, $episode); + if ($episodeObj) { + print_r($episodeObj); + } + } elseif ($season == 0 && $episode == 0) { + $episodeObj = $tvmaze->client->getEpisodesByShowID($series[0]->id); + if (is_array($episodeObj)) { + echo '*'; + foreach ($episodeObj as $ep) { + print_r($ep); + } + } + } else { + exit($c->error('Invalid episode data returned from TVMaze API.')); + } + } else { + exit($c->error('Invalid show data returned from TVMaze API.')); + } } else { - exit($c->error("Invalid arguments. This script requires a text string (show name) followed by a season and episode number.")); + exit($c->error('Invalid arguments. This script requires a text string (show name) followed by a season and episode number.')); } diff --git a/misc/testing/Tests/timetest.php b/misc/testing/Tests/timetest.php index 7f7aacf84..717416255 100644 --- a/misc/testing/Tests/timetest.php +++ b/misc/testing/Tests/timetest.php @@ -1,27 +1,26 @@ queryOneRow( sprintf("Select now()")); -foreach($res as $time){ -echo "Mysql Time Is Now ".$time."\n";} -$res=""; +$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=""; +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"; +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"; } -else -{ - exec("date", $res); - echo "System Time is Now ".$res['0']."\n"; -} - diff --git a/misc/testing/Tests/transactiontest.php b/misc/testing/Tests/transactiontest.php index f43110426..02ce1d257 100644 --- a/misc/testing/Tests/transactiontest.php +++ b/misc/testing/Tests/transactiontest.php @@ -1,5 +1,6 @@ setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Start the transaction - if( $db->beginTransaction() ) - { + if ($db->beginTransaction()) { // Loop 20 times - for($i=1 ; $i<=20 ; $i++ ) - { + for ($i = 1; $i <= 20; $i++) { // Header - echo "--[ Insert run: {$i} ]----------------------------------------". PHP_EOL; + 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() ); + var_dump($newDb, $newDb->getPDO()); // Insert some data $sql = sprintf(" @@ -32,15 +31,15 @@ try { VALUES ('%s', '%s', '%s', '%s', '%s')", $i, $i, $i, $i, $i ); - $newDb->exec( $sql ); + $newDb->exec($sql); // Check for inserted data - var_dump( $newDb->query( sprintf( "SELECT * FROM `testdata` WHERE id = %d", $i ) ) ); + var_dump($newDb->query(sprintf('SELECT * FROM `testdata` WHERE id = %d', $i))); } // Now rollback using the last db class instance - var_dump( $newDb->rollback() ); + var_dump($newDb->rollback()); } -} catch(PDOException $e) { - var_dump( $e ); +} catch (PDOException $e) { + var_dump($e); } diff --git a/misc/testing/Various/find_password_hash_cost.php b/misc/testing/Various/find_password_hash_cost.php index c5572f8c2..697a7a68d 100644 --- a/misc/testing/Various/find_password_hash_cost.php +++ b/misc/testing/Various/find_password_hash_cost.php @@ -7,23 +7,22 @@ * * Set this number in www/settings.php, the nZEDb_PASSWORD_HASH_COST setting. */ - -if (!isset($argv[1]) || !is_numeric($argv[1]) || $argv[1] < 0.05) { - exit( - 'You can pass in a target time, which will be used to determine the cost.' . PHP_EOL . - 'The target time is the amount of time it will take to hash a password.' . PHP_EOL . - 'Hashing of passwords happens when a user registers an account or their hash needs to be updated because it is insecure.' . PHP_EOL . - 'Values between 0.2 and 0.5 are recommended. The minimum is 0.05 for security reasons.' . PHP_EOL +if (! isset($argv[1]) || ! is_numeric($argv[1]) || $argv[1] < 0.05) { + exit( + 'You can pass in a target time, which will be used to determine the cost.'.PHP_EOL. + 'The target time is the amount of time it will take to hash a password.'.PHP_EOL. + 'Hashing of passwords happens when a user registers an account or their hash needs to be updated because it is insecure.'.PHP_EOL. + 'Values between 0.2 and 0.5 are recommended. The minimum is 0.05 for security reasons.'.PHP_EOL ); } $timeTarget = $argv[1]; $cost = 7; do { - $cost++; - $start = microtime(true); - password_hash("test", PASSWORD_DEFAULT, ["cost" => $cost]); - $end = microtime(true); + $cost++; + $start = microtime(true); + password_hash('test', PASSWORD_DEFAULT, ['cost' => $cost]); + $end = microtime(true); } while (($end - $start) < $timeTarget); -echo "Appropriate Cost Found: " . $cost . PHP_EOL; +echo 'Appropriate Cost Found: '.$cost.PHP_EOL; diff --git a/misc/testing/Various/renametopre.php b/misc/testing/Various/renametopre.php index 68973eb10..509affda4 100644 --- a/misc/testing/Various/renametopre.php +++ b/misc/testing/Various/renametopre.php @@ -1,15 +1,16 @@ log->error( +if (! (isset($argv[1]) && ($argv[1] == 'all' || $argv[1] == 'full' || $argv[1] == 'predb_id' || is_numeric($argv[1])))) { + exit($pdo->log->error( "\nThis script will attempt to rename releases using regexes first from ReleaseCleaning.php and then from this file.\n" - . "An optional last argument, show, will display the release name changes.\n\n" - . "php $argv[0] full ...: To process all releases not previously renamed.\n" - . "php $argv[0] 2 ...: To process all releases added in the previous 2 hours not previously renamed.\n" - . "php $argv[0] all ...: To process all releases.\n" - . "php $argv[0] full 155 ...: To process all releases in groupid 155 not previously renamed.\n" - . "php $argv[0] all 155 ...: To process all releases in groupid 155.\n" - . "php $argv[0] all '(155, 140)' ...: To process all releases in group_ids 155 and 140.\n" - . "php $argv[0] predb_id ...: To process all releases where not matched to predb.\n" + ."An optional last argument, show, will display the release name changes.\n\n" + ."php $argv[0] full ...: To process all releases not previously renamed.\n" + ."php $argv[0] 2 ...: To process all releases added in the previous 2 hours not previously renamed.\n" + ."php $argv[0] all ...: To process all releases.\n" + ."php $argv[0] full 155 ...: To process all releases in groupid 155 not previously renamed.\n" + ."php $argv[0] all 155 ...: To process all releases in groupid 155.\n" + ."php $argv[0] all '(155, 140)' ...: To process all releases in group_ids 155 and 140.\n" + ."php $argv[0] predb_id ...: To process all releases where not matched to predb.\n" )); } preName($argv, $argc); function preName($argv, $argc) { - global $pdo; - $groups = new Groups(['Settings' => $pdo]); - $category = new Categorize(['Settings' => $pdo]); - $internal = $external = $pre = 0; - $show = 2; - if ($argv[$argc - 1] === 'show') { - $show = 1; - } else if ($argv[$argc - 1] === 'bad') { - $show = 3; - } - $counter = 0; - $pdo->log = new ColorCLI(); - $full = $all = $usepre = false; - $what = $where = ''; - if ($argv[1] === 'full') { - $full = true; - } else if ($argv[1] === 'all') { - $all = true; - } else if ($argv[1] === 'predb_id') { - $usepre = true; - } else if (is_numeric($argv[1])) { - $what = ' AND adddate > NOW() - INTERVAL ' . $argv[1] . ' HOUR'; - } - if ($usepre === true) { - $where = ''; - $why = ' WHERE predb_id = 0 AND nzbstatus = 1'; - } else if (isset($argv[1]) && is_numeric($argv[1])) { - $where = ''; - $why = ' WHERE nzbstatus = 1 AND isrenamed = 0'; - } else if (isset($argv[2]) && is_numeric($argv[2]) && $full === true) { - $where = ' AND groups_id = ' . $argv[2]; - $why = ' WHERE nzbstatus = 1 AND isrenamed = 0'; - } else if (isset($argv[2]) && preg_match('/\([\d, ]+\)/', $argv[2]) && $full === true) { - $where = ' AND groups_id IN ' . $argv[2]; - $why = ' WHERE nzbstatus = 1 AND isrenamed = 0'; - } else if (isset($argv[2]) && preg_match('/\([\d, ]+\)/', $argv[2]) && $all === true) { - $where = ' AND groups_id IN ' . $argv[2]; - $why = ' WHERE nzbstatus = 1'; - } else if (isset($argv[2]) && is_numeric($argv[2]) && $all === true) { - $where = ' AND groups_id = ' . $argv[2]; - $why = ' WHERE nzbstatus = 1 and predb_id = 0'; - } else if (isset($argv[2]) && is_numeric($argv[2])) { - $where = ' AND groups_id = ' . $argv[2]; - $why = ' WHERE nzbstatus = 1 AND isrenamed = 0'; - } else if ($full === true) { - $why = ' WHERE nzbstatus = 1 AND (isrenamed = 0 OR categories_id between 7000 AND 7999)'; - } else if ($all === true) { - $why = ' WHERE nzbstatus = 1'; - } else { - $why = ' WHERE 1=1'; - } - resetSearchnames(); - echo $pdo->log->header( - "SELECT id, name, searchname, fromname, size, groups_id, categories_id FROM releases" . $why . $what . - $where . ";\n" + global $pdo; + $groups = new Groups(['Settings' => $pdo]); + $category = new Categorize(['Settings' => $pdo]); + $internal = $external = $pre = 0; + $show = 2; + if ($argv[$argc - 1] === 'show') { + $show = 1; + } elseif ($argv[$argc - 1] === 'bad') { + $show = 3; + } + $counter = 0; + $pdo->log = new ColorCLI(); + $full = $all = $usepre = false; + $what = $where = ''; + if ($argv[1] === 'full') { + $full = true; + } elseif ($argv[1] === 'all') { + $all = true; + } elseif ($argv[1] === 'predb_id') { + $usepre = true; + } elseif (is_numeric($argv[1])) { + $what = ' AND adddate > NOW() - INTERVAL '.$argv[1].' HOUR'; + } + if ($usepre === true) { + $where = ''; + $why = ' WHERE predb_id = 0 AND nzbstatus = 1'; + } elseif (isset($argv[1]) && is_numeric($argv[1])) { + $where = ''; + $why = ' WHERE nzbstatus = 1 AND isrenamed = 0'; + } elseif (isset($argv[2]) && is_numeric($argv[2]) && $full === true) { + $where = ' AND groups_id = '.$argv[2]; + $why = ' WHERE nzbstatus = 1 AND isrenamed = 0'; + } elseif (isset($argv[2]) && preg_match('/\([\d, ]+\)/', $argv[2]) && $full === true) { + $where = ' AND groups_id IN '.$argv[2]; + $why = ' WHERE nzbstatus = 1 AND isrenamed = 0'; + } elseif (isset($argv[2]) && preg_match('/\([\d, ]+\)/', $argv[2]) && $all === true) { + $where = ' AND groups_id IN '.$argv[2]; + $why = ' WHERE nzbstatus = 1'; + } elseif (isset($argv[2]) && is_numeric($argv[2]) && $all === true) { + $where = ' AND groups_id = '.$argv[2]; + $why = ' WHERE nzbstatus = 1 and predb_id = 0'; + } elseif (isset($argv[2]) && is_numeric($argv[2])) { + $where = ' AND groups_id = '.$argv[2]; + $why = ' WHERE nzbstatus = 1 AND isrenamed = 0'; + } elseif ($full === true) { + $why = ' WHERE nzbstatus = 1 AND (isrenamed = 0 OR categories_id between 7000 AND 7999)'; + } elseif ($all === true) { + $why = ' WHERE nzbstatus = 1'; + } else { + $why = ' WHERE 1=1'; + } + resetSearchnames(); + echo $pdo->log->header( + 'SELECT id, name, searchname, fromname, size, groups_id, categories_id FROM releases'.$why.$what. + $where.";\n" ); - $res = $pdo->queryDirect("SELECT id, name, searchname, fromname, size, groups_id, categories_id FROM releases" . $why . $what . $where); - $total = $res->rowCount(); - if ($total > 0) { - $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); - foreach ($res as $row) { - $groupname = $groups->getNameByID($row['groups_id']); - $cleanerName = releaseCleaner($row['name'], $row['fromname'], $row['size'], $groupname, $usepre); - $preid = 0; - $predb = $predbfile = $increment = false; - if (!is_array($cleanerName)) { - $cleanName = trim((string)$cleanerName); - $propername = $increment = true; - if ($cleanName != '' && $cleanerName != false) { - $run = $pdo->queryOneRow("SELECT id FROM predb WHERE title = " . $pdo->escapeString($cleanName)); - if (isset($run['id'])) { - $preid = $run['id']; - $predb = true; - } - } - } else { - $cleanName = trim($cleanerName["cleansubject"]); - $propername = $cleanerName["properlynamed"]; - if (isset($cleanerName["increment"])) { - $increment = $cleanerName["increment"]; - } - if (isset($cleanerName["predb"])) { - $preid = $cleanerName["predb"]; - $predb = true; - } - } - if ($cleanName != '') { - if (preg_match('/alt\.binaries\.e\-?book(\.[a-z]+)?/', $groupname)) { - if (preg_match('/^[0-9]{1,6}-[0-9]{1,6}-[0-9]{1,6}$/', $cleanName, $match)) { - $rf = new ReleaseFiles($pdo); - $files = $rf->get($row['id']); - foreach ($files as $f) { - if (preg_match( - '/^(?P.+?)(\\[\w\[\]\(\). -]+)?\.(pdf|htm(l)?|epub|mobi|azw|tif|doc(x)?|lit|txt|rtf|opf|fb2|prc|djvu|cb[rz])/', $f["name"], + $res = $pdo->queryDirect('SELECT id, name, searchname, fromname, size, groups_id, categories_id FROM releases'.$why.$what.$where); + $total = $res->rowCount(); + if ($total > 0) { + $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); + foreach ($res as $row) { + $groupname = $groups->getNameByID($row['groups_id']); + $cleanerName = releaseCleaner($row['name'], $row['fromname'], $row['size'], $groupname, $usepre); + $preid = 0; + $predb = $predbfile = $increment = false; + if (! is_array($cleanerName)) { + $cleanName = trim((string) $cleanerName); + $propername = $increment = true; + if ($cleanName != '' && $cleanerName != false) { + $run = $pdo->queryOneRow('SELECT id FROM predb WHERE title = '.$pdo->escapeString($cleanName)); + if (isset($run['id'])) { + $preid = $run['id']; + $predb = true; + } + } + } else { + $cleanName = trim($cleanerName['cleansubject']); + $propername = $cleanerName['properlynamed']; + if (isset($cleanerName['increment'])) { + $increment = $cleanerName['increment']; + } + if (isset($cleanerName['predb'])) { + $preid = $cleanerName['predb']; + $predb = true; + } + } + if ($cleanName != '') { + if (preg_match('/alt\.binaries\.e\-?book(\.[a-z]+)?/', $groupname)) { + if (preg_match('/^[0-9]{1,6}-[0-9]{1,6}-[0-9]{1,6}$/', $cleanName, $match)) { + $rf = new ReleaseFiles($pdo); + $files = $rf->get($row['id']); + foreach ($files as $f) { + if (preg_match( + '/^(?P<title>.+?)(\\[\w\[\]\(\). -]+)?\.(pdf|htm(l)?|epub|mobi|azw|tif|doc(x)?|lit|txt|rtf|opf|fb2|prc|djvu|cb[rz])/', $f['name'], $match ) ) { - $cleanName = $match['title']; - break; - } - } - } - } - //try to match clean name against predb filename - $prefile = $pdo->queryOneRow("SELECT id, title FROM predb WHERE filename = " . $pdo->escapeString($cleanName)); - if (isset($prefile['id'])) { - $preid = $prefile['id']; - $cleanName = $prefile['title']; - $predbfile = true; - $propername = true; - } - if ($cleanName != $row['name'] && $cleanName != $row['searchname']) { - if (strlen(utf8_decode($cleanName)) <= 3) { - } else { - $determinedcat = $category->determineCategory($row["groups_id"], $cleanName); - if ($propername == true) { - $pdo->queryExec( + $cleanName = $match['title']; + break; + } + } + } + } + //try to match clean name against predb filename + $prefile = $pdo->queryOneRow('SELECT id, title FROM predb WHERE filename = '.$pdo->escapeString($cleanName)); + if (isset($prefile['id'])) { + $preid = $prefile['id']; + $cleanName = $prefile['title']; + $predbfile = true; + $propername = true; + } + if ($cleanName != $row['name'] && $cleanName != $row['searchname']) { + if (strlen(utf8_decode($cleanName)) <= 3) { + } else { + $determinedcat = $category->determineCategory($row['groups_id'], $cleanName); + if ($propername == true) { + $pdo->queryExec( sprintf( - "UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, bookinfo_id = NULL, anidbid = NULL, " - . "iscategorized = 1, isrenamed = 1, searchname = %s, categories_id = %d, predb_id = " . $preid . " WHERE id = %d", $pdo->escapeString($cleanName), $determinedcat, $row['id'] + 'UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, bookinfo_id = NULL, anidbid = NULL, ' + .'iscategorized = 1, isrenamed = 1, searchname = %s, categories_id = %d, predb_id = '.$preid.' WHERE id = %d', $pdo->escapeString($cleanName), $determinedcat, $row['id'] ) ); - } else { - $pdo->queryExec( + } else { + $pdo->queryExec( sprintf( - "UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, bookinfo_id = NULL, anidbid = NULL, " - . "iscategorized = 1, searchname = %s, categories_id = %d, predb_id = " . $preid . " WHERE id = %d", $pdo->escapeString($cleanName), $determinedcat, $row['id'] + 'UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, bookinfo_id = NULL, anidbid = NULL, ' + .'iscategorized = 1, searchname = %s, categories_id = %d, predb_id = '.$preid.' WHERE id = %d', $pdo->escapeString($cleanName), $determinedcat, $row['id'] ) ); - } - if ($increment === true) { - $internal++; - } else if ($predb === true) { - $pre++; - } else if ($predbfile === true) { - $pre++; - } else if ($propername === true) { - $external++; - } - if ($show === 1) { - $oldcatname = $category->getNameByID($row["categories_id"]); - $newcatname = $category->getNameByID($determinedcat); + } + if ($increment === true) { + $internal++; + } elseif ($predb === true) { + $pre++; + } elseif ($predbfile === true) { + $pre++; + } elseif ($propername === true) { + $external++; + } + if ($show === 1) { + $oldcatname = $category->getNameByID($row['categories_id']); + $newcatname = $category->getNameByID($determinedcat); - NameFixer::echoChangedReleaseName([ + NameFixer::echoChangedReleaseName([ 'new_name' => $cleanName, - 'old_name' => $row["searchname"], + 'old_name' => $row['searchname'], 'new_category' => $newcatname, 'old_category' => $oldcatname, 'group' => $groupname, - 'releases_id' => $row["id"], - 'method' => 'misc/testing/Various/renametopre.php' + 'releases_id' => $row['id'], + 'method' => 'misc/testing/Various/renametopre.php', ] ); - } - } - } else if ($show === 3 && preg_match('/^\[?\d*\].+?yEnc/i', $row['name'])) { - echo $pdo->log->primary($row['name']); - } - } - if ($cleanName == $row['name']) { - $pdo->queryExec(sprintf("UPDATE releases SET isrenamed = 1, iscategorized = 1 WHERE id = %d", $row['id'])); - } - if ($show === 2 && $usepre === false) { - $consoletools->overWritePrimary("Renamed Releases: [Internal=" . number_format($internal) . "][External=" . number_format($external) . "][Predb=" . number_format($pre) . "] " . $consoletools->percentString(++$counter, $total)); - } else if ($show === 2 && $usepre === true) { - $consoletools->overWritePrimary("Renamed Releases: [" . number_format($pre) . "] " . $consoletools->percentString(++$counter, $total)); - } - } - } - echo $pdo->log->header("\n" . number_format($pre) . " renamed using preDB Match\n" . number_format($external) . " renamed using ReleaseCleaning.php\n" . number_format($internal) . " using renametopre.php\nout of " . number_format($total) . " releases.\n"); - if (isset($argv[1]) && is_numeric($argv[1]) && !isset($argv[2])) { - echo $pdo->log->header("Categorizing all releases using searchname from the last ${argv[1]} hours. This can take a while, be patient."); - } else if (isset($argv[1]) && $argv[1] !== "all" && isset($argv[2]) && !is_numeric($argv[2]) && !preg_match('/\([\d, ]+\)/', $argv[2])) { - echo $pdo->log->header("Categorizing all non-categorized releases in other->misc using searchname. This can take a while, be patient."); - } else if (isset($argv[1]) && isset($argv[2]) && (is_numeric($argv[2]) || preg_match('/\([\d, ]+\)/', $argv[2]))) { - echo $pdo->log->header("Categorizing all non-categorized releases in ${argv[2]} using searchname. This can take a while, be patient."); - } else { - echo $pdo->log->header("Categorizing all releases using searchname. This can take a while, be patient."); - } - $timestart = time(); - if (isset($argv[1]) && is_numeric($argv[1])) { - $relcount = catRelease("searchname", "WHERE (iscategorized = 0 OR categories_id = 0010) AND adddate > NOW() - INTERVAL " . $argv[1] . " HOUR", true); - } else if (isset($argv[2]) && preg_match('/\([\d, ]+\)/', $argv[2]) && $full === true) { - $relcount = catRelease("searchname", str_replace(" AND", "WHERE", $where) . " AND iscategorized = 0 ", true); - } else if (isset($argv[2]) && preg_match('/\([\d, ]+\)/', $argv[2]) && $all === true) { - $relcount = catRelease("searchname", str_replace(" AND", "WHERE", $where), true); - } else if (isset($argv[2]) && is_numeric($argv[2]) && $argv[1] == "full") { - $relcount = catRelease("searchname", str_replace(" AND", "WHERE", $where) . " AND iscategorized = 0 ", true); - } else if (isset($argv[2]) && is_numeric($argv[2]) && $argv[1] == "all") { - $relcount = catRelease("searchname", str_replace(" AND", "WHERE", $where), true); - } else if (isset($argv[1]) && $argv[1] == "full") { - $relcount = catRelease("searchname", "WHERE categories_id = 0010 OR iscategorized = 0", true); - } else if (isset($argv[1]) && $argv[1] == "all") { - $relcount = catRelease("searchname", "", true); - } else if (isset($argv[1]) && $argv[1] == "predb_id") { - $relcount = catRelease("searchname", "WHERE predb_id = 0 AND nzbstatus = 1", true); - } else { - $relcount = catRelease("searchname", "WHERE (iscategorized = 0 OR categories_id = 0010) AND adddate > NOW() - INTERVAL " . $argv[1] . " HOUR", true); - } - $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); - $time = $consoletools->convertTime(time() - $timestart); - echo $pdo->log->header("Finished categorizing " . number_format($relcount) . " releases in " . $time . " seconds, using the usenet subject.\n"); - resetSearchnames(); + } + } + } elseif ($show === 3 && preg_match('/^\[?\d*\].+?yEnc/i', $row['name'])) { + echo $pdo->log->primary($row['name']); + } + } + if ($cleanName == $row['name']) { + $pdo->queryExec(sprintf('UPDATE releases SET isrenamed = 1, iscategorized = 1 WHERE id = %d', $row['id'])); + } + if ($show === 2 && $usepre === false) { + $consoletools->overWritePrimary('Renamed Releases: [Internal='.number_format($internal).'][External='.number_format($external).'][Predb='.number_format($pre).'] '.$consoletools->percentString(++$counter, $total)); + } elseif ($show === 2 && $usepre === true) { + $consoletools->overWritePrimary('Renamed Releases: ['.number_format($pre).'] '.$consoletools->percentString(++$counter, $total)); + } + } + } + echo $pdo->log->header("\n".number_format($pre)." renamed using preDB Match\n".number_format($external)." renamed using ReleaseCleaning.php\n".number_format($internal)." using renametopre.php\nout of ".number_format($total)." releases.\n"); + if (isset($argv[1]) && is_numeric($argv[1]) && ! isset($argv[2])) { + echo $pdo->log->header("Categorizing all releases using searchname from the last ${argv[1]} hours. This can take a while, be patient."); + } elseif (isset($argv[1]) && $argv[1] !== 'all' && isset($argv[2]) && ! is_numeric($argv[2]) && ! preg_match('/\([\d, ]+\)/', $argv[2])) { + echo $pdo->log->header('Categorizing all non-categorized releases in other->misc using searchname. This can take a while, be patient.'); + } elseif (isset($argv[1]) && isset($argv[2]) && (is_numeric($argv[2]) || preg_match('/\([\d, ]+\)/', $argv[2]))) { + echo $pdo->log->header("Categorizing all non-categorized releases in ${argv[2]} using searchname. This can take a while, be patient."); + } else { + echo $pdo->log->header('Categorizing all releases using searchname. This can take a while, be patient.'); + } + $timestart = time(); + if (isset($argv[1]) && is_numeric($argv[1])) { + $relcount = catRelease('searchname', 'WHERE (iscategorized = 0 OR categories_id = 0010) AND adddate > NOW() - INTERVAL '.$argv[1].' HOUR', true); + } elseif (isset($argv[2]) && preg_match('/\([\d, ]+\)/', $argv[2]) && $full === true) { + $relcount = catRelease('searchname', str_replace(' AND', 'WHERE', $where).' AND iscategorized = 0 ', true); + } elseif (isset($argv[2]) && preg_match('/\([\d, ]+\)/', $argv[2]) && $all === true) { + $relcount = catRelease('searchname', str_replace(' AND', 'WHERE', $where), true); + } elseif (isset($argv[2]) && is_numeric($argv[2]) && $argv[1] == 'full') { + $relcount = catRelease('searchname', str_replace(' AND', 'WHERE', $where).' AND iscategorized = 0 ', true); + } elseif (isset($argv[2]) && is_numeric($argv[2]) && $argv[1] == 'all') { + $relcount = catRelease('searchname', str_replace(' AND', 'WHERE', $where), true); + } elseif (isset($argv[1]) && $argv[1] == 'full') { + $relcount = catRelease('searchname', 'WHERE categories_id = 0010 OR iscategorized = 0', true); + } elseif (isset($argv[1]) && $argv[1] == 'all') { + $relcount = catRelease('searchname', '', true); + } elseif (isset($argv[1]) && $argv[1] == 'predb_id') { + $relcount = catRelease('searchname', 'WHERE predb_id = 0 AND nzbstatus = 1', true); + } else { + $relcount = catRelease('searchname', 'WHERE (iscategorized = 0 OR categories_id = 0010) AND adddate > NOW() - INTERVAL '.$argv[1].' HOUR', true); + } + $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); + $time = $consoletools->convertTime(time() - $timestart); + echo $pdo->log->header('Finished categorizing '.number_format($relcount).' releases in '.$time." seconds, using the usenet subject.\n"); + resetSearchnames(); } function resetSearchnames() { - global $pdo; - echo $pdo->log->header("Resetting blank searchnames."); - $bad = $pdo->queryDirect( - "UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, bookinfo_id = NULL, anidbid = NULL, " - . "predb_id = 0, searchname = name, isrenamed = 0, iscategorized = 0 WHERE searchname = ''" + global $pdo; + echo $pdo->log->header('Resetting blank searchnames.'); + $bad = $pdo->queryDirect( + 'UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, bookinfo_id = NULL, anidbid = NULL, ' + ."predb_id = 0, searchname = name, isrenamed = 0, iscategorized = 0 WHERE searchname = ''" ); - $tot = $bad->rowCount(); - if ($tot > 0) { - echo $pdo->log->primary(number_format($tot) . " Releases had no searchname."); - } - echo $pdo->log->header("Resetting searchnames that are 8 characters or less."); - $run = $pdo->queryDirect( - "UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, bookinfo_id = NULL, anidbid = NULL, " - . "predb_id = 0, searchname = name, isrenamed = 0, iscategorized = 0 WHERE LENGTH(searchname) <= 8 AND LENGTH(name) > 8" + $tot = $bad->rowCount(); + if ($tot > 0) { + echo $pdo->log->primary(number_format($tot).' Releases had no searchname.'); + } + echo $pdo->log->header('Resetting searchnames that are 8 characters or less.'); + $run = $pdo->queryDirect( + 'UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, bookinfo_id = NULL, anidbid = NULL, ' + .'predb_id = 0, searchname = name, isrenamed = 0, iscategorized = 0 WHERE LENGTH(searchname) <= 8 AND LENGTH(name) > 8' ); - $total = $run->rowCount(); - if ($total > 0) { - echo $pdo->log->primary(number_format($total) . " Releases had searchnames that were 8 characters or less."); - } + $total = $run->rowCount(); + if ($total > 0) { + echo $pdo->log->primary(number_format($total).' Releases had searchnames that were 8 characters or less.'); + } } // Categorizes releases. @@ -274,37 +275,38 @@ function resetSearchnames() // Returns the quantity of categorized releases. function catRelease($type, $where, $echooutput = false) { - global $pdo; - $cat = new Categorize(['Settings' => $pdo]); - $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); - $relcount = 0; - echo $pdo->log->primary("SELECT id, " . $type . ", groups_id FROM releases " . $where); - $resrel = $pdo->queryDirect("SELECT id, " . $type . ", groups_id FROM releases " . $where); - $total = $resrel->rowCount(); - if ($total > 0) { - foreach ($resrel as $rowrel) { - $catId = $cat->determineCategory($rowrel['groups_id'], $rowrel[$type]); - $pdo->queryExec(sprintf("UPDATE releases SET iscategorized = 1, categories_id = %d WHERE id = %d", $catId, $rowrel['id'])); - $relcount++; - if ($echooutput) { - $consoletools->overWritePrimary("Categorizing: " . $consoletools->percentString($relcount, $total)); - } - } - } - if ($echooutput !== false && $relcount > 0) { - echo "\n"; - } - return $relcount; + global $pdo; + $cat = new Categorize(['Settings' => $pdo]); + $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); + $relcount = 0; + echo $pdo->log->primary('SELECT id, '.$type.', groups_id FROM releases '.$where); + $resrel = $pdo->queryDirect('SELECT id, '.$type.', groups_id FROM releases '.$where); + $total = $resrel->rowCount(); + if ($total > 0) { + foreach ($resrel as $rowrel) { + $catId = $cat->determineCategory($rowrel['groups_id'], $rowrel[$type]); + $pdo->queryExec(sprintf('UPDATE releases SET iscategorized = 1, categories_id = %d WHERE id = %d', $catId, $rowrel['id'])); + $relcount++; + if ($echooutput) { + $consoletools->overWritePrimary('Categorizing: '.$consoletools->percentString($relcount, $total)); + } + } + } + if ($echooutput !== false && $relcount > 0) { + echo "\n"; + } + + return $relcount; } function releaseCleaner($subject, $fromName, $size, $groupname, $usepre) { - $groups = new Groups(); - $releaseCleaning = new ReleaseCleaning($groups->pdo); - $cleanerName = $releaseCleaning->releaseCleaner($subject, $fromName, $size, $groupname, $usepre); - if (!is_array($cleanerName) && $cleanerName != false) { - return ["cleansubject" => $cleanerName, "properlynamed" => true, "increment" => false]; - } else { - return $cleanerName; - } + $groups = new Groups(); + $releaseCleaning = new ReleaseCleaning($groups->pdo); + $cleanerName = $releaseCleaning->releaseCleaner($subject, $fromName, $size, $groupname, $usepre); + if (! is_array($cleanerName) && $cleanerName != false) { + return ['cleansubject' => $cleanerName, 'properlynamed' => true, 'increment' => false]; + } else { + return $cleanerName; + } } diff --git a/misc/testing/_run_once/tpg_delete_triggers_2015-08-14.php b/misc/testing/_run_once/tpg_delete_triggers_2015-08-14.php index cc1bf80ac..9fee670d8 100644 --- a/misc/testing/_run_once/tpg_delete_triggers_2015-08-14.php +++ b/misc/testing/_run_once/tpg_delete_triggers_2015-08-14.php @@ -18,28 +18,26 @@ * @author niel * @copyright 2014 nZEDb */ -require_once dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'bootstrap.php'; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; $pdo = new DB(); -if (!Settings::value('..tablepergroup')) { - exit("Tables per groups is not enabled, quitting!"); +if (! Settings::value('..tablepergroup')) { + exit('Tables per groups is not enabled, quitting!'); } // Doing it this way in case there are tables existing not related to the active/backfill list (i.e. I don't have a clue when these tables get deleted so I'm doing any that are there). $tables = $pdo->queryDirect("SELECT SUBSTR(TABLE_NAME, 12) AS suffix FROM information_schema.TABLES WHERE TABLE_SCHEMA = (SELECT DATABASE()) AND TABLE_NAME LIKE 'collections_%' ORDER BY TABLE_NAME"); -$query1 = "DROP TRIGGER IF EXISTS delete_collections%s"; +$query1 = 'DROP TRIGGER IF EXISTS delete_collections%s'; if ($tables instanceof \Traversable) { - foreach ($tables as $table) { - echo "Updating table collections{$table['suffix']}" . PHP_EOL; - $pdo->queryExec(sprintf($query1, $table['suffix']), true); - } - echo 'All done!' . PHP_EOL; + foreach ($tables as $table) { + echo "Updating table collections{$table['suffix']}".PHP_EOL; + $pdo->queryExec(sprintf($query1, $table['suffix']), true); + } + echo 'All done!'.PHP_EOL; } - -?> diff --git a/misc/testing/_run_once/tpg_fixes.php b/misc/testing/_run_once/tpg_fixes.php index 0a7d953bd..e63b06843 100644 --- a/misc/testing/_run_once/tpg_fixes.php +++ b/misc/testing/_run_once/tpg_fixes.php @@ -18,33 +18,31 @@ * @author niel / kevin * @copyright 2014 nZEDb */ - -if (!isset($argv[1]) || !in_array($argv[1], ['1'])) { - exit( - 'Options: (enter a number, it\'s not recommended to rerun the same fix)' . PHP_EOL . - '1: 2014-07-28: Add unique key to binaryhash to be able to do multiple updates in 1 statement.' . PHP_EOL +if (! isset($argv[1]) || ! in_array($argv[1], ['1'])) { + exit( + 'Options: (enter a number, it\'s not recommended to rerun the same fix)'.PHP_EOL. + '1: 2014-07-28: Add unique key to binaryhash to be able to do multiple updates in 1 statement.'.PHP_EOL ); } -require_once dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'bootstrap.php'; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; $pdo = new DB(); -if (!Settings::value('..tablepergroup')) { - exit("Tables per groups is not enabled, quitting!"); +if (! Settings::value('..tablepergroup')) { + exit('Tables per groups is not enabled, quitting!'); } $groups = $pdo->queryDirect('SELECT id FROM groups WHERE active = 1 OR backfill = 1'); if ($groups === false) { - echo "No active groups. Fix not needed.\n"; + echo "No active groups. Fix not needed.\n"; } else { + $queries = []; - $queries = []; - - switch ($argv[1]) { + switch ($argv[1]) { case 1: // Drop this index, as we will recreate it as a unique. $queries[] = ['t' => 1, 'q' => 'ALTER TABLE binaries_%d DROP INDEX ix_binary_binaryhash']; @@ -55,12 +53,12 @@ if ($groups === false) { exit(); } - $groupCount = $groups->rowCount(); - if ($groups instanceof \Traversable && count($queries) && $groupCount) { - foreach ($groups as $group) { - echo 'Fixing group ' . $group['id'] . PHP_EOL; - foreach ($queries as $query) { - switch ($query['t']) { + $groupCount = $groups->rowCount(); + if ($groups instanceof \Traversable && count($queries) && $groupCount) { + foreach ($groups as $group) { + echo 'Fixing group '.$group['id'].PHP_EOL; + foreach ($queries as $query) { + switch ($query['t']) { // Queries needing 1 group id. case 1: $pdo->queryExec(sprintf($query['q'], $group['id']), true); @@ -74,9 +72,9 @@ if ($groups === false) { $pdo->queryExec(sprintf($query['q'], $group['id'], $group['id'], $group['id']), true); break; } - } - echo 'Finished fixing group ' . $group['id'] . ', ' . (--$groupCount) . ' to go!' .PHP_EOL; - } - } - echo 'All done!' . PHP_EOL; + } + echo 'Finished fixing group '.$group['id'].', '.(--$groupCount).' to go!'.PHP_EOL; + } + } + echo 'All done!'.PHP_EOL; } diff --git a/misc/testing/_run_once/tpg_update_triggers_2014-09-25.php b/misc/testing/_run_once/tpg_update_triggers_2014-09-25.php index 88c1d9aa4..22a3213f3 100644 --- a/misc/testing/_run_once/tpg_update_triggers_2014-09-25.php +++ b/misc/testing/_run_once/tpg_update_triggers_2014-09-25.php @@ -18,39 +18,37 @@ * @author niel * @copyright 2014 nZEDb */ -require_once dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'bootstrap.php'; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; $pdo = new DB(); -if (!Settings::value('..tablepergroup')) { - exit("Tables per groups is not enabled, quitting!"); +if (! Settings::value('..tablepergroup')) { + exit('Tables per groups is not enabled, quitting!'); } // Doing it this way in case there are tables existing not related to the active/backfill list (i.e. I don't have a clue when these tables get deleted so I'm doing any that are there). $tables = $pdo->queryDirect("SELECT SUBSTR(TABLE_NAME, 9) AS suffix FROM information_schema.TABLES WHERE TABLE_SCHEMA = (SELECT DATABASE()) AND TABLE_NAME LIKE 'binaries%' ORDER BY TABLE_NAME"); -$query1 = "ALTER TABLE binaries%s DROP INDEX ix_binary_collection"; -$query2 = "DROP TRIGGER IF EXISTS delete_collections%s"; -$query3 = "CREATE TRIGGER delete_collections%s BEFORE DELETE ON collections%s FOR EACH ROW BEGIN DELETE FROM binaries%s WHERE collections_id = OLD.id; DELETE FROM parts%s WHERE collections_id = OLD.id; END"; -$query4 = "ALTER TABLE binaries%s ADD INDEX ix_parts_collection_id(collections_id)"; +$query1 = 'ALTER TABLE binaries%s DROP INDEX ix_binary_collection'; +$query2 = 'DROP TRIGGER IF EXISTS delete_collections%s'; +$query3 = 'CREATE TRIGGER delete_collections%s BEFORE DELETE ON collections%s FOR EACH ROW BEGIN DELETE FROM binaries%s WHERE collections_id = OLD.id; DELETE FROM parts%s WHERE collections_id = OLD.id; END'; +$query4 = 'ALTER TABLE binaries%s ADD INDEX ix_parts_collection_id(collections_id)'; if ($tables instanceof \Traversable) { - foreach ($tables as $table) { - echo "Updating table binaries{$table['suffix']}" . PHP_EOL; - $pdo->queryExec(sprintf($query1, $table['suffix']), true); - $pdo->queryExec(sprintf($query2, $table['suffix']), true); - $pdo->queryExec(sprintf($query3, + foreach ($tables as $table) { + echo "Updating table binaries{$table['suffix']}".PHP_EOL; + $pdo->queryExec(sprintf($query1, $table['suffix']), true); + $pdo->queryExec(sprintf($query2, $table['suffix']), true); + $pdo->queryExec(sprintf($query3, $table['suffix'], $table['suffix'], $table['suffix'], $table['suffix']), true); - $pdo->queryExec(sprintf($query4, $table['suffix']), true); - } - echo 'All done!' . PHP_EOL; + $pdo->queryExec(sprintf($query4, $table['suffix']), true); + } + echo 'All done!'.PHP_EOL; } - -?> diff --git a/misc/testing/dumpnfo.php b/misc/testing/dumpnfo.php index bcd1b529f..bf2df47b7 100644 --- a/misc/testing/dumpnfo.php +++ b/misc/testing/dumpnfo.php @@ -5,28 +5,26 @@ // Its not very efficient to pull them all out, should really work out which day you need and go from there. // -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\db\DB; use nntmux\utility\Utility; - $db = new DB(); -$res = $db->queryDirect("select releases.searchname, releases.postdate, uncompress(release_nfos.nfo) as nfo from releases inner join release_nfos on releases.ID = release_nfos.releaseID and release_nfos.nfo is not null order by postdate"); -while ($row = $db->getAssocArray($res)) -{ - $dir = date("Ymd", strtotime($row["postdate"])); +$res = $db->queryDirect('select releases.searchname, releases.postdate, uncompress(release_nfos.nfo) as nfo from releases inner join release_nfos on releases.ID = release_nfos.releaseID and release_nfos.nfo is not null order by postdate'); +while ($row = $db->getAssocArray($res)) { + $dir = date('Ymd', strtotime($row['postdate'])); - if (!file_exists($dir)) - mkdir($dir); + if (! file_exists($dir)) { + mkdir($dir); + } - $filename = $dir."/".safeFilename($row["searchname"]).".nfo"; + $filename = $dir.'/'.safeFilename($row['searchname']).'.nfo'; - if (!file_exists($filename)) - { - $fh = fopen($filename, 'w'); - fwrite($fh, Utility::cp437toUTF($row["nfo"])); - fclose($fh); - } + if (! file_exists($filename)) { + $fh = fopen($filename, 'w'); + fwrite($fh, Utility::cp437toUTF($row['nfo'])); + fclose($fh); + } } diff --git a/misc/testing/fix_filesize.php b/misc/testing/fix_filesize.php index 4b8cab00c..438ef29f0 100644 --- a/misc/testing/fix_filesize.php +++ b/misc/testing/fix_filesize.php @@ -6,11 +6,11 @@ If after import you have a bunch of zero sized releases run this Author: lordgnu <lordgnu@me.com> */ -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; -use App\Models\Settings; -use nntmux\db\DB; use nntmux\NZB; +use nntmux\db\DB; +use App\Models\Settings; $pdo = new DB; $nzb = new NZB($pdo); @@ -18,27 +18,26 @@ $nzb = new NZB($pdo); $items = $pdo->query('SELECT id,guid FROM releases WHERE size = 0'); $total = count($items); $compl = 0; -echo 'Updating file size for ' . count($items) . ' release(s)' . PHP_EOL; +echo 'Updating file size for '.count($items).' release(s)'.PHP_EOL; -while ($item = array_pop($items)) -{ - $nzbpath = $nzb->getNZBPath($item['guid'], Settings::value('..nzbpath')); +while ($item = array_pop($items)) { + $nzbpath = $nzb->getNZBPath($item['guid'], Settings::value('..nzbpath')); - ob_start(); - @readgzfile($nzbpath); - $nzbfile = ob_get_contents(); - ob_end_clean(); + ob_start(); + @readgzfile($nzbpath); + $nzbfile = ob_get_contents(); + ob_end_clean(); - $ret = $nzb->nzbFileList($nzbfile); + $ret = $nzb->nzbFileList($nzbfile); - $filesize = '0'; + $filesize = '0'; - foreach ($ret as $file) { - $filesize = bcadd($filesize, $file['size']); - } + foreach ($ret as $file) { + $filesize = bcadd($filesize, $file['size']); + } - $pdo->queryExec("UPDATE releases SET size = '{$filesize}' WHERE id = '{$item['id']}' LIMIT 1"); + $pdo->queryExec("UPDATE releases SET size = '{$filesize}' WHERE id = '{$item['id']}' LIMIT 1"); - $compl++; - echo sprintf("[%6d / %6d] %0.2f",$compl, $total, ($compl/$total) * 100) . '%' . "\n"; + $compl++; + echo sprintf('[%6d / %6d] %0.2f', $compl, $total, ($compl / $total) * 100).'%'."\n"; } diff --git a/misc/testing/nzb-export.php b/misc/testing/nzb-export.php index 9342c7f06..b4113be38 100644 --- a/misc/testing/nzb-export.php +++ b/misc/testing/nzb-export.php @@ -1,5 +1,6 @@ <?php -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; + +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\NZBExport; @@ -7,24 +8,24 @@ $n = PHP_EOL; // Print usage. if (count($argv) !== 6) { - exit( - 'This will export NZB files(to .nzb or .nzb.gz) into sub folders (using group name) of the specified folder.' . $n . $n . - 'Usage: ' . $n . - $_SERVER['_'] . ' ' . __FILE__ . ' arg1 arg2 arg3 arg4 arg5' . $n . $n . - 'arg1 : Path to folder where NZB files are to be stored. | a folder path' . $n . - 'arg2 : The start date in this format: 01/01/2008 or false | date/false' . $n . - 'arg3 : The end date in this format: 01/01/2008 or false | date/false' . $n . - 'arg4 : Group ID for the group or false | number/false' . $n . - 'arg5 : Gzip the NZB files (recommended, faster/takes less space) | true/false' . $n . $n . - 'Examples: ' . $n . - $_SERVER['_'] . ' ' . $argv[0] . ' ' . NN_ROOT . 'exportFolder' . DS . ' 01/01/2012 01/01/2014 false true' . $n . - $_SERVER['_'] . ' ' . $argv[0] . ' ' . NN_ROOT . 'exportFolder' . DS . ' false 01/01/2014 12 false' . $n + exit( + 'This will export NZB files(to .nzb or .nzb.gz) into sub folders (using group name) of the specified folder.'.$n.$n. + 'Usage: '.$n. + $_SERVER['_'].' '.__FILE__.' arg1 arg2 arg3 arg4 arg5'.$n.$n. + 'arg1 : Path to folder where NZB files are to be stored. | a folder path'.$n. + 'arg2 : The start date in this format: 01/01/2008 or false | date/false'.$n. + 'arg3 : The end date in this format: 01/01/2008 or false | date/false'.$n. + 'arg4 : Group ID for the group or false | number/false'.$n. + 'arg5 : Gzip the NZB files (recommended, faster/takes less space) | true/false'.$n.$n. + 'Examples: '.$n. + $_SERVER['_'].' '.$argv[0].' '.NN_ROOT.'exportFolder'.DS.' 01/01/2012 01/01/2014 false true'.$n. + $_SERVER['_'].' '.$argv[0].' '.NN_ROOT.'exportFolder'.DS.' false 01/01/2014 12 false'.$n ); } $NE = new NZBExport(); $NE->beginExport( - array( + [ // Path. $argv[1], // Start time. @@ -32,8 +33,8 @@ $NE->beginExport( // End time. (strtolower($argv[3]) === 'false' ? '' : $argv[3]), // Group ID. - (strtolower($argv[4]) === 'false' ? 0 : (int)$argv[4]), + (strtolower($argv[4]) === 'false' ? 0 : (int) $argv[4]), // Gzip. - (strtolower($argv[5]) === 'true' ? true : false) - ) + (strtolower($argv[5]) === 'true' ? true : false), + ] ); diff --git a/misc/testing/nzb-import.php b/misc/testing/nzb-import.php index 566eaba56..8ae2780c1 100644 --- a/misc/testing/nzb-import.php +++ b/misc/testing/nzb-import.php @@ -1,5 +1,6 @@ <?php -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; + +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\NZBImport; @@ -7,44 +8,44 @@ $n = PHP_EOL; // Print usage. if (count($argv) !== 6) { - exit( - 'This will import NZB files(.nzb or .nzb.gz), into your newznab site from a folder recursively(it will go down into sub-folders).' . $n . - 'Please use arg5, something sensible like 100k, if you have millions of NZB files the initial scan will be VERY slow otherwise.' . $n . $n . - 'Usage: ' . $n . - $_SERVER['_'] . ' ' . __FILE__ . ' arg1 arg2 arg3 arg4 arg5' . $n . $n . - 'arg1 : Path to folder where NZB files are stored. | a folder path' . $n . - 'arg2 : Delete NZB when successfully imported.(recommended) | true/false' . $n . - 'arg3 : Delete NZB when unsuccessfully imported.(not recommended) | true/false' . $n . - 'arg4 : Use NZB file name as release name.(not recommended) | true/false' . $n . - 'arg5 : Import this many NZB files. (RECOMMENDED 100,000) | a number' . $n . $n . - 'ie: ' . $_SERVER['_'] . ' ' . __FILE__ . ' ' . NN_ROOT . 'nzbToImport' . DS . ' true false false 1000' . $n + exit( + 'This will import NZB files(.nzb or .nzb.gz), into your newznab site from a folder recursively(it will go down into sub-folders).'.$n. + 'Please use arg5, something sensible like 100k, if you have millions of NZB files the initial scan will be VERY slow otherwise.'.$n.$n. + 'Usage: '.$n. + $_SERVER['_'].' '.__FILE__.' arg1 arg2 arg3 arg4 arg5'.$n.$n. + 'arg1 : Path to folder where NZB files are stored. | a folder path'.$n. + 'arg2 : Delete NZB when successfully imported.(recommended) | true/false'.$n. + 'arg3 : Delete NZB when unsuccessfully imported.(not recommended) | true/false'.$n. + 'arg4 : Use NZB file name as release name.(not recommended) | true/false'.$n. + 'arg5 : Import this many NZB files. (RECOMMENDED 100,000) | a number'.$n.$n. + 'ie: '.$_SERVER['_'].' '.__FILE__.' '.NN_ROOT.'nzbToImport'.DS.' true false false 1000'.$n ); } // Verify arguments. -if (!is_dir($argv[1])) { - exit('Error: arg1 must be a path (you might not have read access to this path)' . $n); +if (! is_dir($argv[1])) { + exit('Error: arg1 must be a path (you might not have read access to this path)'.$n); } -if (!in_array($argv[2], array('true', 'false'))) { - exit('Error: arg2 must be true or false' . $n); +if (! in_array($argv[2], ['true', 'false'])) { + exit('Error: arg2 must be true or false'.$n); } -if (!in_array($argv[3], array('true', 'false'))) { - exit('Error: arg3 must be true or false' . $n); +if (! in_array($argv[3], ['true', 'false'])) { + exit('Error: arg3 must be true or false'.$n); } -if (!in_array($argv[4], array('true', 'false'))) { - exit('Error: arg4 must be true or false' . $n); +if (! in_array($argv[4], ['true', 'false'])) { + exit('Error: arg4 must be true or false'.$n); } -if (!is_numeric($argv[5])) { - exit('Error: arg5 must be a number' . $n); +if (! is_numeric($argv[5])) { + exit('Error: arg5 must be a number'.$n); } if ($argv[5] < 0) { - exit('Error: arg5 must be 0 or higher' . $n); + exit('Error: arg5 must be 0 or higher'.$n); } $path = $argv[1]; // Check if path ends with dir separator. if (substr($path, -1) !== DS) { - $path .= DS; + $path .= DS; } $files = new \RegexIterator( @@ -58,25 +59,24 @@ $files = new \RegexIterator( $i = 1; $nzbFiles = []; foreach ($files as $file) { - $nzbFiles[] = $file[0]; - if ($i++ >= $argv[5]) { - break; - } + $nzbFiles[] = $file[0]; + if ($i++ >= $argv[5]) { + break; + } } if ($i > 1) { + unset($files); - unset($files); + // Check these user argument values, convert them to bool. + $deleteNZB = ($argv[2] == 'true') ? true : false; + $deleteFailedNZB = ($argv[3] == 'true') ? true : false; + $useNzbName = ($argv[4] == 'true') ? true : false; - // Check these user argument values, convert them to bool. - $deleteNZB = ($argv[2] == 'true') ? true : false; - $deleteFailedNZB = ($argv[3] == 'true') ? true : false; - $useNzbName = ($argv[4] == 'true') ? true : false; + // Create a new instance of NZBImport and send it the file locations. + $NZBImport = new NZBImport(); - // Create a new instance of NZBImport and send it the file locations. - $NZBImport = new NZBImport(); - - $NZBImport->beginImport($nzbFiles, $useNzbName, $deleteNZB, $deleteFailedNZB); + $NZBImport->beginImport($nzbFiles, $useNzbName, $deleteNZB, $deleteFailedNZB); } else { - echo 'Nothing found to import!' . $n; + echo 'Nothing found to import!'.$n; } diff --git a/misc/testing/refreshMovie.php b/misc/testing/refreshMovie.php index ee47d67de..1d7c71a28 100644 --- a/misc/testing/refreshMovie.php +++ b/misc/testing/refreshMovie.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\db\DB; use nntmux\Movie; @@ -29,16 +29,14 @@ $sleepsecsbetweenscrape = 1; // 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) -{ +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"; +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); + echo 'Updating '.$mov['imdbid'].' ('.$counter++.'/'.count($movies).")\n"; + $mov = $movie->updateMovieInfo($mov['imdbid']); + sleep($sleepsecsbetweenscrape); } diff --git a/misc/testing/spotnab.php b/misc/testing/spotnab.php index 13968f21f..fac4de677 100644 --- a/misc/testing/spotnab.php +++ b/misc/testing/spotnab.php @@ -1,4 +1,5 @@ <?php + // Author l2g // Date: Mar 17th, 2013 // Version: 0.97.4 @@ -172,7 +173,7 @@ SHARING recognize or want to test out the source. */ -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\SpotNab; @@ -181,291 +182,293 @@ use nntmux\SpotNab; // 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::"; +$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" -); +$longopts = [ + '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 " +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" + echo ' requiring that your releases database' ." table is up to date\n"; - echo " with all GID (Global Identifiers) so" + echo ' with all GID (Global Identifiers) so' ." it can correctly\n"; - echo " communicate with other servers that " + 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 " + 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 " + echo ' Specifying this switch will remove ' ."these dead releses.\n"; - echo " -f, --fetch Get latest spotnab comments from " + 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" + 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 " + 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 " + 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 " + 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" + 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 " + 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"; + echo " the internals of the class...\n"; + echo "\n"; } -if(!$options){ display_help(); exit(1);} -if(!count($options)){ display_help(); exit(1);} +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-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('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"; +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('K', $options) || + array_key_exists('force-keygen', $options)) { + $spotnab = new SpotNab(); + $spotnab->keygen(true, true); +} elseif (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('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('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 (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"; + 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"; + echo "Fetching $days day(s) back ... "; + $spotnab = new SpotNab(); + $spotnab->fetch(time() - ($days * 86400)); + echo "Done\n"; +} elseif (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('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 (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"; - } + 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 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"; + } elseif (! 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( + printf('%s INFO - Testing small message encode/decode ...', + date('Y-m-d H:i:s')); + $before = [ + 'server' => [ 'code' => 'l2g', - 'title' => 'l2g newznab' - ), + 'title' => 'l2g newznab', + ], 'postdate_utc' => $spotnab->local2utc(), - 'comments' => array( - array( + 'comments' => [ + [ 'gid' => 'ABCDEFHIJKLMNOPQRSTUVWXYZ0123456', 'cid' => 'ABCDEFHIJKLMNOPQRSTUVWXYZ0123456', 'comment' => 'testing comment 1', 'username' => 'l2g', 'is_visible' => 1, - 'postdate_utc' => $spotnab->local2utc(time()-86400) - ), - array( + 'postdate_utc' => $spotnab->local2utc(time() - 86400), + ], + [ '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( + '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 = [ + 'server' => [ 'code' => 'l2g', - 'title' => 'l2g newznab' - ), + 'title' => 'l2g newznab', + ], 'postdate_utc' => $spotnab->local2utc(), - 'comments' => [] - ); - for($i=0;$i<3000;$i++){ - // Build large post - $before['comments'][] =array( + 'comments' => [], + ]; + for ($i = 0; $i < 3000; $i++) { + // Build large post + $before['comments'][] = [ 'gid' => 'ABCDEFHIJKLMNOPQRSTUVWXYZ0123456', 'cid' => 'ABCDEFHIJKLMNOPQRSTUVWXYZ0123456', - 'comment' => $refc = $spotnab->getRandomStr(rand(15,200)), + '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"; - } + '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( + printf('%s INFO - Testing fake usenet parse ...', + date('Y-m-d H:i:s')); + // Fake group hash table + $hash = [[ 'ID' => 0, 'key' => $spotnab->decompstr($keys['pubkey']), 'user' => 'nntp', @@ -473,60 +476,60 @@ if(array_key_exists("t", $options) || // 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 - )); + 'ref' => $article[2]['Epoch'] - 1, + ]]; - // Fake headers (use debug information from encodePost) - $headers = array($article[2]); + // Fake headers (use debug information from encodePost) + $headers = [$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")); - } + $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"; + 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()); +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()); } diff --git a/misc/testing/tidynzbfolder.php b/misc/testing/tidynzbfolder.php index f2c26cb0e..5808fe8e9 100644 --- a/misc/testing/tidynzbfolder.php +++ b/misc/testing/tidynzbfolder.php @@ -1,5 +1,6 @@ <?php -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; + +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\db\DB; use nntmux\Releases; @@ -27,7 +28,6 @@ foreach(new RecursiveIteratorIterator($it) as $file) } */ - // // Option Two - delete all from the database where it doesnt exist on disk // diff --git a/misc/update/backfill.php b/misc/update/backfill.php index 393c14429..e8ac92b08 100644 --- a/misc/update/backfill.php +++ b/misc/update/backfill.php @@ -1,8 +1,9 @@ <?php -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; -use nntmux\db\DB; +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; + use nntmux\NNTP; +use nntmux\db\DB; use nntmux\Backfill; $pdo = new DB(); @@ -10,34 +11,34 @@ $pdo = new DB(); // Create the connection here and pass $nntp = new NNTP(['Settings' => $pdo]); if ($nntp->doConnect() !== true) { - exit($pdo->log->error('Unable to connect to usenet.')); + exit($pdo->log->error('Unable to connect to usenet.')); } -if (isset($argv[1]) && $argv[1] === 'all' && !isset($argv[2])) { - $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); - $backfill->backfillAllGroups(); -} else if (isset($argv[1]) && !isset($argv[2]) && preg_match('/^alt\.binaries\..+$/i', $argv[1])) { - $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); - $backfill->backfillAllGroups($argv[1]); -} else if (isset($argv[1], $argv[2]) && is_numeric($argv[2]) && preg_match('/^alt\.binaries\..+$/i', $argv[1])) { - $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); - $backfill->backfillAllGroups($argv[1], $argv[2]); -} else if (isset($argv[1], $argv[2]) && $argv[1] === 'alph' && is_numeric($argv[2])) { - $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); - $backfill->backfillAllGroups('', $argv[2], 'normal'); -} else if (isset($argv[1], $argv[2]) && $argv[1] === 'date' && is_numeric($argv[2])) { - $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); - $backfill->backfillAllGroups('', $argv[2], 'date'); -} else if (isset($argv[1], $argv[2]) && $argv[1] === 'safe' && is_numeric($argv[2])) { - $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); - $backfill->safeBackfill($argv[2]); +if (isset($argv[1]) && $argv[1] === 'all' && ! isset($argv[2])) { + $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); + $backfill->backfillAllGroups(); +} elseif (isset($argv[1]) && ! isset($argv[2]) && preg_match('/^alt\.binaries\..+$/i', $argv[1])) { + $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); + $backfill->backfillAllGroups($argv[1]); +} elseif (isset($argv[1], $argv[2]) && is_numeric($argv[2]) && preg_match('/^alt\.binaries\..+$/i', $argv[1])) { + $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); + $backfill->backfillAllGroups($argv[1], $argv[2]); +} elseif (isset($argv[1], $argv[2]) && $argv[1] === 'alph' && is_numeric($argv[2])) { + $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); + $backfill->backfillAllGroups('', $argv[2], 'normal'); +} elseif (isset($argv[1], $argv[2]) && $argv[1] === 'date' && is_numeric($argv[2])) { + $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); + $backfill->backfillAllGroups('', $argv[2], 'date'); +} elseif (isset($argv[1], $argv[2]) && $argv[1] === 'safe' && is_numeric($argv[2])) { + $backfill = new Backfill(['NNTP' => $nntp, 'Settings' => $pdo]); + $backfill->safeBackfill($argv[2]); } else { - exit(\nntmux\ColorCLI::error("\nWrong set of arguments.\n" - . 'php backfill.php safe 200000 ...: Backfill an active group alphabetically, x articles, the script stops,' . "\n" - . ' ...: if the group has reached reached 2012-06-24, the next group will backfill.' . "\n" - . 'php backfill.php alph 200000 ...: Backfills all groups (sorted alphabetically) by number of articles' . "\n" - . 'php backfill.php date 200000 ...: Backfills all groups (sorted by least backfilled in time) by number of articles' . "\n" - . 'php backfill.php alt.binaries.ath 200000 ...: Backfills a group by name by number of articles' . "\n" - . 'php backfill.php all ...: Backfills all groups 1 at a time, by date (set in admin-view groups)' . "\n" - . 'php backfill.php alt.binaries.ath ...: Backfills a group by name, by date (set in admin-view groups)' . "\n")); + exit(\nntmux\ColorCLI::error("\nWrong set of arguments.\n" + .'php backfill.php safe 200000 ...: Backfill an active group alphabetically, x articles, the script stops,'."\n" + .' ...: if the group has reached reached 2012-06-24, the next group will backfill.'."\n" + .'php backfill.php alph 200000 ...: Backfills all groups (sorted alphabetically) by number of articles'."\n" + .'php backfill.php date 200000 ...: Backfills all groups (sorted by least backfilled in time) by number of articles'."\n" + .'php backfill.php alt.binaries.ath 200000 ...: Backfills a group by name by number of articles'."\n" + .'php backfill.php all ...: Backfills all groups 1 at a time, by date (set in admin-view groups)'."\n" + .'php backfill.php alt.binaries.ath ...: Backfills a group by name, by date (set in admin-view groups)'."\n")); } diff --git a/misc/update/decrypt_hashes.php b/misc/update/decrypt_hashes.php index f7eaa4111..a4094ead1 100755 --- a/misc/update/decrypt_hashes.php +++ b/misc/update/decrypt_hashes.php @@ -1,73 +1,74 @@ <?php -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; -use nntmux\ConsoleTools; -use nntmux\NameFixer; +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; + use nntmux\db\DB; +use nntmux\NameFixer; +use nntmux\ConsoleTools; $pdo = new DB(); -if (!isset($argv[1]) || ($argv[1] != "all" && $argv[1] != "full" && !is_numeric($argv[1]))) { - exit($pdo->log->error( +if (! isset($argv[1]) || ($argv[1] != 'all' && $argv[1] != 'full' && ! is_numeric($argv[1]))) { + exit($pdo->log->error( "\nThis script tries to match hashes of the releases.name or releases.searchname to predb hashes.\n" - . "To display the changes, use 'show' as the second argument.\n\n" - . "php decrypt_hashes.php 1000 ...: to limit to 1000 sorted by newest postdate.\n" - . "php decrypt_hashes.php full ...: to run on full database.\n" - . "php decrypt_hashes.php all ...: to run on all hashed releases(including previously renamed).\n" + ."To display the changes, use 'show' as the second argument.\n\n" + ."php decrypt_hashes.php 1000 ...: to limit to 1000 sorted by newest postdate.\n" + ."php decrypt_hashes.php full ...: to run on full database.\n" + ."php decrypt_hashes.php all ...: to run on all hashed releases(including previously renamed).\n" )); } -echo $pdo->log->header("\nDecrypt Hashes (${argv[1]}) Started at " . date('g:i:s')); -echo $pdo->log->primary("Matching predb hashes to hash(releases.name or releases.searchname)"); +echo $pdo->log->header("\nDecrypt Hashes (${argv[1]}) Started at ".date('g:i:s')); +echo $pdo->log->primary('Matching predb hashes to hash(releases.name or releases.searchname)'); getPreName($argv); function getPreName($argv) { - global $pdo; - $timestart = time(); - $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); - $namefixer = new NameFixer(['Settings' => $pdo, 'ConsoleTools' => $consoletools]); + global $pdo; + $timestart = time(); + $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); + $namefixer = new NameFixer(['Settings' => $pdo, 'ConsoleTools' => $consoletools]); - $res = false; - if (isset($argv[1]) && $argv[1] === "all") { - $res = $pdo->queryDirect('SELECT id AS releases_id, name, searchname, groups_id, categories_id, dehashstatus FROM releases WHERE predb_id = 0 AND ishashed = 1'); - } else if (isset($argv[1]) && $argv[1] === "full") { - $res = $pdo->queryDirect('SELECT id AS releases_id, name, searchname, groups_id, categories_id, dehashstatus FROM releases WHERE categories_id = 7020 AND ishashed = 1 AND dehashstatus BETWEEN -6 AND 0'); - } else if (isset($argv[1]) && is_numeric($argv[1])) { - $res = $pdo->queryDirect('SELECT id AS releases_id, name, searchname, groups_id, categories_id, dehashstatus FROM releases WHERE categories_id = 7020 AND ishashed = 1 AND dehashstatus BETWEEN -6 AND 0 ORDER BY postdate DESC LIMIT ' . $argv[1]); - } + $res = false; + if (isset($argv[1]) && $argv[1] === 'all') { + $res = $pdo->queryDirect('SELECT id AS releases_id, name, searchname, groups_id, categories_id, dehashstatus FROM releases WHERE predb_id = 0 AND ishashed = 1'); + } elseif (isset($argv[1]) && $argv[1] === 'full') { + $res = $pdo->queryDirect('SELECT id AS releases_id, name, searchname, groups_id, categories_id, dehashstatus FROM releases WHERE categories_id = 7020 AND ishashed = 1 AND dehashstatus BETWEEN -6 AND 0'); + } elseif (isset($argv[1]) && is_numeric($argv[1])) { + $res = $pdo->queryDirect('SELECT id AS releases_id, name, searchname, groups_id, categories_id, dehashstatus FROM releases WHERE categories_id = 7020 AND ishashed = 1 AND dehashstatus BETWEEN -6 AND 0 ORDER BY postdate DESC LIMIT '.$argv[1]); + } - $counter = $counted = $total = 0; - if ($res !== false) { - $total = $res->rowCount(); - } - $show = (!isset($argv[2]) || $argv[2] !== 'show') ? 0 : 1; - if ($total > 0) { - echo $pdo->log->header("\n" . number_format($total) . ' releases to process.'); - sleep(2); + $counter = $counted = $total = 0; + if ($res !== false) { + $total = $res->rowCount(); + } + $show = (! isset($argv[2]) || $argv[2] !== 'show') ? 0 : 1; + if ($total > 0) { + echo $pdo->log->header("\n".number_format($total).' releases to process.'); + sleep(2); - foreach ($res as $row) { - $success = 0; - if (preg_match('/[a-fA-F0-9]{32,40}/i', $row['name'], $matches)) { - $success = $namefixer->matchPredbHash($matches[0], $row, 1, 1, true, $show); - } else if (preg_match('/[a-fA-F0-9]{32,40}/i', $row['searchname'], $matches)) { - $success = $namefixer->matchPredbHash($matches[0], $row, 1, 1, true, $show); - } + foreach ($res as $row) { + $success = 0; + if (preg_match('/[a-fA-F0-9]{32,40}/i', $row['name'], $matches)) { + $success = $namefixer->matchPredbHash($matches[0], $row, 1, 1, true, $show); + } elseif (preg_match('/[a-fA-F0-9]{32,40}/i', $row['searchname'], $matches)) { + $success = $namefixer->matchPredbHash($matches[0], $row, 1, 1, true, $show); + } - if ($success === 0) { - $pdo->queryDirect(sprintf('UPDATE releases SET dehashstatus = dehashstatus - 1 WHERE id = %d', $row['releaseid'])); - } else { - $counted++; - } - if ($show === 0) { - $consoletools->overWritePrimary("Renamed Releases: [" . number_format($counted) . "] " . $consoletools->percentString(++$counter, $total)); - } - } - } - if ($total > 0) { - echo $pdo->log->header("\nRenamed " . $counted . " releases in " . $consoletools->convertTime(time() - $timestart) . "."); - } else { - echo $pdo->log->info("\nNothing to do."); - } + if ($success === 0) { + $pdo->queryDirect(sprintf('UPDATE releases SET dehashstatus = dehashstatus - 1 WHERE id = %d', $row['releaseid'])); + } else { + $counted++; + } + if ($show === 0) { + $consoletools->overWritePrimary('Renamed Releases: ['.number_format($counted).'] '.$consoletools->percentString(++$counter, $total)); + } + } + } + if ($total > 0) { + echo $pdo->log->header("\nRenamed ".$counted.' releases in '.$consoletools->convertTime(time() - $timestart).'.'); + } else { + echo $pdo->log->info("\nNothing to do."); + } } diff --git a/misc/update/match_prefiles.php b/misc/update/match_prefiles.php index 99a163966..201f5c413 100755 --- a/misc/update/match_prefiles.php +++ b/misc/update/match_prefiles.php @@ -1,16 +1,17 @@ <?php -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; + +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\ColorCLI; use nntmux\NameFixer; -if (!isset($argv[1]) && ($argv[1] !== 'full' || !is_numeric($argv[1]))) { - exit( +if (! isset($argv[1]) && ($argv[1] !== 'full' || ! is_numeric($argv[1]))) { + exit( ColorCLI::error(PHP_EOL - . 'This script tries to match release filenames to PreDB filenames.' . PHP_EOL - . 'To display the changes, use "show" as the second argument. The optional third argument will limit the amount of filenames to attempt to match.' . PHP_EOL . PHP_EOL - . 'php match_prefiles.php full show ...: to run on full database and show renames.' . PHP_EOL - . 'php match_prefiles.php 2000 show ...: to run against 2000 distinct releases and show renames.' . PHP_EOL + .'This script tries to match release filenames to PreDB filenames.'.PHP_EOL + .'To display the changes, use "show" as the second argument. The optional third argument will limit the amount of filenames to attempt to match.'.PHP_EOL.PHP_EOL + .'php match_prefiles.php full show ...: to run on full database and show renames.'.PHP_EOL + .'php match_prefiles.php 2000 show ...: to run against 2000 distinct releases and show renames.'.PHP_EOL ) ); } diff --git a/misc/update/nix/multiprocessing/backfill.php b/misc/update/nix/multiprocessing/backfill.php index 7d7c8348f..c7a679128 100644 --- a/misc/update/nix/multiprocessing/backfill.php +++ b/misc/update/nix/multiprocessing/backfill.php @@ -1,7 +1,9 @@ <?php + declare(ticks=1); -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\libraries\Forking; + // Check if argument 1 is numeric, which is to limit article count. (new Forking())->processWorkType( 'backfill', (isset($argv[1]) && is_numeric($argv[1]) && $argv[1] > 0 ? [0 => $argv[1]] : [0 => false]) diff --git a/misc/update/nix/multiprocessing/binaries.php b/misc/update/nix/multiprocessing/binaries.php index a354dd9bb..55ddabfaf 100644 --- a/misc/update/nix/multiprocessing/binaries.php +++ b/misc/update/nix/multiprocessing/binaries.php @@ -1,10 +1,12 @@ <?php -if (!isset($argv[1]) || !is_numeric($argv[1])) { - exit( - 'Argument 1 => (Number) Set to 0 to ignore, else fetches up to x new headers for every active group.' . PHP_EOL + +if (! isset($argv[1]) || ! is_numeric($argv[1])) { + exit( + 'Argument 1 => (Number) Set to 0 to ignore, else fetches up to x new headers for every active group.'.PHP_EOL ); } declare(ticks=1); -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\libraries\Forking; -(new Forking())->processWorkType('binaries', array(0 => $argv[1])); + +(new Forking())->processWorkType('binaries', [0 => $argv[1]]); diff --git a/misc/update/nix/multiprocessing/fixrelnames.php b/misc/update/nix/multiprocessing/fixrelnames.php index a64b83e6c..cf4e30976 100644 --- a/misc/update/nix/multiprocessing/fixrelnames.php +++ b/misc/update/nix/multiprocessing/fixrelnames.php @@ -1,16 +1,17 @@ <?php -if (!isset($argv[1]) || !in_array($argv[1], ['standard', 'predbft'])) { - exit( - 'First argument (mandatory):' . PHP_EOL . - 'standard => Attempt to fix release name using standard methods.' . PHP_EOL . - 'predbft => Attempt to fix release name using Predb full text matching.' . PHP_EOL . PHP_EOL + +if (! isset($argv[1]) || ! in_array($argv[1], ['standard', 'predbft'])) { + exit( + 'First argument (mandatory):'.PHP_EOL. + 'standard => Attempt to fix release name using standard methods.'.PHP_EOL. + 'predbft => Attempt to fix release name using Predb full text matching.'.PHP_EOL.PHP_EOL ); } -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\libraries\Forking; -declare(ticks = 1); +declare(ticks=1); -(new Forking())->processWorkType('fixRelNames_' . $argv[1], [0 => $argv[1]]); +(new Forking())->processWorkType('fixRelNames_'.$argv[1], [0 => $argv[1]]); diff --git a/misc/update/nix/multiprocessing/import.php b/misc/update/nix/multiprocessing/import.php index d5a9f17e2..86281b898 100644 --- a/misc/update/nix/multiprocessing/import.php +++ b/misc/update/nix/multiprocessing/import.php @@ -1,26 +1,27 @@ <?php + declare(ticks=1); -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\libraries\ForkingImportNZB; -if (!isset($argv[1]) || !is_dir($argv[1])) { - exit( - 'First argument (mandatory):' . PHP_EOL . - 'Path to a folder, containing folders with .nzb or .nzb.gz files inside them.' . PHP_EOL . - 'If you supply a path containing only files, the files will be ignored.' . PHP_EOL . - 'The sub-folders will be searched recursively for NZB files.' . PHP_EOL . PHP_EOL . - 'Second argument (optional):' . PHP_EOL . - 'Number of processes, how many processes to run max at a time. (default is 1)' . PHP_EOL . PHP_EOL . - 'Third argument (optional):' . PHP_EOL . - 'true|false => Delete the NZB files after they are imported (recommended), if you stop and restart you will have to go over the imported files again.' . PHP_EOL . PHP_EOL . - 'Fourth argument (optional)' . PHP_EOL . - 'true|false => Delete the NZB if importing it fails (not recommended).' . PHP_EOL . - 'Fifth argument (optional):' . PHP_EOL . - 'true|false => Use the NZB file name as the release name (not recommended), the names in the NZB are better.' . PHP_EOL . PHP_EOL . - 'Sixth argument (optional):' . PHP_EOL . - 'How many NZB files to import per process, if this is not set, it will do 50,000 per process.' . PHP_EOL . PHP_EOL . - 'Note that successfully imported NZB files WILL be deleted.' . PHP_EOL +if (! isset($argv[1]) || ! is_dir($argv[1])) { + exit( + 'First argument (mandatory):'.PHP_EOL. + 'Path to a folder, containing folders with .nzb or .nzb.gz files inside them.'.PHP_EOL. + 'If you supply a path containing only files, the files will be ignored.'.PHP_EOL. + 'The sub-folders will be searched recursively for NZB files.'.PHP_EOL.PHP_EOL. + 'Second argument (optional):'.PHP_EOL. + 'Number of processes, how many processes to run max at a time. (default is 1)'.PHP_EOL.PHP_EOL. + 'Third argument (optional):'.PHP_EOL. + 'true|false => Delete the NZB files after they are imported (recommended), if you stop and restart you will have to go over the imported files again.'.PHP_EOL.PHP_EOL. + 'Fourth argument (optional)'.PHP_EOL. + 'true|false => Delete the NZB if importing it fails (not recommended).'.PHP_EOL. + 'Fifth argument (optional):'.PHP_EOL. + 'true|false => Use the NZB file name as the release name (not recommended), the names in the NZB are better.'.PHP_EOL.PHP_EOL. + 'Sixth argument (optional):'.PHP_EOL. + 'How many NZB files to import per process, if this is not set, it will do 50,000 per process.'.PHP_EOL.PHP_EOL. + 'Note that successfully imported NZB files WILL be deleted.'.PHP_EOL ); } diff --git a/misc/update/nix/multiprocessing/postprocess.php b/misc/update/nix/multiprocessing/postprocess.php index 5d3413b6d..ef95d898e 100644 --- a/misc/update/nix/multiprocessing/postprocess.php +++ b/misc/update/nix/multiprocessing/postprocess.php @@ -1,21 +1,22 @@ <?php -if (!isset($argv[1]) || !in_array($argv[1], ['ama', 'add', 'mov', 'nfo', 'sha', 'tv'])) { - exit( - 'First argument (mandatory):' . PHP_EOL . - 'ama => Do amazon processing, this does not use multi-processing, because of amazon API restrictions.' . PHP_EOL . - 'add => Do additional (rar|zip) processing.' . PHP_EOL . - 'mov => Do movie processing.' . PHP_EOL . - 'nfo => Do NFO processing.' . PHP_EOL . - 'sha => Do sharing processing, this does not use multi-processing.' . PHP_EOL . - 'tv => Do TV processing.' . PHP_EOL . PHP_EOL . - 'Second argument (optional):' . PHP_EOL . - 'true|false => Only post-process renamed releases. This is for the mov|tv options.' . PHP_EOL + +if (! isset($argv[1]) || ! in_array($argv[1], ['ama', 'add', 'mov', 'nfo', 'sha', 'tv'])) { + exit( + 'First argument (mandatory):'.PHP_EOL. + 'ama => Do amazon processing, this does not use multi-processing, because of amazon API restrictions.'.PHP_EOL. + 'add => Do additional (rar|zip) processing.'.PHP_EOL. + 'mov => Do movie processing.'.PHP_EOL. + 'nfo => Do NFO processing.'.PHP_EOL. + 'sha => Do sharing processing, this does not use multi-processing.'.PHP_EOL. + 'tv => Do TV processing.'.PHP_EOL.PHP_EOL. + 'Second argument (optional):'.PHP_EOL. + 'true|false => Only post-process renamed releases. This is for the mov|tv options.'.PHP_EOL ); } declare(ticks=1); -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\libraries\Forking; -(new Forking())->processWorkType('postProcess_' . $argv[1], (isset($argv[2]) && $argv[2] === 'true' ? [0 => true] : [])); +(new Forking())->processWorkType('postProcess_'.$argv[1], (isset($argv[2]) && $argv[2] === 'true' ? [0 => true] : [])); diff --git a/misc/update/nix/multiprocessing/releases.php b/misc/update/nix/multiprocessing/releases.php index 387d2c21d..0958ddcbe 100644 --- a/misc/update/nix/multiprocessing/releases.php +++ b/misc/update/nix/multiprocessing/releases.php @@ -1,6 +1,7 @@ <?php + declare(ticks=1); -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\libraries\Forking; diff --git a/misc/update/nix/multiprocessing/requestid.php b/misc/update/nix/multiprocessing/requestid.php index 816f415fa..635cab2ae 100644 --- a/misc/update/nix/multiprocessing/requestid.php +++ b/misc/update/nix/multiprocessing/requestid.php @@ -1,7 +1,8 @@ <?php -declare(ticks=1); -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; -use \nntmux\libraries\Forking; +declare(ticks=1); +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; + +use nntmux\libraries\Forking; (new Forking())->processWorkType('request_id'); diff --git a/misc/update/nix/multiprocessing/safe.php b/misc/update/nix/multiprocessing/safe.php index de9af747a..eccd04e72 100644 --- a/misc/update/nix/multiprocessing/safe.php +++ b/misc/update/nix/multiprocessing/safe.php @@ -1,15 +1,16 @@ <?php -if (!isset($argv[1]) || !in_array($argv[1], ['backfill', 'binaries'])) { - exit( - 'First argument (mandatory):' . PHP_EOL . - 'binaries => Do Safe Binaries update.' . PHP_EOL . - 'backfill => Do Safe Backfill update.' . PHP_EOL + +if (! isset($argv[1]) || ! in_array($argv[1], ['backfill', 'binaries'])) { + exit( + 'First argument (mandatory):'.PHP_EOL. + 'binaries => Do Safe Binaries update.'.PHP_EOL. + 'backfill => Do Safe Backfill update.'.PHP_EOL ); } declare(ticks=1); -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; -use \nntmux\libraries\Forking; +use nntmux\libraries\Forking; -(new Forking())->processWorkType('safe_' . $argv[1]); +(new Forking())->processWorkType('safe_'.$argv[1]); diff --git a/misc/update/nix/multiprocessing/update_per_group.php b/misc/update/nix/multiprocessing/update_per_group.php index 0305cfea7..4a1c010cf 100644 --- a/misc/update/nix/multiprocessing/update_per_group.php +++ b/misc/update/nix/multiprocessing/update_per_group.php @@ -1,8 +1,9 @@ <?php -declare(ticks=1); -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; -use \nntmux\libraries\Forking; +declare(ticks=1); +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; + +use nntmux\libraries\Forking; // This is the same as the python update_threaded.php (new Forking())->processWorkType('update_per_group'); diff --git a/misc/update/nix/tmux/bin/groupfixrelnames.php b/misc/update/nix/tmux/bin/groupfixrelnames.php index f4a3e8b60..088b0bdfe 100644 --- a/misc/update/nix/tmux/bin/groupfixrelnames.php +++ b/misc/update/nix/tmux/bin/groupfixrelnames.php @@ -1,22 +1,23 @@ <?php -require_once dirname(__DIR__, 5) . DIRECTORY_SEPARATOR . 'bootstrap.php'; -use App\Models\Settings; +require_once dirname(__DIR__, 5).DIRECTORY_SEPARATOR.'bootstrap.php'; + +use nntmux\Nfo; +use nntmux\NZB; +use nntmux\NNTP; +use nntmux\db\DB; use nntmux\Category; use nntmux\ColorCLI; -use nntmux\MiscSorter; use nntmux\NameFixer; -use nntmux\Nfo; -use nntmux\NNTP; -use nntmux\NZB; +use nntmux\MiscSorter; use nntmux\NZBContents; -use nntmux\db\DB; +use App\Models\Settings; use nntmux\processing\PostProcess; $pdo = new DB(); -if (!isset($argv[1])) { - exit(ColorCLI::error('This script is not intended to be run manually, it is called from Multiprocessing.')); +if (! isset($argv[1])) { + exit(ColorCLI::error('This script is not intended to be run manually, it is called from Multiprocessing.')); } $namefixer = new NameFixer(['Settings' => $pdo]); $sorter = new MiscSorter(true, $pdo); @@ -101,142 +102,140 @@ switch (true) { ); if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $namefixer->checked++; + $namefixer->reset(); - foreach ($releases as $release) { + echo PHP_EOL.ColorCLI::primaryOver("[{$release['releases_id']}]"); - $namefixer->checked++; - $namefixer->reset(); + if ((int) $release['ishashed'] === 1 && (int) $release['dehashstatus'] >= -6 && (int) $release['dehashstatus'] <= 0) { + echo ColorCLI::primaryOver('m'); + if (preg_match('/[a-fA-F0-9]{32,40}/i', $release['name'], $matches)) { + $namefixer->matchPredbHash($matches[0], $release, 1, 1, true, 1); + } + if ($namefixer->matched === false && ! empty($release['filehash']) && preg_match('/[a-fA-F0-9]{32,40}/i', $release['filehash'], $matches)) { + echo ColorCLI::primaryOver('h'); + $namefixer->matchPredbHash($matches[0], $release, true, 1, true, 1); + } + } - echo PHP_EOL . ColorCLI::primaryOver("[{$release['releases_id']}]"); + if ($namefixer->matched) { + continue; + } + $namefixer->reset(); - if ((int)$release['ishashed'] === 1 && (int)$release['dehashstatus'] >= -6 && (int)$release['dehashstatus'] <= 0) { - echo ColorCLI::primaryOver('m'); - if (preg_match('/[a-fA-F0-9]{32,40}/i', $release['name'], $matches)) { - $namefixer->matchPredbHash($matches[0], $release, 1, 1, true, 1); - } - if ($namefixer->matched === false && !empty($release['filehash']) && preg_match('/[a-fA-F0-9]{32,40}/i', $release['filehash'], $matches)) { - echo ColorCLI::primaryOver('h'); - $namefixer->matchPredbHash($matches[0], $release, true, 1, true, 1); - } - } + if ((int) $release['proc_uid'] === NameFixer::PROC_UID_NONE && ! empty($release['uid'])) { + echo ColorCLI::primaryOver('U'); + $namefixer->uidCheck($release, true, 'UID, ', 1, 1); + } + // Not all gate requirements in query always set column status as PP Add check is in query + $namefixer->_updateSingleColumn('proc_uid', NameFixer::PROC_UID_DONE, $release['releases_id']); - if ($namefixer->matched) { - continue; - } - $namefixer->reset(); + if ($namefixer->matched) { + continue; + } + $namefixer->reset(); - if ((int)$release['proc_uid'] === NameFixer::PROC_UID_NONE && !empty($release['uid'])) { - echo ColorCLI::primaryOver('U'); - $namefixer->uidCheck($release, true, 'UID, ', 1, 1); - } - // Not all gate requirements in query always set column status as PP Add check is in query - $namefixer->_updateSingleColumn('proc_uid', NameFixer::PROC_UID_DONE, $release['releases_id']); + if ((int) $release['proc_srr'] === NameFixer::PROC_SRR_NONE) { + echo ColorCLI::primaryOver('sr'); + $namefixer->srrNameCheck($release, true, 'SRR, ', 1, 1); + } + // Not all gate requirements in query always set column status as PP Add check is in query + $namefixer->_updateSingleColumn('proc_srr', NameFixer::PROC_SRR_DONE, $release['releases_id']); - if ($namefixer->matched) { - continue; - } - $namefixer->reset(); + if ($namefixer->matched) { + continue; + } + $namefixer->reset(); - if ((int)$release['proc_srr'] === NameFixer::PROC_SRR_NONE) { - echo ColorCLI::primaryOver('sr'); - $namefixer->srrNameCheck($release, true, 'SRR, ', 1, 1); - } - // Not all gate requirements in query always set column status as PP Add check is in query - $namefixer->_updateSingleColumn('proc_srr', NameFixer::PROC_SRR_DONE, $release['releases_id']); + if ((int) $release['proc_hash16k'] === NameFixer::PROC_HASH16K_NONE && ! empty($release['hash'])) { + echo ColorCLI::primaryOver('U'); + $namefixer->hashCheck($release, true, 'PAR2 hash, ', 1, 1); + } + // Not all gate requirements in query always set column status as PP Add check is in query + $namefixer->_updateSingleColumn('proc_hash16k', NameFixer::PROC_HASH16K_DONE, $release['releases_id']); - if ($namefixer->matched) { - continue; - } - $namefixer->reset(); + if ($namefixer->matched) { + continue; + } + $namefixer->reset(); - if ((int)$release['proc_hash16k'] === NameFixer::PROC_HASH16K_NONE && !empty($release['hash'])) { - echo ColorCLI::primaryOver('U'); - $namefixer->hashCheck($release, true, 'PAR2 hash, ', 1, 1); - } - // Not all gate requirements in query always set column status as PP Add check is in query - $namefixer->_updateSingleColumn('proc_hash16k', NameFixer::PROC_HASH16K_DONE, $release['releases_id']); + if ((int) $release['nfostatus'] === Nfo::NFO_FOUND && (int) $release['proc_nfo'] === NameFixer::PROC_NFO_NONE) { + if (! empty($release['textstring']) && ! preg_match('/^=newz\[NZB\]=\w+/', $release['textstring'])) { + echo ColorCLI::primaryOver('n'); + $namefixer->done = $namefixer->matched = false; + $namefixer->checkName($release, true, 'NFO, ', 1, 1); + } + $namefixer->_updateSingleColumn('proc_nfo', NameFixer::PROC_NFO_DONE, $release['releases_id']); + } - if ($namefixer->matched) { - continue; - } - $namefixer->reset(); + if ($namefixer->matched) { + continue; + } + $namefixer->reset(); - if ((int)$release['nfostatus'] === Nfo::NFO_FOUND && (int)$release['proc_nfo'] === NameFixer::PROC_NFO_NONE) { - if (!empty($release['textstring']) && !preg_match('/^=newz\[NZB\]=\w+/', $release['textstring'])) { - echo ColorCLI::primaryOver('n'); - $namefixer->done = $namefixer->matched = false; - $namefixer->checkName($release, true, 'NFO, ', 1, 1); - } - $namefixer->_updateSingleColumn('proc_nfo', NameFixer::PROC_NFO_DONE, $release['releases_id']); - } + if ((int) $release['fileid'] > 0 && (int) $release['proc_files'] === NameFixer::PROC_FILES_NONE) { + echo ColorCLI::primaryOver('F'); + $namefixer->done = $namefixer->matched = false; + $fileNames = explode('|', $release['filestring']); + if (is_array($fileNames)) { + $releaseFile = $release; + foreach ($fileNames as $fileName) { + if ($namefixer->matched === false) { + echo ColorCLI::primaryOver('f'); + $releaseFile['textstring'] = $fileName; + $namefixer->checkName($releaseFile, true, 'Filenames, ', 1, 1); + if ($namefixer->matched === false) { + echo ColorCLI::primaryOver('xf'); + $namefixer->xxxNameCheck($releaseFile, true, 'Filenames, ', 1, 1); + } + } + } + } + } + // Not all gate requirements in query always set column status as PP Add check is in query + $namefixer->_updateSingleColumn('proc_files', NameFixer::PROC_FILES_DONE, $release['releases_id']); - if ($namefixer->matched) { - continue; - } - $namefixer->reset(); + if ($namefixer->matched) { + continue; + } + $namefixer->reset(); - if ((int)$release['fileid'] > 0 && (int)$release['proc_files'] === NameFixer::PROC_FILES_NONE) { - echo ColorCLI::primaryOver('F'); - $namefixer->done = $namefixer->matched = false; - $fileNames = explode('|', $release['filestring']); - if (is_array($fileNames)) { - $releaseFile = $release; - foreach ($fileNames AS $fileName) { - if ($namefixer->matched === false) { - echo ColorCLI::primaryOver('f'); - $releaseFile['textstring'] = $fileName; - $namefixer->checkName($releaseFile, true, 'Filenames, ', 1, 1); - if ($namefixer->matched === false) { - echo ColorCLI::primaryOver('xf'); - $namefixer->xxxNameCheck($releaseFile, true, 'Filenames, ', 1, 1); - } - } - } - } - } - // Not all gate requirements in query always set column status as PP Add check is in query - $namefixer->_updateSingleColumn('proc_files', NameFixer::PROC_FILES_DONE, $release['releases_id']); - - if ($namefixer->matched) { - continue; - } - $namefixer->reset(); - - if ((int)$release['proc_par2'] === NameFixer::PROC_PAR2_NONE) { - echo ColorCLI::primaryOver('p'); - if (!isset($nzbcontents)) { - $nntp = new NNTP(['Settings' => $pdo]); - if (((int)Settings::value('..alternate_nntp') === 1 ? $nntp->doConnect(true, true) : $nntp->doConnect()) !== true) { - ColorCLI::error('Unable to connect to usenet.'); - } - $Nfo = new Nfo(['Settings' => $pdo, 'Echo' => true]); - $nzbcontents = new NZBContents( + if ((int) $release['proc_par2'] === NameFixer::PROC_PAR2_NONE) { + echo ColorCLI::primaryOver('p'); + if (! isset($nzbcontents)) { + $nntp = new NNTP(['Settings' => $pdo]); + if (((int) Settings::value('..alternate_nntp') === 1 ? $nntp->doConnect(true, true) : $nntp->doConnect()) !== true) { + ColorCLI::error('Unable to connect to usenet.'); + } + $Nfo = new Nfo(['Settings' => $pdo, 'Echo' => true]); + $nzbcontents = new NZBContents( [ 'Echo' => true, 'NNTP' => $nntp, 'Nfo' => $Nfo, 'Settings' => $pdo, - 'PostProcess' => new PostProcess(['Settings' => $pdo, 'Nfo' => $Nfo, 'NameFixer' => $namefixer]) + 'PostProcess' => new PostProcess(['Settings' => $pdo, 'Nfo' => $Nfo, 'NameFixer' => $namefixer]), ] ); - } - if ($namefixer->hashCheck($release, true, 'PAR2 hash, ', 1, 1) === false) { - $nzbcontents->checkPAR2($release['guid'], $release['releases_id'], $release['groups_id'], 1, 1); - } - } + } + if ($namefixer->hashCheck($release, true, 'PAR2 hash, ', 1, 1) === false) { + $nzbcontents->checkPAR2($release['guid'], $release['releases_id'], $release['groups_id'], 1, 1); + } + } - // Not all gate requirements in query always set column status as PP Add check is in query - $namefixer->_updateSingleColumn('proc_par2', NameFixer::PROC_PAR2_DONE, $release['releases_id']); + // Not all gate requirements in query always set column status as PP Add check is in query + $namefixer->_updateSingleColumn('proc_par2', NameFixer::PROC_PAR2_DONE, $release['releases_id']); - if ($namefixer->matched) { - continue; - } - $namefixer->reset(); + if ($namefixer->matched) { + continue; + } + $namefixer->reset(); - if ((int)$release['nfostatus'] === Nfo::NFO_FOUND && (int)$release['proc_sorter'] === MiscSorter::PROC_SORTER_NONE) { - echo ColorCLI::primaryOver('S'); - $res = $sorter->nfosorter(null, $release['releases_id']); - // All gate requirements in query, only set column status if it ran the routine - $namefixer->_updateSingleColumn('proc_sorter', MiscSorter::PROC_SORTER_DONE, $release['releases_id']); - } - } + if ((int) $release['nfostatus'] === Nfo::NFO_FOUND && (int) $release['proc_sorter'] === MiscSorter::PROC_SORTER_NONE) { + echo ColorCLI::primaryOver('S'); + $res = $sorter->nfosorter(null, $release['releases_id']); + // All gate requirements in query, only set column status if it ran the routine + $namefixer->_updateSingleColumn('proc_sorter', MiscSorter::PROC_SORTER_DONE, $release['releases_id']); + } + } } break; @@ -257,20 +256,20 @@ switch (true) { ); if ($pres instanceof \Traversable) { - foreach ($pres as $pre) { - $namefixer->done = $namefixer->matched = false; - $ftmatched = $searched = 0; - $ftmatched = $namefixer->matchPredbFT($pre, true, 1, true, 1); - if ($ftmatched > 0) { - $searched = 1; - } elseif ($ftmatched < 0) { - $searched = -6; - echo '*'; - } else { - $searched = $pre['searched'] - 1; - echo '.'; - } - $pdo->queryExec( + foreach ($pres as $pre) { + $namefixer->done = $namefixer->matched = false; + $ftmatched = $searched = 0; + $ftmatched = $namefixer->matchPredbFT($pre, true, 1, true, 1); + if ($ftmatched > 0) { + $searched = 1; + } elseif ($ftmatched < 0) { + $searched = -6; + echo '*'; + } else { + $searched = $pre['searched'] - 1; + echo '.'; + } + $pdo->queryExec( sprintf(' UPDATE predb SET searched = %d @@ -279,7 +278,7 @@ switch (true) { $pre['predb_id'] ) ); - $namefixer->checked++; - } + $namefixer->checked++; + } } } diff --git a/misc/update/nix/tmux/bin/postprocess_pre.php b/misc/update/nix/tmux/bin/postprocess_pre.php index cc695c048..957fbb49b 100755 --- a/misc/update/nix/tmux/bin/postprocess_pre.php +++ b/misc/update/nix/tmux/bin/postprocess_pre.php @@ -1,5 +1,6 @@ <?php -require_once dirname(__DIR__, 5) . DIRECTORY_SEPARATOR . 'bootstrap.php'; + +require_once dirname(__DIR__, 5).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\PreDb; diff --git a/misc/update/nix/tmux/bin/postprocess_threaded.php b/misc/update/nix/tmux/bin/postprocess_threaded.php index 061955650..6714b3b83 100644 --- a/misc/update/nix/tmux/bin/postprocess_threaded.php +++ b/misc/update/nix/tmux/bin/postprocess_threaded.php @@ -1,18 +1,17 @@ <?php -require_once dirname(__DIR__, 5) . DIRECTORY_SEPARATOR . 'bootstrap.php'; -use nntmux\processing\PostProcess; -use nntmux\ColorCLI; -use nntmux\Tmux; +require_once dirname(__DIR__, 5).DIRECTORY_SEPARATOR.'bootstrap.php'; + use nntmux\NNTP; - +use nntmux\Tmux; +use nntmux\ColorCLI; +use nntmux\processing\PostProcess; $c = new ColorCLI(); -if (!isset($argv[1])) { - exit($c->error("This script is not intended to be run manually, it is called from postprocess.php.")); +if (! isset($argv[1])) { + exit($c->error('This script is not intended to be run manually, it is called from postprocess.php.')); } - $tmux = new Tmux; $torun = $tmux->get()->post; @@ -20,27 +19,26 @@ $pieces = explode(' =+= ', $argv[1]); $postprocess = new PostProcess(['Echo' => true]); if (isset($pieces[6])) { - // Create the connection here and pass - $nntp = new NNTP(); - if ($nntp->doConnect() === false) { - exit($c->error("Unable to connect to usenet.")); - } + // Create the connection here and pass + $nntp = new NNTP(); + if ($nntp->doConnect() === false) { + exit($c->error('Unable to connect to usenet.')); + } - $postprocess->processAdditional($nntp, $argv[1]); - $nntp->doQuit(); -} else if (isset($pieces[3])) { - // Create the connection here and pass - $nntp = new NNTP(); - if ($nntp->doConnect() === false) { - exit($c->error("Unable to connect to usenet.")); - } + $postprocess->processAdditional($nntp, $argv[1]); + $nntp->doQuit(); +} elseif (isset($pieces[3])) { + // Create the connection here and pass + $nntp = new NNTP(); + if ($nntp->doConnect() === false) { + exit($c->error('Unable to connect to usenet.')); + } - $postprocess->processNfos($argv[1], $nntp); - $nntp->doQuit(); - -} else if (isset($pieces[2])) { - $postprocess->processMovies($argv[1]); - echo '.'; -} else if (isset($pieces[1])) { - $postprocess->processTv($argv[1]); + $postprocess->processNfos($argv[1], $nntp); + $nntp->doQuit(); +} elseif (isset($pieces[2])) { + $postprocess->processMovies($argv[1]); + echo '.'; +} elseif (isset($pieces[1])) { + $postprocess->processTv($argv[1]); } diff --git a/misc/update/nix/tmux/bin/showsleep.php b/misc/update/nix/tmux/bin/showsleep.php index ad4355bd4..4858ee052 100644 --- a/misc/update/nix/tmux/bin/showsleep.php +++ b/misc/update/nix/tmux/bin/showsleep.php @@ -1,11 +1,11 @@ <?php -require_once dirname(__DIR__, 5) . DIRECTORY_SEPARATOR . 'bootstrap.php'; + +require_once dirname(__DIR__, 5).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\ConsoleTools; // This script is simply so I can show sleep progress in bash script $consoletools = new ConsoleTools(); -if (isset($argv[1]) && is_numeric($argv[1])) -{ - $consoletools->showsleep($argv[1]); +if (isset($argv[1]) && is_numeric($argv[1])) { + $consoletools->showsleep($argv[1]); } diff --git a/misc/update/nix/tmux/bin/update_groups.php b/misc/update/nix/tmux/bin/update_groups.php index c685f2f94..4a561af36 100644 --- a/misc/update/nix/tmux/bin/update_groups.php +++ b/misc/update/nix/tmux/bin/update_groups.php @@ -1,11 +1,11 @@ <?php -require_once dirname(__DIR__, 5) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 5).DIRECTORY_SEPARATOR.'bootstrap.php'; + +use nntmux\NNTP; use nntmux\db\DB; use nntmux\ColorCLI; use nntmux\ConsoleTools; -use nntmux\NNTP; - $start = time(); $pdo = new DB(); @@ -14,13 +14,13 @@ $consoleTools = new ConsoleTools(['ColorCLI' => $pdo->log]); // Create the connection here and pass $nntp = new NNTP(['Settings' => $pdo]); if ($nntp->doConnect() !== true) { - exit(ColorCLI::error('Unable to connect to usenet.')); + exit(ColorCLI::error('Unable to connect to usenet.')); } echo ColorCLI::header('Getting first/last for all your active groups.'); $data = $nntp->getGroups(); if ($nntp->isError($data)) { - exit(ColorCLI::error('Failed to getGroups() from nntp server.')); + exit(ColorCLI::error('Failed to getGroups() from nntp server.')); } echo ColorCLI::header('Inserting new values into short_groups table.'); @@ -31,28 +31,29 @@ $pdo->queryExec('TRUNCATE TABLE short_groups'); $res = $pdo->query('SELECT name FROM groups WHERE active = 1 OR backfill = 1'); foreach ($data as $newgroup) { - if (myInArray($res, $newgroup['group'], 'name')) { - $pdo->queryInsert(sprintf('INSERT INTO short_groups (name, first_record, last_record, updated) VALUES (%s, %s, %s, NOW())', $pdo->escapeString($newgroup['group']), $pdo->escapeString($newgroup['first']), $pdo->escapeString($newgroup['last']))); - echo ColorCLI::primary('Updated ' . $newgroup['group']); - } + if (myInArray($res, $newgroup['group'], 'name')) { + $pdo->queryInsert(sprintf('INSERT INTO short_groups (name, first_record, last_record, updated) VALUES (%s, %s, %s, NOW())', $pdo->escapeString($newgroup['group']), $pdo->escapeString($newgroup['first']), $pdo->escapeString($newgroup['last']))); + echo ColorCLI::primary('Updated '.$newgroup['group']); + } } -echo ColorCLI::header('Running time: ' . $consoleTools->convertTimer(time() - $start)); +echo ColorCLI::header('Running time: '.$consoleTools->convertTimer(time() - $start)); function myInArray($array, $value, $key) { - //loop through the array - foreach ($array as $val) { - //if $val is an array cal myInArray again with $val as array input - if (is_array($val)) { - if (myInArray($val, $value, $key)) { - return true; - } - } else { - //else check if the given key has $value as value - if ($array[$key] == $value) { - return true; - } - } - } - return false; + //loop through the array + foreach ($array as $val) { + //if $val is an array cal myInArray again with $val as array input + if (is_array($val)) { + if (myInArray($val, $value, $key)) { + return true; + } + } else { + //else check if the given key has $value as value + if ($array[$key] == $value) { + return true; + } + } + } + + return false; } diff --git a/misc/update/nix/tmux/monitor.php b/misc/update/nix/tmux/monitor.php index 3cad6a972..b4a241845 100644 --- a/misc/update/nix/tmux/monitor.php +++ b/misc/update/nix/tmux/monitor.php @@ -1,12 +1,13 @@ <?php -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; -use App\Models\Settings; -use nntmux\Category; +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; + use nntmux\Tmux; -use nntmux\TmuxOutput; -use nntmux\TmuxRun; use nntmux\db\DB; +use nntmux\TmuxRun; +use nntmux\Category; +use nntmux\TmuxOutput; +use App\Models\Settings; use nntmux\utility\Utility; $pdo = new DB(); @@ -15,8 +16,8 @@ $tRun = new TmuxRun($pdo); $tOut = new TmuxOutput($pdo); $runVar['paths']['misc'] = NN_MISC; -$runVar['paths']['cli'] = NN_ROOT . 'cli/'; -$runVar['paths']['scraper'] = NN_MISC . 'IRCScraper' . DS . 'scrape.php'; +$runVar['paths']['cli'] = NN_ROOT.'cli/'; +$runVar['paths']['scraper'] = NN_MISC.'IRCScraper'.DS.'scrape.php'; $db_name = env('DB_NAME'); $dbtype = env('DB_SYSTEM'); @@ -31,9 +32,9 @@ $PYTHON = ($tRun->command_exist('python3') ? 'python3 -OOu' : 'python -OOu'); //assign shell commands $show_time = (NN_DEBUG ? '/usr/bin/time' : ''); -$runVar['commands']['_php'] = $show_time . " nice -n{$tmux_niceness} $PHP"; +$runVar['commands']['_php'] = $show_time." nice -n{$tmux_niceness} $PHP"; $runVar['commands']['_phpn'] = "nice -n{$tmux_niceness} $PHP"; -$runVar['commands']['_python'] = $show_time . " nice -n{$tmux_niceness} $PYTHON"; +$runVar['commands']['_python'] = $show_time." nice -n{$tmux_niceness} $PYTHON"; $runVar['commands']['_sleep'] = "{$runVar['commands']['_phpn']} {$runVar['paths']['misc']}update/nix/tmux/bin/showsleep.php"; //spawn IRCScraper as soon as possible @@ -56,10 +57,10 @@ $runVar['timers']['query']['tpg1_time'] = 0; // Analyze release table if not using innoDB (innoDB uses online analysis) $engine = $pdo->queryOneRow(sprintf("SELECT ENGINE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME = 'releases'", $pdo->escapeString($db_name))); -if (!in_array($engine['engine'], ['InnoDB', 'TokuDB'], false)) { - printf($pdo->log->info(PHP_EOL . 'Analyzing your tables to refresh your indexes.')); - $pdo->optimise(false, 'analyze', false, ['releases']); - Utility::clearScreen(); +if (! in_array($engine['engine'], ['InnoDB', 'TokuDB'], false)) { + printf($pdo->log->info(PHP_EOL.'Analyzing your tables to refresh your indexes.')); + $pdo->optimise(false, 'analyze', false, ['releases']); + Utility::clearScreen(); } $runVar['settings']['monitor'] = 0; @@ -67,34 +68,34 @@ $runVar['counts']['iterations'] = 1; $runVar['modsettings']['fc']['firstrun'] = true; $runVar['modsettings']['fc']['num'] = 0; -$tblCount = 'SELECT TABLE_ROWS AS count FROM information_schema.TABLES WHERE TABLE_NAME = :table AND TABLE_SCHEMA = ' . $pdo->escapeString($db_name); +$tblCount = 'SELECT TABLE_ROWS AS count FROM information_schema.TABLES WHERE TABLE_NAME = :table AND TABLE_SCHEMA = '.$pdo->escapeString($db_name); $psTableRowCount = $pdo->Prepare($tblCount); while ($runVar['counts']['iterations'] > 0) { //check the db connection - if ($pdo->ping(true) === false) { - unset($pdo); - $pdo = new DB(); - } + if ($pdo->ping(true) === false) { + unset($pdo); + $pdo = new DB(); + } - $timer01 = time(); - // These queries are very fast, run every loop -- tmux and site settings - $runVar['settings'] = $pdo->queryOneRow($tRun->getMonitorSettings(), false); - $runVar['timers']['query']['tmux_time'] = (time() - $timer01); + $timer01 = time(); + // These queries are very fast, run every loop -- tmux and site settings + $runVar['settings'] = $pdo->queryOneRow($tRun->getMonitorSettings(), false); + $runVar['timers']['query']['tmux_time'] = (time() - $timer01); - $runVar['settings']['book_reqids'] = (!empty($runVar['settings']['book_reqids']) + $runVar['settings']['book_reqids'] = (! empty($runVar['settings']['book_reqids']) ? $runVar['settings']['book_reqids'] : Category::BOOKS_ROOT); - //get usenet connection info - $runVar['connections'] = $tOut->getConnectionsInfo($runVar['constants']); + //get usenet connection info + $runVar['connections'] = $tOut->getConnectionsInfo($runVar['constants']); - $runVar['constants']['pre_lim'] = ($runVar['counts']['iterations'] > 1 ? '7' : ''); + $runVar['constants']['pre_lim'] = ($runVar['counts']['iterations'] > 1 ? '7' : ''); - //assign scripts - $runVar['scripts']['releases'] = "{$runVar['commands']['_php']} {$runVar['paths']['misc']}update/nix/multiprocessing/releases.php"; + //assign scripts + $runVar['scripts']['releases'] = "{$runVar['commands']['_php']} {$runVar['paths']['misc']}update/nix/multiprocessing/releases.php"; - switch ((int)$runVar['settings']['binaries_run']) { + switch ((int) $runVar['settings']['binaries_run']) { case 1: $runVar['scripts']['binaries'] = "{$runVar['commands']['_php']} {$runVar['paths']['misc']}update/nix/multiprocessing/binaries.php 0"; break; @@ -105,7 +106,7 @@ while ($runVar['counts']['iterations'] > 0) { $runVar['scripts']['binaries'] = 0; } - switch ((int)$runVar['settings']['backfill']) { + switch ((int) $runVar['settings']['backfill']) { case 1: $runVar['scripts']['backfill'] = "{$runVar['commands']['_php']} {$runVar['paths']['misc']}update/nix/multiprocessing/backfill.php"; break; @@ -113,46 +114,45 @@ while ($runVar['counts']['iterations'] > 0) { $runVar['scripts']['backfill'] = "{$runVar['commands']['_php']} {$runVar['paths']['misc']}update/nix/multiprocessing/safe.php backfill"; } - //get usenet connection counts - unset ($runVar['conncounts']); - $runVar['conncounts'] = $tOut->getUSPConnections('primary', $runVar['connections']); + //get usenet connection counts + unset($runVar['conncounts']); + $runVar['conncounts'] = $tOut->getUSPConnections('primary', $runVar['connections']); - if ($runVar['constants']['alternate_nntp'] == 1) { - $runVar['conncounts'] += $tOut->getUSPConnections('alternate', $runVar['connections']); - } + if ($runVar['constants']['alternate_nntp'] == 1) { + $runVar['conncounts'] += $tOut->getUSPConnections('alternate', $runVar['connections']); + } - //run queries only after time exceeded, these queries can take awhile - if ($runVar['counts']['iterations'] == 1 || (time() - $runVar['timers']['timer2'] >= $runVar['settings']['monitor'] && $runVar['settings']['is_running'] == 1)) { + //run queries only after time exceeded, these queries can take awhile + if ($runVar['counts']['iterations'] == 1 || (time() - $runVar['timers']['timer2'] >= $runVar['settings']['monitor'] && $runVar['settings']['is_running'] == 1)) { + $runVar['counts']['proc1'] = $runVar['counts']['proc2'] = $runVar['counts']['proc3'] = $splitqry = $newOldqry = false; + $runVar['counts']['now']['total_work'] = 0; + $runVar['modsettings']['fix_crap'] = explode(', ', ($runVar['settings']['fix_crap'])); - $runVar['counts']['proc1'] = $runVar['counts']['proc2'] = $runVar['counts']['proc3'] = $splitqry = $newOldqry = false; - $runVar['counts']['now']['total_work'] = 0; - $runVar['modsettings']['fix_crap'] = explode(', ', ($runVar['settings']['fix_crap'])); + echo $pdo->log->info("\nThe numbers(queries) above are currently being refreshed. \nNo pane(script) can be (re)started until these have completed.\n"); + $timer02 = time(); - echo $pdo->log->info("\nThe numbers(queries) above are currently being refreshed. \nNo pane(script) can be (re)started until these have completed.\n"); - $timer02 = time(); + $splitqry = $newOldqry = ''; - $splitqry = $newOldqry = ''; + $splitqry = $tRun->proc_query(4, null, null, $db_name); + $newOldqry = $tRun->proc_query(6, null, null, null); - $splitqry = $tRun->proc_query(4, null, null, $db_name); - $newOldqry = $tRun->proc_query(6, null, null, null); + $splitres = $pdo->queryOneRow($splitqry, false); + $runVar['timers']['newOld'] = $pdo->queryOneRow($newOldqry, false); - $splitres = $pdo->queryOneRow($splitqry, false); - $runVar['timers']['newOld'] = $pdo->queryOneRow($newOldqry, false); + //assign split query results to main var + if (is_array($splitres)) { + foreach ($splitres as $splitkey => $split) { + $runVar['counts']['now'][$splitkey] = $split; + } + } - //assign split query results to main var - if (is_array($splitres)) { - foreach ($splitres as $splitkey => $split) { - $runVar['counts']['now'][$splitkey] = $split; - } - } + $runVar['timers']['query']['split_time'] = (time() - $timer02); + $runVar['timers']['query']['split1_time'] = (time() - $timer01); - $runVar['timers']['query']['split_time'] = (time() - $timer02); - $runVar['timers']['query']['split1_time'] = (time() - $timer01); + $timer03 = time(); - $timer03 = time(); - - //This is subpartition compatible -- loops through all partitions and adds their total row counts instead of doing a slow query count - $partitions = $pdo->queryDirect( + //This is subpartition compatible -- loops through all partitions and adds their total row counts instead of doing a slow query count + $partitions = $pdo->queryDirect( sprintf(" SELECT SUM(TABLE_ROWS) AS count, PARTITION_NAME AS category FROM information_schema.PARTITIONS @@ -162,22 +162,22 @@ while ($runVar['counts']['iterations'] > 0) { $pdo->escapeString($db_name) ) ); - foreach ($partitions as $partition) { - $runVar['counts']['now'][$partition['category']] = $partition['count']; - } - unset($partitions); + foreach ($partitions as $partition) { + $runVar['counts']['now'][$partition['category']] = $partition['count']; + } + unset($partitions); - $runVar['timers']['query']['init_time'] = (time() - $timer03); - $runVar['timers']['query']['init1_time'] = (time() - $timer01); + $runVar['timers']['query']['init_time'] = (time() - $timer03); + $runVar['timers']['query']['init1_time'] = (time() - $timer01); - $timer04 = time(); - $proc1qry = $tRun->proc_query(1, $runVar['settings']['book_reqids'], $runVar['settings']['request_hours'], $db_name); - $proc1res = $pdo->queryOneRow(($proc1qry !== false ? $proc1qry : ''), $tRun->rand_bool($runVar['counts']['iterations'])); - $runVar['timers']['query']['proc1_time'] = (time() - $timer04); - $runVar['timers']['query']['proc11_time'] = (time() - $timer01); + $timer04 = time(); + $proc1qry = $tRun->proc_query(1, $runVar['settings']['book_reqids'], $runVar['settings']['request_hours'], $db_name); + $proc1res = $pdo->queryOneRow(($proc1qry !== false ? $proc1qry : ''), $tRun->rand_bool($runVar['counts']['iterations'])); + $runVar['timers']['query']['proc1_time'] = (time() - $timer04); + $runVar['timers']['query']['proc11_time'] = (time() - $timer01); - $timer05 = time(); - $proc2qry = $tRun->proc_query( + $timer05 = time(); + $proc2qry = $tRun->proc_query( 2, $runVar['settings']['book_reqids'], $runVar['settings']['request_hours'], @@ -185,31 +185,31 @@ while ($runVar['counts']['iterations'] > 0) { $runVar['settings']['maxsize_pp'], $runVar['settings']['minsize_pp'] ); - $proc2res = $pdo->queryOneRow(($proc2qry !== false ? $proc2qry : ''), $tRun->rand_bool($runVar['counts']['iterations'])); - $runVar['timers']['query']['proc2_time'] = (time() - $timer05); - $runVar['timers']['query']['proc21_time'] = (time() - $timer01); + $proc2res = $pdo->queryOneRow(($proc2qry !== false ? $proc2qry : ''), $tRun->rand_bool($runVar['counts']['iterations'])); + $runVar['timers']['query']['proc2_time'] = (time() - $timer05); + $runVar['timers']['query']['proc21_time'] = (time() - $timer01); - // Need to remove this - $timer06 = time(); - $runVar['timers']['query']['proc3_time'] = (time() - $timer06); - $runVar['timers']['query']['proc31_time'] = (time() - $timer01); + // Need to remove this + $timer06 = time(); + $runVar['timers']['query']['proc3_time'] = (time() - $timer06); + $runVar['timers']['query']['proc31_time'] = (time() - $timer01); - $timer07 = time(); - $tables = $tMain->cbpmTableQuery(); - $age = time(); + $timer07 = time(); + $tables = $tMain->cbpmTableQuery(); + $age = time(); - $runVar['counts']['now']['collections_table'] = $runVar['counts']['now']['binaries_table'] = 0; - $runVar['counts']['now']['parts_table'] = $runVar['counts']['now']['parterpair_table'] = 0; + $runVar['counts']['now']['collections_table'] = $runVar['counts']['now']['binaries_table'] = 0; + $runVar['counts']['now']['parts_table'] = $runVar['counts']['now']['parterpair_table'] = 0; - if ($psTableRowCount === false) { - echo 'Unable to prepare statement, skipping monitor updates!'; - } else { - if ($tables instanceof \Traversable) { - foreach ($tables as $row) { - $tbl = $row['name']; - $stamp = 'UNIX_TIMESTAMP(MIN(dateadded))'; + if ($psTableRowCount === false) { + echo 'Unable to prepare statement, skipping monitor updates!'; + } else { + if ($tables instanceof \Traversable) { + foreach ($tables as $row) { + $tbl = $row['name']; + $stamp = 'UNIX_TIMESTAMP(MIN(dateadded))'; - switch (true) { + switch (true) { case strpos($tbl, 'collections') !== false: $runVar['counts']['now']['collections_table'] += getTableRowCount($psTableRowCount, $tbl); @@ -217,7 +217,7 @@ while ($runVar['counts']['iterations'] > 0) { if (isset($added['dateadded']) && is_numeric($added['dateadded']) && $added['dateadded'] < $age ) { - $age = $added['dateadded']; + $age = $added['dateadded']; } break; case strpos($tbl, 'binaries') !== false: @@ -236,161 +236,160 @@ while ($runVar['counts']['iterations'] > 0) { break; default: } - } - $runVar['timers']['newOld']['oldestcollection'] = $age; + } + $runVar['timers']['newOld']['oldestcollection'] = $age; - //free up memory used by now stale data - unset($age, $added, $tables); + //free up memory used by now stale data + unset($age, $added, $tables); - $runVar['timers']['query']['tpg_time'] = (time() - $timer07); - $runVar['timers']['query']['tpg1_time'] = (time() - $timer01); - } - } - $runVar['timers']['timer2'] = time(); + $runVar['timers']['query']['tpg_time'] = (time() - $timer07); + $runVar['timers']['query']['tpg1_time'] = (time() - $timer01); + } + } + $runVar['timers']['timer2'] = time(); - //assign postprocess values from $proc - if (is_array($proc1res)) { - foreach ($proc1res as $proc1key => $proc1) { - $runVar['counts']['now'][$proc1key] = $proc1; - } - } else { - errorOnSQL($pdo); - } + //assign postprocess values from $proc + if (is_array($proc1res)) { + foreach ($proc1res as $proc1key => $proc1) { + $runVar['counts']['now'][$proc1key] = $proc1; + } + } else { + errorOnSQL($pdo); + } - if (is_array($proc2res)) { - foreach ($proc2res as $proc2key => $proc2) { - $runVar['counts']['now'][$proc2key] = $proc2; - } - } else { - errorOnSQL($pdo); - } + if (is_array($proc2res)) { + foreach ($proc2res as $proc2key => $proc2) { + $runVar['counts']['now'][$proc2key] = $proc2; + } + } else { + errorOnSQL($pdo); + } - // now that we have merged our query data we can unset these to free up memory - unset($proc1res, $proc2res, $splitres); + // now that we have merged our query data we can unset these to free up memory + unset($proc1res, $proc2res, $splitres); - // Zero out any post proc counts when that type of pp has been turned off - foreach ($runVar['settings'] as $settingkey => $setting) { - if (strpos($settingkey, 'process') == 0 && $setting == 0) { - $runVar['counts']['now'][$settingkey] = $runVar['counts']['start'][$settingkey] = 0; - } - if ($settingkey == 'fix_names' && $setting == 0) { - $runVar['counts']['now']['processrenames'] = $runVar['counts']['start']['processrenames'] = 0; - } - } + // Zero out any post proc counts when that type of pp has been turned off + foreach ($runVar['settings'] as $settingkey => $setting) { + if (strpos($settingkey, 'process') == 0 && $setting == 0) { + $runVar['counts']['now'][$settingkey] = $runVar['counts']['start'][$settingkey] = 0; + } + if ($settingkey == 'fix_names' && $setting == 0) { + $runVar['counts']['now']['processrenames'] = $runVar['counts']['start']['processrenames'] = 0; + } + } - //set initial start postproc values from work queries -- this is used to determine diff variables - if ($runVar['counts']['iterations'] == 1) { - $runVar['counts']['start'] = $runVar['counts']['now']; - } + //set initial start postproc values from work queries -- this is used to determine diff variables + if ($runVar['counts']['iterations'] == 1) { + $runVar['counts']['start'] = $runVar['counts']['now']; + } - foreach ($runVar['counts']['now'] as $key => $proc) { + foreach ($runVar['counts']['now'] as $key => $proc) { //if key is a process type, add it to total_work - if (strpos($key, 'process') === 0) { - $runVar['counts']['now']['total_work'] += $proc; - } + if (strpos($key, 'process') === 0) { + $runVar['counts']['now']['total_work'] += $proc; + } - //calculate diffs - $runVar['counts']['diff'][$key] = number_format($proc - $runVar['counts']['start'][$key]); + //calculate diffs + $runVar['counts']['diff'][$key] = number_format($proc - $runVar['counts']['start'][$key]); - //calculate percentages -- if user has no releases, set 0 for each key or this will fail on divide by zero - $runVar['counts']['percent'][$key] = ($runVar['counts']['now']['releases'] > 0 - ? sprintf("%02s", floor(($proc / $runVar['counts']['now']['releases']) * 100)) : 0); - } + //calculate percentages -- if user has no releases, set 0 for each key or this will fail on divide by zero + $runVar['counts']['percent'][$key] = ($runVar['counts']['now']['releases'] > 0 + ? sprintf('%02s', floor(($proc / $runVar['counts']['now']['releases']) * 100)) : 0); + } - $runVar['counts']['now']['total_work'] += $runVar['counts']['now']['work']; + $runVar['counts']['now']['total_work'] += $runVar['counts']['now']['work']; - // Set initial total work count for diff - if ($runVar['counts']['iterations'] == 1) { - $runVar['counts']['start']['total_work'] = $runVar['counts']['now']['total_work']; - } + // Set initial total work count for diff + if ($runVar['counts']['iterations'] == 1) { + $runVar['counts']['start']['total_work'] = $runVar['counts']['now']['total_work']; + } - // Set diff total work count - $runVar['counts']['diff']['total_work'] = number_format($runVar['counts']['now']['total_work'] - $runVar['counts']['start']['total_work']); - } + // Set diff total work count + $runVar['counts']['diff']['total_work'] = number_format($runVar['counts']['now']['total_work'] - $runVar['counts']['start']['total_work']); + } - //set kill switches - $runVar['killswitch']['pp'] = (($runVar['settings']['postprocess_kill'] < $runVar['counts']['now']['total_work']) && ($runVar['settings']['postprocess_kill'] != 0) + //set kill switches + $runVar['killswitch']['pp'] = (($runVar['settings']['postprocess_kill'] < $runVar['counts']['now']['total_work']) && ($runVar['settings']['postprocess_kill'] != 0) ? true : false ); - $runVar['killswitch']['coll'] = (($runVar['settings']['collections_kill'] < $runVar['counts']['now']['collections_table']) && ($runVar['settings']['collections_kill'] != 0) + $runVar['killswitch']['coll'] = (($runVar['settings']['collections_kill'] < $runVar['counts']['now']['collections_table']) && ($runVar['settings']['collections_kill'] != 0) ? true : false ); - $tOut->updateMonitorPane($runVar); + $tOut->updateMonitorPane($runVar); - //begin pane run execution - if ($runVar['settings']['is_running'] === '1') { + //begin pane run execution + if ($runVar['settings']['is_running'] === '1') { //run main updating function(s) - $tRun->runPane('main', $runVar); + $tRun->runPane('main', $runVar); - //run nzb-import - $tRun->runPane('import', $runVar); + //run nzb-import + $tRun->runPane('import', $runVar); - //run postprocess_releases amazon - $tRun->runPane('amazon', $runVar); + //run postprocess_releases amazon + $tRun->runPane('amazon', $runVar); - //respawn IRCScraper if it has been killed - $tRun->runPane('scraper', $runVar); + //respawn IRCScraper if it has been killed + $tRun->runPane('scraper', $runVar); - //run sharing regardless of sequential setting - $tRun->runPane('sharing', $runVar); + //run sharing regardless of sequential setting + $tRun->runPane('sharing', $runVar); - //update tv and theaters - $tRun->runPane('updatetv', $runVar); + //update tv and theaters + $tRun->runPane('updatetv', $runVar); - //run these if complete sequential not set - if ($runVar['constants']['sequential'] != 2) { + //run these if complete sequential not set + if ($runVar['constants']['sequential'] != 2) { //fix names - $tRun->runPane('fixnames', $runVar); + $tRun->runPane('fixnames', $runVar); - //dehash releases - $tRun->runPane('dehash', $runVar); + //dehash releases + $tRun->runPane('dehash', $runVar); - // Remove crap releases. - $tRun->runPane('removecrap', $runVar); + // Remove crap releases. + $tRun->runPane('removecrap', $runVar); - //run postprocess_releases additional - $tRun->runPane('ppadditional', $runVar); + //run postprocess_releases additional + $tRun->runPane('ppadditional', $runVar); - //run postprocess_releases non amazon - $tRun->runPane('nonamazon', $runVar); - } + //run postprocess_releases non amazon + $tRun->runPane('nonamazon', $runVar); + } + } elseif ($runVar['settings']['is_running'] === '0') { + $tRun->runPane('notrunning', $runVar); + } - } else if ($runVar['settings']['is_running'] === '0') { - $tRun->runPane('notrunning', $runVar); - } - - $exit = Settings::value('tmux.running.exit'); - if ($exit == 0) { - $runVar['counts']['iterations']++; - sleep(10); - } else { - // Set counter to less than one so the loop will exit. - $runVar['counts']['iterations'] = ($exit < 0) ? $exit : 0; - } + $exit = Settings::value('tmux.running.exit'); + if ($exit == 0) { + $runVar['counts']['iterations']++; + sleep(10); + } else { + // Set counter to less than one so the loop will exit. + $runVar['counts']['iterations'] = ($exit < 0) ? $exit : 0; + } } // TODO add code here to handle all panes shutting down before closing. function errorOnSQL($pdo) { - echo $pdo->log->error(PHP_EOL . 'Monitor encountered severe errors retrieving process data from MySQL. Please diagnose and try running again.' . PHP_EOL); - exit; + echo $pdo->log->error(PHP_EOL.'Monitor encountered severe errors retrieving process data from MySQL. Please diagnose and try running again.'.PHP_EOL); + exit; } function getTableRowCount(\PDOStatement $ps, $table) { - $success = $ps->execute([':table' => $table]); - if ($success) { - $result = $ps->fetch(); + $success = $ps->execute([':table' => $table]); + if ($success) { + $result = $ps->fetch(); - return is_numeric($result['count']) ? $result['count'] : 0; - } + return is_numeric($result['count']) ? $result['count'] : 0; + } - return false; + return false; } diff --git a/misc/update/nix/tmux/run.php b/misc/update/nix/tmux/run.php index 3cc4f81ff..b4d115ad9 100644 --- a/misc/update/nix/tmux/run.php +++ b/misc/update/nix/tmux/run.php @@ -1,11 +1,12 @@ <?php -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; -use App\Models\Settings; -use nntmux\db\DB; -use nntmux\utility\Utility; +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; + use nntmux\Tmux; +use nntmux\db\DB; use nntmux\ColorCLI; +use App\Models\Settings; +use nntmux\utility\Utility; $pdo = new DB(); $DIR = NN_TMUX; @@ -18,23 +19,22 @@ $seq = $tmux->sequential ?? 0; $powerline = $tmux->powerline ?? 0; $colors = $tmux->colors ?? 0; $delaytimet = Settings::value('..delaytime'); -$delaytimet = $delaytimet ? (int)$delaytimet : 2; +$delaytimet = $delaytimet ? (int) $delaytimet : 2; Utility::isPatched(); Utility::clearScreen(); -echo 'Starting Tmux...' . PHP_EOL; +echo 'Starting Tmux...'.PHP_EOL; // Create a placeholder session so tmux commands do not throw server not found errors. exec('tmux new-session -ds placeholder 2>/dev/null'); exec('tmux list-session', $session); - //check if session exists $session = shell_exec("tmux list-session | grep $tmux_session"); // Kill the placeholder exec('tmux kill-session -t placeholder'); if (count($session) !== 0) { - exit(ColorCLI::error("tmux session: '" . $tmux_session . "' is already running, aborting.\n")); + exit(ColorCLI::error("tmux session: '".$tmux_session."' is already running, aborting.\n")); } //reset collections dateadded to now if dateadded > delay time check @@ -44,204 +44,204 @@ $sql = 'SHOW table status'; $tables = $pdo->queryDirect($sql); $ran = 0; foreach ($tables as $row) { - $tbl = $row['name']; - if (preg_match('/(multigroup\_)?collections(_\d+)?/', $tbl)) { - $run = $pdo->queryExec('UPDATE ' . $tbl . - ' SET dateadded = now() WHERE dateadded < now() - INTERVAL ' . - $delaytimet . ' HOUR' + $tbl = $row['name']; + if (preg_match('/(multigroup\_)?collections(_\d+)?/', $tbl)) { + $run = $pdo->queryExec('UPDATE '.$tbl. + ' SET dateadded = now() WHERE dateadded < now() - INTERVAL '. + $delaytimet.' HOUR' ); - if ($run !== false) { - $ran += $run->rowCount(); - } - } + if ($run !== false) { + $ran += $run->rowCount(); + } + } } -echo ColorCLI::primary(number_format($ran) . ' collections reset.'); +echo ColorCLI::primary(number_format($ran).' collections reset.'); sleep(2); function writelog($pane) { - $path = NN_RES . 'logs'; - $getdate = gmdate('Ymd'); - $tmux = new Tmux(); - $logs = $tmux->get()->write_logs; - if ((int)$logs === 1) { - return "2>&1 | tee -a $path/$pane-$getdate.log"; - } - return ''; + $path = NN_RES.'logs'; + $getdate = gmdate('Ymd'); + $tmux = new Tmux(); + $logs = $tmux->get()->write_logs; + if ((int) $logs === 1) { + return "2>&1 | tee -a $path/$pane-$getdate.log"; + } + return ''; } function command_exist($cmd) { - $returnVal = exec("which $cmd 2>/dev/null"); + $returnVal = exec("which $cmd 2>/dev/null"); - return (empty($returnVal) ? false : true); + return empty($returnVal) ? false : true; } //check for apps -$apps = array('time', 'tmux', 'nice', 'python', 'tee'); +$apps = ['time', 'tmux', 'nice', 'python', 'tee']; foreach ($apps as &$value) { - if (!command_exist($value)) { - exit(ColorCLI::error('Tmux scripts require ' . $value . ' but its not installed. Aborting.' . PHP_EOL)); - } + if (! command_exist($value)) { + exit(ColorCLI::error('Tmux scripts require '.$value.' but its not installed. Aborting.'.PHP_EOL)); + } } unset($value); function python_module_exist($module) { - $output = $returnCode = ''; - exec("python -c \"import $module\"", $output, $returnCode); + $output = $returnCode = ''; + exec("python -c \"import $module\"", $output, $returnCode); - return ((int)$returnCode === 0 ? true : false); + return (int) $returnCode === 0 ? true : false; } function start_apps($tmux_session) { - $t = new Tmux(); - $tmux = $t->get(); - $htop = $tmux->htop; - $vnstat = $tmux->vnstat; - $vnstat_args = $tmux->vnstat_args; - $tcptrack = $tmux->tcptrack; - $tcptrack_args = $tmux->tcptrack_args; - $nmon = $tmux->nmon; - $bwmng = $tmux->bwmng; - $mytop = $tmux->mytop; - $showprocesslist = $tmux->showprocesslist; - $processupdate = $tmux->processupdate; - $console_bash = $tmux->console; + $t = new Tmux(); + $tmux = $t->get(); + $htop = $tmux->htop; + $vnstat = $tmux->vnstat; + $vnstat_args = $tmux->vnstat_args; + $tcptrack = $tmux->tcptrack; + $tcptrack_args = $tmux->tcptrack_args; + $nmon = $tmux->nmon; + $bwmng = $tmux->bwmng; + $mytop = $tmux->mytop; + $showprocesslist = $tmux->showprocesslist; + $processupdate = $tmux->processupdate; + $console_bash = $tmux->console; - if ((int)$htop === 1 && command_exist('htop')) { - exec("tmux new-window -t $tmux_session -n htop 'printf \"\033]2;htop\033\" && htop'"); - } + if ((int) $htop === 1 && command_exist('htop')) { + exec("tmux new-window -t $tmux_session -n htop 'printf \"\033]2;htop\033\" && htop'"); + } - if ((int)$nmon === 1 && command_exist('nmon')) { - exec("tmux new-window -t $tmux_session -n nmon 'printf \"\033]2;nmon\033\" && nmon -t'"); - } + if ((int) $nmon === 1 && command_exist('nmon')) { + exec("tmux new-window -t $tmux_session -n nmon 'printf \"\033]2;nmon\033\" && nmon -t'"); + } - if ((int)$vnstat === 1 && command_exist('vnstat')) { - exec("tmux new-window -t $tmux_session -n vnstat 'printf \"\033]2;vnstat\033\" && watch -n10 \"vnstat ${vnstat_args}\"'"); - } + if ((int) $vnstat === 1 && command_exist('vnstat')) { + exec("tmux new-window -t $tmux_session -n vnstat 'printf \"\033]2;vnstat\033\" && watch -n10 \"vnstat ${vnstat_args}\"'"); + } - if ((int)$tcptrack === 1 && command_exist('tcptrack')) { - exec("tmux new-window -t $tmux_session -n tcptrack 'printf \"\033]2;tcptrack\033\" && tcptrack ${tcptrack_args}'"); - } + if ((int) $tcptrack === 1 && command_exist('tcptrack')) { + exec("tmux new-window -t $tmux_session -n tcptrack 'printf \"\033]2;tcptrack\033\" && tcptrack ${tcptrack_args}'"); + } - if ((int)$bwmng === 1 && command_exist('bwm-ng')) { - exec("tmux new-window -t $tmux_session -n bwm-ng 'printf \"\033]2;bwm-ng\033\" && bwm-ng'"); - } + if ((int) $bwmng === 1 && command_exist('bwm-ng')) { + exec("tmux new-window -t $tmux_session -n bwm-ng 'printf \"\033]2;bwm-ng\033\" && bwm-ng'"); + } - if ((int)$mytop === 1 && command_exist('mytop')) { - exec("tmux new-window -t $tmux_session -n mytop 'printf \"\033]2;mytop\033\" && mytop -u'"); - } + if ((int) $mytop === 1 && command_exist('mytop')) { + exec("tmux new-window -t $tmux_session -n mytop 'printf \"\033]2;mytop\033\" && mytop -u'"); + } - if ((int)$showprocesslist === 1) { - exec("tmux new-window -t $tmux_session -n showprocesslist 'printf \"\033]2;showprocesslist\033\" && watch -n .5 \"mysql -e \\\"SELECT time, state, info FROM information_schema.processlist WHERE command != \\\\\\\"Sleep\\\\\\\" AND time >= $processupdate ORDER BY time DESC \\\G\\\"\"'"); - } - //exec("tmux new-window -t $tmux_session -n showprocesslist 'printf \"\033]2;showprocesslist\033\" && watch -n .2 \"mysql -e \\\"SELECT time, state, rows_examined, info FROM information_schema.processlist WHERE command != \\\\\\\"Sleep\\\\\\\" AND time >= $processupdate ORDER BY time DESC \\\G\\\"\"'"); + if ((int) $showprocesslist === 1) { + exec("tmux new-window -t $tmux_session -n showprocesslist 'printf \"\033]2;showprocesslist\033\" && watch -n .5 \"mysql -e \\\"SELECT time, state, info FROM information_schema.processlist WHERE command != \\\\\\\"Sleep\\\\\\\" AND time >= $processupdate ORDER BY time DESC \\\G\\\"\"'"); + } + //exec("tmux new-window -t $tmux_session -n showprocesslist 'printf \"\033]2;showprocesslist\033\" && watch -n .2 \"mysql -e \\\"SELECT time, state, rows_examined, info FROM information_schema.processlist WHERE command != \\\\\\\"Sleep\\\\\\\" AND time >= $processupdate ORDER BY time DESC \\\G\\\"\"'"); - if ((int)$console_bash === 1) { - exec("tmux new-window -t $tmux_session -n bash 'printf \"\033]2;Bash\033\" && bash -i'"); - } + if ((int) $console_bash === 1) { + exec("tmux new-window -t $tmux_session -n bash 'printf \"\033]2;Bash\033\" && bash -i'"); + } } function window_utilities($tmux_session) { - exec("tmux new-window -t $tmux_session -n utils 'printf \"\033]2;fixReleaseNames\033\"'"); - exec("tmux splitw -t $tmux_session:1 -v -p 50 'printf \"\033]2;updateTVandTheaters\033\"'"); - exec("tmux selectp -t $tmux_session:1.0; tmux splitw -t $tmux_session:1 -h -p 50 'printf \"\033]2;removeCrapReleases\033\"'"); - exec("tmux selectp -t $tmux_session:1.2; tmux splitw -t $tmux_session:1 -h -p 50 'printf \"\033]2;decryptHashes\033\"'"); + exec("tmux new-window -t $tmux_session -n utils 'printf \"\033]2;fixReleaseNames\033\"'"); + exec("tmux splitw -t $tmux_session:1 -v -p 50 'printf \"\033]2;updateTVandTheaters\033\"'"); + exec("tmux selectp -t $tmux_session:1.0; tmux splitw -t $tmux_session:1 -h -p 50 'printf \"\033]2;removeCrapReleases\033\"'"); + exec("tmux selectp -t $tmux_session:1.2; tmux splitw -t $tmux_session:1 -h -p 50 'printf \"\033]2;decryptHashes\033\"'"); } function window_stripped_utilities($tmux_session) { - exec("tmux new-window -t $tmux_session -n utils 'printf \"\033]2;updateTVandTheaters\033\"'"); - exec("tmux selectp -t $tmux_session:1.0; tmux splitw -t $tmux_session:1 -h -p 50 'printf \"\033]2;postprocessing_amazon\033\"'"); + exec("tmux new-window -t $tmux_session -n utils 'printf \"\033]2;updateTVandTheaters\033\"'"); + exec("tmux selectp -t $tmux_session:1.0; tmux splitw -t $tmux_session:1 -h -p 50 'printf \"\033]2;postprocessing_amazon\033\"'"); } function window_ircscraper($tmux_session) { - exec("tmux new-window -t $tmux_session -n IRCScraper 'printf \"\033]2;scrapeIRC\033\"'"); + exec("tmux new-window -t $tmux_session -n IRCScraper 'printf \"\033]2;scrapeIRC\033\"'"); } function window_post($tmux_session) { - exec("tmux new-window -t $tmux_session -n post 'printf \"\033]2;postprocessing_additional\033\"'"); - exec("tmux splitw -t $tmux_session:2 -v -p 67 'printf \"\033]2;postprocessing_non_amazon\033\"'"); - exec("tmux splitw -t $tmux_session:2 -v -p 50 'printf \"\033]2;postprocessing_amazon\033\"'"); + exec("tmux new-window -t $tmux_session -n post 'printf \"\033]2;postprocessing_additional\033\"'"); + exec("tmux splitw -t $tmux_session:2 -v -p 67 'printf \"\033]2;postprocessing_non_amazon\033\"'"); + exec("tmux splitw -t $tmux_session:2 -v -p 50 'printf \"\033]2;postprocessing_amazon\033\"'"); } function window_optimize($tmux_session) { - exec("tmux new-window -t $tmux_session -n optimize 'printf \"\033]2;update_Tmux\033\"'"); - exec("tmux splitw -t $tmux_session:3 -v -p 50 'printf \"\033]2;optimize\033\"'"); + exec("tmux new-window -t $tmux_session -n optimize 'printf \"\033]2;update_Tmux\033\"'"); + exec("tmux splitw -t $tmux_session:3 -v -p 50 'printf \"\033]2;optimize\033\"'"); } function window_sharing($tmux_session) { - $pdo = new nntmux\db\Settings(); - $sharing = $pdo->queryOneRow('SELECT enabled, posting, fetching FROM sharing'); - $t = new Tmux(); - $tmux = $t->get(); - $tmux_share = $tmux->run_sharing ?? 0; + $pdo = new nntmux\db\Settings(); + $sharing = $pdo->queryOneRow('SELECT enabled, posting, fetching FROM sharing'); + $t = new Tmux(); + $tmux = $t->get(); + $tmux_share = $tmux->run_sharing ?? 0; - if ($tmux_share && (int)$sharing['enabled'] === 1 && ((int)$sharing['posting'] === 1 || (int)$sharing['fetching'] === 1)) { - exec("tmux new-window -t $tmux_session -n Sharing 'printf \"\033]2;comment_sharing\033\"'"); - } + if ($tmux_share && (int) $sharing['enabled'] === 1 && ((int) $sharing['posting'] === 1 || (int) $sharing['fetching'] === 1)) { + exec("tmux new-window -t $tmux_session -n Sharing 'printf \"\033]2;comment_sharing\033\"'"); + } } function attach($DIR, $tmux_session) { - $PHP = 'php'; + $PHP = 'php'; - //get list of panes by name - $panes_win_1 = exec("echo `tmux list-panes -t $tmux_session:0 -F '#{pane_title}'`"); - $panes0 = str_replace("\n", '', explode(' ', $panes_win_1)); - $log = writelog($panes0[0]); - exec("tmux respawnp -t $tmux_session:0.0 '$PHP " . $DIR . "monitor.php $log'"); - exec("tmux select-window -t $tmux_session:0; tmux attach-session -d -t $tmux_session"); + //get list of panes by name + $panes_win_1 = exec("echo `tmux list-panes -t $tmux_session:0 -F '#{pane_title}'`"); + $panes0 = str_replace("\n", '', explode(' ', $panes_win_1)); + $log = writelog($panes0[0]); + exec("tmux respawnp -t $tmux_session:0.0 '$PHP ".$DIR."monitor.php $log'"); + exec("tmux select-window -t $tmux_session:0; tmux attach-session -d -t $tmux_session"); } //create tmux session -if ((int)$powerline === 1) { - $tmuxconfig = $DIR . 'powerline/tmux.conf'; +if ((int) $powerline === 1) { + $tmuxconfig = $DIR.'powerline/tmux.conf'; } else { - $tmuxconfig = $DIR . 'tmux.conf'; + $tmuxconfig = $DIR.'tmux.conf'; } -if ((int)$seq === 1) { - exec("cd ${DIR}; tmux -f $tmuxconfig new-session -d -s $tmux_session -n Monitor 'printf \"\033]2;\"Monitor\"\033\"'"); - exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -h -p 67 'printf \"\033]2;update_releases\033\"'"); - exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -v -p 25 'printf \"\033]2;nzb-import\033\"'"); +if ((int) $seq === 1) { + exec("cd ${DIR}; tmux -f $tmuxconfig new-session -d -s $tmux_session -n Monitor 'printf \"\033]2;\"Monitor\"\033\"'"); + exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -h -p 67 'printf \"\033]2;update_releases\033\"'"); + exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -v -p 25 'printf \"\033]2;nzb-import\033\"'"); - window_utilities($tmux_session); - window_post($tmux_session); - window_ircscraper($tmux_session); - window_sharing($tmux_session); - start_apps($tmux_session); - attach($DIR, $tmux_session); -} else if ((int)$seq === 2) { - exec("cd ${DIR}; tmux -f $tmuxconfig new-session -d -s $tmux_session -n Monitor 'printf \"\033]2;\"Monitor\"\033\"'"); - exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -h -p 67 'printf \"\033]2;sequential\033\"'"); - exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -v -p 25 'printf \"\033]2;nzb-import\033\"'"); + window_utilities($tmux_session); + window_post($tmux_session); + window_ircscraper($tmux_session); + window_sharing($tmux_session); + start_apps($tmux_session); + attach($DIR, $tmux_session); +} elseif ((int) $seq === 2) { + exec("cd ${DIR}; tmux -f $tmuxconfig new-session -d -s $tmux_session -n Monitor 'printf \"\033]2;\"Monitor\"\033\"'"); + exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -h -p 67 'printf \"\033]2;sequential\033\"'"); + exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -v -p 25 'printf \"\033]2;nzb-import\033\"'"); - window_stripped_utilities($tmux_session); - window_ircscraper($tmux_session); - window_sharing($tmux_session); - start_apps($tmux_session); - attach($DIR, $tmux_session); + window_stripped_utilities($tmux_session); + window_ircscraper($tmux_session); + window_sharing($tmux_session); + start_apps($tmux_session); + attach($DIR, $tmux_session); } else { - exec("cd ${DIR}; tmux -f $tmuxconfig new-session -d -s $tmux_session -n Monitor 'printf \"\033]2;Monitor\033\"'"); - exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -h -p 67 'printf \"\033]2;update_binaries\033\"'"); - exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -v -p 25 'printf \"\033]2;nzb-import\033\"'"); - exec("tmux selectp -t $tmux_session:0.2; tmux splitw -t $tmux_session:0 -v -p 67 'printf \"\033]2;backfill\033\"'"); - exec("tmux splitw -t $tmux_session -v -p 50 'printf \"\033]2;update_releases\033\"'"); + exec("cd ${DIR}; tmux -f $tmuxconfig new-session -d -s $tmux_session -n Monitor 'printf \"\033]2;Monitor\033\"'"); + exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -h -p 67 'printf \"\033]2;update_binaries\033\"'"); + exec("tmux selectp -t $tmux_session:0.0; tmux splitw -t $tmux_session:0 -v -p 25 'printf \"\033]2;nzb-import\033\"'"); + exec("tmux selectp -t $tmux_session:0.2; tmux splitw -t $tmux_session:0 -v -p 67 'printf \"\033]2;backfill\033\"'"); + exec("tmux splitw -t $tmux_session -v -p 50 'printf \"\033]2;update_releases\033\"'"); - window_utilities($tmux_session); - window_post($tmux_session); - window_ircscraper($tmux_session); - window_sharing($tmux_session); - start_apps($tmux_session); - attach($DIR, $tmux_session); + window_utilities($tmux_session); + window_post($tmux_session); + window_ircscraper($tmux_session); + window_sharing($tmux_session); + start_apps($tmux_session); + attach($DIR, $tmux_session); } diff --git a/misc/update/nix/tmux/start.php b/misc/update/nix/tmux/start.php index d6a1d06a9..89ba0a7a8 100644 --- a/misc/update/nix/tmux/start.php +++ b/misc/update/nix/tmux/start.php @@ -6,19 +6,19 @@ * * It will start the tmux server and monitoring scripts if needed. */ -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\Tmux; use nntmux\ColorCLI; // Ensure compatible tmux version is installed $tmux_version == "tmux 2.1\n" || $tmux_version == "tmux 2.2\n" if (`which tmux`) { - $tmux_version = trim(str_replace('tmux ', '', shell_exec('tmux -V'))); - if (version_compare($tmux_version, '2.0', '>') && version_compare($tmux_version, '2.4', '<')) { - exit(ColorCLI::error('tmux versions above 2.0 are not compatible with NNTmux. Aborting' . PHP_EOL)); - } + $tmux_version = trim(str_replace('tmux ', '', shell_exec('tmux -V'))); + if (version_compare($tmux_version, '2.0', '>') && version_compare($tmux_version, '2.4', '<')) { + exit(ColorCLI::error('tmux versions above 2.0 are not compatible with NNTmux. Aborting'.PHP_EOL)); + } } else { - exit(ColorCLI::error('tmux binary not found. Aborting' . PHP_EOL)); + exit(ColorCLI::error('tmux binary not found. Aborting'.PHP_EOL)); } $tmux = new Tmux(); @@ -37,6 +37,6 @@ $session = shell_exec("tmux list-session | grep $tmux_session"); // Kill the placeholder exec('tmux kill-session -t placeholder'); if (count($session) === 0) { - echo ColorCLI::info("Starting the tmux server and monitor script.\n"); - passthru("php $path/run.php"); + echo ColorCLI::info("Starting the tmux server and monitor script.\n"); + passthru("php $path/run.php"); } diff --git a/misc/update/nix/tmux/stop.php b/misc/update/nix/tmux/stop.php index 7015b3793..102d595a4 100644 --- a/misc/update/nix/tmux/stop.php +++ b/misc/update/nix/tmux/stop.php @@ -1,5 +1,6 @@ <?php -require_once dirname(__DIR__, 4) . DIRECTORY_SEPARATOR . 'bootstrap.php'; + +require_once dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\Tmux; diff --git a/misc/update/postprocess.php b/misc/update/postprocess.php index f9d0f31f3..380c1be60 100644 --- a/misc/update/postprocess.php +++ b/misc/update/postprocess.php @@ -1,17 +1,17 @@ <?php -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; -use App\Models\Settings; -use nntmux\db\DB; -use nntmux\processing\PostProcess; +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; + use nntmux\NNTP; +use nntmux\db\DB; +use App\Models\Settings; +use nntmux\processing\PostProcess; $pdo = new DB(); /** -Array with possible arguments for run and -whether or not those methods of operation require NNTP + * Array with possible arguments for run and + * whether or not those methods of operation require NNTP. **/ - $args = [ 'additional' => true, 'all' => true, @@ -32,47 +32,47 @@ $args = [ 'xxx' => false, ]; -$bool = array( +$bool = [ 'true', - 'false' -); + 'false', +]; -if (!isset($argv[1]) || !in_array($argv[1], $args, false) || !isset($argv[2]) || !in_array($argv[2], $bool, false)) { - exit( +if (! isset($argv[1]) || ! in_array($argv[1], $args, false) || ! isset($argv[2]) || ! in_array($argv[2], $bool, false)) { + exit( \nntmux\ColorCLI::error( "\nIncorrect arguments.\n" - . "The second argument (true/false) determines wether to echo or not.\n\n" - . "php postprocess.php all true ...: Does all the types of post processing.\n" - . "php postprocess.php pre true ...: Processes all Predb sites.\n" - . "php postprocess.php nfo true ...: Processes NFO files.\n" - . "php postprocess.php movies true ...: Processes movies.\n" - . "php postprocess.php music true ...: Processes music.\n" - . "php postprocess.php console true ...: Processes console games.\n" - . "php postprocess.php games true ...: Processes games.\n" - . "php postprocess.php book true ...: Processes books.\n" - . "php postprocess.php anime true ...: Processes anime.\n" - . "php postprocess.php tv true ...: Processes tv.\n" - . "php postprocess.php xxx true ...: Processes xxx.\n" - . "php postprocess.php additional true ...: Processes previews/mediainfo/etc...\n" - . "php postprocess.php sharing true ...: Processes uploading/downloading comments.\n" - . "php postprocess.php spotnab true ...: Processes uploading/downloading comments from spotnab.\n" - . "php postprocess.php allinf true ...: Does all the types of post processing on a loop, sleeping 15 seconds between.\n" - . "php postprocess.php amazon true ...: Does all the amazon (books/console/games/music/xxx).\n" + ."The second argument (true/false) determines wether to echo or not.\n\n" + ."php postprocess.php all true ...: Does all the types of post processing.\n" + ."php postprocess.php pre true ...: Processes all Predb sites.\n" + ."php postprocess.php nfo true ...: Processes NFO files.\n" + ."php postprocess.php movies true ...: Processes movies.\n" + ."php postprocess.php music true ...: Processes music.\n" + ."php postprocess.php console true ...: Processes console games.\n" + ."php postprocess.php games true ...: Processes games.\n" + ."php postprocess.php book true ...: Processes books.\n" + ."php postprocess.php anime true ...: Processes anime.\n" + ."php postprocess.php tv true ...: Processes tv.\n" + ."php postprocess.php xxx true ...: Processes xxx.\n" + ."php postprocess.php additional true ...: Processes previews/mediainfo/etc...\n" + ."php postprocess.php sharing true ...: Processes uploading/downloading comments.\n" + ."php postprocess.php spotnab true ...: Processes uploading/downloading comments from spotnab.\n" + ."php postprocess.php allinf true ...: Does all the types of post processing on a loop, sleeping 15 seconds between.\n" + ."php postprocess.php amazon true ...: Does all the amazon (books/console/games/music/xxx).\n" ) ); } $nntp = null; if ($args[$argv[1]] === true) { - $nntp = new NNTP(['Settings' => $pdo]); - if ((Settings::value('..alternate_nntp') === 1 ? $nntp->doConnect(true, true) : $nntp->doConnect()) !== true) { - exit($pdo->log->error('Unable to connect to usenet.' . PHP_EOL)); - } + $nntp = new NNTP(['Settings' => $pdo]); + if ((Settings::value('..alternate_nntp') === 1 ? $nntp->doConnect(true, true) : $nntp->doConnect()) !== true) { + exit($pdo->log->error('Unable to connect to usenet.'.PHP_EOL)); + } } $postProcess = new PostProcess(['Settings' => $pdo, 'Echo' => $argv[2] === 'true' ? true : false]); -$charArray = ['a','b','c','d','e','f','0','1','2','3','4','5','6','7','8','9']; +$charArray = ['a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; switch ($argv[1]) { @@ -82,8 +82,8 @@ switch ($argv[1]) { case 'allinf': $i = 1; while ($i = 1) { - $postProcess->processAll($nntp); - sleep(15); + $postProcess->processAll($nntp); + sleep(15); } break; case 'additional': diff --git a/misc/update/requestid.php b/misc/update/requestid.php index 6d365e818..8ed0c40e3 100755 --- a/misc/update/requestid.php +++ b/misc/update/requestid.php @@ -1,34 +1,35 @@ <?php -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; + +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; use nntmux\ColorCLI; -use nntmux\RequestIDLocal; use nntmux\RequestIDWeb; +use nntmux\RequestIDLocal; $cli = new ColorCLI(); -if (!isset($argv[1]) || ($argv[1] != "all" && $argv[1] != "full" && $argv[1] != "web" && !is_numeric($argv[1])) || !isset($argv[2]) || !in_array($argv[2], ['true', 'false'])) { - exit ($cli->error( +if (! isset($argv[1]) || ($argv[1] != 'all' && $argv[1] != 'full' && $argv[1] != 'web' && ! is_numeric($argv[1])) || ! isset($argv[2]) || ! in_array($argv[2], ['true', 'false'])) { + exit($cli->error( PHP_EOL - . "This script tries to match a release request ID by group to a PreDB request ID by group doing local lookup only." . PHP_EOL - . "In addition an optional final argument is time, in minutes, to check releases that have previously been checked." . PHP_EOL . PHP_EOL - . "Argument 1: full|all|number|web => (mandatory)" . PHP_EOL - . "all does only requestid releases, full does full database, number limits to x amount of releases, web does web requestID's" . PHP_EOL - . "Argument 2: true|false => (mandatory) Display full info on how the release was renamed or not." . PHP_EOL - . "Argument 3: number => (optional) This is to limit how old the releases to work on (in hours)." . PHP_EOL - . "php requestid.php 1000 true => to limit to 1000 sorted by newest postdate and show renaming." . PHP_EOL . PHP_EOL - . "php requestid.php full true => to run on full database and show renaming." . PHP_EOL - . "php requestid.php all true => to run on all requestid releases (including previously renamed) and show renaming." . PHP_EOL + .'This script tries to match a release request ID by group to a PreDB request ID by group doing local lookup only.'.PHP_EOL + .'In addition an optional final argument is time, in minutes, to check releases that have previously been checked.'.PHP_EOL.PHP_EOL + .'Argument 1: full|all|number|web => (mandatory)'.PHP_EOL + ."all does only requestid releases, full does full database, number limits to x amount of releases, web does web requestID's".PHP_EOL + .'Argument 2: true|false => (mandatory) Display full info on how the release was renamed or not.'.PHP_EOL + .'Argument 3: number => (optional) This is to limit how old the releases to work on (in hours).'.PHP_EOL + .'php requestid.php 1000 true => to limit to 1000 sorted by newest postdate and show renaming.'.PHP_EOL.PHP_EOL + .'php requestid.php full true => to run on full database and show renaming.'.PHP_EOL + .'php requestid.php all true => to run on all requestid releases (including previously renamed) and show renaming.'.PHP_EOL ) ); } if ($argv[1] === 'web') { - (new RequestIDWeb())->lookupRequestIDs( + (new RequestIDWeb())->lookupRequestIDs( ['limit' => 1000, 'show' => $argv[2], 'time' => (isset($argv[3]) && is_numeric($argv[3]) && $argv[3] > 0 ? $argv[3] : 0)] ); } else { - (new RequestIDLocal())->lookupRequestIDs( + (new RequestIDLocal())->lookupRequestIDs( ['limit' => $argv[1], 'show' => $argv[2], 'time' => (isset($argv[3]) && is_numeric($argv[3]) && $argv[3] > 0 ? $argv[3] : 0)] ); } diff --git a/misc/update/update_binaries.php b/misc/update/update_binaries.php index 00f81e92c..e414823e4 100644 --- a/misc/update/update_binaries.php +++ b/misc/update/update_binaries.php @@ -1,35 +1,36 @@ <?php -require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'bootstrap.php'; -use App\Models\Settings; -use nntmux\db\DB; -use nntmux\ColorCLI; +require_once dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'bootstrap.php'; + use nntmux\NNTP; -use nntmux\Binaries; +use nntmux\db\DB; use nntmux\Groups; +use nntmux\Binaries; +use nntmux\ColorCLI; +use App\Models\Settings; $pdo = new DB(); -$maxHeaders = (int)Settings::value('max.headers.iteration') ?: 1000000; +$maxHeaders = (int) Settings::value('max.headers.iteration') ?: 1000000; // Create the connection here and pass $nntp = new NNTP(['Settings' => $pdo]); if ($nntp->doConnect() !== true) { - exit(ColorCLI::error('Unable to connect to usenet.')); + exit(ColorCLI::error('Unable to connect to usenet.')); } $binaries = new Binaries(['NNTP' => $nntp, 'Settings' => $pdo]); -if (isset($argv[1]) && !is_numeric($argv[1])) { - $groupName = $argv[1]; - echo ColorCLI::header("Updating group: $groupName"); +if (isset($argv[1]) && ! is_numeric($argv[1])) { + $groupName = $argv[1]; + echo ColorCLI::header("Updating group: $groupName"); - $grp = new Groups(['Settings' => $pdo]); - $group = $grp->getByName($groupName); - if (is_array($group)) { - $binaries->updateGroup($group, + $grp = new Groups(['Settings' => $pdo]); + $group = $grp->getByName($groupName); + if (is_array($group)) { + $binaries->updateGroup($group, (isset($argv[2]) && is_numeric($argv[2]) && $argv[2] > 0 ? $argv[2] : $maxHeaders)); - } + } } else { - $binaries->updateAllGroups((isset($argv[1]) && is_numeric($argv[1]) && $argv[1] > 0 ? $argv[1] : + $binaries->updateAllGroups((isset($argv[1]) && is_numeric($argv[1]) && $argv[1] > 0 ? $argv[1] : $maxHeaders)); } diff --git a/nntmux/AniDB.php b/nntmux/AniDB.php index f661caed0..a8d3657c8 100755 --- a/nntmux/AniDB.php +++ b/nntmux/AniDB.php @@ -1,51 +1,52 @@ <?php + namespace nntmux; use nntmux\db\DB; class AniDB { - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @param array $options Class instances / Echo to cli. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances / Echo to cli. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + } - /** - * Updates stored AniDB entries in the database - * - * @param int $anidbID - * @param string $title - * @param string $type - * @param string $startdate - * @param string $enddate - * @param string $related - * @param string $similar - * @param string $creators - * @param string $description - * @param string $rating - * @param string $categories - * @param string $characters - * @param $epnos - * @param $airdates - * @param $episodetitles - */ - public function updateTitle($anidbID, $title, $type, $startdate, $enddate, $related, $similar, $creators, $description, $rating, $categories, $characters, $epnos, $airdates, $episodetitles): void - { - $this->pdo->queryExec( + /** + * Updates stored AniDB entries in the database. + * + * @param int $anidbID + * @param string $title + * @param string $type + * @param string $startdate + * @param string $enddate + * @param string $related + * @param string $similar + * @param string $creators + * @param string $description + * @param string $rating + * @param string $categories + * @param string $characters + * @param $epnos + * @param $airdates + * @param $episodetitles + */ + public function updateTitle($anidbID, $title, $type, $startdate, $enddate, $related, $similar, $creators, $description, $rating, $categories, $characters, $epnos, $airdates, $episodetitles): void + { + $this->pdo->queryExec( sprintf(' UPDATE anidb_titles at INNER JOIN anidb_info ai ON ai.anidbid = at.anidbid @@ -72,16 +73,16 @@ class AniDB $anidbID ) ); - } + } - /** - * Deletes stored AniDB entries in the database - * - * @param int $anidbID - */ - public function deleteTitle($anidbID): void - { - $this->pdo->queryExec( + /** + * Deletes stored AniDB entries in the database. + * + * @param int $anidbID + */ + public function deleteTitle($anidbID): void + { + $this->pdo->queryExec( sprintf(' DELETE at, ai, ae FROM anidb_titles AS at @@ -91,31 +92,31 @@ class AniDB $anidbID ) ); - } + } - /** - * Retrieves a list of Anime titles, optionally filtered by starting character and title - * - * @param string $letter - * @param string $animetitle - * @return array|bool - */ - public function getAnimeList($letter = '', $animetitle = '') - { - $rsql = $tsql = ''; + /** + * Retrieves a list of Anime titles, optionally filtered by starting character and title. + * + * @param string $letter + * @param string $animetitle + * @return array|bool + */ + public function getAnimeList($letter = '', $animetitle = '') + { + $rsql = $tsql = ''; - if ($letter !== '') { - if ($letter === '0-9') { - $letter = '[0-9]'; - } - $rsql .= sprintf('AND at.title REGEXP %s', $this->pdo->escapeString('^' . $letter)); - } + if ($letter !== '') { + if ($letter === '0-9') { + $letter = '[0-9]'; + } + $rsql .= sprintf('AND at.title REGEXP %s', $this->pdo->escapeString('^'.$letter)); + } - if ($animetitle !== '') { - $tsql .= sprintf('AND at.title %s', $this->pdo->likeString($animetitle, true, true)); - } + if ($animetitle !== '') { + $tsql .= sprintf('AND at.title %s', $this->pdo->likeString($animetitle, true, true)); + } - return $this->pdo->queryDirect( + return $this->pdo->queryDirect( sprintf(' SELECT at.anidbid, at.title, ai.type, ai.categories, ai.rating, ai.startdate, ai.enddate @@ -131,30 +132,30 @@ class AniDB Category::TV_ANIME ) ); - } + } - /** - * Retrieves a range of Anime titles for site display - * - * @param int $start - * @param int $num - * @param string $animetitle - * @return array|bool - */ - public function getAnimeRange($start, $num, $animetitle = '') - { - if ($start === false) { - $limit = ''; - } else { - $limit = ' LIMIT ' . $num . ' OFFSET ' . $start; - } + /** + * Retrieves a range of Anime titles for site display. + * + * @param int $start + * @param int $num + * @param string $animetitle + * @return array|bool + */ + public function getAnimeRange($start, $num, $animetitle = '') + { + if ($start === false) { + $limit = ''; + } else { + $limit = ' LIMIT '.$num.' OFFSET '.$start; + } - $rsql = ''; - if ($animetitle !== '') { - $rsql = sprintf('AND at.title %s', $this->pdo->likeString($animetitle, true, true)); - } + $rsql = ''; + if ($animetitle !== '') { + $rsql = sprintf('AND at.title %s', $this->pdo->likeString($animetitle, true, true)); + } - return $this->pdo->query( + return $this->pdo->query( sprintf(" SELECT at.anidbid, GROUP_CONCAT(at.title SEPARATOR ', ') AS title, ai.description @@ -168,22 +169,22 @@ class AniDB $limit ) ); - } + } - /** - * Retrives the count of Anime titles for pager functions optionally filtered by title - * - * @param string $animetitle - * @return int - */ - public function getAnimeCount($animetitle = ''): int - { - $rsql = ''; - if ($animetitle !== '') { - $rsql .= sprintf('AND at.title %s', $this->pdo->likeString($animetitle, true, true)); - } + /** + * Retrives the count of Anime titles for pager functions optionally filtered by title. + * + * @param string $animetitle + * @return int + */ + public function getAnimeCount($animetitle = ''): int + { + $rsql = ''; + if ($animetitle !== '') { + $rsql .= sprintf('AND at.title %s', $this->pdo->likeString($animetitle, true, true)); + } - $res = $this->pdo->queryOneRow( + $res = $this->pdo->queryOneRow( sprintf(' SELECT COUNT(DISTINCT at.anidbid) AS num FROM anidb_titles AS at @@ -194,18 +195,18 @@ class AniDB ) ); - return $res['num']; - } + return $res['num']; + } - /** - * Retrieves all info for a specific AniDB ID - * - * @param int $anidbID - * @return array|boolean - */ - public function getAnimeInfo($anidbID) - { - $animeInfo = $this->pdo->query( + /** + * Retrieves all info for a specific AniDB ID. + * + * @param int $anidbID + * @return array|bool + */ + public function getAnimeInfo($anidbID) + { + $animeInfo = $this->pdo->query( sprintf(' SELECT at.anidbid, at.lang, at.title, ai.startdate, ai.enddate, ai.updated, ai.related, ai.creators, ai.description, @@ -219,6 +220,6 @@ class AniDB ) ); - return $animeInfo[0] ?? false; - } + return $animeInfo[0] ?? false; + } } diff --git a/nntmux/Backfill.php b/nntmux/Backfill.php index 6d392a8e1..2dfc4f018 100755 --- a/nntmux/Backfill.php +++ b/nntmux/Backfill.php @@ -1,353 +1,355 @@ <?php + namespace nntmux; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; class Backfill { - /** - * Instance of class Settings - * - * @var DB - */ - public $pdo; + /** + * Instance of class Settings. + * + * @var DB + */ + public $pdo; - /** - * @var Binaries - */ - protected $_binaries; + /** + * @var Binaries + */ + protected $_binaries; - /** - * Instance of class ColorCLI. - * - * @var ColorCLI - */ - protected $_colorCLI; + /** + * Instance of class ColorCLI. + * + * @var ColorCLI + */ + protected $_colorCLI; - /** - * Instance of class debugging. - * - * @var Logger - */ - protected $_debugging; + /** + * Instance of class debugging. + * + * @var Logger + */ + protected $_debugging; - /** - * @var Groups - */ - protected $_groups; + /** + * @var Groups + */ + protected $_groups; - /** - * @var NNTP - */ - protected $_nntp; - /** - * Should we use compression for headers? - * - * @var bool - */ - protected $_compressedHeaders; + /** + * @var NNTP + */ + protected $_nntp; + /** + * Should we use compression for headers? + * + * @var bool + */ + protected $_compressedHeaders; - /** - * Log and or echo debug. - * @var bool - */ - protected $_debug = false; + /** + * Log and or echo debug. + * @var bool + */ + protected $_debug = false; - /** - * Echo to cli? - * @var bool - */ - protected $_echoCLI; + /** + * Echo to cli? + * @var bool + */ + protected $_echoCLI; - /** - * How far back should we go on safe back fill? - * - * @var string - */ - protected $_safeBackFillDate; + /** + * How far back should we go on safe back fill? + * + * @var string + */ + protected $_safeBackFillDate; - /** - * @var string - */ - protected $_safePartRepair; + /** + * @var string + */ + protected $_safePartRepair; - /** - * Should we disable the group if we have backfilled far enough? - * @var bool - */ - protected $_disableBackfillGroup; + /** + * Should we disable the group if we have backfilled far enough? + * @var bool + */ + protected $_disableBackfillGroup; - /** - * Constructor. - * - * @param array $options Class instances / Echo to cli? - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Constructor. + * + * @param array $options Class instances / Echo to cli? + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => true, 'Logger' => null, 'Groups' => null, 'NNTP' => null, - 'Settings' => null + 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->_echoCLI = ($options['Echo'] && NN_ECHOCLI); + $this->_echoCLI = ($options['Echo'] && NN_ECHOCLI); - $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 + $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]) ); - $this->_debug = (NN_LOGGING || NN_DEBUG); - if ($this->_debug) { - try { - $this->_debugging = ($options['Logger'] instanceof Logger ? $options['Logger'] : new Logger(['ColorCLI' => $this->pdo->log])); - } catch (LoggerException $error) { - $this->_debug = false; - } - } + $this->_debug = (NN_LOGGING || NN_DEBUG); + if ($this->_debug) { + try { + $this->_debugging = ($options['Logger'] instanceof Logger ? $options['Logger'] : new Logger(['ColorCLI' => $this->pdo->log])); + } catch (LoggerException $error) { + $this->_debug = false; + } + } - $this->_compressedHeaders = (int)Settings::value('..compressedheaders') === 1; - $this->_safeBackFillDate = Settings::value('..safebackfilldate') !== '' ? (string)Settings::value('safebackfilldate') : '2008-08-14'; - $this->_safePartRepair = (int)Settings::value('..safepartrepair') === 1 ? 'update' : 'backfill'; - $this->_disableBackfillGroup = (int)Settings::value('..disablebackfillgroup') === 1; - } + $this->_compressedHeaders = (int) Settings::value('..compressedheaders') === 1; + $this->_safeBackFillDate = Settings::value('..safebackfilldate') !== '' ? (string) Settings::value('safebackfilldate') : '2008-08-14'; + $this->_safePartRepair = (int) Settings::value('..safepartrepair') === 1 ? 'update' : 'backfill'; + $this->_disableBackfillGroup = (int) Settings::value('..disablebackfillgroup') === 1; + } - /** - * Backfill all the groups up to user specified time/date. - * - * @param string $groupName - * @param string|int $articles - * @param string $type - * - * @return void - * @throws \Exception - */ - public function backfillAllGroups($groupName = '', $articles ='', $type = ''): void - { - $res = []; - if ($groupName !== '') { - $grp = $this->_groups->getByName($groupName); - if ($grp) { - $res = [$grp]; - } - } else { - $res = $this->_groups->getActiveBackfill($type); - } + /** + * Backfill all the groups up to user specified time/date. + * + * @param string $groupName + * @param string|int $articles + * @param string $type + * + * @return void + * @throws \Exception + */ + public function backfillAllGroups($groupName = '', $articles = '', $type = ''): void + { + $res = []; + if ($groupName !== '') { + $grp = $this->_groups->getByName($groupName); + if ($grp) { + $res = [$grp]; + } + } else { + $res = $this->_groups->getActiveBackfill($type); + } - $groupCount = count($res); - if ($groupCount > 0) { - $counter = 1; - $allTime = microtime(true); - $dMessage = ( - 'Backfilling: ' . - $groupCount . - ' group(s) - Using compression? ' . + $groupCount = count($res); + if ($groupCount > 0) { + $counter = 1; + $allTime = microtime(true); + $dMessage = ( + 'Backfilling: '. + $groupCount. + ' group(s) - Using compression? '. ($this->_compressedHeaders ? 'Yes' : 'No') ); - if ($this->_debug) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_INFO); - } + if ($this->_debug) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_INFO); + } - if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::header($dMessage), true); - } + if ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::header($dMessage), true); + } - $this->_binaries = new Binaries( + $this->_binaries = new Binaries( ['NNTP' => $this->_nntp, 'Echo' => $this->_echoCLI, 'Settings' => $this->pdo, 'Groups' => $this->_groups] ); - if ($articles !== '' && !is_numeric($articles)) { - $articles = 20000; - } + if ($articles !== '' && ! is_numeric($articles)) { + $articles = 20000; + } - // Loop through groups. - foreach ($res as $groupArr) { - if ($groupName === '') { - $dMessage = 'Starting group ' . $counter . ' of ' . $groupCount; - if ($this->_debug) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_INFO); - } + // Loop through groups. + foreach ($res as $groupArr) { + if ($groupName === '') { + $dMessage = 'Starting group '.$counter.' of '.$groupCount; + if ($this->_debug) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_INFO); + } - if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::header($dMessage), true); - } - } - $this->backfillGroup($groupArr, $groupCount - $counter, $articles); - $counter++; - } + if ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::header($dMessage), true); + } + } + $this->backfillGroup($groupArr, $groupCount - $counter, $articles); + $counter++; + } - $dMessage = 'Backfilling completed in ' . number_format(microtime(true) - $allTime, 2) . ' seconds.'; - if ($this->_debug) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_INFO); - } + $dMessage = 'Backfilling completed in '.number_format(microtime(true) - $allTime, 2).' seconds.'; + if ($this->_debug) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_INFO); + } - if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::primary($dMessage)); - } - } else { - $dMessage = 'No groups specified. Ensure groups are added to database for updating.'; - if ($this->_debug) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_FATAL); - } + if ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::primary($dMessage)); + } + } else { + $dMessage = 'No groups specified. Ensure groups are added to database for updating.'; + if ($this->_debug) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_FATAL); + } - if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::warning($dMessage), true); - } - } - } + if ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::warning($dMessage), true); + } + } + } - /** - * Backfill single group. - * - * @param array $groupArr - * @param int $left - * @param int|string $articles - * - * @return void - * @throws \Exception - */ - public function backfillGroup($groupArr, $left, $articles = ''): void - { - // Start time for this group. - $startGroup = microtime(true); + /** + * Backfill single group. + * + * @param array $groupArr + * @param int $left + * @param int|string $articles + * + * @return void + * @throws \Exception + */ + public function backfillGroup($groupArr, $left, $articles = ''): void + { + // Start time for this group. + $startGroup = microtime(true); - $this->_binaries->logIndexerStart(); + $this->_binaries->logIndexerStart(); - $groupName = str_replace('alt.binaries', 'a.b', $groupArr['name']); + $groupName = str_replace('alt.binaries', 'a.b', $groupArr['name']); - // If our local oldest article 0, it means we never ran update_binaries on the group. - if ($groupArr['first_record'] <= 0) { - $dMessage = - 'You need to run update_binaries on ' . - $groupName . + // If our local oldest article 0, it means we never ran update_binaries on the group. + if ($groupArr['first_record'] <= 0) { + $dMessage = + 'You need to run update_binaries on '. + $groupName. '. Otherwise the group is dead, you must disable it.'; - if ($this->_debug) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_ERROR); - } + if ($this->_debug) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_ERROR); + } - if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::error($dMessage)); - } - return; - } + if ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::error($dMessage)); + } - // Select group, here, only once - $data = $this->_nntp->selectGroup($groupArr['name']); - if ($this->_nntp->isError($data)) { - $data = $this->_nntp->dataError($this->_nntp, $groupArr['name']); - if ($this->_nntp->isError($data)) { - return; - } - } + return; + } - if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::primary('Processing ' . $groupName), true); - } + // Select group, here, only once + $data = $this->_nntp->selectGroup($groupArr['name']); + if ($this->_nntp->isError($data)) { + $data = $this->_nntp->dataError($this->_nntp, $groupArr['name']); + if ($this->_nntp->isError($data)) { + return; + } + } - // Check if this is days or post backfill. - $postCheck = $articles !== ''; + if ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::primary('Processing '.$groupName), true); + } - // Get target post based on date or user specified number. - $targetpost = (string)($postCheck + // Check if this is days or post backfill. + $postCheck = $articles !== ''; + + // Get target post based on date or user specified number. + $targetpost = (string) ($postCheck ? round($groupArr['first_record'] - $articles) : $this->_binaries->daytopost($groupArr['backfill_target'], $data) ); - // Check if target post is smaller than server's oldest, set it to oldest if so. - if ($targetpost < $data['first']) { - $targetpost = $data['first']; - } + // Check if target post is smaller than server's oldest, set it to oldest if so. + if ($targetpost < $data['first']) { + $targetpost = $data['first']; + } - // Check if our target post is newer than our oldest post or if our local oldest article is older than the servers oldest. - if ($targetpost >= $groupArr['first_record'] || $groupArr['first_record'] <= $data['first']) { - $dMessage = - 'We have hit the maximum we can backfill for ' . - $groupName . + // Check if our target post is newer than our oldest post or if our local oldest article is older than the servers oldest. + if ($targetpost >= $groupArr['first_record'] || $groupArr['first_record'] <= $data['first']) { + $dMessage = + 'We have hit the maximum we can backfill for '. + $groupName. ($this->_disableBackfillGroup ? ', disabling backfill on it.' : ', skipping it, consider disabling backfill on it.'); - if ($this->_debug) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_NOTICE); - } + if ($this->_debug) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_NOTICE); + } - if ($this->_disableBackfillGroup) { - $this->_groups->updateGroupStatus($groupArr['id'], 'backfill', 0); - } + if ($this->_disableBackfillGroup) { + $this->_groups->updateGroupStatus($groupArr['id'], 'backfill', 0); + } - if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::notice($dMessage), true); - } - return; - } + if ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::notice($dMessage), true); + } - if ($this->_echoCLI) { - ColorCLI::doEcho( + return; + } + + if ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - 'Group ' . - $groupName . - "'s oldest article is " . - number_format($data['first']) . - ', newest is ' . - number_format($data['last']) . - ".\nOur target article is " . - number_format($targetpost) . - '. Our oldest article is article ' . - number_format($groupArr['first_record']) . + 'Group '. + $groupName. + "'s oldest article is ". + number_format($data['first']). + ', newest is '. + number_format($data['last']). + ".\nOur target article is ". + number_format($targetpost). + '. Our oldest article is article '. + number_format($groupArr['first_record']). '.' ) ); - } + } - // Set first and last, moving the window by max messages. - $last = ($groupArr['first_record'] - 1); - // Set the initial "chunk". - $first = ($last - $this->_binaries->messageBuffer + 1); + // Set first and last, moving the window by max messages. + $last = ($groupArr['first_record'] - 1); + // Set the initial "chunk". + $first = ($last - $this->_binaries->messageBuffer + 1); - // Just in case this is the last chunk we needed. - if ($targetpost > $first) { - $first = $targetpost; - } + // Just in case this is the last chunk we needed. + if ($targetpost > $first) { + $first = $targetpost; + } - $done = false; - while ($done === false) { - - if ($this->_echoCLI) { - ColorCLI::doEcho( - ColorCLI::set256('Yellow') . - PHP_EOL . 'Getting ' . - number_format($last - $first + 1) . - ' articles from ' . - $groupName . - ', ' . - $left . - ' group(s) left. (' . - number_format($first - $targetpost) . - ' articles in queue).' . + $done = false; + while ($done === false) { + if ($this->_echoCLI) { + ColorCLI::doEcho( + ColorCLI::set256('Yellow'). + PHP_EOL.'Getting '. + number_format($last - $first + 1). + ' articles from '. + $groupName. + ', '. + $left. + ' group(s) left. ('. + number_format($first - $targetpost). + ' articles in queue).'. ColorCLI::rsetColor(), true ); - } + } - flush(); - $lastMsg = $this->_binaries->scan($groupArr, $first, $last, $this->_safePartRepair); + flush(); + $lastMsg = $this->_binaries->scan($groupArr, $first, $last, $this->_safePartRepair); - // Get the oldest date. - if (isset($lastMsg['firstArticleDate'])) { - // Try to get it from the oldest pulled article. - $newdate = strtotime($lastMsg['firstArticleDate']); - } else { - // If above failed, try to get it with postdate method. - $newdate = $this->_binaries->postdate($first, $data); - } + // Get the oldest date. + if (isset($lastMsg['firstArticleDate'])) { + // Try to get it from the oldest pulled article. + $newdate = strtotime($lastMsg['firstArticleDate']); + } else { + // If above failed, try to get it with postdate method. + $newdate = $this->_binaries->postdate($first, $data); + } - $this->pdo->queryExec( + $this->pdo->queryExec( sprintf(' UPDATE groups SET first_record_postdate = %s, first_record = %s, last_updated = NOW() @@ -356,44 +358,44 @@ class Backfill $this->pdo->escapeString($first), $groupArr['id']) ); - if ($first === $targetpost) { - $done = true; - } else { - // Keep going: set new last, new first, check for last chunk. - $last = ($first - 1); - $first = ($last - $this->_binaries->messageBuffer + 1); - if ($targetpost > $first) { - $first = $targetpost; - } - } - } + if ($first === $targetpost) { + $done = true; + } else { + // Keep going: set new last, new first, check for last chunk. + $last = ($first - 1); + $first = ($last - $this->_binaries->messageBuffer + 1); + if ($targetpost > $first) { + $first = $targetpost; + } + } + } - if ($this->_echoCLI) { - ColorCLI::doEcho( + if ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - PHP_EOL . - 'Group ' . - $groupName . - ' processed in ' . - number_format(microtime(true) - $startGroup, 2) . + PHP_EOL. + 'Group '. + $groupName. + ' processed in '. + number_format(microtime(true) - $startGroup, 2). ' seconds.' ), true ); - } - } + } + } - /** - * Safe backfill using posts. Going back to a date specified by the user on the site settings. - * This does 1 group for x amount of parts until it reaches the date. - * - * @param string $articles - * - * @return void - * @throws \Exception - */ - public function safeBackfill($articles = ''): void - { - $groupname = $this->pdo->queryOneRow( + /** + * Safe backfill using posts. Going back to a date specified by the user on the site settings. + * This does 1 group for x amount of parts until it reaches the date. + * + * @param string $articles + * + * @return void + * @throws \Exception + */ + public function safeBackfill($articles = ''): void + { + $groupname = $this->pdo->queryOneRow( sprintf(' SELECT name FROM groups WHERE first_record_postdate BETWEEN %s AND NOW() @@ -403,17 +405,16 @@ class Backfill ) ); - if (!$groupname) { - $dMessage = - 'No groups to backfill, they are all at the target date ' . - $this->_safeBackFillDate . - ', or you have not enabled them to be backfilled in the groups page.' . PHP_EOL; - if ($this->_debug) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_FATAL); - } - exit($dMessage); - } - $this->backfillAllGroups($groupname['name'], $articles); - } - + if (! $groupname) { + $dMessage = + 'No groups to backfill, they are all at the target date '. + $this->_safeBackFillDate. + ', or you have not enabled them to be backfilled in the groups page.'.PHP_EOL; + if ($this->_debug) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $dMessage, Logger::LOG_FATAL); + } + exit($dMessage); + } + $this->backfillAllGroups($groupname['name'], $articles); + } } diff --git a/nntmux/Binaries.php b/nntmux/Binaries.php index 19bc649ab..2c263abae 100755 --- a/nntmux/Binaries.php +++ b/nntmux/Binaries.php @@ -1,249 +1,250 @@ <?php + namespace nntmux; -use App\Models\BinaryBlacklist; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; +use App\Models\BinaryBlacklist; use nntmux\processing\ProcessReleasesMultiGroup; /** - * Class Binaries + * Class Binaries. */ class Binaries { - const OPTYPE_BLACKLIST = 1; - const OPTYPE_WHITELIST = 2; + const OPTYPE_BLACKLIST = 1; + const OPTYPE_WHITELIST = 2; - const BLACKLIST_DISABLED = 0; - const BLACKLIST_ENABLED = 1; + const BLACKLIST_DISABLED = 0; + const BLACKLIST_ENABLED = 1; - const BLACKLIST_FIELD_SUBJECT = 1; - const BLACKLIST_FIELD_FROM = 2; - const BLACKLIST_FIELD_MESSAGEID = 3; + const BLACKLIST_FIELD_SUBJECT = 1; + const BLACKLIST_FIELD_FROM = 2; + const BLACKLIST_FIELD_MESSAGEID = 3; - /** - * Cache of black list regexes. - * - * @var array - */ - public $blackList = []; + /** + * Cache of black list regexes. + * + * @var array + */ + public $blackList = []; - /** - * Cache of white list regexes. - * @var array - */ - public $whiteList = []; + /** + * Cache of white list regexes. + * @var array + */ + public $whiteList = []; - /** - * How many headers do we download per loop? - * - * @var int - */ - public $messageBuffer; + /** + * How many headers do we download per loop? + * + * @var int + */ + public $messageBuffer; - /** - * @var ColorCLI - */ - protected $_colorCLI; + /** + * @var ColorCLI + */ + protected $_colorCLI; - /** - * @var CollectionsCleaning - */ - protected $_collectionsCleaning; + /** + * @var CollectionsCleaning + */ + protected $_collectionsCleaning; - /** - * @var Logger - */ - protected $_debugging; + /** + * @var Logger + */ + protected $_debugging; - /** - * @var Groups - */ - protected $_groups; + /** + * @var Groups + */ + protected $_groups; - /** - * @var NNTP - */ - protected $_nntp; + /** + * @var NNTP + */ + protected $_nntp; - /** - * Should we use header compression? - * - * @var bool - */ - protected $_compressedHeaders; + /** + * Should we use header compression? + * + * @var bool + */ + protected $_compressedHeaders; - /** - * Should we use part repair? - * - * @var bool - */ - protected $_partRepair; + /** + * Should we use part repair? + * + * @var bool + */ + protected $_partRepair; - /** - * @var DB - */ - protected $_pdo; + /** + * @var DB + */ + protected $_pdo; - /** - * How many days to go back on a new group? - * - * @var bool - */ - protected $_newGroupScanByDays; + /** + * How many days to go back on a new group? + * + * @var bool + */ + protected $_newGroupScanByDays; - /** - * How many headers to download on new groups? - * - * @var int - */ - protected $_newGroupMessagesToScan; + /** + * How many headers to download on new groups? + * + * @var int + */ + protected $_newGroupMessagesToScan; - /** - * How many days to go back on new groups? - * - * @var int - */ - protected $_newGroupDaysToScan; + /** + * How many days to go back on new groups? + * + * @var int + */ + protected $_newGroupDaysToScan; - /** - * How many headers to download per run of part repair? - * - * @var int - */ - protected $_partRepairLimit; + /** + * How many headers to download per run of part repair? + * + * @var int + */ + protected $_partRepairLimit; - /** - * Should we show dropped yEnc to CLI? - * - * @var bool - */ - protected $_showDroppedYEncParts; + /** + * Should we show dropped yEnc to CLI? + * + * @var bool + */ + protected $_showDroppedYEncParts; - /** - * Echo to cli? - * - * @var bool - */ - protected $_echoCLI; + /** + * Echo to cli? + * + * @var bool + */ + protected $_echoCLI; - /** - * @var bool - */ - protected $_debug = false; + /** + * @var bool + */ + protected $_debug = false; - /** - * Max tries to download headers. - * @var int - */ - protected $_partRepairMaxTries; + /** + * Max tries to download headers. + * @var int + */ + protected $_partRepairMaxTries; - /** - * An array of binaryblacklist IDs that should have their activity date updated - * @var array(int) - */ - protected $_binaryBlacklistIdsToUpdate = array(); + /** + * An array of binaryblacklist IDs that should have their activity date updated. + * @var array(int) + */ + protected $_binaryBlacklistIdsToUpdate = []; - /** - * @var float microseconds time of cleaning process start - */ - protected $startCleaning; + /** + * @var float microseconds time of cleaning process start + */ + protected $startCleaning; - /** - * @var float microseconds time of the start of the scan function - */ - protected $startLoop; + /** + * @var float microseconds time of the start of the scan function + */ + protected $startLoop; - /** - * @var bool Is this retrieved header a multigroup one? - */ - protected $multiGroup; + /** + * @var bool Is this retrieved header a multigroup one? + */ + protected $multiGroup; - /** - * @var string How long it took in seconds to download headers - */ - protected $timeHeaders; + /** + * @var string How long it took in seconds to download headers + */ + protected $timeHeaders; - /** - * @var string How long it took in seconds to clean/parse headers - */ - protected $timeCleaning; + /** + * @var string How long it took in seconds to clean/parse headers + */ + protected $timeCleaning; - /** - * @var float microseconds time part repair was started - */ - protected $startPR; + /** + * @var float microseconds time part repair was started + */ + protected $startPR; - /** - * @var array The CBP/MGR tables names - */ - protected $tableNames; + /** + * @var array The CBP/MGR tables names + */ + protected $tableNames; - /** - * @var float microseconds time header update was started - */ - protected $startUpdate; + /** + * @var float microseconds time header update was started + */ + protected $startUpdate; - /** - * @var string The time it took to insert the headers - */ - protected $timeInsert; + /** + * @var string The time it took to insert the headers + */ + protected $timeInsert; - /** - * @var array the header currently being scanned - */ - protected $header; + /** + * @var array the header currently being scanned + */ + protected $header; - /** - * @var bool Should we add parts to part repair queue? - */ - protected $addToPartRepair; + /** + * @var bool Should we add parts to part repair queue? + */ + protected $addToPartRepair; - /** - * @var array Numbers of Headers received from the USP - */ - protected $headersReceived; + /** + * @var array Numbers of Headers received from the USP + */ + protected $headersReceived; - /** - * @var array The current newsgroup information being updated - */ - protected $groupMySQL; + /** + * @var array The current newsgroup information being updated + */ + protected $groupMySQL; - /** - * @var int the last article number in the range - */ - protected $last; + /** + * @var int the last article number in the range + */ + protected $last; - /** - * @var int the first article number in the range - */ - protected $first; + /** + * @var int the first article number in the range + */ + protected $first; - /** - * @var int How many received headers were not yEnc encoded - */ - protected $notYEnc; + /** + * @var int How many received headers were not yEnc encoded + */ + protected $notYEnc; - /** - * @var int How many received headers were blacklist matched - */ - protected $headersBlackListed; + /** + * @var int How many received headers were blacklist matched + */ + protected $headersBlackListed; - /** - * @var array Header numbers that were not inserted - */ - protected $headersNotInserted; + /** + * @var array Header numbers that were not inserted + */ + protected $headersNotInserted; - /** - * Constructor. - * - * @param array $options Class instances / echo to CLI? - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Constructor. + * + * @param array $options Class instances / echo to CLI? + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => true, 'CollectionsCleaning' => null, 'ColorCLI' => null, @@ -252,156 +253,154 @@ class Binaries 'NNTP' => null, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->_echoCLI = ($options['Echo'] && NN_ECHOCLI); + $this->_echoCLI = ($options['Echo'] && NN_ECHOCLI); - $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])); - $this->_collectionsCleaning = ($options['CollectionsCleaning'] instanceof CollectionsCleaning ? $options['CollectionsCleaning'] : new CollectionsCleaning(['Settings' => $this->_pdo])); + $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])); + $this->_collectionsCleaning = ($options['CollectionsCleaning'] instanceof CollectionsCleaning ? $options['CollectionsCleaning'] : new CollectionsCleaning(['Settings' => $this->_pdo])); - $this->_debug = (NN_DEBUG || NN_LOGGING); + $this->_debug = (NN_DEBUG || NN_LOGGING); - if ($this->_debug) { - try { - $this->_debugging = ($options['Logger'] instanceof Logger ? $options['Logger'] : new Logger(['ColorCLI' => $this->_colorCLI])); - } catch (LoggerException $error) { - $this->_debug = false; - } - } + if ($this->_debug) { + try { + $this->_debugging = ($options['Logger'] instanceof Logger ? $options['Logger'] : new Logger(['ColorCLI' => $this->_colorCLI])); + } catch (LoggerException $error) { + $this->_debug = false; + } + } - $this->messageBuffer = Settings::value('..maxmssgs') !== '' ? - (int)Settings::value('..maxmssgs') : 20000; - $this->_compressedHeaders = Settings::value('..compressedheaders') === 1; - $this->_partRepair = Settings::value('..partrepair') === 1; - $this->_newGroupScanByDays = Settings::value('..newgroupscanmethod') === 1; - $this->_newGroupMessagesToScan = Settings::value('..newgroupmsgstoscan') !== '' ? (int)Settings::value('..newgroupmsgstoscan') : 50000; - $this->_newGroupDaysToScan = Settings::value('..newgroupdaystoscan') !== '' ? (int)Settings::value('..newgroupdaystoscan') : 3; - $this->_partRepairLimit = Settings::value('..maxpartrepair') !== '' ? (int)Settings::value('..maxpartrepair') : 15000; - $this->_partRepairMaxTries = (Settings::value('..partrepairmaxtries') !== '' ? (int)Settings::value('..partrepairmaxtries') : 3); - $this->_showDroppedYEncParts = Settings::value('..showdroppedyencparts') === 1; + $this->messageBuffer = Settings::value('..maxmssgs') !== '' ? + (int) Settings::value('..maxmssgs') : 20000; + $this->_compressedHeaders = Settings::value('..compressedheaders') === 1; + $this->_partRepair = Settings::value('..partrepair') === 1; + $this->_newGroupScanByDays = Settings::value('..newgroupscanmethod') === 1; + $this->_newGroupMessagesToScan = Settings::value('..newgroupmsgstoscan') !== '' ? (int) Settings::value('..newgroupmsgstoscan') : 50000; + $this->_newGroupDaysToScan = Settings::value('..newgroupdaystoscan') !== '' ? (int) Settings::value('..newgroupdaystoscan') : 3; + $this->_partRepairLimit = Settings::value('..maxpartrepair') !== '' ? (int) Settings::value('..maxpartrepair') : 15000; + $this->_partRepairMaxTries = (Settings::value('..partrepairmaxtries') !== '' ? (int) Settings::value('..partrepairmaxtries') : 3); + $this->_showDroppedYEncParts = Settings::value('..showdroppedyencparts') === 1; - $this->blackList = $this->whiteList = []; - } + $this->blackList = $this->whiteList = []; + } - /** - * Download new headers for all active groups. - * - * @param int $maxHeaders (Optional) How many headers to download max. - * - * @return void - * @throws \Exception - */ - public function updateAllGroups($maxHeaders = 100000): void - { - $groups = $this->_groups->getActive(); + /** + * Download new headers for all active groups. + * + * @param int $maxHeaders (Optional) How many headers to download max. + * + * @return void + * @throws \Exception + */ + public function updateAllGroups($maxHeaders = 100000): void + { + $groups = $this->_groups->getActive(); - $groupCount = count($groups); - if ($groupCount > 0) { - $counter = 1; - $allTime = microtime(true); + $groupCount = count($groups); + if ($groupCount > 0) { + $counter = 1; + $allTime = microtime(true); - $this->log( - 'Updating: ' . $groupCount . ' group(s) - Using compression? ' . ($this->_compressedHeaders ? 'Yes' : 'No'), + $this->log( + 'Updating: '.$groupCount.' group(s) - Using compression? '.($this->_compressedHeaders ? 'Yes' : 'No'), __FUNCTION__, Logger::LOG_INFO, 'header' ); - // Loop through groups. - foreach ($groups as $group) { - $this->log( - 'Starting group ' . $counter . ' of ' . $groupCount, + // Loop through groups. + foreach ($groups as $group) { + $this->log( + 'Starting group '.$counter.' of '.$groupCount, __FUNCTION__, Logger::LOG_INFO, 'header' ); - $this->updateGroup($group, $maxHeaders); - $counter++; - } + $this->updateGroup($group, $maxHeaders); + $counter++; + } - $this->log( - 'Updating completed in ' . number_format(microtime(true) - $allTime, 2) . ' seconds.', + $this->log( + 'Updating completed in '.number_format(microtime(true) - $allTime, 2).' seconds.', __FUNCTION__, Logger::LOG_INFO, 'primary' ); - } else { - $this->log( + } else { + $this->log( 'No groups specified. Ensure groups are added to NNTmux\'s database for updating.', __FUNCTION__, Logger::LOG_NOTICE, 'warning' ); - } - } + } + } - /** - * When the indexer is started, log the date/time. - */ - public function logIndexerStart(): void - { - Settings::query()->where('setting', '=', 'last_run_time')->update(['value' => (new \DateTime())->format('Y-m-d H:i:s')]); - } + /** + * When the indexer is started, log the date/time. + */ + public function logIndexerStart(): void + { + Settings::query()->where('setting', '=', 'last_run_time')->update(['value' => (new \DateTime())->format('Y-m-d H:i:s')]); + } - /** - * Download new headers for a single group. - * - * @param array $groupMySQL Array of MySQL results for a single group. - * @param int $maxHeaders (Optional) How many headers to download max. - * - * @return void - * @throws \Exception - */ - public function updateGroup($groupMySQL, $maxHeaders = 0): void - { - $startGroup = microtime(true); + /** + * Download new headers for a single group. + * + * @param array $groupMySQL Array of MySQL results for a single group. + * @param int $maxHeaders (Optional) How many headers to download max. + * + * @return void + * @throws \Exception + */ + public function updateGroup($groupMySQL, $maxHeaders = 0): void + { + $startGroup = microtime(true); - $this->logIndexerStart(); + $this->logIndexerStart(); - // Select the group on the NNTP server, gets the latest info on it. - $groupNNTP = $this->_nntp->selectGroup($groupMySQL['name']); - if ($this->_nntp->isError($groupNNTP)) { - $groupNNTP = $this->_nntp->dataError($this->_nntp, $groupMySQL['name']); - if ($groupNNTP->code === 411) { - $this->_groups->disableIfNotExist($groupMySQL['id']); - } - if ($this->_nntp->isError($groupNNTP)) { - return; - } - } + // Select the group on the NNTP server, gets the latest info on it. + $groupNNTP = $this->_nntp->selectGroup($groupMySQL['name']); + if ($this->_nntp->isError($groupNNTP)) { + $groupNNTP = $this->_nntp->dataError($this->_nntp, $groupMySQL['name']); + if ($groupNNTP->code === 411) { + $this->_groups->disableIfNotExist($groupMySQL['id']); + } + if ($this->_nntp->isError($groupNNTP)) { + return; + } + } - if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::primary('Processing ' . $groupMySQL['name']), true); - } + if ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::primary('Processing '.$groupMySQL['name']), true); + } - // Attempt to repair any missing parts before grabbing new ones. - if ((int)$groupMySQL['last_record'] !== 0) { - if ($this->_partRepair) { - if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::primary('Part repair enabled. Checking for missing parts.'), true); - } - $this->partRepair($groupMySQL); + // Attempt to repair any missing parts before grabbing new ones. + if ((int) $groupMySQL['last_record'] !== 0) { + if ($this->_partRepair) { + if ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::primary('Part repair enabled. Checking for missing parts.'), true); + } + $this->partRepair($groupMySQL); - $mgrPosters = $this->getMultiGroupPosters(); - if(!empty($mgrPosters)) { - $tableNames = ProcessReleasesMultiGroup::tableNames(); - $this->partRepair($groupMySQL, $tableNames); - } + $mgrPosters = $this->getMultiGroupPosters(); + if (! empty($mgrPosters)) { + $tableNames = ProcessReleasesMultiGroup::tableNames(); + $this->partRepair($groupMySQL, $tableNames); + } + } elseif ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::primary('Part repair disabled by user.'), true); + } + } - } else if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::primary('Part repair disabled by user.'), true); - } - } + // Generate postdate for first record, for those that upgraded. + if ($groupMySQL['first_record_postdate'] === null && (int) $groupMySQL['first_record'] !== 0) { + $groupMySQL['first_record_postdate'] = $this->postdate($groupMySQL['first_record'], $groupNNTP); - // Generate postdate for first record, for those that upgraded. - if ($groupMySQL['first_record_postdate'] === null && (int)$groupMySQL['first_record'] !== 0) { - - $groupMySQL['first_record_postdate'] = $this->postdate($groupMySQL['first_record'], $groupNNTP); - - $this->_pdo->queryExec( + $this->_pdo->queryExec( sprintf(' UPDATE groups SET first_record_postdate = %s @@ -410,127 +409,126 @@ class Binaries $groupMySQL['id'] ) ); - } + } - // Get first article we want aka the oldest. - if ((int)$groupMySQL['last_record'] === 0) { - if ($this->_newGroupScanByDays) { - // For new newsgroups - determine here how far we want to go back using date. - $first = $this->daytopost($this->_newGroupDaysToScan, $groupNNTP); - } else if ($groupNNTP['first'] >= ($groupNNTP['last'] - ($this->_newGroupMessagesToScan + $this->messageBuffer))) { - // If what we want is lower than the groups first article, set the wanted first to the first. - $first = $groupNNTP['first']; - } else { - // Or else, use the newest article minus how much we should get for new groups. - $first = (string)($groupNNTP['last'] - ($this->_newGroupMessagesToScan + $this->messageBuffer)); - } + // Get first article we want aka the oldest. + if ((int) $groupMySQL['last_record'] === 0) { + if ($this->_newGroupScanByDays) { + // For new newsgroups - determine here how far we want to go back using date. + $first = $this->daytopost($this->_newGroupDaysToScan, $groupNNTP); + } elseif ($groupNNTP['first'] >= ($groupNNTP['last'] - ($this->_newGroupMessagesToScan + $this->messageBuffer))) { + // If what we want is lower than the groups first article, set the wanted first to the first. + $first = $groupNNTP['first']; + } else { + // Or else, use the newest article minus how much we should get for new groups. + $first = (string) ($groupNNTP['last'] - ($this->_newGroupMessagesToScan + $this->messageBuffer)); + } - // We will use this to subtract so we leave articles for the next time (in case the server doesn't have them yet) - $leaveOver = $this->messageBuffer; + // We will use this to subtract so we leave articles for the next time (in case the server doesn't have them yet) + $leaveOver = $this->messageBuffer; - // If this is not a new group, go from our newest to the servers newest. - } else { - // Set our oldest wanted to our newest local article. - $first = $groupMySQL['last_record']; + // If this is not a new group, go from our newest to the servers newest. + } else { + // Set our oldest wanted to our newest local article. + $first = $groupMySQL['last_record']; - // This is how many articles we will grab. (the servers newest minus our newest). - $totalCount = (string)($groupNNTP['last'] - $first); + // This is how many articles we will grab. (the servers newest minus our newest). + $totalCount = (string) ($groupNNTP['last'] - $first); - // Check if the server has more articles than our loop limit x 2. - if ($totalCount > ($this->messageBuffer * 2)) { - // Get the remainder of $totalCount / $this->message buffer - $leaveOver = round($totalCount % $this->messageBuffer, 0, PHP_ROUND_HALF_DOWN) + $this->messageBuffer; - } else { - // Else get half of the available. - $leaveOver = round($totalCount / 2, 0, PHP_ROUND_HALF_DOWN); - } - } + // Check if the server has more articles than our loop limit x 2. + if ($totalCount > ($this->messageBuffer * 2)) { + // Get the remainder of $totalCount / $this->message buffer + $leaveOver = round($totalCount % $this->messageBuffer, 0, PHP_ROUND_HALF_DOWN) + $this->messageBuffer; + } else { + // Else get half of the available. + $leaveOver = round($totalCount / 2, 0, PHP_ROUND_HALF_DOWN); + } + } - // The last article we want, aka the newest. - $last = $groupLast = (string)($groupNNTP['last'] - $leaveOver); + // The last article we want, aka the newest. + $last = $groupLast = (string) ($groupNNTP['last'] - $leaveOver); - // If the newest we want is older than the oldest we want somehow.. set them equal. - if ($last < $first) { - $last = $groupLast = $first; - } + // If the newest we want is older than the oldest we want somehow.. set them equal. + if ($last < $first) { + $last = $groupLast = $first; + } - // This is how many articles we are going to get. - $total = (string)($groupLast - $first); - // This is how many articles are available (without $leaveOver). - $realTotal = (string)($groupNNTP['last'] - $first); + // This is how many articles we are going to get. + $total = (string) ($groupLast - $first); + // This is how many articles are available (without $leaveOver). + $realTotal = (string) ($groupNNTP['last'] - $first); - // Check if we should limit the amount of fetched new headers. - if ($maxHeaders > 0) { - if ($maxHeaders < ($groupLast - $first)) { - $groupLast = $last = (string)($first + $maxHeaders); - } - $total = (string)($groupLast - $first); - } + // Check if we should limit the amount of fetched new headers. + if ($maxHeaders > 0) { + if ($maxHeaders < ($groupLast - $first)) { + $groupLast = $last = (string) ($first + $maxHeaders); + } + $total = (string) ($groupLast - $first); + } - // If total is bigger than 0 it means we have new parts in the newsgroup. - if ($total > 0) { - - if ($this->_echoCLI) { - ColorCLI::doEcho( + // If total is bigger than 0 it means we have new parts in the newsgroup. + if ($total > 0) { + if ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - ((int)$groupMySQL['last_record'] === 0 - ? 'New group ' . $groupNNTP['group'] . ' starting with ' . + ((int) $groupMySQL['last_record'] === 0 + ? 'New group '.$groupNNTP['group'].' starting with '. ($this->_newGroupScanByDays - ? $this->_newGroupDaysToScan . ' days' - : number_format($this->_newGroupMessagesToScan) . ' messages' - ) . ' worth.' - : 'Group ' . $groupNNTP['group'] . ' has ' . number_format($realTotal) . ' new articles.' - ) . - ' Leaving ' . number_format($leaveOver) . - " for next pass.\nServer oldest: " . number_format($groupNNTP['first']) . - ' Server newest: ' . number_format($groupNNTP['last']) . - ' Local newest: ' . number_format($groupMySQL['last_record']) + ? $this->_newGroupDaysToScan.' days' + : number_format($this->_newGroupMessagesToScan).' messages' + ).' worth.' + : 'Group '.$groupNNTP['group'].' has '.number_format($realTotal).' new articles.' + ). + ' Leaving '.number_format($leaveOver). + " for next pass.\nServer oldest: ".number_format($groupNNTP['first']). + ' Server newest: '.number_format($groupNNTP['last']). + ' Local newest: '.number_format($groupMySQL['last_record']) ), true ); - } + } - $done = false; - // Get all the parts (in portions of $this->messageBuffer to not use too much memory). - while ($done === false) { + $done = false; + // Get all the parts (in portions of $this->messageBuffer to not use too much memory). + while ($done === false) { // Increment last until we reach $groupLast (group newest article). - if ($total > $this->messageBuffer) { - if ((string)($first + $this->messageBuffer) > $groupLast) { - $last = $groupLast; - } else { - $last = (string)($first + $this->messageBuffer); - } - } - // Increment first so we don't get an article we already had. - $first++; + if ($total > $this->messageBuffer) { + if ((string) ($first + $this->messageBuffer) > $groupLast) { + $last = $groupLast; + } else { + $last = (string) ($first + $this->messageBuffer); + } + } + // Increment first so we don't get an article we already had. + $first++; - if ($this->_echoCLI) { - ColorCLI::doEcho( + if ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::header( - PHP_EOL . 'Getting ' . number_format($last - $first + 1) . ' articles (' . number_format($first) . - ' to ' . number_format($last) . ') from ' . $groupMySQL['name'] . ' - (' . - number_format($groupLast - $last) . ' articles in queue).' + PHP_EOL.'Getting '.number_format($last - $first + 1).' articles ('.number_format($first). + ' to '.number_format($last).') from '.$groupMySQL['name'].' - ('. + number_format($groupLast - $last).' articles in queue).' ) ); - } + } - // Get article headers from newsgroup. - $scanSummary = $this->scan($groupMySQL, $first, $last); + // Get article headers from newsgroup. + $scanSummary = $this->scan($groupMySQL, $first, $last); - // Check if we fetched headers. - if (!empty($scanSummary)) { + // Check if we fetched headers. + if (! empty($scanSummary)) { // If new group, update first record & postdate - if ($groupMySQL['first_record_postdate'] === null && (int)$groupMySQL['first_record'] === 0) { - $groupMySQL['first_record'] = $scanSummary['firstArticleNumber']; + if ($groupMySQL['first_record_postdate'] === null && (int) $groupMySQL['first_record'] === 0) { + $groupMySQL['first_record'] = $scanSummary['firstArticleNumber']; - if (isset($scanSummary['firstArticleDate'])) { - $groupMySQL['first_record_postdate'] = strtotime($scanSummary['firstArticleDate']); - } else { - $groupMySQL['first_record_postdate'] = $this->postdate($groupMySQL['first_record'], $groupNNTP); - } + if (isset($scanSummary['firstArticleDate'])) { + $groupMySQL['first_record_postdate'] = strtotime($scanSummary['firstArticleDate']); + } else { + $groupMySQL['first_record_postdate'] = $this->postdate($groupMySQL['first_record'], $groupNNTP); + } - $this->_pdo->queryExec( + $this->_pdo->queryExec( sprintf(' UPDATE groups SET first_record = %s, first_record_postdate = %s @@ -540,14 +538,14 @@ class Binaries $groupMySQL['id'] ) ); - } + } - $scanSummary['lastArticleDate'] = (isset($scanSummary['lastArticleDate']) ? strtotime($scanSummary['lastArticleDate']) : false); - if (!is_numeric($scanSummary['lastArticleDate'])) { - $scanSummary['lastArticleDate'] = $this->postdate($scanSummary['lastArticleNumber'], $groupNNTP); - } + $scanSummary['lastArticleDate'] = (isset($scanSummary['lastArticleDate']) ? strtotime($scanSummary['lastArticleDate']) : false); + if (! is_numeric($scanSummary['lastArticleDate'])) { + $scanSummary['lastArticleDate'] = $this->postdate($scanSummary['lastArticleNumber'], $groupNNTP); + } - $this->_pdo->queryExec( + $this->_pdo->queryExec( sprintf(' UPDATE groups SET last_record = %s, last_record_postdate = %s, last_updated = NOW() @@ -557,9 +555,9 @@ class Binaries $groupMySQL['id'] ) ); - } else { - // If we didn't fetch headers, update the record still. - $this->_pdo->queryExec( + } else { + // If we didn't fetch headers, update the record still. + $this->_pdo->queryExec( sprintf(' UPDATE groups SET last_record = %s, last_updated = NOW() @@ -568,355 +566,355 @@ class Binaries $groupMySQL['id'] ) ); - } + } - if ((int)$last === (int)$groupLast) { - $done = true; - } else { - $first = $last; - } - } + if ((int) $last === (int) $groupLast) { + $done = true; + } else { + $first = $last; + } + } - if ($this->_echoCLI) { - ColorCLI::doEcho( + if ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - PHP_EOL . 'Group ' . $groupMySQL['name'] . ' processed in ' . - number_format(microtime(true) - $startGroup, 2) . ' seconds.' + PHP_EOL.'Group '.$groupMySQL['name'].' processed in '. + number_format(microtime(true) - $startGroup, 2).' seconds.' ), true ); - } - } else if ($this->_echoCLI) { - ColorCLI::doEcho( + } + } elseif ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - 'No new articles for ' . $groupMySQL['name'] . ' (first ' . number_format($first) . - ', last ' . number_format($last) . ', grouplast ' . number_format($groupMySQL['last_record']) . - ', total ' . number_format($total) . ")\n" . 'Server oldest: ' . number_format($groupNNTP['first']) . - ' Server newest: ' . number_format($groupNNTP['last']) . ' Local newest: ' . number_format($groupMySQL['last_record']) + 'No new articles for '.$groupMySQL['name'].' (first '.number_format($first). + ', last '.number_format($last).', grouplast '.number_format($groupMySQL['last_record']). + ', total '.number_format($total).")\n".'Server oldest: '.number_format($groupNNTP['first']). + ' Server newest: '.number_format($groupNNTP['last']).' Local newest: '.number_format($groupMySQL['last_record']) ), true ); - } - } + } + } - /** - * Loop over range of wanted headers, insert headers into DB. - * - * @param array $groupMySQL The group info from mysql. - * @param int $first The oldest wanted header. - * @param int $last The newest wanted header. - * @param string $type Is this partrepair or update or backfill? - * @param null|array $missingParts If we are running in partrepair, the list of missing article numbers. - * - * @return array Empty on failure. - * @throws \Exception - */ - public function scan($groupMySQL, $first, $last, $type = 'update', $missingParts = null): array - { - // Start time of scan method and of fetching headers. - $this->startLoop = microtime(true); - $this->groupMySQL = $groupMySQL; - $this->last = $last; - $this->first = $first; + /** + * Loop over range of wanted headers, insert headers into DB. + * + * @param array $groupMySQL The group info from mysql. + * @param int $first The oldest wanted header. + * @param int $last The newest wanted header. + * @param string $type Is this partrepair or update or backfill? + * @param null|array $missingParts If we are running in partrepair, the list of missing article numbers. + * + * @return array Empty on failure. + * @throws \Exception + */ + public function scan($groupMySQL, $first, $last, $type = 'update', $missingParts = null): array + { + // Start time of scan method and of fetching headers. + $this->startLoop = microtime(true); + $this->groupMySQL = $groupMySQL; + $this->last = $last; + $this->first = $first; - $this->notYEnc = $this->headersBlackListed = 0; + $this->notYEnc = $this->headersBlackListed = 0; - // Check if MySQL tables exist, create if they do not, get their names at the same time. - $this->tableNames = $this->_groups->getCBPTableNames($this->groupMySQL['id']); + // Check if MySQL tables exist, create if they do not, get their names at the same time. + $this->tableNames = $this->_groups->getCBPTableNames($this->groupMySQL['id']); - $mgrPosters = $this->getMultiGroupPosters(); + $mgrPosters = $this->getMultiGroupPosters(); - if(!empty($mgrPosters)) { - $mgrActive = true; - $mgrPosters = array_flip(array_column($mgrPosters, 'poster')); - } else { - $mgrActive = false; - } + if (! empty($mgrPosters)) { + $mgrActive = true; + $mgrPosters = array_flip(array_column($mgrPosters, 'poster')); + } else { + $mgrActive = false; + } - $returnArray = $stdHeaders = $mgrHeaders = []; + $returnArray = $stdHeaders = $mgrHeaders = []; - $partRepair = ($type === 'partrepair'); - $this->addToPartRepair = ($type === 'update' && $this->_partRepair); + $partRepair = ($type === 'partrepair'); + $this->addToPartRepair = ($type === 'update' && $this->_partRepair); - // Download the headers. - if ($partRepair === true) { - // This is slower but possibly is better with missing headers. - $headers = $this->_nntp->getOverview($this->first . '-' . $this->last, true, false); - } else { - $headers = $this->_nntp->getXOVER($this->first . '-' . $this->last); - } + // Download the headers. + if ($partRepair === true) { + // This is slower but possibly is better with missing headers. + $headers = $this->_nntp->getOverview($this->first.'-'.$this->last, true, false); + } else { + $headers = $this->_nntp->getXOVER($this->first.'-'.$this->last); + } - // If there was an error, try to reconnect. - if ($this->_nntp->isError($headers)) { + // If there was an error, try to reconnect. + if ($this->_nntp->isError($headers)) { // Increment if part repair and return false. - if ($partRepair === true) { - $this->_pdo->queryExec( + if ($partRepair === true) { + $this->_pdo->queryExec( sprintf( 'UPDATE %s SET attempts = attempts + 1 WHERE groups_id = %d AND numberid %s', $this->tableNames['prname'], $this->groupMySQL['id'], - ((int)$this->first === (int)$this->last ? '= ' . $this->first : 'IN (' . implode(',', range($this->first, $this->last)) . ')') + ((int) $this->first === (int) $this->last ? '= '.$this->first : 'IN ('.implode(',', range($this->first, $this->last)).')') ) ); - return $returnArray; - } - // This is usually a compression error, so try disabling compression. - $this->_nntp->doQuit(); - if ($this->_nntp->doConnect(false) !== true) { - return $returnArray; - } + return $returnArray; + } - // Re-select group, download headers again without compression and re-enable compression. - $this->_nntp->selectGroup($this->groupMySQL['name']); - $headers = $this->_nntp->getXOVER($this->first . '-' . $this->last); - $this->_nntp->enableCompression(); + // This is usually a compression error, so try disabling compression. + $this->_nntp->doQuit(); + if ($this->_nntp->doConnect(false) !== true) { + return $returnArray; + } - // Check if the non-compression headers have an error. - if ($this->_nntp->isError($headers)) { - $message = ((int)$headers->code === 0 ? 'Unknown error' : $headers->message); - $this->log( + // Re-select group, download headers again without compression and re-enable compression. + $this->_nntp->selectGroup($this->groupMySQL['name']); + $headers = $this->_nntp->getXOVER($this->first.'-'.$this->last); + $this->_nntp->enableCompression(); + + // Check if the non-compression headers have an error. + if ($this->_nntp->isError($headers)) { + $message = ((int) $headers->code === 0 ? 'Unknown error' : $headers->message); + $this->log( "Code {$headers->code}: $message\nSkipping group: {$this->groupMySQL['name']}", __FUNCTION__, Logger::LOG_WARNING, 'error' ); - return $returnArray; - } - } - // Start of processing headers. - $this->startCleaning = microtime(true); + return $returnArray; + } + } - // End of the getting data from usenet. - $this->timeHeaders = number_format($this->startCleaning - $this->startLoop, 2); + // Start of processing headers. + $this->startCleaning = microtime(true); - // Check if we got headers. - $msgCount = count($headers); + // End of the getting data from usenet. + $this->timeHeaders = number_format($this->startCleaning - $this->startLoop, 2); - if ($msgCount < 1) { - return $returnArray; - } + // Check if we got headers. + $msgCount = count($headers); - $this->getHighLowArticleInfo($returnArray, $headers, $msgCount); + if ($msgCount < 1) { + return $returnArray; + } - $headersRepaired = $rangeNotReceived = $this->headersReceived = $this->headersNotInserted = []; + $this->getHighLowArticleInfo($returnArray, $headers, $msgCount); - foreach ($headers as $header) { + $headersRepaired = $rangeNotReceived = $this->headersReceived = $this->headersNotInserted = []; + + foreach ($headers as $header) { // Check if we got the article or not. - if (isset($header['Number'])) { - $this->headersReceived[] = $header['Number']; - } else { - if ($this->addToPartRepair) { - $rangeNotReceived[] = $header['Number']; - } - continue; - } + if (isset($header['Number'])) { + $this->headersReceived[] = $header['Number']; + } else { + if ($this->addToPartRepair) { + $rangeNotReceived[] = $header['Number']; + } + continue; + } - // If set we are running in partRepair mode. - if ($partRepair === true && $missingParts !== null) { - if (!in_array($header['Number'], $missingParts, false)) { - // If article isn't one that is missing skip it. - continue; - } - // We got the part this time. Remove article from part repair. - $headersRepaired[] = $header['Number']; - } + // If set we are running in partRepair mode. + if ($partRepair === true && $missingParts !== null) { + if (! in_array($header['Number'], $missingParts, false)) { + // If article isn't one that is missing skip it. + continue; + } + // We got the part this time. Remove article from part repair. + $headersRepaired[] = $header['Number']; + } - /* - * Find part / total parts. Ignore if no part count found. - * - * \s* Trims the leading space. - * (?!"Usenet Index Post) ignores these types of articles, they are useless. - * (.+) Fetches the subject. - * \s+ Trims trailing space after the subject. - * \((\d+)\/(\d+)\) Gets the part count. - * No ending ($) as there are cases of subjects with extra data after the part count. - */ - if (preg_match('/^\s*(?!"Usenet Index Post)(.+)\s+\((\d+)\/(\d+)\)/', $header['Subject'], $header['matches'])) { - // Add yEnc to subjects that do not have them, but have the part number at the end of the header. - if (stripos($header['Subject'], 'yEnc') === false) { - $header['matches'][1] .= ' yEnc'; - } - } else { - if ($this->_showDroppedYEncParts === true && strpos($header['Subject'], '"Usenet Index Post') !== 0) { - file_put_contents( - NN_LOGS . 'not_yenc' . $this->groupMySQL['name'] . '.dropped.log', - $header['Subject'] . PHP_EOL, FILE_APPEND + /* + * Find part / total parts. Ignore if no part count found. + * + * \s* Trims the leading space. + * (?!"Usenet Index Post) ignores these types of articles, they are useless. + * (.+) Fetches the subject. + * \s+ Trims trailing space after the subject. + * \((\d+)\/(\d+)\) Gets the part count. + * No ending ($) as there are cases of subjects with extra data after the part count. + */ + if (preg_match('/^\s*(?!"Usenet Index Post)(.+)\s+\((\d+)\/(\d+)\)/', $header['Subject'], $header['matches'])) { + // Add yEnc to subjects that do not have them, but have the part number at the end of the header. + if (stripos($header['Subject'], 'yEnc') === false) { + $header['matches'][1] .= ' yEnc'; + } + } else { + if ($this->_showDroppedYEncParts === true && strpos($header['Subject'], '"Usenet Index Post') !== 0) { + file_put_contents( + NN_LOGS.'not_yenc'.$this->groupMySQL['name'].'.dropped.log', + $header['Subject'].PHP_EOL, FILE_APPEND ); - } - $this->notYEnc++; - continue; - } + } + $this->notYEnc++; + continue; + } - // Filter subject based on black/white list. - if ($this->isBlackListed($header, $this->groupMySQL['name'])) { - $this->headersBlackListed++; - continue; - } + // Filter subject based on black/white list. + if ($this->isBlackListed($header, $this->groupMySQL['name'])) { + $this->headersBlackListed++; + continue; + } - if (!isset($header['Bytes'])) { - $header['Bytes'] = (isset($this->header[':bytes']) ? $header[':bytes'] : 0); - } - $header['Bytes'] = (int)$header['Bytes']; + if (! isset($header['Bytes'])) { + $header['Bytes'] = (isset($this->header[':bytes']) ? $header[':bytes'] : 0); + } + $header['Bytes'] = (int) $header['Bytes']; - if ($mgrActive === true && array_key_exists($header['From'], $mgrPosters)) { - $mgrHeaders[] = $header; - } else { - $stdHeaders[] = $header; - } - } + if ($mgrActive === true && array_key_exists($header['From'], $mgrPosters)) { + $mgrHeaders[] = $header; + } else { + $stdHeaders[] = $header; + } + } - unset($headers); // Reclaim memory now that headers are split. + unset($headers); // Reclaim memory now that headers are split. - if (!empty($this->_binaryBlacklistIdsToUpdate)) { - $this->updateBlacklistUsage(); - } + if (! empty($this->_binaryBlacklistIdsToUpdate)) { + $this->updateBlacklistUsage(); + } - if ($this->_echoCLI && $partRepair === false) { - $this->outputHeaderInitial(); - } + if ($this->_echoCLI && $partRepair === false) { + $this->outputHeaderInitial(); + } - // MGR headers goes first - if (!empty($mgrHeaders)) { - $this->tableNames = ProcessReleasesMultiGroup::tableNames(); - $this->storeHeaders($mgrHeaders, true); - } - unset($mgrHeaders); + // MGR headers goes first + if (! empty($mgrHeaders)) { + $this->tableNames = ProcessReleasesMultiGroup::tableNames(); + $this->storeHeaders($mgrHeaders, true); + } + unset($mgrHeaders); - // Standard headers go second so we can switch tableNames back and do part repair to standard group tables - if (!empty($stdHeaders)) { - $this->tableNames = $this->_groups->getCBPTableNames($this->groupMySQL['id']); - $this->storeHeaders($stdHeaders, false); - } - unset($stdHeaders); + // Standard headers go second so we can switch tableNames back and do part repair to standard group tables + if (! empty($stdHeaders)) { + $this->tableNames = $this->_groups->getCBPTableNames($this->groupMySQL['id']); + $this->storeHeaders($stdHeaders, false); + } + unset($stdHeaders); - // Start of part repair. - $this->startPR = microtime(true); + // Start of part repair. + $this->startPR = microtime(true); - // End of inserting. - $this->timeInsert = number_format($this->startPR - $this->startUpdate, 2); + // End of inserting. + $this->timeInsert = number_format($this->startPR - $this->startUpdate, 2); - if ($partRepair && count($headersRepaired) > 0) { + if ($partRepair && count($headersRepaired) > 0) { + $this->removeRepairedParts($headersRepaired, $this->tableNames['prname'], $this->groupMySQL['id']); + } + unset($headersRepaired); - $this->removeRepairedParts($headersRepaired, $this->tableNames['prname'], $this->groupMySQL['id']); - } - unset($headersRepaired); + if ($this->addToPartRepair) { + $notInsertedCount = count($this->headersNotInserted); + if ($notInsertedCount > 0) { + $this->addMissingParts($this->headersNotInserted, $this->tableNames['prname'], $this->groupMySQL['id']); - if ($this->addToPartRepair) { - - $notInsertedCount = count($this->headersNotInserted); - if ($notInsertedCount > 0) { - $this->addMissingParts($this->headersNotInserted, $this->tableNames['prname'], $this->groupMySQL['id']); - - $this->log( - $notInsertedCount . ' articles failed to insert!', + $this->log( + $notInsertedCount.' articles failed to insert!', __FUNCTION__, Logger::LOG_WARNING, 'warning' ); - } - unset($this->headersNotInserted); + } + unset($this->headersNotInserted); - // Check if we have any missing headers. - if (($this->last - $this->first - $this->notYEnc - $this->headersBlackListed + 1) > count($this->headersReceived)) { - $rangeNotReceived = array_merge($rangeNotReceived, array_diff(range($this->first, $this->last), $this->headersReceived)); - } - $notReceivedCount = count($rangeNotReceived); - if ($notReceivedCount > 0) { - $this->addMissingParts($rangeNotReceived, $this->tableNames['prname'], $this->groupMySQL['id']); + // Check if we have any missing headers. + if (($this->last - $this->first - $this->notYEnc - $this->headersBlackListed + 1) > count($this->headersReceived)) { + $rangeNotReceived = array_merge($rangeNotReceived, array_diff(range($this->first, $this->last), $this->headersReceived)); + } + $notReceivedCount = count($rangeNotReceived); + if ($notReceivedCount > 0) { + $this->addMissingParts($rangeNotReceived, $this->tableNames['prname'], $this->groupMySQL['id']); - if ($this->_echoCLI) { - ColorCLI::doEcho( + if ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::alternate( - 'Server did not return ' . $notReceivedCount . - ' articles from ' . $this->groupMySQL['name'] . '.' + 'Server did not return '.$notReceivedCount. + ' articles from '.$this->groupMySQL['name'].'.' ), true ); - } - } - unset($rangeNotReceived); - } + } + } + unset($rangeNotReceived); + } - $this->outputHeaderDuration(); - return $returnArray; - } + $this->outputHeaderDuration(); - /** - * Parse headers into collections/binaries and store header data as parts - * - * @param array $headers The retrieved headers - * @param bool $multiGroup Is this task being run in MGR mode? - * - * @throws \Exception - */ - protected function storeHeaders(array $headers, $multiGroup): void - { - $this->multiGroup = $multiGroup; - $binariesUpdate = $collectionIDs = $articles = []; + return $returnArray; + } - $this->_pdo->beginTransaction(); + /** + * Parse headers into collections/binaries and store header data as parts. + * + * @param array $headers The retrieved headers + * @param bool $multiGroup Is this task being run in MGR mode? + * + * @throws \Exception + */ + protected function storeHeaders(array $headers, $multiGroup): void + { + $this->multiGroup = $multiGroup; + $binariesUpdate = $collectionIDs = $articles = []; - $partsQuery = $partsCheck = + $this->_pdo->beginTransaction(); + + $partsQuery = $partsCheck = "INSERT IGNORE INTO {$this->tableNames['pname']} (binaries_id, number, messageid, partnumber, size) VALUES "; - // Loop articles, figure out files/parts. - foreach ($headers as $this->header) - { - // Set up the info for inserting into parts/binaries/collections tables. - if (!isset($articles[$this->header['matches'][1]])) { + // Loop articles, figure out files/parts. + foreach ($headers as $this->header) { + // Set up the info for inserting into parts/binaries/collections tables. + if (! isset($articles[$this->header['matches'][1]])) { // check whether file count should be ignored (XXX packs for now only). - $whitelistMatch = false; - if ($this->_ignoreFileCount($this->groupMySQL['name'], $this->header['matches'][1])) { - $whitelistMatch = true; - $fileCount[1] = $fileCount[3] = 0; - } + $whitelistMatch = false; + if ($this->_ignoreFileCount($this->groupMySQL['name'], $this->header['matches'][1])) { + $whitelistMatch = true; + $fileCount[1] = $fileCount[3] = 0; + } - // Attempt to find the file count. If it is not found, set it to 0. - if (!$whitelistMatch && !preg_match('/[[(\s](\d{1,5})(\/|[\s_]of[\s_]|-)(\d{1,5})[])\s$:]/i', $this->header['matches'][1], $fileCount)) { - $fileCount[1] = $fileCount[3] = 0; - if ($this->_showDroppedYEncParts === true) { - file_put_contents( - NN_LOGS . 'no_files' . $this->groupMySQL['name'] . '.log', - $this->header['Subject'] . PHP_EOL, FILE_APPEND + // Attempt to find the file count. If it is not found, set it to 0. + if (! $whitelistMatch && ! preg_match('/[[(\s](\d{1,5})(\/|[\s_]of[\s_]|-)(\d{1,5})[])\s$:]/i', $this->header['matches'][1], $fileCount)) { + $fileCount[1] = $fileCount[3] = 0; + if ($this->_showDroppedYEncParts === true) { + file_put_contents( + NN_LOGS.'no_files'.$this->groupMySQL['name'].'.log', + $this->header['Subject'].PHP_EOL, FILE_APPEND ); - } - } + } + } - if ($this->multiGroup) { - $ckName = ''; - $ckId = ''; - } else { - $ckName = $this->groupMySQL['name']; - $ckId = $this->groupMySQL['id']; - } + if ($this->multiGroup) { + $ckName = ''; + $ckId = ''; + } else { + $ckName = $this->groupMySQL['name']; + $ckId = $this->groupMySQL['id']; + } - $collMatch = $this->_collectionsCleaning->collectionsCleaner( + $collMatch = $this->_collectionsCleaning->collectionsCleaner( $this->header['matches'][1], $ckName ); - // Used to group articles together when forming the release. MGR requires this to be group irrespective - $this->header['CollectionKey'] = $collMatch['name'] . $this->header['From'] . $ckId . $fileCount[3]; + // Used to group articles together when forming the release. MGR requires this to be group irrespective + $this->header['CollectionKey'] = $collMatch['name'].$this->header['From'].$ckId.$fileCount[3]; - // If this header's collection key isn't in memory, attempt to insert the collection - if (!isset($collectionIDs[$this->header['CollectionKey']])) { + // If this header's collection key isn't in memory, attempt to insert the collection + if (! isset($collectionIDs[$this->header['CollectionKey']])) { /* Date from header should be a string this format: * 31 Mar 2014 15:36:04 GMT or 6 Oct 1998 04:38:40 -0500 * Still make sure it's not unix time, convert it to unix time if it is. */ - $this->header['Date'] = (is_numeric($this->header['Date']) ? $this->header['Date'] : strtotime($this->header['Date'])); + $this->header['Date'] = (is_numeric($this->header['Date']) ? $this->header['Date'] : strtotime($this->header['Date'])); - // Get the current unixtime from PHP. - $now = time(); + // Get the current unixtime from PHP. + $now = time(); - $xref = ($this->multiGroup === true ? sprintf('xref = CONCAT(xref, "\\n"%s ),', $this->_pdo->escapeString(substr($this->header['Xref'], 2, 255))) : ''); - $date = $this->header['Date'] > $now ? $now : $this->header['Date']; - $unixtime = is_numeric($this->header['Date']) ? $date : $now; + $xref = ($this->multiGroup === true ? sprintf('xref = CONCAT(xref, "\\n"%s ),', $this->_pdo->escapeString(substr($this->header['Xref'], 2, 255))) : ''); + $date = $this->header['Date'] > $now ? $now : $this->header['Date']; + $unixtime = is_numeric($this->header['Date']) ? $date : $now; - $collectionID = $this->_pdo->queryInsert( + $collectionID = $this->_pdo->queryInsert( sprintf(" INSERT INTO %s (subject, fromname, date, xref, groups_id, totalfiles, collectionhash, collection_regexes_id, dateadded) @@ -936,23 +934,23 @@ class Binaries ) ); - if ($collectionID === false) { - if ($this->addToPartRepair) { - $this->headersNotInserted[] = $this->header['Number']; - } - $this->_pdo->Rollback(); - $this->_pdo->beginTransaction(); - continue; - } - $collectionIDs[$this->header['CollectionKey']] = $collectionID; - } else { - $collectionID = $collectionIDs[$this->header['CollectionKey']]; - } + if ($collectionID === false) { + if ($this->addToPartRepair) { + $this->headersNotInserted[] = $this->header['Number']; + } + $this->_pdo->Rollback(); + $this->_pdo->beginTransaction(); + continue; + } + $collectionIDs[$this->header['CollectionKey']] = $collectionID; + } else { + $collectionID = $collectionIDs[$this->header['CollectionKey']]; + } - // MGR or Standard, Binary Hash should be unique to the group - $hash = md5($this->header['matches'][1] . $this->header['From'] . $this->groupMySQL['id']); + // MGR or Standard, Binary Hash should be unique to the group + $hash = md5($this->header['matches'][1].$this->header['From'].$this->groupMySQL['id']); - $binaryID = $this->_pdo->queryInsert( + $binaryID = $this->_pdo->queryInsert( sprintf(" INSERT INTO %s (binaryhash, name, collections_id, totalparts, currentparts, filenumber, partsize) VALUES (UNHEX('%s'), %s, %d, %d, 1, %d, %d) @@ -968,194 +966,192 @@ class Binaries ) ); - if ($binaryID === false) { - if ($this->addToPartRepair) { - $this->headersNotInserted[] = $this->header['Number']; - } - $this->_pdo->Rollback(); - $this->_pdo->beginTransaction(); - continue; - } + if ($binaryID === false) { + if ($this->addToPartRepair) { + $this->headersNotInserted[] = $this->header['Number']; + } + $this->_pdo->Rollback(); + $this->_pdo->beginTransaction(); + continue; + } - $binariesUpdate[$binaryID]['Size'] = 0; - $binariesUpdate[$binaryID]['Parts'] = 0; + $binariesUpdate[$binaryID]['Size'] = 0; + $binariesUpdate[$binaryID]['Parts'] = 0; - $articles[$this->header['matches'][1]]['CollectionID'] = $collectionID; - $articles[$this->header['matches'][1]]['BinaryID'] = $binaryID; + $articles[$this->header['matches'][1]]['CollectionID'] = $collectionID; + $articles[$this->header['matches'][1]]['BinaryID'] = $binaryID; + } else { + $binaryID = $articles[$this->header['matches'][1]]['BinaryID']; + $binariesUpdate[$binaryID]['Size'] += $this->header['Bytes']; + $binariesUpdate[$binaryID]['Parts']++; + } - } else { - $binaryID = $articles[$this->header['matches'][1]]['BinaryID']; - $binariesUpdate[$binaryID]['Size'] += $this->header['Bytes']; - $binariesUpdate[$binaryID]['Parts']++; - } + // Strip the < and >, saves space in DB. + $this->header['Message-ID'][0] = "'"; - // Strip the < and >, saves space in DB. - $this->header['Message-ID'][0] = "'"; + $partsQuery .= + '('.$binaryID.','.$this->header['Number'].','.rtrim($this->header['Message-ID'], '>')."',". + $this->header['matches'][2].','.$this->header['Bytes'].'),'; + } - $partsQuery .= - '(' . $binaryID . ',' . $this->header['Number'] . ',' . rtrim($this->header['Message-ID'], '>') . "'," . - $this->header['matches'][2] . ',' . $this->header['Bytes'] . '),'; - } + unset($headers); // Reclaim memory. - unset($headers); // Reclaim memory. + // Start of inserting into SQL. + $this->startUpdate = microtime(true); - // Start of inserting into SQL. - $this->startUpdate = microtime(true); + // End of processing headers. + $this->timeCleaning = number_format($this->startUpdate - $this->startCleaning, 2); + $binariesQuery = $binariesCheck = sprintf('INSERT INTO %s (id, partsize, currentparts) VALUES ', $this->tableNames['bname']); + foreach ($binariesUpdate as $binaryID => $binary) { + $binariesQuery .= '('.$binaryID.','.$binary['Size'].','.$binary['Parts'].'),'; + } + $binariesEnd = ' ON DUPLICATE KEY UPDATE partsize = VALUES(partsize) + partsize, currentparts = VALUES(currentparts) + currentparts'; + $binariesQuery = rtrim($binariesQuery, ',').$binariesEnd; - // End of processing headers. - $this->timeCleaning = number_format($this->startUpdate - $this->startCleaning, 2); - $binariesQuery = $binariesCheck = sprintf('INSERT INTO %s (id, partsize, currentparts) VALUES ', $this->tableNames['bname']); - foreach ($binariesUpdate as $binaryID => $binary) { - $binariesQuery .= '(' . $binaryID . ',' . $binary['Size'] . ',' . $binary['Parts'] . '),'; - } - $binariesEnd = ' ON DUPLICATE KEY UPDATE partsize = VALUES(partsize) + partsize, currentparts = VALUES(currentparts) + currentparts'; - $binariesQuery = rtrim($binariesQuery, ',') . $binariesEnd; - - // Check if we got any binaries. If we did, try to insert them. - if (strlen($binariesCheck . $binariesEnd) === strlen($binariesQuery) ? true : $this->_pdo->queryExec($binariesQuery)) { - if ($this->_debug) { - ColorCLI::doEcho( + // Check if we got any binaries. If we did, try to insert them. + if (strlen($binariesCheck.$binariesEnd) === strlen($binariesQuery) ? true : $this->_pdo->queryExec($binariesQuery)) { + if ($this->_debug) { + ColorCLI::doEcho( ColorCLI::debug( - 'Sending ' . round(strlen($partsQuery) / 1024, 2) . - ' KB of' . ($this->multiGroup ? ' MGR' : '') . ' parts to MySQL' + 'Sending '.round(strlen($partsQuery) / 1024, 2). + ' KB of'.($this->multiGroup ? ' MGR' : '').' parts to MySQL' ) ); - } - if (strlen($partsQuery) === strlen($partsCheck) ? true : $this->_pdo->queryExec(rtrim($partsQuery, ','))) { - $this->_pdo->Commit(); - } else { - if ($this->addToPartRepair) { - $this->headersNotInserted += $this->headersReceived; - } - $this->_pdo->Rollback(); - } - } else { - if ($this->addToPartRepair) { - $this->headersNotInserted += $this->headersReceived; - } - $this->_pdo->Rollback(); - } - } + } + if (strlen($partsQuery) === strlen($partsCheck) ? true : $this->_pdo->queryExec(rtrim($partsQuery, ','))) { + $this->_pdo->Commit(); + } else { + if ($this->addToPartRepair) { + $this->headersNotInserted += $this->headersReceived; + } + $this->_pdo->Rollback(); + } + } else { + if ($this->addToPartRepair) { + $this->headersNotInserted += $this->headersReceived; + } + $this->_pdo->Rollback(); + } + } - /** - * Gets the First and Last Article Number and Date for the received headers - * - * @param array $returnArray - * @param array $headers - * @param int $msgCount - */ - protected function getHighLowArticleInfo(array &$returnArray, array $headers, int $msgCount): void - { - // Get highest and lowest article numbers/dates. - $iterator1 = 0; - $iterator2 = $msgCount - 1; - while (true) { - if (!isset($returnArray['firstArticleNumber']) && isset($headers[$iterator1]['Number'])) { - $returnArray['firstArticleNumber'] = $headers[$iterator1]['Number']; - $returnArray['firstArticleDate'] = $headers[$iterator1]['Date']; - } + /** + * Gets the First and Last Article Number and Date for the received headers. + * + * @param array $returnArray + * @param array $headers + * @param int $msgCount + */ + protected function getHighLowArticleInfo(array &$returnArray, array $headers, int $msgCount): void + { + // Get highest and lowest article numbers/dates. + $iterator1 = 0; + $iterator2 = $msgCount - 1; + while (true) { + if (! isset($returnArray['firstArticleNumber']) && isset($headers[$iterator1]['Number'])) { + $returnArray['firstArticleNumber'] = $headers[$iterator1]['Number']; + $returnArray['firstArticleDate'] = $headers[$iterator1]['Date']; + } - if (!isset($returnArray['lastArticleNumber']) && isset($headers[$iterator2]['Number'])) { - $returnArray['lastArticleNumber'] = $headers[$iterator2]['Number']; - $returnArray['lastArticleDate'] = $headers[$iterator2]['Date']; - } + if (! isset($returnArray['lastArticleNumber']) && isset($headers[$iterator2]['Number'])) { + $returnArray['lastArticleNumber'] = $headers[$iterator2]['Number']; + $returnArray['lastArticleDate'] = $headers[$iterator2]['Date']; + } - // Break if we found non empty articles. - if (isset($returnArray['firstArticleNumber, lastArticleNumber'])) { - break; - } + // Break if we found non empty articles. + if (isset($returnArray['firstArticleNumber, lastArticleNumber'])) { + break; + } - // Break out if we couldn't find anything. - if ($iterator1++ >= $msgCount - 1 || $iterator2-- <= 0) { - break; - } - } - } + // Break out if we couldn't find anything. + if ($iterator1++ >= $msgCount - 1 || $iterator2-- <= 0) { + break; + } + } + } - /** - * Updates Blacklist Regex Timers in DB to reflect last usage - */ - protected function updateBlacklistUsage(): void - { - BinaryBlacklist::query()->whereIn('id', $this->_binaryBlacklistIdsToUpdate)->update(['last_activity' => new \DateTime('NOW')]); - $this->_binaryBlacklistIdsToUpdate = []; - } + /** + * Updates Blacklist Regex Timers in DB to reflect last usage. + */ + protected function updateBlacklistUsage(): void + { + BinaryBlacklist::query()->whereIn('id', $this->_binaryBlacklistIdsToUpdate)->update(['last_activity' => new \DateTime('NOW')]); + $this->_binaryBlacklistIdsToUpdate = []; + } - /** - * Outputs the initial header scan results after yEnc check and blacklist routines - */ - protected function outputHeaderInitial(): void - { - ColorCLI::doEcho( + /** + * Outputs the initial header scan results after yEnc check and blacklist routines. + */ + protected function outputHeaderInitial(): void + { + ColorCLI::doEcho( ColorCLI::primary( - 'Received ' . count($this->headersReceived) . - ' articles of ' . number_format($this->last - $this->first + 1) . ' requested, ' . - $this->headersBlackListed . ' blacklisted, ' . $this->notYEnc . ' not yEnc.' + 'Received '.count($this->headersReceived). + ' articles of '.number_format($this->last - $this->first + 1).' requested, '. + $this->headersBlackListed.' blacklisted, '.$this->notYEnc.' not yEnc.' ) ); - } + } - /** - * Outputs speed metrics of the scan function to CLI - */ - protected function outputHeaderDuration(): void - { - $currentMicroTime = microtime(true); - if ($this->_echoCLI) { - ColorCLI::doEcho( - ColorCLI::alternateOver($this->timeHeaders . 's') . - ColorCLI::primaryOver(' to download articles, ') . - ColorCLI::alternateOver($this->timeCleaning . 's') . - ColorCLI::primaryOver(' to process collections, ') . - ColorCLI::alternateOver($this->timeInsert . 's') . - ColorCLI::primaryOver(' to insert binaries/parts, ') . - ColorCLI::alternateOver(number_format($currentMicroTime - $this->startPR, 2) . 's') . - ColorCLI::primaryOver(' for part repair, ') . - ColorCLI::alternateOver(number_format($currentMicroTime - $this->startLoop, 2) . 's') . + /** + * Outputs speed metrics of the scan function to CLI. + */ + protected function outputHeaderDuration(): void + { + $currentMicroTime = microtime(true); + if ($this->_echoCLI) { + ColorCLI::doEcho( + ColorCLI::alternateOver($this->timeHeaders.'s'). + ColorCLI::primaryOver(' to download articles, '). + ColorCLI::alternateOver($this->timeCleaning.'s'). + ColorCLI::primaryOver(' to process collections, '). + ColorCLI::alternateOver($this->timeInsert.'s'). + ColorCLI::primaryOver(' to insert binaries/parts, '). + ColorCLI::alternateOver(number_format($currentMicroTime - $this->startPR, 2).'s'). + ColorCLI::primaryOver(' for part repair, '). + ColorCLI::alternateOver(number_format($currentMicroTime - $this->startLoop, 2).'s'). ColorCLI::primary(' total.') ); - } - } + } + } - /** - * If we failed to insert Collections/Binaries/Parts, rollback the transaction and add the parts to part repair. - * - * @param array $headers Array of headers containing sub-arrays with parts. - * - * @return array Array of article numbers to add to part repair. - * - * @access protected - */ - protected function _rollbackAddToPartRepair(array $headers): array - { - $headersNotInserted = []; - foreach ($headers as $header) { - foreach ($header as $file) { - $headersNotInserted[] = $file['Parts']['number']; - } - } - $this->_pdo->Rollback(); - return $headersNotInserted; - } + /** + * If we failed to insert Collections/Binaries/Parts, rollback the transaction and add the parts to part repair. + * + * @param array $headers Array of headers containing sub-arrays with parts. + * + * @return array Array of article numbers to add to part repair. + */ + protected function _rollbackAddToPartRepair(array $headers): array + { + $headersNotInserted = []; + foreach ($headers as $header) { + foreach ($header as $file) { + $headersNotInserted[] = $file['Parts']['number']; + } + } + $this->_pdo->Rollback(); - /** - * Attempt to get missing article headers. - * - * @param array|string $tables - * @param array $groupArr The info for this group from mysql. - * - * @return void - * @throws \Exception - */ - public function partRepair($groupArr, $tables = ''): void - { - $tableNames = $tables; + return $headersNotInserted; + } - if ($tableNames === '') { - $tableNames = $this->_groups->getCBPTableNames($groupArr['id']); - } - // Get all parts in partrepair table. - $missingParts = $this->_pdo->query( + /** + * Attempt to get missing article headers. + * + * @param array|string $tables + * @param array $groupArr The info for this group from mysql. + * + * @return void + * @throws \Exception + */ + public function partRepair($groupArr, $tables = ''): void + { + $tableNames = $tables; + + if ($tableNames === '') { + $tableNames = $this->_groups->getCBPTableNames($groupArr['id']); + } + // Get all parts in partrepair table. + $missingParts = $this->_pdo->query( sprintf(' SELECT * FROM %s WHERE groups_id = %d AND attempts < %d @@ -1167,61 +1163,59 @@ class Binaries ) ); - $missingCount = count($missingParts); - if ($missingCount > 0) { - if ($this->_echoCLI) { - ColorCLI::doEcho( + $missingCount = count($missingParts); + if ($missingCount > 0) { + if ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - 'Attempting to repair ' . - number_format($missingCount) . + 'Attempting to repair '. + number_format($missingCount). ' parts.' ), true ); - } + } - // Loop through each part to group into continuous ranges with a maximum range of messagebuffer/4. - $ranges = $partList = []; - $firstPart = $lastNum = $missingParts[0]['numberid']; + // Loop through each part to group into continuous ranges with a maximum range of messagebuffer/4. + $ranges = $partList = []; + $firstPart = $lastNum = $missingParts[0]['numberid']; - foreach ($missingParts as $part) { - if (($part['numberid'] - $firstPart) > ($this->messageBuffer / 4)) { - - $ranges[] = [ + foreach ($missingParts as $part) { + if (($part['numberid'] - $firstPart) > ($this->messageBuffer / 4)) { + $ranges[] = [ 'partfrom' => $firstPart, 'partto' => $lastNum, - 'partlist' => $partList + 'partlist' => $partList, ]; - $firstPart = $part['numberid']; - $partList = []; - } - $partList[] = $part['numberid']; - $lastNum = $part['numberid']; - } + $firstPart = $part['numberid']; + $partList = []; + } + $partList[] = $part['numberid']; + $lastNum = $part['numberid']; + } - $ranges[] = [ + $ranges[] = [ 'partfrom' => $firstPart, 'partto' => $lastNum, - 'partlist' => $partList + 'partlist' => $partList, ]; - // Download missing parts in ranges. - foreach ($ranges as $range) { + // Download missing parts in ranges. + foreach ($ranges as $range) { + $partFrom = $range['partfrom']; + $partTo = $range['partto']; + $partList = $range['partlist']; - $partFrom = $range['partfrom']; - $partTo = $range['partto']; - $partList = $range['partlist']; + if ($this->_echoCLI) { + echo chr(random_int(45, 46)).PHP_EOL; + } - if ($this->_echoCLI) { - echo chr(random_int(45, 46)) . PHP_EOL; - } + // Get article headers from newsgroup. + $this->scan($groupArr, $partFrom, $partTo, 'missed_parts', $partList); + } - // Get article headers from newsgroup. - $this->scan($groupArr, $partFrom, $partTo, 'missed_parts', $partList); - } - - // Calculate parts repaired - $result = $this->_pdo->queryOneRow( + // Calculate parts repaired + $result = $this->_pdo->queryOneRow( sprintf(' SELECT COUNT(id) AS num FROM %s @@ -1233,14 +1227,14 @@ class Binaries ) ); - $partsRepaired = 0; - if ($result !== false) { - $partsRepaired = ($missingCount - $result['num']); - } + $partsRepaired = 0; + if ($result !== false) { + $partsRepaired = ($missingCount - $result['num']); + } - // Update attempts on remaining parts for active group - if (isset($missingParts[$missingCount - 1]['id'])) { - $this->_pdo->queryExec( + // Update attempts on remaining parts for active group + if (isset($missingParts[$missingCount - 1]['id'])) { + $this->_pdo->queryExec( sprintf(' UPDATE %s SET attempts = attempts + 1 @@ -1251,21 +1245,21 @@ class Binaries $missingParts[$missingCount - 1]['numberid'] ) ); - } + } - if ($this->_echoCLI) { - ColorCLI::doEcho( + if ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - PHP_EOL . - number_format($partsRepaired) . + PHP_EOL. + number_format($partsRepaired). ' parts repaired.' ), true ); - } - } + } + } - // Remove articles that we cant fetch after x attempts. - $this->_pdo->queryExec( + // Remove articles that we cant fetch after x attempts. + $this->_pdo->queryExec( sprintf( 'DELETE FROM %s WHERE attempts >= %d AND groups_id = %d', $tableNames['prname'], @@ -1273,34 +1267,34 @@ class Binaries $groupArr['id'] ) ); - } + } - /** - * Returns unix time for an article number. - * - * @param int $post The article number to get the time from. - * @param array $groupData Usenet group info from NNTP selectGroup method. - * - * @return int Timestamp. - * @throws \Exception - */ - public function postdate($post, array $groupData): int - { - // Set table names - $groupID = $this->_groups->getIDByName($groupData['group']); - $group = []; - if ($groupID !== '') { - $group = $this->_groups->getCBPTableNames($groupID); - } + /** + * Returns unix time for an article number. + * + * @param int $post The article number to get the time from. + * @param array $groupData Usenet group info from NNTP selectGroup method. + * + * @return int Timestamp. + * @throws \Exception + */ + public function postdate($post, array $groupData): int + { + // Set table names + $groupID = $this->_groups->getIDByName($groupData['group']); + $group = []; + if ($groupID !== '') { + $group = $this->_groups->getCBPTableNames($groupID); + } - $currentPost = $post; + $currentPost = $post; - $attempts = $date = 0; - do { - // Try to get the article date locally first. - if ($groupID !== '') { - // Try to get locally. - $local = $this->_pdo->queryOneRow( + $attempts = $date = 0; + do { + // Try to get the article date locally first. + if ($groupID !== '') { + // Try to get locally. + $local = $this->_pdo->queryOneRow( sprintf(' SELECT c.date AS date FROM %s c @@ -1313,319 +1307,322 @@ class Binaries $currentPost ) ); - if ($local !== false) { - $date = $local['date']; - break; - } - } + if ($local !== false) { + $date = $local['date']; + break; + } + } - // If we could not find it locally, try usenet. - $header = $this->_nntp->getXOVER($currentPost); - if (!$this->_nntp->isError($header)) { - // Check if the date is set. - if (isset($header[0]['Date']) && strlen($header[0]['Date']) > 0) { - $date = $header[0]['Date']; - break; - } - } + // If we could not find it locally, try usenet. + $header = $this->_nntp->getXOVER($currentPost); + if (! $this->_nntp->isError($header)) { + // Check if the date is set. + if (isset($header[0]['Date']) && strlen($header[0]['Date']) > 0) { + $date = $header[0]['Date']; + break; + } + } - // Try to get a different article number. - if (abs($currentPost - $groupData['first']) > abs($groupData['last'] - $currentPost)) { - $tempPost = round($currentPost / (random_int(1005, 1012) / 1000), 0, PHP_ROUND_HALF_UP); - if ($tempPost < $groupData['first']) { - $tempPost = $groupData['first']; - } - } else { - $tempPost = round((random_int(1005, 1012) / 1000) * $currentPost, 0, PHP_ROUND_HALF_UP); - if ($tempPost > $groupData['last']) { - $tempPost = $groupData['last']; - } - } - // If we got the same article number as last time, give up. - if ($tempPost === $currentPost) { - break; - } - $currentPost = $tempPost; + // Try to get a different article number. + if (abs($currentPost - $groupData['first']) > abs($groupData['last'] - $currentPost)) { + $tempPost = round($currentPost / (random_int(1005, 1012) / 1000), 0, PHP_ROUND_HALF_UP); + if ($tempPost < $groupData['first']) { + $tempPost = $groupData['first']; + } + } else { + $tempPost = round((random_int(1005, 1012) / 1000) * $currentPost, 0, PHP_ROUND_HALF_UP); + if ($tempPost > $groupData['last']) { + $tempPost = $groupData['last']; + } + } + // If we got the same article number as last time, give up. + if ($tempPost === $currentPost) { + break; + } + $currentPost = $tempPost; - if ($this->_debug) { - ColorCLI::doEcho(ColorCLI::debug('Postdate retried ' . $attempts . ' time(s).')); - } - } while ($attempts++ <= 20); + if ($this->_debug) { + ColorCLI::doEcho(ColorCLI::debug('Postdate retried '.$attempts.' time(s).')); + } + } while ($attempts++ <= 20); - // If we didn't get a date, set it to now. - if (!$date) { - $date = time(); - } else { - $date = strtotime($date); - } + // If we didn't get a date, set it to now. + if (! $date) { + $date = time(); + } else { + $date = strtotime($date); + } - if ($this->_debug) { - $this->_debugging->log( + if ($this->_debug) { + $this->_debugging->log( __CLASS__, __FUNCTION__, - 'Article (' . - $post . - "'s) date is (" . - $date . - ') (' . - $this->daysOld($date) . + 'Article ('. + $post. + "'s) date is (". + $date. + ') ('. + $this->daysOld($date). ' days old)', Logger::LOG_INFO ); - } + } - return $date; - } + return $date; + } - /** - * Returns article number based on # of days. - * - * @param int $days How many days back we want to go. - * @param array $data Group data from usenet. - * - * @return string - * @throws \Exception - */ - public function daytopost($days, $data): string - { - $goalTime = time() - (86400 * $days); - // The time we want = current unix time (ex. 1395699114) - minus 86400 (seconds in a day) - // times days wanted. (ie 1395699114 - 2592000 (30days)) = 1393107114 + /** + * Returns article number based on # of days. + * + * @param int $days How many days back we want to go. + * @param array $data Group data from usenet. + * + * @return string + * @throws \Exception + */ + public function daytopost($days, $data): string + { + $goalTime = time() - (86400 * $days); + // The time we want = current unix time (ex. 1395699114) - minus 86400 (seconds in a day) + // times days wanted. (ie 1395699114 - 2592000 (30days)) = 1393107114 - // The servers oldest date. - $firstDate = $this->postdate($data['first'], $data); - if ($goalTime < $firstDate) { - // If the date we want is older than the oldest date in the group return the groups oldest article. - return $data['first']; - } + // The servers oldest date. + $firstDate = $this->postdate($data['first'], $data); + if ($goalTime < $firstDate) { + // If the date we want is older than the oldest date in the group return the groups oldest article. + return $data['first']; + } - // The servers newest date. - $lastDate = $this->postdate($data['last'], $data); - if ($goalTime > $lastDate) { - // If the date we want is newer than the groups newest date, return the groups newest article. - return $data['last']; - } + // The servers newest date. + $lastDate = $this->postdate($data['last'], $data); + if ($goalTime > $lastDate) { + // If the date we want is newer than the groups newest date, return the groups newest article. + return $data['last']; + } - if ($this->_echoCLI) { - ColorCLI::doEcho( + if ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - 'Searching for an approximate article number for group ' . $data['group'] . ' ' . $days . ' days back.' + 'Searching for an approximate article number for group '.$data['group'].' '.$days.' days back.' ) ); - } + } - // Pick the middle to start with - $wantedArticle = round(($data['last'] + $data['first']) / 2); - $aMax = $data['last']; - $aMin = $data['first']; - $reallyOldArticle = $oldArticle = $articleTime = null; + // Pick the middle to start with + $wantedArticle = round(($data['last'] + $data['first']) / 2); + $aMax = $data['last']; + $aMin = $data['first']; + $reallyOldArticle = $oldArticle = $articleTime = null; - while (true) { - // Article exists outside of available range, this shouldn't happen - if ($wantedArticle <= $data['first'] || $wantedArticle >= $data['last']) { - break; - } + while (true) { + // Article exists outside of available range, this shouldn't happen + if ($wantedArticle <= $data['first'] || $wantedArticle >= $data['last']) { + break; + } - // Keep a note of the last articles we checked - $reallyOldArticle = $oldArticle; - $oldArticle = $wantedArticle; + // Keep a note of the last articles we checked + $reallyOldArticle = $oldArticle; + $oldArticle = $wantedArticle; - // Get the date of this article - $articleTime = $this->postdate($wantedArticle, $data); + // Get the date of this article + $articleTime = $this->postdate($wantedArticle, $data); - // Article doesn't exist, start again with something random - if (!$articleTime) { - $wantedArticle = random_int($aMin, $aMax); - $articleTime = $this->postdate($wantedArticle, $data); - } + // Article doesn't exist, start again with something random + if (! $articleTime) { + $wantedArticle = random_int($aMin, $aMax); + $articleTime = $this->postdate($wantedArticle, $data); + } - if ($articleTime < $goalTime) { - // Article is older than we want - $aMin = $oldArticle; - $wantedArticle = round(($aMax + $oldArticle) / 2); - if ($this->_echoCLI) { - echo '-'; - } - } else if ($articleTime > $goalTime) { - // Article is newer than we want - $aMax = $oldArticle; - $wantedArticle = round(($aMin + $oldArticle) / 2); - if ($this->_echoCLI) { - echo '+'; - } - } else if ($articleTime === $goalTime) { - // Exact match. We did it! (this will likely never happen though) - break; - } + if ($articleTime < $goalTime) { + // Article is older than we want + $aMin = $oldArticle; + $wantedArticle = round(($aMax + $oldArticle) / 2); + if ($this->_echoCLI) { + echo '-'; + } + } elseif ($articleTime > $goalTime) { + // Article is newer than we want + $aMax = $oldArticle; + $wantedArticle = round(($aMin + $oldArticle) / 2); + if ($this->_echoCLI) { + echo '+'; + } + } elseif ($articleTime === $goalTime) { + // Exact match. We did it! (this will likely never happen though) + break; + } - // We seem to be flip-flopping between 2 articles, assume we're out of articles to check. - // End on an article more recent than our oldest so that we don't miss any releases. - if ($reallyOldArticle === $wantedArticle && ($goalTime - $articleTime) <= 0) { - break; - } - } + // We seem to be flip-flopping between 2 articles, assume we're out of articles to check. + // End on an article more recent than our oldest so that we don't miss any releases. + if ($reallyOldArticle === $wantedArticle && ($goalTime - $articleTime) <= 0) { + break; + } + } - $wantedArticle = (int)$wantedArticle; - if ($this->_echoCLI) { - ColorCLI::doEcho( + $wantedArticle = (int) $wantedArticle; + if ($this->_echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - PHP_EOL . 'Found article #' . $wantedArticle . ' which has a date of ' . date('r', $articleTime) . - ', vs wanted date of ' . date('r', $goalTime) . '. Difference from goal is ' . round(($goalTime - $articleTime) / 60 / 60 / 24, 1) . ' days.' + PHP_EOL.'Found article #'.$wantedArticle.' which has a date of '.date('r', $articleTime). + ', vs wanted date of '.date('r', $goalTime).'. Difference from goal is '.round(($goalTime - $articleTime) / 60 / 60 / 24, 1).' days.' ) ); - } + } - return $wantedArticle; - } + return $wantedArticle; + } - /** - * Convert unix time to days ago. - * - * @param int $timestamp unix time - * - * @return float - */ - private function daysOld($timestamp) - { - return round((time() - (!is_numeric($timestamp) ? strtotime($timestamp) : $timestamp)) / 86400, 1); - } + /** + * Convert unix time to days ago. + * + * @param int $timestamp unix time + * + * @return float + */ + private function daysOld($timestamp) + { + return round((time() - (! is_numeric($timestamp) ? strtotime($timestamp) : $timestamp)) / 86400, 1); + } - /** - * Add article numbers from missing headers to DB. - * - * @param array $numbers The article numbers of the missing headers. - * @param string $tableName Name of the partrepair table to insert into. - * @param int $groupID The ID of this groups. - * - * @return bool - */ - private function addMissingParts($numbers, $tableName, $groupID): bool - { - $insertStr = 'INSERT INTO ' . $tableName . ' (numberid, groups_id) VALUES '; - foreach ($numbers as $number) { - $insertStr .= '(' . $number . ',' . $groupID . '),'; - } - return $this->_pdo->queryInsert(rtrim($insertStr, ',') . ' ON DUPLICATE KEY UPDATE attempts=attempts+1'); - } + /** + * Add article numbers from missing headers to DB. + * + * @param array $numbers The article numbers of the missing headers. + * @param string $tableName Name of the partrepair table to insert into. + * @param int $groupID The ID of this groups. + * + * @return bool + */ + private function addMissingParts($numbers, $tableName, $groupID): bool + { + $insertStr = 'INSERT INTO '.$tableName.' (numberid, groups_id) VALUES '; + foreach ($numbers as $number) { + $insertStr .= '('.$number.','.$groupID.'),'; + } - /** - * Clean up part repair table. - * - * @param array $numbers The article numbers. - * @param string $tableName Name of the part repair table to work on. - * @param int $groupID The ID of the group. - * - * @return void - */ - private function removeRepairedParts(array $numbers, $tableName, $groupID): void - { - $sql = 'DELETE FROM ' . $tableName . ' WHERE numberid in ('; - foreach ($numbers as $number) { - $sql .= $number . ','; - } - $this->_pdo->queryExec(rtrim($sql, ',') . ') AND groups_id = ' . $groupID); - } + return $this->_pdo->queryInsert(rtrim($insertStr, ',').' ON DUPLICATE KEY UPDATE attempts=attempts+1'); + } - /** - * Are white or black lists loaded for a group name? - * @var array - */ - protected $_listsFound = []; + /** + * Clean up part repair table. + * + * @param array $numbers The article numbers. + * @param string $tableName Name of the part repair table to work on. + * @param int $groupID The ID of the group. + * + * @return void + */ + private function removeRepairedParts(array $numbers, $tableName, $groupID): void + { + $sql = 'DELETE FROM '.$tableName.' WHERE numberid in ('; + foreach ($numbers as $number) { + $sql .= $number.','; + } + $this->_pdo->queryExec(rtrim($sql, ',').') AND groups_id = '.$groupID); + } - /** - * Get blacklist and cache it. Return if already cached. - * - * @param string $groupName - * - * @return void - */ - protected function _retrieveBlackList($groupName): void - { - if (!isset($this->blackList[$groupName])) { - $this->blackList[$groupName] = $this->getBlacklist(true, self::OPTYPE_BLACKLIST, $groupName, true); - } - if (!isset($this->whiteList[$groupName])) { - $this->whiteList[$groupName] = $this->getBlacklist(true, self::OPTYPE_WHITELIST, $groupName, true); - } - $this->_listsFound[$groupName] = ($this->blackList[$groupName] || $this->whiteList[$groupName]); - } + /** + * Are white or black lists loaded for a group name? + * @var array + */ + protected $_listsFound = []; - /** - * Check if an article is blacklisted. - * - * @param array $msg The article header (OVER format). - * @param string $groupName The group name. - * - * @return bool - */ - public function isBlackListed($msg, $groupName): bool - { - if (!isset($this->_listsFound[$groupName])) { - $this->_retrieveBlackList($groupName); - } - if (!$this->_listsFound[$groupName]) { - return false; - } + /** + * Get blacklist and cache it. Return if already cached. + * + * @param string $groupName + * + * @return void + */ + protected function _retrieveBlackList($groupName): void + { + if (! isset($this->blackList[$groupName])) { + $this->blackList[$groupName] = $this->getBlacklist(true, self::OPTYPE_BLACKLIST, $groupName, true); + } + if (! isset($this->whiteList[$groupName])) { + $this->whiteList[$groupName] = $this->getBlacklist(true, self::OPTYPE_WHITELIST, $groupName, true); + } + $this->_listsFound[$groupName] = ($this->blackList[$groupName] || $this->whiteList[$groupName]); + } - $blackListed = false; + /** + * Check if an article is blacklisted. + * + * @param array $msg The article header (OVER format). + * @param string $groupName The group name. + * + * @return bool + */ + public function isBlackListed($msg, $groupName): bool + { + if (! isset($this->_listsFound[$groupName])) { + $this->_retrieveBlackList($groupName); + } + if (! $this->_listsFound[$groupName]) { + return false; + } - $field = [ + $blackListed = false; + + $field = [ self::BLACKLIST_FIELD_SUBJECT => $msg['Subject'], self::BLACKLIST_FIELD_FROM => $msg['From'], - self::BLACKLIST_FIELD_MESSAGEID => $msg['Message-ID'] + self::BLACKLIST_FIELD_MESSAGEID => $msg['Message-ID'], ]; - // Try white lists first. - if ($this->whiteList[$groupName]) { - // There are white lists for this group, so anything that doesn't match a white list should be considered black listed. - $blackListed = true; - foreach ($this->whiteList[$groupName] as $whiteList) { - if (preg_match('/' . $whiteList['regex'] . '/i', $field[$whiteList['msgcol']])) { - // This field matched a white list, so it might not be black listed. - $blackListed = false; - $this->_binaryBlacklistIdsToUpdate[$whiteList['id']] = $whiteList['id']; - break; - } - } - } + // Try white lists first. + if ($this->whiteList[$groupName]) { + // There are white lists for this group, so anything that doesn't match a white list should be considered black listed. + $blackListed = true; + foreach ($this->whiteList[$groupName] as $whiteList) { + if (preg_match('/'.$whiteList['regex'].'/i', $field[$whiteList['msgcol']])) { + // This field matched a white list, so it might not be black listed. + $blackListed = false; + $this->_binaryBlacklistIdsToUpdate[$whiteList['id']] = $whiteList['id']; + break; + } + } + } - // Check if the field is black listed. - if (!$blackListed && $this->blackList[$groupName]) { - foreach ($this->blackList[$groupName] as $blackList) { - if (preg_match('/' . $blackList['regex'] . '/i', $field[$blackList['msgcol']])) { - $blackListed = true; - $this->_binaryBlacklistIdsToUpdate[$blackList['id']] = $blackList['id']; - break; - } - } - } - return $blackListed; - } + // Check if the field is black listed. + if (! $blackListed && $this->blackList[$groupName]) { + foreach ($this->blackList[$groupName] as $blackList) { + if (preg_match('/'.$blackList['regex'].'/i', $field[$blackList['msgcol']])) { + $blackListed = true; + $this->_binaryBlacklistIdsToUpdate[$blackList['id']] = $blackList['id']; + break; + } + } + } - /** - * Return all blacklists. - * - * @param bool $activeOnly Only display active blacklists ? - * @param int|string $opType Optional, get white or black lists (use Binaries constants). - * @param string $groupName Optional, group. - * @param bool $groupRegex Optional Join groups / binaryblacklist using regexp for equals. - * - * @return array - */ - public function getBlacklist($activeOnly = true, $opType = -1, $groupName = '', $groupRegex = false): array - { - switch ($opType) { + return $blackListed; + } + + /** + * Return all blacklists. + * + * @param bool $activeOnly Only display active blacklists ? + * @param int|string $opType Optional, get white or black lists (use Binaries constants). + * @param string $groupName Optional, group. + * @param bool $groupRegex Optional Join groups / binaryblacklist using regexp for equals. + * + * @return array + */ + public function getBlacklist($activeOnly = true, $opType = -1, $groupName = '', $groupRegex = false): array + { + switch ($opType) { case self::OPTYPE_BLACKLIST: - $opType = 'AND bb.optype = ' . self::OPTYPE_BLACKLIST; + $opType = 'AND bb.optype = '.self::OPTYPE_BLACKLIST; break; case self::OPTYPE_WHITELIST: - $opType = 'AND bb.optype = ' . self::OPTYPE_WHITELIST; + $opType = 'AND bb.optype = '.self::OPTYPE_WHITELIST; break; default: $opType = ''; break; } - return $this->_pdo->query( + + return $this->_pdo->query( sprintf(' SELECT bb.id, bb.optype, bb.status, bb.description, @@ -1638,155 +1635,152 @@ class Binaries ($groupRegex ? 'REGEXP' : '='), ($activeOnly ? 'AND bb.status = 1' : ''), $opType, - ($groupName ? ('AND g.name REGEXP ' . $this->_pdo->escapeString($groupName)) : '') + ($groupName ? ('AND g.name REGEXP '.$this->_pdo->escapeString($groupName)) : '') ) ); - } + } - /** - * Return the specified blacklist. - * - * @param int $id The blacklist ID. - * - * @return \Illuminate\Database\Eloquent\Model|null|static - */ - public function getBlacklistByID($id) - { - return BinaryBlacklist::query()->where('id', $id)->first(); - } + /** + * Return the specified blacklist. + * + * @param int $id The blacklist ID. + * + * @return \Illuminate\Database\Eloquent\Model|null|static + */ + public function getBlacklistByID($id) + { + return BinaryBlacklist::query()->where('id', $id)->first(); + } - /** - * Delete a blacklist. - * - * @param int $id The ID of the blacklist. - * - */ - public function deleteBlacklist($id): void - { - BinaryBlacklist::query()->where('id', $id)->delete(); - } + /** + * Delete a blacklist. + * + * @param int $id The ID of the blacklist. + */ + public function deleteBlacklist($id): void + { + BinaryBlacklist::query()->where('id', $id)->delete(); + } - /** - * @param $blacklistArray - */ - public function updateBlacklist($blacklistArray): void - { - BinaryBlacklist::query()->where('id', $blacklistArray['id'])->update( + /** + * @param $blacklistArray + */ + public function updateBlacklist($blacklistArray): void + { + BinaryBlacklist::query()->where('id', $blacklistArray['id'])->update( [ 'groupname' => $blacklistArray['groupname'] === '' ? 'null' : preg_replace('/a\.b\./i', 'alt.binaries.', $blacklistArray['groupname']), 'regex' => $blacklistArray['regex'], 'status' => $blacklistArray['status'], 'description' => $blacklistArray['description'], 'optype' => $blacklistArray['optype'], - 'msgcol' => $blacklistArray['msgcol'] + 'msgcol' => $blacklistArray['msgcol'], ] ); - } + } - /** - * Adds a new blacklist from binary blacklist edit admin web page. - * - * @param array $blacklistArray - * - */ - public function addBlacklist($blacklistArray): void - { - BinaryBlacklist::query()->insert( + /** + * Adds a new blacklist from binary blacklist edit admin web page. + * + * @param array $blacklistArray + */ + public function addBlacklist($blacklistArray): void + { + BinaryBlacklist::query()->insert( [ 'groupname' => $blacklistArray['groupname'] === '' ? 'null' : preg_replace('/a\.b\./i', 'alt.binaries.', $blacklistArray['groupname']), 'regex' => $blacklistArray['regex'], 'status' => $blacklistArray['status'], 'description' => $blacklistArray['description'], 'optype' => $blacklistArray['optype'], - 'msgcol' => $blacklistArray['msgcol'] + 'msgcol' => $blacklistArray['msgcol'], ] ); - } + } - /** - * Delete Collections/Binaries/Parts for a Collection ID. - * - * @param int $collectionID Collections table ID - * - * @note A trigger automatically deletes the parts/binaries. - * - * @return void - */ - public function delete($collectionID): void - { - $this->_pdo->queryExec(sprintf('DELETE FROM collections WHERE id = %d', $collectionID)); - } + /** + * Delete Collections/Binaries/Parts for a Collection ID. + * + * @param int $collectionID Collections table ID + * + * @note A trigger automatically deletes the parts/binaries. + * + * @return void + */ + public function delete($collectionID): void + { + $this->_pdo->queryExec(sprintf('DELETE FROM collections WHERE id = %d', $collectionID)); + } - /** - * Delete all Collections/Binaries/Parts for a group ID. - * - * @param int $groupID The ID of the group. - * - * @note A trigger automatically deletes the parts/binaries. - * - * @return void - */ - public function purgeGroup($groupID): void - { - $this->_pdo->queryExec(sprintf('DELETE c FROM collections c WHERE c.groups_id = %d', $groupID)); - } + /** + * Delete all Collections/Binaries/Parts for a group ID. + * + * @param int $groupID The ID of the group. + * + * @note A trigger automatically deletes the parts/binaries. + * + * @return void + */ + public function purgeGroup($groupID): void + { + $this->_pdo->queryExec(sprintf('DELETE c FROM collections c WHERE c.groups_id = %d', $groupID)); + } - /** - * Log / Echo message. - * - * @param string $message Message to log. - * @param string $method Method that called this. - * @param int $level Logger severity level constant. - * @param string $color ColorCLI method name. - */ - private function log($message, $method, $level, $color): void - { - if ($this->_echoCLI) { - ColorCLI::doEcho( - ColorCLI::$color($message . ' [' . __CLASS__ . "::$method]"), true + /** + * Log / Echo message. + * + * @param string $message Message to log. + * @param string $method Method that called this. + * @param int $level Logger severity level constant. + * @param string $color ColorCLI method name. + */ + private function log($message, $method, $level, $color): void + { + if ($this->_echoCLI) { + ColorCLI::doEcho( + ColorCLI::$color($message.' ['.__CLASS__."::$method]"), true ); - } + } - if ($this->_debug) { - $this->_debugging->log(__CLASS__, $method, $message, $level); - } - } + if ($this->_debug) { + $this->_debugging->log(__CLASS__, $method, $message, $level); + } + } - /** - * Check if we should ignore the file count and return true or false. - * - * @param string $groupName - * @param string $subject - * - * @return bool - * @access protected - * - */ - protected function _ignoreFileCount($groupName, $subject): bool - { - $ignore = false; - switch ($groupName) { + /** + * Check if we should ignore the file count and return true or false. + * + * @param string $groupName + * @param string $subject + * + * @return bool + */ + protected function _ignoreFileCount($groupName, $subject): bool + { + $ignore = false; + switch ($groupName) { case 'alt.binaries.erotica': if (preg_match('/^\[\d+\]-\[FULL\]-\[#a\.b\.erotica@EFNet\]-\[ \d{2,3}_/', $subject)) { - $ignore = true; + $ignore = true; } break; } - return $ignore; - } - /** - * Returns all multigroup poster entries from the database - * - * @return array - */ - protected function getMultiGroupPosters(): array - { - return $this->_pdo->query(' + return $ignore; + } + + /** + * Returns all multigroup poster entries from the database. + * + * @return array + */ + protected function getMultiGroupPosters(): array + { + return $this->_pdo->query(' SELECT poster FROM multigroup_posters', true, NN_CACHE_EXPIRY_SHORT ); - } + } } diff --git a/nntmux/Books.php b/nntmux/Books.php index 0437eb165..0173999d4 100755 --- a/nntmux/Books.php +++ b/nntmux/Books.php @@ -1,182 +1,183 @@ <?php + namespace nntmux; -use ApaiIO\Request\GuzzleRequest; -use ApaiIO\ResponseTransformer\XmlToSimpleXmlObject; +use nntmux\db\DB; +use ApaiIO\ApaiIO; +use GuzzleHttp\Client; use App\Models\BookInfo; use App\Models\Settings; -use GuzzleHttp\Client; -use nntmux\db\DB; -use ApaiIO\Configuration\GenericConfiguration; use ApaiIO\Operations\Search; -use ApaiIO\ApaiIO; +use ApaiIO\Request\GuzzleRequest; +use ApaiIO\Configuration\GenericConfiguration; +use ApaiIO\ResponseTransformer\XmlToSimpleXmlObject; /* * Class for processing book info. */ class Books { - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var bool - */ - public $echooutput; + /** + * @var bool + */ + public $echooutput; - /** - * @var array|bool|string - */ - public $pubkey; + /** + * @var array|bool|string + */ + public $pubkey; - /** - * @var array|bool|string - */ - public $privkey; + /** + * @var array|bool|string + */ + public $privkey; - /** - * @var array|bool|string - */ - public $asstag; + /** + * @var array|bool|string + */ + public $asstag; - /** - * @var array|bool|int|string - */ - public $bookqty; + /** + * @var array|bool|int|string + */ + public $bookqty; - /** - * @var array|bool|int|string - */ - public $sleeptime; + /** + * @var array|bool|int|string + */ + public $sleeptime; - /** - * @var string - */ - public $imgSavePath; + /** + * @var string + */ + public $imgSavePath; - /** - * @var array|bool|int|string - */ - public $bookreqids; + /** + * @var array|bool|int|string + */ + public $bookreqids; - /** - * @var string - */ - public $renamed; + /** + * @var string + */ + public $renamed; - /** - * Store names of failed Amazon lookup items - * @var array - */ - public $failCache; + /** + * Store names of failed Amazon lookup items. + * @var array + */ + public $failCache; - /** - * @param array $options Class instances / Echo to cli. - * - * @throws \Exception - */ - public function __construct(array $options =[]) - { - $defaults = [ + /** + * @param array $options Class instances / Echo to cli. + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->pubkey = Settings::value('APIs..amazonpubkey'); - $this->privkey = Settings::value('APIs..amazonprivkey'); - $this->asstag = Settings::value('APIs..amazonassociatetag'); - $this->bookqty = Settings::value('..maxbooksprocessed') !== '' ? Settings::value('..maxbooksprocessed') : 300; - $this->sleeptime = Settings::value('..amazonsleep') !== '' ? Settings::value('..amazonsleep') : 1000; - $this->imgSavePath = NN_COVERS . 'book' . DS; - $result = Settings::value('..book_reqids'); - $this->bookreqids = empty($result) ? Category::BOOKS_EBOOK : $result; - $this->renamed = ''; - if ((int)Settings::value('..lookupbooks') === 2) { - $this->renamed = 'AND isrenamed = 1'; - } + $this->pubkey = Settings::value('APIs..amazonpubkey'); + $this->privkey = Settings::value('APIs..amazonprivkey'); + $this->asstag = Settings::value('APIs..amazonassociatetag'); + $this->bookqty = Settings::value('..maxbooksprocessed') !== '' ? Settings::value('..maxbooksprocessed') : 300; + $this->sleeptime = Settings::value('..amazonsleep') !== '' ? Settings::value('..amazonsleep') : 1000; + $this->imgSavePath = NN_COVERS.'book'.DS; + $result = Settings::value('..book_reqids'); + $this->bookreqids = empty($result) ? Category::BOOKS_EBOOK : $result; + $this->renamed = ''; + if ((int) Settings::value('..lookupbooks') === 2) { + $this->renamed = 'AND isrenamed = 1'; + } - $this->failCache = []; - } + $this->failCache = []; + } - /** - * @param $id - * - * @return \Illuminate\Database\Eloquent\Model|null|static - */ - public function getBookInfo($id) - { - return BookInfo::query()->where('id', $id)->first(); - } + /** + * @param $id + * + * @return \Illuminate\Database\Eloquent\Model|null|static + */ + public function getBookInfo($id) + { + return BookInfo::query()->where('id', $id)->first(); + } - /** - * @param $author - * @param $title - * - * @return array|bool - */ - public function getBookInfoByName($author, $title) - { - $pdo = $this->pdo; + /** + * @param $author + * @param $title + * + * @return array|bool + */ + public function getBookInfoByName($author, $title) + { + $pdo = $this->pdo; - //only used to get a count of words - $searchwords = $searchsql = ''; - $title = preg_replace('/( - | -|\(.+\)|\(|\))/', ' ', $title); - $title = preg_replace('/[^\w ]+/', '', $title); - $title = trim(preg_replace('/\s\s+/i', ' ', $title)); - $title = trim($title); - $words = explode(' ', $title); + //only used to get a count of words + $searchwords = $searchsql = ''; + $title = preg_replace('/( - | -|\(.+\)|\(|\))/', ' ', $title); + $title = preg_replace('/[^\w ]+/', '', $title); + $title = trim(preg_replace('/\s\s+/i', ' ', $title)); + $title = trim($title); + $words = explode(' ', $title); - foreach ($words as $word) { - $word = trim(rtrim(trim($word), '-')); - if ($word !== '' && $word !== '-') { - $word = '+' . $word; - $searchwords .= sprintf('%s ', $word); - } - } - $searchwords = trim($searchwords); - $searchsql .= sprintf(' MATCH(author, title) AGAINST(%s IN BOOLEAN MODE)', $pdo->escapeString($searchwords)); - return $pdo->queryOneRow(sprintf('SELECT * FROM bookinfo WHERE %s', $searchsql)); - } + foreach ($words as $word) { + $word = trim(rtrim(trim($word), '-')); + if ($word !== '' && $word !== '-') { + $word = '+'.$word; + $searchwords .= sprintf('%s ', $word); + } + } + $searchwords = trim($searchwords); + $searchsql .= sprintf(' MATCH(author, title) AGAINST(%s IN BOOLEAN MODE)', $pdo->escapeString($searchwords)); - /** - * @param $cat - * @param $start - * @param $num - * @param $orderby - * @param array $excludedcats - * - * @return array - * @throws \Exception - */ - public function getBookRange($cat, $start, $num, $orderby, array $excludedcats = []): array - { + return $pdo->queryOneRow(sprintf('SELECT * FROM bookinfo WHERE %s', $searchsql)); + } - $browseby = $this->getBrowseBy(); + /** + * @param $cat + * @param $start + * @param $num + * @param $orderby + * @param array $excludedcats + * + * @return array + * @throws \Exception + */ + public function getBookRange($cat, $start, $num, $orderby, array $excludedcats = []): array + { + $browseby = $this->getBrowseBy(); - $catsrch = ''; - if (count($cat) > 0 && $cat[0] !== -1) { - $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); - } + $catsrch = ''; + if (count($cat) > 0 && $cat[0] !== -1) { + $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); + } - $maxage = ''; - if ($maxage > 0) { - $maxage = sprintf(' AND r.postdate > NOW() - INTERVAL %d DAY ', $maxage); - } + $maxage = ''; + if ($maxage > 0) { + $maxage = sprintf(' AND r.postdate > NOW() - INTERVAL %d DAY ', $maxage); + } - $exccatlist = ''; - if (count($excludedcats) > 0) { - $exccatlist = ' AND r.categories_id NOT IN (' . implode(',', $excludedcats) . ')'; - } + $exccatlist = ''; + if (count($excludedcats) > 0) { + $exccatlist = ' AND r.categories_id NOT IN ('.implode(',', $excludedcats).')'; + } - $order = $this->getBookOrder($orderby); + $order = $this->getBookOrder($orderby); - $books = $this->pdo->queryCalc( + $books = $this->pdo->queryCalc( sprintf(" SELECT SQL_CALC_FOUND_ROWS boo.id, GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id @@ -196,20 +197,20 @@ class Books $exccatlist, $order[0], $order[1], - ($start === false ? '' : ' LIMIT ' . $num . ' OFFSET ' . $start) + ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start) ), true, NN_CACHE_EXPIRY_MEDIUM ); - $bookIDs = $releaseIDs = false; + $bookIDs = $releaseIDs = false; - if (is_array($books['result'])) { - foreach ($books['result'] AS $book => $id) { - $bookIDs[] = $id['id']; - $releaseIDs[] = $id['grp_release_id']; - } - } + if (is_array($books['result'])) { + foreach ($books['result'] as $book => $id) { + $bookIDs[] = $id['id']; + $releaseIDs[] = $id['grp_release_id']; + } + } - $sql = sprintf(" + $sql = sprintf(" SELECT GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id, GROUP_CONCAT(r.rarinnerfilecount ORDER BY r.postdate DESC SEPARATOR ',') as grp_rarinnerfilecount, @@ -245,24 +246,24 @@ class Books $order[0], $order[1] ); - $return = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - if (!empty($return)) { - $return[0]['_totalcount'] = $books['total'] ?? 0; - } - return $return; - } + $return = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); + if (! empty($return)) { + $return[0]['_totalcount'] = $books['total'] ?? 0; + } + return $return; + } - /** - * @param $orderby - * - * @return array - */ - public function getBookOrder($orderby): array - { - $order = ($orderby === '') ? 'r.postdate' : $orderby; - $orderArr = explode('_', $order); - switch ($orderArr[0]) { + /** + * @param $orderby + * + * @return array + */ + public function getBookOrder($orderby): array + { + $order = ($orderby === '') ? 'r.postdate' : $orderby; + $orderArr = explode('_', $order); + switch ($orderArr[0]) { case 'title': $orderfield = 'boo.title'; break; @@ -286,16 +287,17 @@ class Books $orderfield = 'r.postdate'; break; } - $ordersort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc'; - return array($orderfield, $ordersort); - } + $ordersort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc'; - /** - * @return array - */ - public function getBookOrdering(): array - { - return array( + return [$orderfield, $ordersort]; + } + + /** + * @return array + */ + public function getBookOrdering(): array + { + return [ 'title_asc', 'title_desc', 'posted_asc', @@ -309,94 +311,94 @@ class Books 'releasedate_asc', 'releasedate_desc', 'author_asc', - 'author_desc' - ); - } + 'author_desc', + ]; + } - /** - * @return array - */ - public function getBrowseByOptions(): array - { - return ['author' => 'author', 'title' => 'title']; - } + /** + * @return array + */ + public function getBrowseByOptions(): array + { + return ['author' => 'author', 'title' => 'title']; + } - /** - * @return string - */ - public function getBrowseBy(): string - { - $browseby = ' '; - $browsebyArr = $this->getBrowseByOptions(); - foreach ($browsebyArr as $bbk => $bbv) { - if (isset($_REQUEST[$bbk]) && !empty($_REQUEST[$bbk])) { - $bbs = stripslashes($_REQUEST[$bbk]); - $browseby .= 'AND boo.' . $bbv . ' ' . $this->pdo->likeString($bbs, true, true); - } - } - return $browseby; - } + /** + * @return string + */ + public function getBrowseBy(): string + { + $browseby = ' '; + $browsebyArr = $this->getBrowseByOptions(); + foreach ($browsebyArr as $bbk => $bbv) { + if (isset($_REQUEST[$bbk]) && ! empty($_REQUEST[$bbk])) { + $bbs = stripslashes($_REQUEST[$bbk]); + $browseby .= 'AND boo.'.$bbv.' '.$this->pdo->likeString($bbs, true, true); + } + } - /** - * @param $title - * - * @return bool|mixed - * @throws \Exception - */ - public function fetchAmazonProperties($title) - { - $conf = new GenericConfiguration(); - $client = new Client(); - $request = new GuzzleRequest($client); + return $browseby; + } - try { - $conf + /** + * @param $title + * + * @return bool|mixed + * @throws \Exception + */ + public function fetchAmazonProperties($title) + { + $conf = new GenericConfiguration(); + $client = new Client(); + $request = new GuzzleRequest($client); + + try { + $conf ->setCountry('com') ->setAccessKey($this->pubkey) ->setSecretKey($this->privkey) ->setAssociateTag($this->asstag) ->setRequest($request) ->setResponseTransformer(new XmlToSimpleXmlObject()); - } catch (\Exception $e) { - echo $e->getMessage(); - } + } catch (\Exception $e) { + echo $e->getMessage(); + } - $search = new Search(); - $search->setCategory('Books'); - $search->setKeywords($title); - $search->setResponseGroup(['Large']); + $search = new Search(); + $search->setCategory('Books'); + $search->setKeywords($title); + $search->setResponseGroup(['Large']); - $apaiIo = new ApaiIO($conf); + $apaiIo = new ApaiIO($conf); - $response = $apaiIo->runOperation($search); - if ($response === false) - { - throw new \RuntimeException('Could not connect to Amazon'); - } + $response = $apaiIo->runOperation($search); + if ($response === false) { + throw new \RuntimeException('Could not connect to Amazon'); + } - if (isset($response->Items->Item->ItemAttributes->Title)) - { - return $response; - } - return false; - } + if (isset($response->Items->Item->ItemAttributes->Title)) { + return $response; + } - /** - * Process book releases, 1 category at a time. - */ - public function processBookReleases(): void - { - $bookids =[]; - if (ctype_digit((string)$this->bookreqids)) { - $bookids[] = $this->bookreqids; - } else { - $bookids = explode(', ', $this->bookreqids); - } + return false; + } - $total = count($bookids); - if ($total > 0) { - for ($i = 0; $i < $total; $i++) { - $this->processBookReleasesHelper( + /** + * Process book releases, 1 category at a time. + */ + public function processBookReleases(): void + { + $bookids = []; + if (ctype_digit((string) $this->bookreqids)) { + $bookids[] = $this->bookreqids; + } else { + $bookids = explode(', ', $this->bookreqids); + } + + $total = count($bookids); + if ($total > 0) { + for ($i = 0; $i < $total; $i++) { + $this->processBookReleasesHelper( $this->pdo->queryDirect( sprintf(' SELECT searchname, id, categories_id @@ -408,229 +410,230 @@ class Books DESC LIMIT %d', $this->renamed, $bookids[$i], $this->bookqty) ), $bookids[$i] ); - } - } - } + } + } + } - /** - * Process book releases. - * - * @param \PDOStatement|bool $res Array containing unprocessed book SQL data set. - * @param int $categoryID The category id. - * - * @void - * @throws \Exception - */ - protected function processBookReleasesHelper($res, $categoryID): void - { - if ($res instanceof \Traversable && $res->rowCount() > 0) { - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::header("\nProcessing " . $res->rowCount() . ' book release(s) for categories id ' . $categoryID)); - } + /** + * Process book releases. + * + * @param \PDOStatement|bool $res Array containing unprocessed book SQL data set. + * @param int $categoryID The category id. + * + * @void + * @throws \Exception + */ + protected function processBookReleasesHelper($res, $categoryID): void + { + if ($res instanceof \Traversable && $res->rowCount() > 0) { + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::header("\nProcessing ".$res->rowCount().' book release(s) for categories id '.$categoryID)); + } - foreach ($res as $arr) { - $startTime = microtime(true); - $usedAmazon = false; - // audiobooks are also books and should be handled in an identical manor, even though it falls under a music category - if ($arr['categories_id'] === '3030') { - // audiobook - $bookInfo = $this->parseTitle($arr['searchname'], $arr['id'], 'audiobook'); - } else { - // ebook - $bookInfo = $this->parseTitle($arr['searchname'], $arr['id'], 'ebook'); - } + foreach ($res as $arr) { + $startTime = microtime(true); + $usedAmazon = false; + // audiobooks are also books and should be handled in an identical manor, even though it falls under a music category + if ($arr['categories_id'] === '3030') { + // audiobook + $bookInfo = $this->parseTitle($arr['searchname'], $arr['id'], 'audiobook'); + } else { + // ebook + $bookInfo = $this->parseTitle($arr['searchname'], $arr['id'], 'ebook'); + } - if ($bookInfo !== false) { - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::headerOver('Looking up: ') . ColorCLI::primary($bookInfo)); - } + if ($bookInfo !== false) { + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::headerOver('Looking up: ').ColorCLI::primary($bookInfo)); + } - // Do a local lookup first - $bookCheck = $this->getBookInfoByName('', $bookInfo); + // Do a local lookup first + $bookCheck = $this->getBookInfoByName('', $bookInfo); - if ($bookCheck === false && in_array($bookInfo, $this->failCache, false)) { - // Lookup recently failed, no point trying again - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::headerOver('Cached previous failure. Skipping.') . PHP_EOL); - } - $bookId = -2; - } else if ($bookCheck === false) { - $bookId = $this->updateBookInfo($bookInfo); - $usedAmazon = true; - if ($bookId === false) { - $bookId = -2; - $this->failCache[] = $bookInfo; - } - } else { - $bookId = $bookCheck['id']; - } + if ($bookCheck === false && in_array($bookInfo, $this->failCache, false)) { + // Lookup recently failed, no point trying again + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::headerOver('Cached previous failure. Skipping.').PHP_EOL); + } + $bookId = -2; + } elseif ($bookCheck === false) { + $bookId = $this->updateBookInfo($bookInfo); + $usedAmazon = true; + if ($bookId === false) { + $bookId = -2; + $this->failCache[] = $bookInfo; + } + } else { + $bookId = $bookCheck['id']; + } - // Update release. - $this->pdo->queryExec(sprintf('UPDATE releases SET bookinfo_id = %d WHERE id = %d', $bookId, $arr['id'])); - } else { // Could not parse release title. - $this->pdo->queryExec(sprintf('UPDATE releases SET bookinfo_id = %d WHERE id = %d', -2, $arr['id'])); - if ($this->echooutput) { - echo '.'; - } - } - // Sleep to not flood amazon. - $diff = floor((microtime(true) - $startTime) * 1000000); - if ($this->sleeptime * 1000 - $diff > 0 && $usedAmazon === true) { - usleep($this->sleeptime * 1000 - $diff); - } - } - } else if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::header('No book releases to process for categories id ' . $categoryID)); - } - } + // Update release. + $this->pdo->queryExec(sprintf('UPDATE releases SET bookinfo_id = %d WHERE id = %d', $bookId, $arr['id'])); + } else { // Could not parse release title. + $this->pdo->queryExec(sprintf('UPDATE releases SET bookinfo_id = %d WHERE id = %d', -2, $arr['id'])); + if ($this->echooutput) { + echo '.'; + } + } + // Sleep to not flood amazon. + $diff = floor((microtime(true) - $startTime) * 1000000); + if ($this->sleeptime * 1000 - $diff > 0 && $usedAmazon === true) { + usleep($this->sleeptime * 1000 - $diff); + } + } + } elseif ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::header('No book releases to process for categories id '.$categoryID)); + } + } - /** - * @param $release_name - * @param $releaseID - * @param $releasetype - * - * @return bool|string - */ - public function parseTitle($release_name, $releaseID, $releasetype) - { - $a = preg_replace('/\d{1,2} \d{1,2} \d{2,4}|(19|20)\d\d|anybody got .+?[a-z]\? |[-._ ](Novel|TIA)([-._ ]|$)|( |\.)HQ(-|\.| )|[\(\)\.\-_ ](AVI|AZW3?|DOC|EPUB|LIT|MOBI|NFO|RETAIL|(si)?PDF|RTF|TXT)[\)\]\.\-_ ](?![a-z0-9])|compleet|DAGSTiDNiNGEN|DiRFiX|\+ extra|r?e ?Books?([\.\-_ ]English|ers)?|azw3?|ePu(b|p)s?|html|mobi|^NEW[\.\-_ ]|PDF([\.\-_ ]English)?|Please post more|Post description|Proper|Repack(fix)?|[\.\-_ ](Chinese|English|French|German|Italian|Retail|Scan|Swedish)|^R4 |Repost|Skytwohigh|TIA!+|TruePDF|V413HAV|(would someone )?please (re)?post.+? "|with the authors name right/i', '', $release_name); - $b = preg_replace('/^(As Req |conversion |eq |Das neue Abenteuer \d+|Fixed version( ignore previous post)?|Full |Per Req As Found|(\s+)?R4 |REQ |revised |version |\d+(\s+)?$)|(COMPLETE|INTERNAL|RELOADED| (AZW3|eB|docx|ENG?|exe|FR|Fix|gnv64|MU|NIV|R\d\s+\d{1,2} \d{1,2}|R\d|Req|TTL|UC|v(\s+)?\d))(\s+)?$/i', '', $a); + /** + * @param $release_name + * @param $releaseID + * @param $releasetype + * + * @return bool|string + */ + public function parseTitle($release_name, $releaseID, $releasetype) + { + $a = preg_replace('/\d{1,2} \d{1,2} \d{2,4}|(19|20)\d\d|anybody got .+?[a-z]\? |[-._ ](Novel|TIA)([-._ ]|$)|( |\.)HQ(-|\.| )|[\(\)\.\-_ ](AVI|AZW3?|DOC|EPUB|LIT|MOBI|NFO|RETAIL|(si)?PDF|RTF|TXT)[\)\]\.\-_ ](?![a-z0-9])|compleet|DAGSTiDNiNGEN|DiRFiX|\+ extra|r?e ?Books?([\.\-_ ]English|ers)?|azw3?|ePu(b|p)s?|html|mobi|^NEW[\.\-_ ]|PDF([\.\-_ ]English)?|Please post more|Post description|Proper|Repack(fix)?|[\.\-_ ](Chinese|English|French|German|Italian|Retail|Scan|Swedish)|^R4 |Repost|Skytwohigh|TIA!+|TruePDF|V413HAV|(would someone )?please (re)?post.+? "|with the authors name right/i', '', $release_name); + $b = preg_replace('/^(As Req |conversion |eq |Das neue Abenteuer \d+|Fixed version( ignore previous post)?|Full |Per Req As Found|(\s+)?R4 |REQ |revised |version |\d+(\s+)?$)|(COMPLETE|INTERNAL|RELOADED| (AZW3|eB|docx|ENG?|exe|FR|Fix|gnv64|MU|NIV|R\d\s+\d{1,2} \d{1,2}|R\d|Req|TTL|UC|v(\s+)?\d))(\s+)?$/i', '', $a); - //remove book series from title as this gets more matches on amazon - $c = preg_replace('/ - \[.+\]|\[.+\]/', '', $b); + //remove book series from title as this gets more matches on amazon + $c = preg_replace('/ - \[.+\]|\[.+\]/', '', $b); - //remove any brackets left behind - $d = preg_replace('/(\(\)|\[\])/', '', $c); - $releasename = trim(preg_replace('/\s\s+/i', ' ', $d)); + //remove any brackets left behind + $d = preg_replace('/(\(\)|\[\])/', '', $c); + $releasename = trim(preg_replace('/\s\s+/i', ' ', $d)); - // the default existing type was ebook, this handles that in the same manor as before - if ($releasetype === 'ebook') { - if (preg_match('/^([a-z0-9] )+$|ArtofUsenet|ekiosk|(ebook|mobi).+collection|erotica|Full Video|ImwithJamie|linkoff org|Mega.+pack|^[a-z0-9]+ (?!((January|February|March|April|May|June|July|August|September|O(c|k)tober|November|De(c|z)ember)))[a-z]+( (ebooks?|The))?$|NY Times|(Book|Massive) Dump|Sexual/i', $releasename)) { - - if ($this->echooutput) { - ColorCLI::doEcho( - ColorCLI::headerOver('Changing category to misc books: ') . ColorCLI::primary($releasename) + // the default existing type was ebook, this handles that in the same manor as before + if ($releasetype === 'ebook') { + if (preg_match('/^([a-z0-9] )+$|ArtofUsenet|ekiosk|(ebook|mobi).+collection|erotica|Full Video|ImwithJamie|linkoff org|Mega.+pack|^[a-z0-9]+ (?!((January|February|March|April|May|June|July|August|September|O(c|k)tober|November|De(c|z)ember)))[a-z]+( (ebooks?|The))?$|NY Times|(Book|Massive) Dump|Sexual/i', $releasename)) { + if ($this->echooutput) { + ColorCLI::doEcho( + ColorCLI::headerOver('Changing category to misc books: ').ColorCLI::primary($releasename) ); - } - $this->pdo->queryExec(sprintf('UPDATE releases SET categories_id = %s WHERE id = %d', Category::BOOKS_UNKNOWN, $releaseID)); - return false; - } + } + $this->pdo->queryExec(sprintf('UPDATE releases SET categories_id = %s WHERE id = %d', Category::BOOKS_UNKNOWN, $releaseID)); - if (preg_match('/^([a-z0-9ü!]+ ){1,2}(N|Vol)?\d{1,4}(a|b|c)?$|^([a-z0-9]+ ){1,2}(Jan( |unar|$)|Feb( |ruary|$)|Mar( |ch|$)|Apr( |il|$)|May(?![a-z0-9])|Jun( |e|$)|Jul( |y|$)|Aug( |ust|$)|Sep( |tember|$)|O(c|k)t( |ober|$)|Nov( |ember|$)|De(c|z)( |ember|$))/ui', $releasename) && !preg_match('/Part \d+/i', $releasename)) { + return false; + } - if ($this->echooutput) { - ColorCLI::doEcho( - ColorCLI::headerOver('Changing category to magazines: ') . ColorCLI::primary($releasename) + if (preg_match('/^([a-z0-9ü!]+ ){1,2}(N|Vol)?\d{1,4}(a|b|c)?$|^([a-z0-9]+ ){1,2}(Jan( |unar|$)|Feb( |ruary|$)|Mar( |ch|$)|Apr( |il|$)|May(?![a-z0-9])|Jun( |e|$)|Jul( |y|$)|Aug( |ust|$)|Sep( |tember|$)|O(c|k)t( |ober|$)|Nov( |ember|$)|De(c|z)( |ember|$))/ui', $releasename) && ! preg_match('/Part \d+/i', $releasename)) { + if ($this->echooutput) { + ColorCLI::doEcho( + ColorCLI::headerOver('Changing category to magazines: ').ColorCLI::primary($releasename) ); - } - $this->pdo->queryExec(sprintf('UPDATE releases SET categories_id = %s WHERE id = %d', Category::BOOKS_MAGAZINES, $releaseID)); - return false; - } - if (!empty($releasename) && !preg_match('/^[a-z0-9]+$|^([0-9]+ ){1,}$|Part \d+/i', $releasename)) { - return $releasename; - } + } + $this->pdo->queryExec(sprintf('UPDATE releases SET categories_id = %s WHERE id = %d', Category::BOOKS_MAGAZINES, $releaseID)); - return false; - } - if ($releasetype === 'audiobook') { - if (!empty($releasename) && !preg_match('/^[a-z0-9]+$|^([0-9]+ ){1,}$|Part \d+/i', $releasename)) { - // we can skip category for audiobooks, since we already know it, so as long as the release name is valid return it so that it is postprocessed by amazon. In the future, determining the type of audiobook could be added (Lecture or book), since we can skip lookups on lectures, but for now handle them all the same way - return $releasename; - } - return false; - } + return false; + } + if (! empty($releasename) && ! preg_match('/^[a-z0-9]+$|^([0-9]+ ){1,}$|Part \d+/i', $releasename)) { + return $releasename; + } - return false; - } + return false; + } + if ($releasetype === 'audiobook') { + if (! empty($releasename) && ! preg_match('/^[a-z0-9]+$|^([0-9]+ ){1,}$|Part \d+/i', $releasename)) { + // we can skip category for audiobooks, since we already know it, so as long as the release name is valid return it so that it is postprocessed by amazon. In the future, determining the type of audiobook could be added (Lecture or book), since we can skip lookups on lectures, but for now handle them all the same way + return $releasename; + } - /** - * @param string $bookInfo - * @param null $amazdata - * - * @return false|int|string - * @throws \Exception - */ - public function updateBookInfo($bookInfo = '', $amazdata = null) - { - $ri = new ReleaseImage($this->pdo); + return false; + } - $book =[]; + return false; + } - $amaz = false; - if ($bookInfo !== '') { - $amaz = $this->fetchAmazonProperties($bookInfo); - } else if ($amazdata !== null) { - $amaz = $amazdata; - } + /** + * @param string $bookInfo + * @param null $amazdata + * + * @return false|int|string + * @throws \Exception + */ + public function updateBookInfo($bookInfo = '', $amazdata = null) + { + $ri = new ReleaseImage($this->pdo); - if (!$amaz) { - return false; - } + $book = []; - $book['title'] = (string)$amaz->Items->Item->ItemAttributes->Title; - $book['author'] = (string)$amaz->Items->Item->ItemAttributes->Author; - $book['asin'] = (string)$amaz->Items->Item->ASIN; - $book['isbn'] = (string)$amaz->Items->Item->ItemAttributes->ISBN; - if ($book['isbn'] === '') { - $book['isbn'] = 'null'; - } + $amaz = false; + if ($bookInfo !== '') { + $amaz = $this->fetchAmazonProperties($bookInfo); + } elseif ($amazdata !== null) { + $amaz = $amazdata; + } - $book['ean'] = (string)$amaz->Items->Item->ItemAttributes->EAN; - if ($book['ean'] === '') { - $book['ean'] = 'null'; - } + if (! $amaz) { + return false; + } - $book['url'] = (string)$amaz->Items->Item->DetailPageURL; - $book['url'] = str_replace('%26tag%3Dws', '%26tag%3Dopensourceins%2D21', $book['url']); + $book['title'] = (string) $amaz->Items->Item->ItemAttributes->Title; + $book['author'] = (string) $amaz->Items->Item->ItemAttributes->Author; + $book['asin'] = (string) $amaz->Items->Item->ASIN; + $book['isbn'] = (string) $amaz->Items->Item->ItemAttributes->ISBN; + if ($book['isbn'] === '') { + $book['isbn'] = 'null'; + } - $book['salesrank'] = (string)$amaz->Items->Item->SalesRank; - if ($book['salesrank'] === '') { - $book['salesrank'] = 'null'; - } + $book['ean'] = (string) $amaz->Items->Item->ItemAttributes->EAN; + if ($book['ean'] === '') { + $book['ean'] = 'null'; + } - $book['publisher'] = (string)$amaz->Items->Item->ItemAttributes->Publisher; - if ($book['publisher'] === '') { - $book['publisher'] = 'null'; - } + $book['url'] = (string) $amaz->Items->Item->DetailPageURL; + $book['url'] = str_replace('%26tag%3Dws', '%26tag%3Dopensourceins%2D21', $book['url']); - $book['publishdate'] = date('Y-m-d', strtotime((string)$amaz->Items->Item->ItemAttributes->PublicationDate)); - if ($book['publishdate'] === '') { - $book['publishdate'] = 'null'; - } + $book['salesrank'] = (string) $amaz->Items->Item->SalesRank; + if ($book['salesrank'] === '') { + $book['salesrank'] = 'null'; + } - $book['pages'] = (string)$amaz->Items->Item->ItemAttributes->NumberOfPages; - if ($book['pages'] === '') { - $book['pages'] = 'null'; - } + $book['publisher'] = (string) $amaz->Items->Item->ItemAttributes->Publisher; + if ($book['publisher'] === '') { + $book['publisher'] = 'null'; + } - if (isset($amaz->Items->Item->EditorialReviews->EditorialReview->Content)) { - $book['overview'] = strip_tags((string)$amaz->Items->Item->EditorialReviews->EditorialReview->Content); - if ($book['overview'] === '') { - $book['overview'] = 'null'; - } - } else { - $book['overview'] = 'null'; - } + $book['publishdate'] = date('Y-m-d', strtotime((string) $amaz->Items->Item->ItemAttributes->PublicationDate)); + if ($book['publishdate'] === '') { + $book['publishdate'] = 'null'; + } - if (isset($amaz->Items->Item->BrowseNodes->BrowseNode->Name)) { - $book['genre'] = (string)$amaz->Items->Item->BrowseNodes->BrowseNode->Name; - if ($book['genre'] === '') { - $book['genre'] = 'null'; - } - } else { - $book['genre'] = 'null'; - } + $book['pages'] = (string) $amaz->Items->Item->ItemAttributes->NumberOfPages; + if ($book['pages'] === '') { + $book['pages'] = 'null'; + } - $book['coverurl'] = (string)$amaz->Items->Item->LargeImage->URL; - if ($book['coverurl'] !== '') { - $book['cover'] = 1; - } else { - $book['cover'] = 0; - } + if (isset($amaz->Items->Item->EditorialReviews->EditorialReview->Content)) { + $book['overview'] = strip_tags((string) $amaz->Items->Item->EditorialReviews->EditorialReview->Content); + if ($book['overview'] === '') { + $book['overview'] = 'null'; + } + } else { + $book['overview'] = 'null'; + } - $check = BookInfo::query()->where('asin', $book['asin'])->first(); - if ($check === false) { - $bookId = BookInfo::query()->insertGetId( + if (isset($amaz->Items->Item->BrowseNodes->BrowseNode->Name)) { + $book['genre'] = (string) $amaz->Items->Item->BrowseNodes->BrowseNode->Name; + if ($book['genre'] === '') { + $book['genre'] = 'null'; + } + } else { + $book['genre'] = 'null'; + } + + $book['coverurl'] = (string) $amaz->Items->Item->LargeImage->URL; + if ($book['coverurl'] !== '') { + $book['cover'] = 1; + } else { + $book['cover'] = 0; + } + + $check = BookInfo::query()->where('asin', $book['asin'])->first(); + if ($check === false) { + $bookId = BookInfo::query()->insertGetId( [ 'title' => $book['title'], 'author' => $book['author'], @@ -646,12 +649,12 @@ class Books 'genre' => $book['genre'], 'cover' => $book['cover'], 'createddate' => new \DateTime('NOW'), - 'updateddate' => new \DateTime('NOW') + 'updateddate' => new \DateTime('NOW'), ] ); - } else { - $bookId = $check['id']; - BookInfo::query()->where('id', $bookId)->update( + } else { + $bookId = $check['id']; + BookInfo::query()->where('id', $bookId)->update( [ 'title' => $book['title'], 'author' => $book['author'], @@ -666,34 +669,35 @@ class Books 'overview' => $book['overview'], 'genre' => $book['genre'], 'cover' => $book['cover'], - 'updateddate' => new \DateTime('NOW') + 'updateddate' => new \DateTime('NOW'), ] ); - } + } - if ($bookId) { - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::header('Added/updated book: ')); - if ($book['author'] !== '') { - ColorCLI::doEcho(ColorCLI::alternateOver(' Author: ') . ColorCLI::primary($book['author'])); - } - echo ColorCLI::alternateOver(' Title: ') . ColorCLI::primary(' ' . $book['title']); - if ($book['genre'] !== 'null') { - ColorCLI::doEcho(ColorCLI::alternateOver(' Genre: ') . ColorCLI::primary(' ' . $book['genre'])); - } - } + if ($bookId) { + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::header('Added/updated book: ')); + if ($book['author'] !== '') { + ColorCLI::doEcho(ColorCLI::alternateOver(' Author: ').ColorCLI::primary($book['author'])); + } + echo ColorCLI::alternateOver(' Title: ').ColorCLI::primary(' '.$book['title']); + if ($book['genre'] !== 'null') { + ColorCLI::doEcho(ColorCLI::alternateOver(' Genre: ').ColorCLI::primary(' '.$book['genre'])); + } + } - $book['cover'] = $ri->saveImage($bookId, $book['coverurl'], $this->imgSavePath, 250, 250); - } else { - if ($this->echooutput) { - ColorCLI::doEcho( - ColorCLI::header('Nothing to update: ') . - ColorCLI::header($book['author'] . - ' - ' . + $book['cover'] = $ri->saveImage($bookId, $book['coverurl'], $this->imgSavePath, 250, 250); + } else { + if ($this->echooutput) { + ColorCLI::doEcho( + ColorCLI::header('Nothing to update: '). + ColorCLI::header($book['author']. + ' - '. $book['title']) ); - } - } - return $bookId; - } + } + } + + return $bookId; + } } diff --git a/nntmux/Captcha.php b/nntmux/Captcha.php index 7e5ccd229..25d1d80af 100755 --- a/nntmux/Captcha.php +++ b/nntmux/Captcha.php @@ -1,166 +1,168 @@ <?php + namespace nntmux; use ReCaptcha\ReCaptcha; -class Captcha { - /** - * Smarty $page - * - * @var \Page - */ - private $page; +class Captcha +{ + /** + * Smarty $page. + * + * @var \Page + */ + private $page; - /** - * ReCaptcha Site Key from the - * settings database. - * - * @var bool|string - */ - private $sitekey; + /** + * ReCaptcha Site Key from the + * settings database. + * + * @var bool|string + */ + private $sitekey; - /** - * ReCaptcha Secret Key from the - * settings database. - * - * @var bool|string - */ - private $secretkey; + /** + * ReCaptcha Secret Key from the + * settings database. + * + * @var bool|string + */ + private $secretkey; - /** - * ReCaptcha instance if enabled. - * - * @var \ReCaptcha\ReCaptcha - */ - private $recaptcha; + /** + * ReCaptcha instance if enabled. + * + * @var \ReCaptcha\ReCaptcha + */ + private $recaptcha; + /** + * Contains the error output if ReCaptcha + * validation fails. + * + * @var string|bool + */ + private $error = false; - /** - * Contains the error output if ReCaptcha - * validation fails. - * - * @var string|bool - */ - private $error = false; + /** + * $_POST key for the user-supplied ReCaptcha response. + */ + const RECAPTCHA_POSTKEY = 'g-recaptcha-response'; + /** + * Error key literals. + */ + const RECAPTCHA_ERROR_MISSING_SECRET = 'missing-input-secret'; + const RECAPTCHA_ERROR_INVALID_SECRET = 'invalid-input-secret'; + const RECAPTCHA_ERROR_MISSING_RESPONSE = 'missing-input-response'; + const RECAPTCHA_ERROR_INVALID_RESPONSE = 'invalid-input-response'; - /** - * $_POST key for the user-supplied ReCaptcha response. - */ - const RECAPTCHA_POSTKEY = 'g-recaptcha-response'; + /** + * Settings key literals. + */ + const RECAPTCHA_SETTING_SITEKEY = 'recaptchapublickey'; + const RECAPTCHA_SETTING_SECRETKEY = 'recaptchaprivatekey'; - /** - * Error key literals. - */ - const RECAPTCHA_ERROR_MISSING_SECRET = 'missing-input-secret'; - const RECAPTCHA_ERROR_INVALID_SECRET = 'invalid-input-secret'; - const RECAPTCHA_ERROR_MISSING_RESPONSE = 'missing-input-response'; - const RECAPTCHA_ERROR_INVALID_RESPONSE = 'invalid-input-response'; + /** + * Construct and decide whether to show the captcha or not. + * + * @note Passing $page by reference to setup smarty vars easily. + * + * @param \Page $page + * + * @throws \InvalidArgumentException + * @throws \RuntimeException + */ + public function __construct(&$page) + { + if (! $page instanceof \Page) { + throw new \InvalidArgumentException('Invalid Page variable provided'); + } - /** - * Settings key literals - */ - const RECAPTCHA_SETTING_SITEKEY = 'recaptchapublickey'; - const RECAPTCHA_SETTING_SECRETKEY = 'recaptchaprivatekey'; + $this->page = $page; - /** - * Construct and decide whether to show the captcha or not. - * - * @note Passing $page by reference to setup smarty vars easily. - * - * @param \Page $page - * - * @throws \InvalidArgumentException - * @throws \RuntimeException - */ - public function __construct(&$page) { - if (!$page instanceof \Page) { - throw new \InvalidArgumentException('Invalid Page variable provided'); - } + if ($this->shouldDisplay()) { + $this->page->smarty->assign('showCaptcha', true); + $this->page->smarty->assign('sitekey', $this->sitekey); - $this->page = $page; + if ($this->page->isPostBack()) { + if (! $this->processCaptcha($_POST, $_SERVER['REMOTE_ADDR'])) { + $this->page->smarty->assign('error', $this->getError()); + } + //Delete this key after using so it doesn't interfere with normal $_POST + //processing. (i.e. contact-us) + unset($_POST[self::RECAPTCHA_POSTKEY]); + } + } else { + $this->page->smarty->assign('showCaptcha', false); + } + } - if ($this->shouldDisplay()) { - $this->page->smarty->assign('showCaptcha', true); - $this->page->smarty->assign('sitekey', $this->sitekey); + /** + * If site admin setup keys properly, + * allow display of recaptcha. + * + * @return bool + * @throws \RuntimeException + */ + public function shouldDisplay(): bool + { + if ($this->_bootstrapCaptcha()) { + return true; + } - if ($this->page->isPostBack()) { - if (!$this->processCaptcha($_POST, $_SERVER['REMOTE_ADDR'])) { - $this->page->smarty->assign('error', $this->getError()); - } - //Delete this key after using so it doesn't interfere with normal $_POST - //processing. (i.e. contact-us) - unset($_POST[self::RECAPTCHA_POSTKEY]); - } - } else { - $this->page->smarty->assign('showCaptcha', false); - } - } + return false; + } - /** - * If site admin setup keys properly, - * allow display of recaptcha. - * - * @return bool - * @throws \RuntimeException - */ - public function shouldDisplay(): bool - { - if ($this->_bootstrapCaptcha()) { - return true; - } + /** + * Return formatted error messages. + * + * + * @return bool|string + */ + public function getError() + { + return $this->error; + } - return false; - } + /** + * Process the submitted captcha and validate. + * + * @param array $response + * @param string $ip + * @return bool + */ + public function processCaptcha($response, $ip): bool + { + if (isset($response[self::RECAPTCHA_POSTKEY])) { + $post_response = $response[self::RECAPTCHA_POSTKEY]; + } else { + $post_response = ''; + } - /** - * Return formatted error messages. - * - * - * @return bool|string - */ - public function getError() - { - return $this->error; - } + $verify_response = $this->recaptcha->verify($post_response, $ip); - /** - * Process the submitted captcha and validate. - * - * @param array $response - * @param string $ip - * @return bool - */ - public function processCaptcha($response, $ip): bool - { - if (isset($response[self::RECAPTCHA_POSTKEY])) { - $post_response = $response[self::RECAPTCHA_POSTKEY]; - } else { - $post_response = ''; - } + if (! $verify_response->isSuccess()) { + $this->_handleErrors($verify_response->getErrorCodes()); - $verify_response = $this->recaptcha->verify($post_response, $ip); + return false; + } - if (!$verify_response->isSuccess()) { - $this->_handleErrors($verify_response->getErrorCodes()); - return false; - } + return true; + } - return true; - } + /** + * Build formatted error string for output using + * Google's reCaptcha error codes. + * + * @param array $codes + */ + private function _handleErrors($codes): void + { + $rc_error = 'ReCaptcha Failed: '; - /** - * Build formatted error string for output using - * Google's reCaptcha error codes. - * - * @param array $codes - */ - private function _handleErrors($codes): void - { - $rc_error = 'ReCaptcha Failed: '; - - foreach ($codes as $c) { - switch($c) { + foreach ($codes as $c) { + switch ($c) { case self::RECAPTCHA_ERROR_MISSING_SECRET: $rc_error .= 'Missing Secret Key'; break; @@ -176,33 +178,33 @@ class Captcha { default: $rc_error .= 'Unknown Error!'; } - } + } - $this->error = $rc_error; - } + $this->error = $rc_error; + } - /** - * Instantiate the ReCaptcha library and store it. - * Return bool on success/failure. - * - * @return bool - * @throws \RuntimeException - */ - private function _bootstrapCaptcha(): bool - { - if ($this->recaptcha instanceof ReCaptcha) { - return true; - } + /** + * Instantiate the ReCaptcha library and store it. + * Return bool on success/failure. + * + * @return bool + * @throws \RuntimeException + */ + private function _bootstrapCaptcha(): bool + { + if ($this->recaptcha instanceof ReCaptcha) { + return true; + } - $this->sitekey = $this->page->settings->getSetting(self::RECAPTCHA_SETTING_SITEKEY); - $this->secretkey = $this->page->settings->getSetting(self::RECAPTCHA_SETTING_SECRETKEY); + $this->sitekey = $this->page->settings->getSetting(self::RECAPTCHA_SETTING_SITEKEY); + $this->secretkey = $this->page->settings->getSetting(self::RECAPTCHA_SETTING_SECRETKEY); - if ($this->sitekey !== false && $this->sitekey !== '' && $this->secretkey !== false && $this->secretkey !== '') { - $this->recaptcha = new ReCaptcha($this->secretkey); + if ($this->sitekey !== false && $this->sitekey !== '' && $this->secretkey !== false && $this->secretkey !== '') { + $this->recaptcha = new ReCaptcha($this->secretkey); - return true; - } + return true; + } - return false; - } + return false; + } } diff --git a/nntmux/Categorize.php b/nntmux/Categorize.php index d6e0b63da..624a4de0c 100755 --- a/nntmux/Categorize.php +++ b/nntmux/Categorize.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; use App\Models\Settings; @@ -10,79 +11,79 @@ use App\Models\Settings; */ class Categorize extends Category { - /** - * @var bool - */ - protected $categorizeForeign; + /** + * @var bool + */ + protected $categorizeForeign; - /** - * @var bool - */ - protected $catWebDL; + /** + * @var bool + */ + protected $catWebDL; - /** - * Temporary category while we sort through the name. - * @var int - */ - protected $tmpCat = Category::OTHER_MISC; + /** + * Temporary category while we sort through the name. + * @var int + */ + protected $tmpCat = Category::OTHER_MISC; - /** - * Release name to sort through. - * @var string - */ - public $releaseName; + /** + * Release name to sort through. + * @var string + */ + public $releaseName; - /** - * Release poster to sort through. - * @var string - */ - public $poster; + /** + * Release poster to sort through. + * @var string + */ + public $poster; - /** - * Group id of the releasename we are sorting through. - * @var int|string - */ - public $groupid; + /** + * Group id of the releasename we are sorting through. + * @var int|string + */ + public $groupid; - /** - * @var Regexes - */ - public $regexes; + /** + * @var Regexes + */ + public $regexes; - /** - * Construct. - * - * @param array $options Class instances. - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - parent::__construct($options); - $this->categorizeForeign = (int)Settings::value('indexer.categorise.categorizeforeign'); - $this->catWebDL = (int)Settings::value('indexer.categorise.catwebdl'); - $this->regexes = new Regexes(['Settings' => $this->pdo, 'Table_Name' => 'category_regexes']); - } + /** + * Construct. + * + * @param array $options Class instances. + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + parent::__construct($options); + $this->categorizeForeign = (int) Settings::value('indexer.categorise.categorizeforeign'); + $this->catWebDL = (int) Settings::value('indexer.categorise.catwebdl'); + $this->regexes = new Regexes(['Settings' => $this->pdo, 'Table_Name' => 'category_regexes']); + } - /** - * Look up the site to see which language of categorizing to use. - * Then work out which category is applicable for either a group or a binary. - * Returns Category::OTHER_MISC if no category is appropriate. - * - * @param string $releaseName The name to parse. - * @param string $poster Name of the release poster to parse - * @param int|string $groupID The groups_id. - * - * @return int The categories_id. - */ - public function determineCategory($groupID, $releaseName = '', $poster = ''): int - { - $this->releaseName = $releaseName; - $this->groupid = $groupID; - $this->tmpCat = Category::OTHER_MISC; - $this->poster = $poster; + /** + * Look up the site to see which language of categorizing to use. + * Then work out which category is applicable for either a group or a binary. + * Returns Category::OTHER_MISC if no category is appropriate. + * + * @param string $releaseName The name to parse. + * @param string $poster Name of the release poster to parse + * @param int|string $groupID The groups_id. + * + * @return int The categories_id. + */ + public function determineCategory($groupID, $releaseName = '', $poster = ''): int + { + $this->releaseName = $releaseName; + $this->groupid = $groupID; + $this->tmpCat = Category::OTHER_MISC; + $this->poster = $poster; - switch (true) { + switch (true) { case $this->isMisc(): // Note that in byGroup() some overrides occur... case $this->databaseRegex(): @@ -97,40 +98,41 @@ class Categorize extends Category case $this->isBook(): return $this->tmpCat; } - return $this->tmpCat; - } - /** - * Cache of group names for group id's. - * @var array - */ - private $groups = []; + return $this->tmpCat; + } - /** - * Sets/Gets a group name for the current group id in the buffer. - * - * @return string Group Name. - */ - private function groupName(): string - { - if (!isset($this->groups[$this->groupid])) { - $group = $this->pdo->queryOneRow(sprintf('SELECT LOWER(name) AS name FROM groups WHERE id = %d', $this->groupid)); - $this->groups[$this->groupid] = ($group === false ? false : $group['name']); - } + /** + * Cache of group names for group id's. + * @var array + */ + private $groups = []; - return $this->groups[$this->groupid]; - } + /** + * Sets/Gets a group name for the current group id in the buffer. + * + * @return string Group Name. + */ + private function groupName(): string + { + if (! isset($this->groups[$this->groupid])) { + $group = $this->pdo->queryOneRow(sprintf('SELECT LOWER(name) AS name FROM groups WHERE id = %d', $this->groupid)); + $this->groups[$this->groupid] = ($group === false ? false : $group['name']); + } - /** - * Determine category by group name. - * - * @return bool - */ - public function byGroup(): bool - { - $group = $this->groupName(); - if ($group !== false) { - switch (true) { + return $this->groups[$this->groupid]; + } + + /** + * Determine category by group name. + * + * @return bool + */ + public function byGroup(): bool + { + $group = $this->groupName(); + if ($group !== false) { + switch (true) { case $group === 'alt.binaries.0day.stuffz': switch (true) { case $this->isBook(): @@ -203,7 +205,7 @@ class Categorize extends Category break; case $group === 'alt.binaries.cd.lossless': if ($this->categorizeForeign && $this->isMusicForeign()) { - break; + break; } $this->tmpCat = Category::MUSIC_LOSSLESS; break; @@ -212,19 +214,19 @@ class Categorize extends Category break; case preg_match('/alt\.binaries\.(comics\.dcp|pictures\.comics\.(complete|dcp|reposts?))/', $group): if ($this->categorizeForeign && $this->isBookForeign()) { - break; + break; } $this->tmpCat = Category::BOOKS_COMICS; break; case $group === 'alt.binaries.console.ps3': if ($this->isGamePS4()) { - break; + break; } $this->tmpCat = Category::GAME_PS3; break; case $group === 'alt.binaries.cores': if ($this->isXxx()) { - break; + break; } return false; @@ -251,16 +253,16 @@ class Categorize extends Category break; case preg_match('/alt\.binaries\.dvd(\-?r)?(\.(movies|))?$/i', $group): if ($this->isMovie()) { - break; + break; } $this->tmpCat = Category::OTHER_MISC; break; case preg_match('/alt\.binaries\.(dvdnordic\.org|nordic\.(dvdr?|xvid))|dk\.(binaer|binaries)\.film(\.divx)?/', $group): if ($this->categorizeForeign && $this->isMovieForeign()) { - break; + break; } if ($this->isMovie()) { - break; + break; } $this->tmpCat = Category::MOVIE_FOREIGN; break; @@ -272,13 +274,13 @@ class Categorize extends Category break; case preg_match('/alt\.binaries\.e\-?books?((\.|\-)(technical|textbooks))/', $group): if ($this->categorizeForeign && $this->isBookForeign()) { - break; + break; } $this->tmpCat = Category::BOOKS_TECHNICAL; break; case $group === 'alt.binaries.e-book.magazines': if ($this->categorizeForeign && $this->isBookForeign()) { - break; + break; } $this->tmpCat = Category::BOOKS_MAGAZINES; break; @@ -312,7 +314,7 @@ class Categorize extends Category break; case preg_match('/alt\.binaries\..*(erotica|ijsklontje|xxx)/', $group): if ($this->isXxx()) { - break; + break; } $this->tmpCat = Category::XXX_OTHER; break; @@ -366,13 +368,13 @@ class Categorize extends Category break; case $group === 'alt.binaries.games.nintendo3ds': if ($this->isGameNDS()) { - break; + break; } $this->tmpCat = Category::GAME_3DS; break; case preg_match('/alt\.binaries\.(games|emulators)?\.?nintendo[\.-]?ds/', $group): if ($this->isGame3DS()) { - break; + break; } $this->tmpCat = Category::GAME_NDS; break; @@ -436,7 +438,7 @@ class Categorize extends Category break; case $group === 'alt.binaries.mma': if ($this->is0day()) { - break; + break; } $this->tmpCat = Category::TV_SPORT; break; @@ -457,7 +459,7 @@ class Categorize extends Category break; case $group === 'alt.binaries.mpeg.video.music': if ($this->categorizeForeign && $this->isMusicForeign()) { - break; + break; } $this->tmpCat = Category::MUSIC_VIDEO; break; @@ -489,9 +491,9 @@ class Categorize extends Category break; } break; - case strpos($group ,'audiobook') !== false: + case strpos($group, 'audiobook') !== false: if ($this->categorizeForeign && $this->isMusicForeign()) { - break; + break; } $this->tmpCat = Category::MUSIC_AUDIOBOOK; break; @@ -512,7 +514,7 @@ class Categorize extends Category switch (true) { case $this->categorizeForeign && $this->isMusicForeign(): break; - case !preg_match('/[-._ ]scans[-._ ]/i', $this->releaseName): + case ! preg_match('/[-._ ]scans[-._ ]/i', $this->releaseName): $this->tmpCat = Category::MUSIC_MP3; break; default: @@ -521,13 +523,13 @@ class Categorize extends Category break; case $group === 'alt.binaries.sounds.ogg': if ($this->categorizeForeign && $this->isMusicForeign()) { - break; + break; } $this->tmpCat = Category::MUSIC_OTHER; break; case $group === 'alt.binaries.sony.psp': if ($this->isGamePSVita()) { - break; + break; } $this->tmpCat = Category::GAME_PSP; break; @@ -548,7 +550,7 @@ class Categorize extends Category break; case $group === 'alt.binaries.warez.smartphone': if ($this->isPhone()) { - break; + break; } $this->tmpCat = Category::PC_PHONE_OTHER; break; @@ -558,41 +560,45 @@ class Categorize extends Category default: return false; } - return true; - } - return false; - } - /** - * Try database regexes against a group / release name. - * @return bool - */ - public function databaseRegex(): bool - { - $cat = $this->regexes->tryRegex($this->releaseName, $this->groupName()); - if ($cat) { - $this->tmpCat = $cat; - return true; - } - return false; - } + return true; + } - // - // Beginning of functions to determine category by release name. - // + return false; + } - /** - * @return bool - */ - public function isTV(): bool - { -// if (/*!preg_match('/s\d{1,3}[-._ ]?[ed]\d{1,3}|season|episode/i', $this->releaseName) &&*/ preg_match('/part[-._ ]?\d/i', $this->releaseName)) { -// return false; -// } + /** + * Try database regexes against a group / release name. + * @return bool + */ + public function databaseRegex(): bool + { + $cat = $this->regexes->tryRegex($this->releaseName, $this->groupName()); + if ($cat) { + $this->tmpCat = $cat; - if (preg_match('/Daily[-_\.]Show|Nightly News|^\[[a-zA-Z\.\-]+\].*[-_].*\d{1,3}[-_. ]((\[|\()(h264-)?\d{3,4}(p|i)(\]|\))\s?(\[AAC\])?|\[[a-fA-F0-9]{8}\]|(8|10)BIT|hi10p)(\[[a-fA-F0-9]{8}\])?|(\d\d-){2}[12]\d{3}|[12]\d{3}(\.\d\d){2}|\d+x\d+|\.e\d{1,3}\.|s\d{1,3}[-._ ]?[ed]\d{1,3}([ex]\d{1,3}|[-.\w ])|[-._ ](\dx\d\d|C4TV|Complete[-._ ]Season|DSR|(D|H|P|S)DTV|EP[-._ ]?\d{1,3}|S\d{1,3}.+Extras|SUBPACK|Season[-._ ]\d{1,2})([-._ ]|$)|TVRIP|TV[-._ ](19|20)\d\d|Troll(HD|UHD)/i', $this->releaseName) - && !preg_match('/[-._ ](flac|imageset|mp3|xxx)[-._ ]|[ .]exe$/i', $this->releaseName)) { - switch (true) { + return true; + } + + return false; + } + + // + // Beginning of functions to determine category by release name. + // + + /** + * @return bool + */ + public function isTV(): bool + { + // if (/*!preg_match('/s\d{1,3}[-._ ]?[ed]\d{1,3}|season|episode/i', $this->releaseName) &&*/ preg_match('/part[-._ ]?\d/i', $this->releaseName)) { + // return false; + // } + + if (preg_match('/Daily[-_\.]Show|Nightly News|^\[[a-zA-Z\.\-]+\].*[-_].*\d{1,3}[-_. ]((\[|\()(h264-)?\d{3,4}(p|i)(\]|\))\s?(\[AAC\])?|\[[a-fA-F0-9]{8}\]|(8|10)BIT|hi10p)(\[[a-fA-F0-9]{8}\])?|(\d\d-){2}[12]\d{3}|[12]\d{3}(\.\d\d){2}|\d+x\d+|\.e\d{1,3}\.|s\d{1,3}[-._ ]?[ed]\d{1,3}([ex]\d{1,3}|[-.\w ])|[-._ ](\dx\d\d|C4TV|Complete[-._ ]Season|DSR|(D|H|P|S)DTV|EP[-._ ]?\d{1,3}|S\d{1,3}.+Extras|SUBPACK|Season[-._ ]\d{1,2})([-._ ]|$)|TVRIP|TV[-._ ](19|20)\d\d|Troll(HD|UHD)/i', $this->releaseName) + && ! preg_match('/[-._ ](flac|imageset|mp3|xxx)[-._ ]|[ .]exe$/i', $this->releaseName)) { + switch (true) { case $this->isOtherTV(): case $this->categorizeForeign && $this->isForeignTV(): case $this->isSportTV(): @@ -606,43 +612,46 @@ class Categorize extends Category return true; default: $this->tmpCat = Category::TV_OTHER; + return true; } - } + } - if (preg_match('/[-._ ]((19|20)\d\d[-._ ]\d{1,2}[-._ ]\d{1,2}[-._ ]VHSRip|Indy[-._ ]?Car|(iMPACT|Smoky[-._ ]Mountain|Texas)[-._ ]Wrestling|Moto[-._ ]?GP|NSCS[-._ ]ROUND|NECW[-._ ]TV|(Per|Post)\-Show|PPV|WrestleMania|WCW|WEB[-._ ]HD|WWE[-._ ](Monday|NXT|RAW|Smackdown|Superstars|WrestleMania))[-._ ]/i', $this->releaseName)) { - if ($this->isSportTV()) { - return true; - } - $this->tmpCat = Category::TV_OTHER; - return true; - } - return false; - } + if (preg_match('/[-._ ]((19|20)\d\d[-._ ]\d{1,2}[-._ ]\d{1,2}[-._ ]VHSRip|Indy[-._ ]?Car|(iMPACT|Smoky[-._ ]Mountain|Texas)[-._ ]Wrestling|Moto[-._ ]?GP|NSCS[-._ ]ROUND|NECW[-._ ]TV|(Per|Post)\-Show|PPV|WrestleMania|WCW|WEB[-._ ]HD|WWE[-._ ](Monday|NXT|RAW|Smackdown|Superstars|WrestleMania))[-._ ]/i', $this->releaseName)) { + if ($this->isSportTV()) { + return true; + } + $this->tmpCat = Category::TV_OTHER; - /** - * @return bool - */ - public function isOtherTV(): bool - { - if (preg_match('/[-._ ]S\d{1,3}.+(EP\d{1,3}|Extras|SUBPACK)[-._ ]|News/i', $this->releaseName) + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isOtherTV(): bool + { + if (preg_match('/[-._ ]S\d{1,3}.+(EP\d{1,3}|Extras|SUBPACK)[-._ ]|News/i', $this->releaseName) //special case for "Have.I.Got.News.For.You" tv show - && !preg_match('/[-._ ]Got[-._ ]News[-._ ]For[-._ ]You/i', $this->releaseName) + && ! preg_match('/[-._ ]Got[-._ ]News[-._ ]For[-._ ]You/i', $this->releaseName) ) { - $this->tmpCat = Category::TV_OTHER; + $this->tmpCat = Category::TV_OTHER; - return true; - } + return true; + } - return false; - } + return false; + } - /** - * @return bool|null - */ - public function isForeignTV(): ?bool - { - switch (true) { + /** + * @return bool|null + */ + public function isForeignTV(): ?bool + { + switch (true) { case preg_match('/[-._ ](NHL|stanley.+cup)[-._ ]/', $this->releaseName): return false; case preg_match('/[-._ ](chinese|dk|fin|french|ger?|heb|ita|jap|kor|nor|nordic|nl|pl|swe)[-._ ]?(sub|dub)(ed|bed|s)?|<German>/i', $this->releaseName): @@ -651,18 +660,19 @@ class Categorize extends Category case preg_match('/(S\d\d[EX]\d\d|DOCU(MENTAIRE)?|TV)?[-._ ](FRENCH|German|Dutch)[-._ ](720p|1080p|dv(b|d)r(ip)?|LD|HD\-?TV|TV[-._ ]?RIP|x264)[-._ ]/i', $this->releaseName): case preg_match('/[-._ ]FastSUB|NL|nlvlaams|patrfa|RealCO|Seizoen|slosinh|Videomann|Vostfr|xslidian[-._ ]|x264\-iZU/i', $this->releaseName): $this->tmpCat = Category::TV_FOREIGN; + return true; default: return false; } - } + } - /** - * @return bool|null - */ - public function isSportTV(): ?bool - { - switch (true) { + /** + * @return bool|null + */ + public function isSportTV(): ?bool + { + switch (true) { case preg_match('/s\d{1,3}[-._ ]?[ed]\d{1,3}([ex]\d{1,3}|[-.\w ])/i', $this->releaseName): return false; case preg_match('/[-._ ]?(Bellator|bundesliga|EPL|ESPN|FIA|la[-._ ]liga|MMA|motogp|NFL|NCAA|PGA|red[-._ ]bull.+race|Sengoku|Strikeforce|supercup|uefa|UFC|wtcc|WWE)[-._ ]/i', $this->releaseName): @@ -671,119 +681,135 @@ class Categorize extends Category case preg_match('/[-._ ]?(Horse)[-._ ]Racing[-._ ]/i', $this->releaseName): case preg_match('/[-._ ](VERUM)/i', $this->releaseName): $this->tmpCat = Category::TV_SPORT; + return true; default: return false; } - } + } - /** - * @return bool - */ - public function isDocumentaryTV(): bool - { - if (preg_match('/[-._ ](Docu|Documentary)[-._ ]/i', $this->releaseName)) { - $this->tmpCat = Category::TV_DOCU; - return true; - } - return false; - } + /** + * @return bool + */ + public function isDocumentaryTV(): bool + { + if (preg_match('/[-._ ](Docu|Documentary)[-._ ]/i', $this->releaseName)) { + $this->tmpCat = Category::TV_DOCU; - /** - * @return bool - */ - public function isWEBDL(): bool - { - if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { - $this->tmpCat = Category::TV_WEBDL; - return true; - } - return false; - } + return true; + } - /** - * @return bool - */ - public function isAnimeTV(): bool - { - if (preg_match('/[-._ ]Anime[-._ ]|^\[[a-zA-Z\.\-]+\].*[-_].*\d{1,3}[-_. ]((\[|\()((\d{1,4}x\d{1,4})|(h264-)?\d{3,4}(p|i))(\]|\))\s?(\[AAC\])?|\[[a-fA-F0-9]{8}\]|(8|10)BIT|hi10p)(\[[a-fA-F0-9]{8}\])?/i', $this->releaseName)) { - $this->tmpCat = Category::TV_ANIME; - return true; - } - if (preg_match('/(ANiHLS|HaiKU|ANiURL)/i', $this->releaseName)) { - $this->tmpCat = Category::TV_ANIME; - return true; - } - return false; - } + return false; + } - /** - * @return bool - */ - public function isHDTV(): bool - { - if (preg_match('/1080(i|p)|720p|bluray/i', $this->releaseName)) { - $this->tmpCat = Category::TV_HD; - return true; - } - if ($this->catWebDL === false) { - if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { - $this->tmpCat = Category::TV_HD; - return true; - } - } - return false; - } + /** + * @return bool + */ + public function isWEBDL(): bool + { + if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { + $this->tmpCat = Category::TV_WEBDL; - /** - * @return bool - */ - public function isUHDTV(): bool - { - if (preg_match('/(S\d+).*(2160p).*(Netflix|Amazon).*(TrollUHD|NTb|VLAD)/i', $this->releaseName)) { - $this->tmpCat = Category::TV_UHD; - return true; - } - return false; - } + return true; + } - /** - * @return bool|null - */ - public function isSDTV(): ?bool - { - switch (true) { + return false; + } + + /** + * @return bool + */ + public function isAnimeTV(): bool + { + if (preg_match('/[-._ ]Anime[-._ ]|^\[[a-zA-Z\.\-]+\].*[-_].*\d{1,3}[-_. ]((\[|\()((\d{1,4}x\d{1,4})|(h264-)?\d{3,4}(p|i))(\]|\))\s?(\[AAC\])?|\[[a-fA-F0-9]{8}\]|(8|10)BIT|hi10p)(\[[a-fA-F0-9]{8}\])?/i', $this->releaseName)) { + $this->tmpCat = Category::TV_ANIME; + + return true; + } + if (preg_match('/(ANiHLS|HaiKU|ANiURL)/i', $this->releaseName)) { + $this->tmpCat = Category::TV_ANIME; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isHDTV(): bool + { + if (preg_match('/1080(i|p)|720p|bluray/i', $this->releaseName)) { + $this->tmpCat = Category::TV_HD; + + return true; + } + if ($this->catWebDL === false) { + if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { + $this->tmpCat = Category::TV_HD; + + return true; + } + } + + return false; + } + + /** + * @return bool + */ + public function isUHDTV(): bool + { + if (preg_match('/(S\d+).*(2160p).*(Netflix|Amazon).*(TrollUHD|NTb|VLAD)/i', $this->releaseName)) { + $this->tmpCat = Category::TV_UHD; + + return true; + } + + return false; + } + + /** + * @return bool|null + */ + public function isSDTV(): ?bool + { + switch (true) { case preg_match('/(360|480|576)p|Complete[-._ ]Season|dvdr(ip)?|dvd5|dvd9|\.pdtv|SD[-._ ]TV|TVRip|NTSC|BDRip|hdtv|xvid/i', $this->releaseName): case preg_match('/((H|P)D[-._ ]?TV|DSR|WebRip)[-._ ]x264/i', $this->releaseName): case preg_match('/s\d{1,3}[-._ ]?[ed]\d{1,3}([ex]\d{1,3}|[-.\w ])|\s\d{3,4}\s/i', $this->releaseName) && preg_match('/(H|P)D[-._ ]?TV|BDRip|WEB[-._ ]x264/i', $this->releaseName): $this->tmpCat = Category::TV_SD; + return true; default: return false; } - } + } - /** - * @return bool - */ - public function isOtherTV2(): bool - { - if (preg_match('/[-._ ]s\d{1,3}[-._ ]?(e|d(isc)?)\d{1,3}([-._ ]|$)/i', $this->releaseName)) { - $this->tmpCat = Category::TV_OTHER; - return true; - } - return false; - } + /** + * @return bool + */ + public function isOtherTV2(): bool + { + if (preg_match('/[-._ ]s\d{1,3}[-._ ]?(e|d(isc)?)\d{1,3}([-._ ]|$)/i', $this->releaseName)) { + $this->tmpCat = Category::TV_OTHER; - // Movies. + return true; + } - /** - * @return bool - */ - public function isMovie(): bool - { - if (preg_match('/[-._ ]AVC|[-._ ]|[BH][DR]RIP|Bluray|BD[-._ ]?(25|50)?|\bBR\b|Camrip|[-._ ]\d{4}[-._ ].+(720p|1080p|Cam|HDTS)|DIVX|[-._ ]DVD[-._ ]|DVD-?(5|9|R|Rip)|Untouched|VHSRip|XVID|[-._ ](DTS|TVrip)[-._ ]/i', $this->releaseName) && !preg_match('/auto(cad|desk)|divx[-._ ]plus|[-._ ]exe$|[-._ ](jav|XXX)[-._ ]|SWE6RUS|\wXXX(1080p|720p|DVD)|Xilisoft/i', $this->releaseName)) { - switch (true) { + return false; + } + + // Movies. + + /** + * @return bool + */ + public function isMovie(): bool + { + if (preg_match('/[-._ ]AVC|[-._ ]|[BH][DR]RIP|Bluray|BD[-._ ]?(25|50)?|\bBR\b|Camrip|[-._ ]\d{4}[-._ ].+(720p|1080p|Cam|HDTS)|DIVX|[-._ ]DVD[-._ ]|DVD-?(5|9|R|Rip)|Untouched|VHSRip|XVID|[-._ ](DTS|TVrip)[-._ ]/i', $this->releaseName) && ! preg_match('/auto(cad|desk)|divx[-._ ]plus|[-._ ]exe$|[-._ ](jav|XXX)[-._ ]|SWE6RUS|\wXXX(1080p|720p|DVD)|Xilisoft/i', $this->releaseName)) { + switch (true) { case $this->categorizeForeign && $this->isMovieForeign(): case $this->isMovieDVD(): case $this->isMovieUHD(): @@ -797,139 +823,158 @@ class Categorize extends Category default: return false; } - } - return false; - } + } - /** - * @return bool|null - */ - public function isMovieForeign(): ?bool - { - switch (true) { + return false; + } + + /** + * @return bool|null + */ + public function isMovieForeign(): ?bool + { + switch (true) { case $this->isConsole(): return true; case preg_match('/(danish|flemish|Deutsch|dutch|french|german|heb|hebrew|nl[-._ ]?sub|dub(bed|s)?|\.NL|norwegian|swedish|swesub|spanish|Staffel)[-._ ]|\(german\)|Multisub/i', $this->releaseName): case stripos($this->releaseName, 'Castellano') !== false: case preg_match('/(720p|1080p|AC3|AVC|DIVX|DVD(5|9|RIP|R)|XVID)[-._ ](Dutch|French|German|ITA)|\(?(Dutch|French|German|ITA)\)?[-._ ](720P|1080p|AC3|AVC|DIVX|DVD(5|9|RIP|R)|HD[-._ ]|XVID)/i', $this->releaseName): $this->tmpCat = Category::MOVIE_FOREIGN; + return true; default: return false; } - } + } - /** - * @return bool - */ - public function isMovieDVD(): bool - { - if (preg_match('/(dvd\-?r|[-._ ]dvd|dvd9|dvd5|[-._ ]r5)[-._ ]/i', $this->releaseName)) { - $this->tmpCat = Category::MOVIE_DVD; - return true; - } - return false; - } + /** + * @return bool + */ + public function isMovieDVD(): bool + { + if (preg_match('/(dvd\-?r|[-._ ]dvd|dvd9|dvd5|[-._ ]r5)[-._ ]/i', $this->releaseName)) { + $this->tmpCat = Category::MOVIE_DVD; - /** - * @return bool - */ - public function isMovieSD(): bool - { - if (preg_match('/(divx|dvdscr|extrascene|dvdrip|\.CAM|HDTS(-LINE)?|vhsrip|xvid(vd)?)[-._ ]/i', $this->releaseName)) { - $this->tmpCat = Category::MOVIE_SD; - return true; - } - return false; - } + return true; + } - /** - * @return bool - */ - public function isMovie3D(): bool - { - if (preg_match('/[-._ ]3D\s?[\.\-_\[ ](1080p|(19|20)\d\d|AVC|BD(25|50)|Blu[-._ ]?ray|CEE|Complete|GER|MVC|MULTi|SBS|H(-)?SBS)[-._ ]/i', $this->releaseName)) { - $this->tmpCat = Category::MOVIE_3D; - return true; - } - return false; - } + return false; + } - /** - * @return bool - */ - public function isMovieBluRay(): bool - { - if (preg_match('/bluray\-|[-._ ]bd?[-._ ]?(25|50)|blu-ray|Bluray\s\-\sUntouched|[-._ ]untouched[-._ ]/i', $this->releaseName) - && !preg_match('/SecretUsenet\.com/i', $this->releaseName)) { - $this->tmpCat = Category::MOVIE_BLURAY; - return true; - } - return false; - } + /** + * @return bool + */ + public function isMovieSD(): bool + { + if (preg_match('/(divx|dvdscr|extrascene|dvdrip|\.CAM|HDTS(-LINE)?|vhsrip|xvid(vd)?)[-._ ]/i', $this->releaseName)) { + $this->tmpCat = Category::MOVIE_SD; - /** - * @return bool - */ - public function isMovieHD(): bool - { - if (preg_match('/720p|1080p|AVC|VC1|VC\-1|web\-dl|wmvhd|x264|XvidHD|bdrip/i', $this->releaseName)) { - $this->tmpCat = Category::MOVIE_HD; - return true; - } - if ($this->catWebDL === false) { - if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { - $this->tmpCat = Category::MOVIE_HD; - return true; - } - } - return false; - } + return true; + } - /** - * @return bool - */ - public function isMovieUHD(): bool - { - if (!preg_match('/(S\d+).*(2160p).*(Netflix|Amazon).*(TrollUHD|NTb|VLAD)/i', $this->releaseName) && preg_match('/2160p/i', $this->releaseName)) { - $this->tmpCat = Category::MOVIE_UHD; - return true; - } - return false; - } + return false; + } - /** - * @return bool - */ - public function isMovieOther(): bool - { - if (preg_match('/[-._ ]cam[-._ ]/i', $this->releaseName)) { - $this->tmpCat = Category::MOVIE_OTHER; - return true; - } - return false; - } + /** + * @return bool + */ + public function isMovie3D(): bool + { + if (preg_match('/[-._ ]3D\s?[\.\-_\[ ](1080p|(19|20)\d\d|AVC|BD(25|50)|Blu[-._ ]?ray|CEE|Complete|GER|MVC|MULTi|SBS|H(-)?SBS)[-._ ]/i', $this->releaseName)) { + $this->tmpCat = Category::MOVIE_3D; - /** - * @return bool - */ - public function isMovieWEBDL(): bool - { - if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { - $this->tmpCat = Category::MOVIE_WEBDL; - return true; - } - return false; - } + return true; + } - // PC. + return false; + } - /** - * @return bool|null - */ - public function isPC(): ?bool - { - switch (true) { + /** + * @return bool + */ + public function isMovieBluRay(): bool + { + if (preg_match('/bluray\-|[-._ ]bd?[-._ ]?(25|50)|blu-ray|Bluray\s\-\sUntouched|[-._ ]untouched[-._ ]/i', $this->releaseName) + && ! preg_match('/SecretUsenet\.com/i', $this->releaseName)) { + $this->tmpCat = Category::MOVIE_BLURAY; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isMovieHD(): bool + { + if (preg_match('/720p|1080p|AVC|VC1|VC\-1|web\-dl|wmvhd|x264|XvidHD|bdrip/i', $this->releaseName)) { + $this->tmpCat = Category::MOVIE_HD; + + return true; + } + if ($this->catWebDL === false) { + if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { + $this->tmpCat = Category::MOVIE_HD; + + return true; + } + } + + return false; + } + + /** + * @return bool + */ + public function isMovieUHD(): bool + { + if (! preg_match('/(S\d+).*(2160p).*(Netflix|Amazon).*(TrollUHD|NTb|VLAD)/i', $this->releaseName) && preg_match('/2160p/i', $this->releaseName)) { + $this->tmpCat = Category::MOVIE_UHD; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isMovieOther(): bool + { + if (preg_match('/[-._ ]cam[-._ ]/i', $this->releaseName)) { + $this->tmpCat = Category::MOVIE_OTHER; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isMovieWEBDL(): bool + { + if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { + $this->tmpCat = Category::MOVIE_WEBDL; + + return true; + } + + return false; + } + + // PC. + + /** + * @return bool|null + */ + public function isPC(): ?bool + { + switch (true) { case preg_match('/s\d{1,3}[-._ ]?[ed]\d{1,3}([ex]\d{1,3}|[-.\w ])|[^a-z0-9](FLAC|Imageset|PICTURESET|MP3|Nintendo|PDTV|PS[23P]|SWE6RUS|UMD(RIP)?|WII|x264|XBOX(360|DVD|ONE)?|XXX)[^a-z0-9]/i', $this->releaseName): return false; case $this->isPhone(): @@ -941,14 +986,14 @@ class Categorize extends Category default: return false; } - } + } - /** - * @return bool - */ - public function isPhone(): bool - { - switch (true) { + /** + * @return bool + */ + public function isPhone(): bool + { + switch (true) { case preg_match('/[^a-z0-9](IPHONE|ITOUCH|IPAD)[-._ ]/i', $this->releaseName): $this->tmpCat = Category::PC_PHONE_IOS; break; @@ -961,74 +1006,80 @@ class Categorize extends Category default: return false; } - return true; - } - /** - * @return bool|null - */ - public function isISO(): ?bool - { - switch (true) { + return true; + } + + /** + * @return bool|null + */ + public function isISO(): ?bool + { + switch (true) { case preg_match('/[-._ ]([a-zA-Z]{2,10})?iso[ _.-]|[-. ]([a-z]{2,10})?iso$/i', $this->releaseName): case preg_match('/[-._ ](DYNAMiCS|INFINITESKILLS|UDEMY|kEISO|PLURALSIGHT|DIGITALTUTORS|TUTSPLUS|OSTraining|PRODEV|CBT\.Nuggets|COMPRISED)/i', $this->releaseName): $this->tmpCat = Category::PC_ISO; + return true; default: return false; } - } + } - /** - * @return bool|null - */ - public function is0day(): ?bool - { - switch (true) { + /** + * @return bool|null + */ + public function is0day(): ?bool + { + switch (true) { case preg_match('/[-._ ]exe$|[-._ ](utorrent|Virtualbox)[-._ ]|\b0DAY\b|incl.+crack| DRM$|>DRM</i', $this->releaseName): case preg_match('/[-._ ]((32|64)bit|converter|i\d86|key(gen|maker)|freebsd|GAMEGUiDE|hpux|irix|linux|multilingual|Patch|Pro v\d{1,3}|portable|regged|software|solaris|template|unix|win2kxp2k3|win64|win(2k|32|64|all|dows|nt(2k)?(xp)?|xp)|win9x(me|nt)?|x(32|64|86))[-._ ]/i', $this->releaseName): case preg_match('/\b(Adobe|auto(cad|desk)|-BEAN|Cracked|Cucusoft|CYGNUS|Divx[-._ ]Plus|\.(deb|exe)|DIGERATI|FOSI|-FONT|Key(filemaker|gen|maker)|Lynda\.com|lz0|MULTiLANGUAGE|Microsoft\s*(Office|Windows|Server)|MultiOS|-(iNViSiBLE|SPYRAL|SUNiSO|UNION|TE)|v\d{1,3}.*?Pro|[-._ ]v\d{1,3}[-._ ]|\(x(64|86)\)|Xilisoft)\b/i', $this->releaseName): $this->tmpCat = Category::PC_0DAY; + return true; default: return false; } - } + } - /** - * @return bool - */ - public function isMac(): bool - { - if (preg_match('/(\b|[-._ ])mac(\.|\s)?osx(\b|[-_. ])/i', $this->releaseName)) { - $this->tmpCat = Category::PC_MAC; - return true; - } - return false; - } + /** + * @return bool + */ + public function isMac(): bool + { + if (preg_match('/(\b|[-._ ])mac(\.|\s)?osx(\b|[-_. ])/i', $this->releaseName)) { + $this->tmpCat = Category::PC_MAC; - /** - * @return bool - */ - public function isPCGame(): bool - { - if (preg_match('/[^a-z0-9](0x0007|ALiAS|BACKLASH|BAT|CLONECD|CPY|FAS(DOX|iSO)|FLT([-._ ]|COGENT)|FLT(DOX)?|PC GAMES?|\(?(Game(s|z)|GAME(S|Z))\)? ?(\((C|c)\))|GENESIS|-GOG|-HATRED|HI2U|INLAWS|JAGUAR|MAZE|MONEY|OUTLAWS|PPTCLASSiCS|PC Game|PROPHET|RAiN|Razor1911|RELOADED|DEViANCE|PLAZA|RiTUELYPOGEiOS|[rR][iI][pP]-[uU][nN][lL][eE][aA][sS][hH][eE][dD]|Steam(\b)?Rip|SKIDROW|TiNYiSO|CODEX)[^a-z0-9]?/', $this->releaseName)) { - $this->tmpCat = Category::PC_GAMES; - return true; - } + return true; + } - return false; - } + return false; + } - // XXX. + /** + * @return bool + */ + public function isPCGame(): bool + { + if (preg_match('/[^a-z0-9](0x0007|ALiAS|BACKLASH|BAT|CLONECD|CPY|FAS(DOX|iSO)|FLT([-._ ]|COGENT)|FLT(DOX)?|PC GAMES?|\(?(Game(s|z)|GAME(S|Z))\)? ?(\((C|c)\))|GENESIS|-GOG|-HATRED|HI2U|INLAWS|JAGUAR|MAZE|MONEY|OUTLAWS|PPTCLASSiCS|PC Game|PROPHET|RAiN|Razor1911|RELOADED|DEViANCE|PLAZA|RiTUELYPOGEiOS|[rR][iI][pP]-[uU][nN][lL][eE][aA][sS][hH][eE][dD]|Steam(\b)?Rip|SKIDROW|TiNYiSO|CODEX)[^a-z0-9]?/', $this->releaseName)) { + $this->tmpCat = Category::PC_GAMES; - /** - * @return bool|null - */ - public function isXxx(): ?bool - { - switch (true) { - case !preg_match('/\bXXX\b|(a\.b\.erotica|ClubSeventeen|Cum(ming|shot)|Err?oticax?|Porn(o|lation)?|Imageset|PICTURESET|JAV Uncensored|lesb(ians?|os?)|mastur(bation|e?bate)|My_Stepfather_Made_Me|nympho?|OLDER ANGELS|pictures\.erotica\.anime|sexontv|slut|Squirt|SWE6RUS|Transsexual|whore)/i', $this->releaseName): + return true; + } + + return false; + } + + // XXX. + + /** + * @return bool|null + */ + public function isXxx(): ?bool + { + switch (true) { + case ! preg_match('/\bXXX\b|(a\.b\.erotica|ClubSeventeen|Cum(ming|shot)|Err?oticax?|Porn(o|lation)?|Imageset|PICTURESET|JAV Uncensored|lesb(ians?|os?)|mastur(bation|e?bate)|My_Stepfather_Made_Me|nympho?|OLDER ANGELS|pictures\.erotica\.anime|sexontv|slut|Squirt|SWE6RUS|Transsexual|whore)/i', $this->releaseName): return false; case $this->isXxxPack(): case $this->isXxxClipSD(): @@ -1046,177 +1097,202 @@ class Categorize extends Category return true; default: $this->tmpCat = Category::XXX_OTHER; + return true; } - } + } - /** - * @return bool - */ - public function isXxx264(): bool - { - if (preg_match('/720p|1080(hd|[ip])|[xh][^a-z0-9]?264/i', $this->releaseName) && !preg_match('/\bwmv\b/i', $this->releaseName) && stripos($this->releaseName, 'SDX264XXX') === false) { - $this->tmpCat = Category::XXX_X264; - return true; - } - if ($this->catWebDL === false) { - if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { - $this->tmpCat = Category::XXX_X264; + /** + * @return bool + */ + public function isXxx264(): bool + { + if (preg_match('/720p|1080(hd|[ip])|[xh][^a-z0-9]?264/i', $this->releaseName) && ! preg_match('/\bwmv\b/i', $this->releaseName) && stripos($this->releaseName, 'SDX264XXX') === false) { + $this->tmpCat = Category::XXX_X264; + + return true; + } + if ($this->catWebDL === false) { + if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { + $this->tmpCat = Category::XXX_X264; + + return true; + } + } + + return false; + } + + /** + * @return bool + */ + public function isXxxUHD(): bool + { + if (preg_match('/^[\w-.]+(\d{2}\.\d{2}\.\d{2}).+(2160p)+[\w-.]+(M[PO][V4]-(KTR|GUSH|FaiLED|SEXORS|hUSHhUSH|YAPG))/i', $this->releaseName)) { + $this->tmpCat = Category::XXX_UHD; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isXxxClipHD(): bool + { + if (preg_match('/^[\w-.]+(\d{2}\.\d{2}\.\d{2}).+(720|1080)+[\w-.]+(M[PO][V4]-(KTR|GUSH|FaiLED|SEXORS|hUSHhUSH|YAPG))/i', $this->releaseName)) { + $this->tmpCat = Category::XXX_CLIPHD; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isXxxWMV(): bool + { + if (preg_match('/(\d{2}\.\d{2}\.\d{2})|([ex]\d{2,})|[^a-z0-9](f4v|flv|isom|(issue\.\d{2,})|mov|mp(4|eg)|multiformat|pack-|realmedia|uhq|wmv)[^a-z0-9]/i', $this->releaseName) && stripos($this->releaseName, 'SDX264XXX') === false) { + $this->tmpCat = Category::XXX_WMV; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isXxxXvid(): bool + { + if (preg_match('/(b[dr]|dvd)rip|detoxication|divx|nympho|pornolation|swe6|tesoro|xvid/i', $this->releaseName)) { + $this->tmpCat = Category::XXX_XVID; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isXxxDVD(): bool + { + if (preg_match('/dvdr[^i]|dvd[59]/i', $this->releaseName)) { + $this->tmpCat = Category::XXX_DVD; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isXxxImageset(): bool + { + if (preg_match('/IMAGESET|PICTURESET|ABPEA/i', $this->releaseName)) { + $this->tmpCat = Category::XXX_IMAGESET; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isXxxPack(): bool + { + if (preg_match('/[ .]PACK[ .]/i', $this->releaseName)) { + $this->tmpCat = Category::XXX_PACK; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isXxxOther(): bool + { + // If nothing else matches, then try these words. + if (preg_match('/[-._ ]Brazzers|Creampie|[-._ ]JAV[-._ ]|North\.Pole|^Nubiles|She[-._ ]?Male|Transsexual|OLDER ANGELS/i', $this->releaseName)) { + $this->tmpCat = Category::XXX_OTHER; + + return true; + } + + return false; + } + + /** + * @return bool|null + */ + public function isXxxClipSD(): ?bool + { + switch (true) { + case $this->checkPoster('/oz@lot[.]com/i', $this->poster, Category::XXX_CLIPSD): return true; - } - } - return false; - } - - /** - * @return bool - */ - public function isXxxUHD(): bool - { - if (preg_match('/^[\w-.]+(\d{2}\.\d{2}\.\d{2}).+(2160p)+[\w-.]+(M[PO][V4]-(KTR|GUSH|FaiLED|SEXORS|hUSHhUSH|YAPG))/i', $this->releaseName)) { - $this->tmpCat = Category::XXX_UHD; - return true; - } - return false; - } - - /** - * @return bool - */ - public function isXxxClipHD(): bool - { - if (preg_match('/^[\w-.]+(\d{2}\.\d{2}\.\d{2}).+(720|1080)+[\w-.]+(M[PO][V4]-(KTR|GUSH|FaiLED|SEXORS|hUSHhUSH|YAPG))/i', $this->releaseName)) { - $this->tmpCat = Category::XXX_CLIPHD; - return true; - } - return false; - } - - /** - * @return bool - */ - public function isXxxWMV(): bool - { - if (preg_match('/(\d{2}\.\d{2}\.\d{2})|([ex]\d{2,})|[^a-z0-9](f4v|flv|isom|(issue\.\d{2,})|mov|mp(4|eg)|multiformat|pack-|realmedia|uhq|wmv)[^a-z0-9]/i', $this->releaseName) && stripos($this->releaseName, 'SDX264XXX') === false) { - $this->tmpCat = Category::XXX_WMV; - return true; - } - return false; - } - - /** - * @return bool - */ - public function isXxxXvid(): bool - { - if (preg_match('/(b[dr]|dvd)rip|detoxication|divx|nympho|pornolation|swe6|tesoro|xvid/i', $this->releaseName)) { - $this->tmpCat = Category::XXX_XVID; - return true; - } - return false; - } - - /** - * @return bool - */ - public function isXxxDVD(): bool - { - if (preg_match('/dvdr[^i]|dvd[59]/i', $this->releaseName)) { - $this->tmpCat = Category::XXX_DVD; - return true; - } - return false; - } - - /** - * @return bool - */ - public function isXxxImageset(): bool - { - if (preg_match('/IMAGESET|PICTURESET|ABPEA/i', $this->releaseName)) { - $this->tmpCat = Category::XXX_IMAGESET; - return true; - } - return false; - } - - /** - * @return bool - */ - public function isXxxPack(): bool - { - if (preg_match('/[ .]PACK[ .]/i', $this->releaseName)) { - $this->tmpCat = Category::XXX_PACK; - return true; - } - return false; - } - - /** - * @return bool - */ - public function isXxxOther(): bool - { - // If nothing else matches, then try these words. - if (preg_match('/[-._ ]Brazzers|Creampie|[-._ ]JAV[-._ ]|North\.Pole|^Nubiles|She[-._ ]?Male|Transsexual|OLDER ANGELS/i', $this->releaseName)) { - $this->tmpCat = Category::XXX_OTHER; - return true; - } - return false; - } - - /** - * @return bool|null - */ - public function isXxxClipSD(): ?bool - { - switch(true) { - case $this->checkPoster( '/oz@lot[.]com/i', $this->poster, Category::XXX_CLIPSD): - return true; - case $this->checkPoster( '/anon@y[.]com/i', $this->poster, Category::XXX_CLIPSD): + case $this->checkPoster('/anon@y[.]com/i', $this->poster, Category::XXX_CLIPSD): return true; case $this->checkPoster('/@md-hobbys[.]com/i', $this->poster, Category::XXX_CLIPSD): return true; case stripos($this->releaseName, 'SDPORN') !== false: $this->tmpCat = Category::XXX_CLIPSD; + return true; default: return false; } - } + } - /** - * @return bool - */ - public function isXxxSD(): bool - { - if (preg_match('/SDX264XXX|XXX\.HR\./i', $this->releaseName)) { - $this->tmpCat = Category::XXX_SD; - return true; - } - return false; - } + /** + * @return bool + */ + public function isXxxSD(): bool + { + if (preg_match('/SDX264XXX|XXX\.HR\./i', $this->releaseName)) { + $this->tmpCat = Category::XXX_SD; - /** - * @return bool - */ - public function isXxxWEBDL(): bool - { - if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { - $this->tmpCat = Category::XXX_WEBDL; - return true; - } - return false; - } + return true; + } - // Console. + return false; + } - /** - * @return bool|null - */ - public function isConsole(): ?bool - { - switch (true) { + /** + * @return bool + */ + public function isXxxWEBDL(): bool + { + if (preg_match('/web[-._ ]dl|web-?rip/i', $this->releaseName)) { + $this->tmpCat = Category::XXX_WEBDL; + + return true; + } + + return false; + } + + // Console. + + /** + * @return bool|null + */ + public function isConsole(): ?bool + { + switch (true) { case $this->isGameNDS(): case $this->isGame3DS(): case $this->isGamePS3(): @@ -1236,252 +1312,287 @@ class Categorize extends Category default: return false; } - } + } - /** - * @return bool - */ - public function isGameNDS(): bool - { - if (preg_match('/^NDS|[^a-zA-Z0-9]NDS|[\._-](nds|NDS)|nintendo.+[^3]n?dsi?/', $this->releaseName)) { - if (preg_match('/\((DE|DSi(\sEnhanched)?|_NDS-|EUR?|FR|GAME|HOL|JP|JPN|NL|NTSC|PAL|KS|USA?)\)/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_NDS; - return true; - } - if (preg_match('/EUR|FR|GAME|HOL|JP|JPN|NL|NTSC|PAL|KS|USA|\bROMS?(et)?\b/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_NDS; - return true; - } - } - return false; - } + /** + * @return bool + */ + public function isGameNDS(): bool + { + if (preg_match('/^NDS|[^a-zA-Z0-9]NDS|[\._-](nds|NDS)|nintendo.+[^3]n?dsi?/', $this->releaseName)) { + if (preg_match('/\((DE|DSi(\sEnhanched)?|_NDS-|EUR?|FR|GAME|HOL|JP|JPN|NL|NTSC|PAL|KS|USA?)\)/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_NDS; - /** - * @return bool - */ - public function isGame3DS(): bool - { - if (preg_match('/\b3DS\b[^max]|[\._-]3ds|nintendo.+3ds|[_\.]3DS-/i', $this->releaseName) && !preg_match('/3ds max/i', $this->releaseName)) { - if (preg_match('/(EUR|FR|GAME|HOL|JP|JPN|NL|NTSC|PAL|KS|USA|ASIA)/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_3DS; - return true; - } - } - return false; - } + return true; + } + if (preg_match('/EUR|FR|GAME|HOL|JP|JPN|NL|NTSC|PAL|KS|USA|\bROMS?(et)?\b/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_NDS; - /** - * @return bool - */ - public function isGameNGC(): bool - { - if (preg_match('/[\._-]N?G(AME)?C(UBE)?-/i', $this->releaseName)) { - if (preg_match('/_(EUR?|FR|GAME|HOL|JP|JPN|NL|NTSC|PAL|KS|USA?)_/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_OTHER; - return true; - } - if (preg_match('/-(((STAR|DEATH|STINKY|MOON|HOLY|G)?CUBE(SOFT)?)|(DARKFORCE|DNL|GP|ICP|iNSOMNIA|JAY|LaKiTu|METHS|NOMIS|QUBiSM|PANDORA|REACT0R|SUNSHiNE|SAVEPOiNT|SYNDiCATE|WAR3X|WRG))/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_OTHER; - return true; - } - } - return false; - } + return true; + } + } - /** - * @return bool - */ - public function isGamePS3(): bool - { - if (preg_match('/[^e]PS3/i', $this->releaseName)) { - if (preg_match('/ANTiDOTE|DLC|DUPLEX|EUR?|Googlecus|GOTY|\-HR|iNSOMNi|JAP|JPN|KONDIOS|\[PS3\]|PSN/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_PS3; - return true; - } - if (preg_match('/AGENCY|APATHY|Caravan|MULTi|NRP|NTSC|PAL|SPLiT|STRiKE|USA?|ZRY/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_PS3; - return true; - } - } - return false; - } + return false; + } - /** - * @return bool - */ - public function isGamePS4(): bool - { - if (preg_match('/[ \(_.-]PS4[ \)_.-]/i', $this->releaseName)) { - if (preg_match('/ANTiDOTE|DLC|DUPLEX|EUR?|Googlecus|GOTY|\-HR|iNSOMNi|JAP|JPN|KONDIOS|\[PS4\]/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_PS4; - return true; - } - if (preg_match('/AGENCY|APATHY|Caravan|MULTi|NRP|NTSC|PAL|SPLiT|STRiKE|USA?|WaYsTeD|ZRY/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_PS4; - return true; - } - } - return false; - } + /** + * @return bool + */ + public function isGame3DS(): bool + { + if (preg_match('/\b3DS\b[^max]|[\._-]3ds|nintendo.+3ds|[_\.]3DS-/i', $this->releaseName) && ! preg_match('/3ds max/i', $this->releaseName)) { + if (preg_match('/(EUR|FR|GAME|HOL|JP|JPN|NL|NTSC|PAL|KS|USA|ASIA)/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_3DS; - /** - * @return bool - */ - public function isGamePSP(): bool - { - if (stripos($this->releaseName, 'PSP') !== false) { - if (preg_match('/[-._ ](BAHAMUT|Caravan|EBOOT|EMiNENT|EUR?|EvoX|GAME|GHS|Googlecus|HandHeld|\-HR|JAP|JPN|KLOTEKLAPPERS|KOR|NTSC|PAL)/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_PSP; - return true; - } - if (preg_match('/[-._ ](Dynarox|HAZARD|ITALIAN|KLB|KuDoS|LIGHTFORCE|MiRiBS|POPSTATiON|(PLAY)?ASiA|PSN|PSX2?PSP|SPANiSH|SUXXORS|UMD(RIP)?|USA?|YARR)/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_PSP; - return true; - } - } - return false; - } + return true; + } + } - /** - * @return bool - */ - public function isGamePSVita(): bool - { - if (preg_match('/PS ?Vita/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_PSVITA; - return true; - } - return false; - } + return false; + } - /** - * @return bool - */ - public function isGameWiiWare(): bool - { - if (preg_match('/(Console|DLC|VC).+[-._ ]WII|(Console|DLC|VC)[-._ ]WII|WII[-._ ].+(Console|DLC|VC)|WII[-._ ](Console|DLC|VC)|WIIWARE/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_WIIWARE; - return true; - } - return false; - } + /** + * @return bool + */ + public function isGameNGC(): bool + { + if (preg_match('/[\._-]N?G(AME)?C(UBE)?-/i', $this->releaseName)) { + if (preg_match('/_(EUR?|FR|GAME|HOL|JP|JPN|NL|NTSC|PAL|KS|USA?)_/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_OTHER; - /** - * @return bool|null - */ - public function isGameWiiU(): ?bool - { - switch (true) { - case !preg_match('/WII-?U/i', $this->releaseName): + return true; + } + if (preg_match('/-(((STAR|DEATH|STINKY|MOON|HOLY|G)?CUBE(SOFT)?)|(DARKFORCE|DNL|GP|ICP|iNSOMNIA|JAY|LaKiTu|METHS|NOMIS|QUBiSM|PANDORA|REACT0R|SUNSHiNE|SAVEPOiNT|SYNDiCATE|WAR3X|WRG))/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_OTHER; + + return true; + } + } + + return false; + } + + /** + * @return bool + */ + public function isGamePS3(): bool + { + if (preg_match('/[^e]PS3/i', $this->releaseName)) { + if (preg_match('/ANTiDOTE|DLC|DUPLEX|EUR?|Googlecus|GOTY|\-HR|iNSOMNi|JAP|JPN|KONDIOS|\[PS3\]|PSN/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_PS3; + + return true; + } + if (preg_match('/AGENCY|APATHY|Caravan|MULTi|NRP|NTSC|PAL|SPLiT|STRiKE|USA?|ZRY/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_PS3; + + return true; + } + } + + return false; + } + + /** + * @return bool + */ + public function isGamePS4(): bool + { + if (preg_match('/[ \(_.-]PS4[ \)_.-]/i', $this->releaseName)) { + if (preg_match('/ANTiDOTE|DLC|DUPLEX|EUR?|Googlecus|GOTY|\-HR|iNSOMNi|JAP|JPN|KONDIOS|\[PS4\]/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_PS4; + + return true; + } + if (preg_match('/AGENCY|APATHY|Caravan|MULTi|NRP|NTSC|PAL|SPLiT|STRiKE|USA?|WaYsTeD|ZRY/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_PS4; + + return true; + } + } + + return false; + } + + /** + * @return bool + */ + public function isGamePSP(): bool + { + if (stripos($this->releaseName, 'PSP') !== false) { + if (preg_match('/[-._ ](BAHAMUT|Caravan|EBOOT|EMiNENT|EUR?|EvoX|GAME|GHS|Googlecus|HandHeld|\-HR|JAP|JPN|KLOTEKLAPPERS|KOR|NTSC|PAL)/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_PSP; + + return true; + } + if (preg_match('/[-._ ](Dynarox|HAZARD|ITALIAN|KLB|KuDoS|LIGHTFORCE|MiRiBS|POPSTATiON|(PLAY)?ASiA|PSN|PSX2?PSP|SPANiSH|SUXXORS|UMD(RIP)?|USA?|YARR)/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_PSP; + + return true; + } + } + + return false; + } + + /** + * @return bool + */ + public function isGamePSVita(): bool + { + if (preg_match('/PS ?Vita/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_PSVITA; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isGameWiiWare(): bool + { + if (preg_match('/(Console|DLC|VC).+[-._ ]WII|(Console|DLC|VC)[-._ ]WII|WII[-._ ].+(Console|DLC|VC)|WII[-._ ](Console|DLC|VC)|WIIWARE/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_WIIWARE; + + return true; + } + + return false; + } + + /** + * @return bool|null + */ + public function isGameWiiU(): ?bool + { + switch (true) { + case ! preg_match('/WII-?U/i', $this->releaseName): return false; case preg_match('/[-._ ](Allstars|BiOSHOCK|dumpTruck|DNi|iCON|JAP|NTSC|PAL|ProCiSiON|PROPER|RANT|REV0|SUNSHiNE|SUSHi|TMD|USA?)/i', $this->releaseName): case preg_match('/[-._ ](APATHY|BAHAMUT|DMZ|ERD|GAME|JPN|LoCAL|MULTi|NAGGERS|OneUp|PLAYME|PONS|Scrubbed|VORTEX|ZARD|ZER0)/i', $this->releaseName): case preg_match('/[-._ ](ALMoST|AMBITION|Caravan|CLiiCHE|DRYB|HaZMaT|KOR|LOADER|MARVEL|PROMiNENT|LaKiTu|LOCAL|QwiiF|RANT)/i', $this->releaseName): $this->tmpCat = Category::GAME_WIIU; + return true; default: return false; } - } + } - /** - * @return bool|null - */ - public function isGameWii(): ?bool - { - switch (true) { + /** + * @return bool|null + */ + public function isGameWii(): ?bool + { + switch (true) { case stripos($this->releaseName, 'WII') === false: return false; case preg_match('/[-._ ](Allstars|BiOSHOCK|dumpTruck|DNi|iCON|JAP|NTSC|PAL|ProCiSiON|PROPER|RANT|REV0|SUNSHiNE|SUSHi|TMD|USA?)/i', $this->releaseName): case preg_match('/[-._ ](APATHY|BAHAMUT|DMZ|ERD|GAME|JPN|LoCAL|MULTi|NAGGERS|OneUp|PLAYME|PONS|Scrubbed|VORTEX|ZARD|ZER0)/i', $this->releaseName): case preg_match('/[-._ ](ALMoST|AMBITION|Caravan|CLiiCHE|DRYB|HaZMaT|KOR|LOADER|MARVEL|PROMiNENT|LaKiTu|LOCAL|QwiiF|RANT)/i', $this->releaseName): $this->tmpCat = Category::GAME_WII; + return true; default: return false; } - } + } - /** - * @return bool - */ - public function isGameXBOX360DLC(): bool - { - if (preg_match('/DLC.+xbox360|xbox360.+DLC|XBLA.+xbox360|xbox360.+XBLA/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_XBOX360DLC; - return true; - } - return false; - } + /** + * @return bool + */ + public function isGameXBOX360DLC(): bool + { + if (preg_match('/DLC.+xbox360|xbox360.+DLC|XBLA.+xbox360|xbox360.+XBLA/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_XBOX360DLC; - /** - * @return bool - */ - public function isGameXBOX360(): bool - { - if (stripos($this->releaseName, '/XBOX360/i') !== false) { - $this->tmpCat = Category::GAME_XBOX360; - return true; - } - if (stripos($this->releaseName, 'x360') !== false) { - if (preg_match('/Allstars|ASiA|CCCLX|COMPLEX|DAGGER|GLoBAL|iMARS|JAP|JPN|MULTi|NTSC|PAL|REPACK|RRoD|RF|SWAG|USA?/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_XBOX360; - return true; - } - if (preg_match('/DAMNATION|GERMAN|GOTY|iNT|iTA|JTAG|KINECT|MARVEL|MUX360|RANT|SPARE|SPANISH|VATOS|XGD/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_XBOX360; - return true; - } - } - return false; - } + return true; + } - /** - * @return bool - */ - public function isGameXBOXONE(): bool - { - if (preg_match('/XBOXONE|XBOX\.ONE/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_XBOXONE; - return true; - } - return false; - } + return false; + } - /** - * @return bool - */ - public function isGameXBOX(): bool - { - if (stripos($this->releaseName, 'XBOX') !== false) { - $this->tmpCat = Category::GAME_XBOX; - return true; - } - return false; - } + /** + * @return bool + */ + public function isGameXBOX360(): bool + { + if (stripos($this->releaseName, '/XBOX360/i') !== false) { + $this->tmpCat = Category::GAME_XBOX360; - /** - * @return bool - */ - public function isGameOther(): bool - { - if (preg_match('/\b(PS(1)X|PS2|SNES|NES|SEGA\s(GENESIS|CD)|GB(A|C)|Dreamcast|SEGA\sSaturn|Atari\s(Jaguar)?|3DO)\b/i', $this->releaseName)) { - if (preg_match('/EUR|FR|GAME|HOL|\bISO\b|JP|JPN|NL|NTSC|PAL|KS|USA|ROMS?(et)?/i', $this->releaseName)) { - $this->tmpCat = Category::GAME_OTHER; - return true; - } - } - return false; - } + return true; + } + if (stripos($this->releaseName, 'x360') !== false) { + if (preg_match('/Allstars|ASiA|CCCLX|COMPLEX|DAGGER|GLoBAL|iMARS|JAP|JPN|MULTi|NTSC|PAL|REPACK|RRoD|RF|SWAG|USA?/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_XBOX360; - // Music. + return true; + } + if (preg_match('/DAMNATION|GERMAN|GOTY|iNT|iTA|JTAG|KINECT|MARVEL|MUX360|RANT|SPARE|SPANISH|VATOS|XGD/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_XBOX360; - /** - * @return bool|null - */ - public function isMusic(): ?bool - { - switch (true) { + return true; + } + } + + return false; + } + + /** + * @return bool + */ + public function isGameXBOXONE(): bool + { + if (preg_match('/XBOXONE|XBOX\.ONE/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_XBOXONE; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isGameXBOX(): bool + { + if (stripos($this->releaseName, 'XBOX') !== false) { + $this->tmpCat = Category::GAME_XBOX; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isGameOther(): bool + { + if (preg_match('/\b(PS(1)X|PS2|SNES|NES|SEGA\s(GENESIS|CD)|GB(A|C)|Dreamcast|SEGA\sSaturn|Atari\s(Jaguar)?|3DO)\b/i', $this->releaseName)) { + if (preg_match('/EUR|FR|GAME|HOL|\bISO\b|JP|JPN|NL|NTSC|PAL|KS|USA|ROMS?(et)?/i', $this->releaseName)) { + $this->tmpCat = Category::GAME_OTHER; + + return true; + } + } + + return false; + } + + // Music. + + /** + * @return bool|null + */ + public function isMusic(): ?bool + { + switch (true) { //They Knew What They Wanted (1940).480p.DVDRIP.MP3-NoGroup -- prevents movies matches with MP3 audio codec in the title case preg_match('/\d{3,4}(p|i)\.DVD(RIP)?\.MP3[-\.].*|WEB(-DL|-?RIP)/i', $this->releaseName): return false; @@ -1494,124 +1605,138 @@ class Categorize extends Category default: return false; } - } + } - /** - * @return bool - */ - public function isMusicForeign(): bool - { - if ($this->categorizeForeign && preg_match('/[ \-\._](brazilian|chinese|croatian|danish|deutsch|dutch|estonian|flemish|finnish|french|german|greek|hebrew|icelandic|italian|ita|latin|mandarin|nordic|norwegian|polish|portuguese|japenese|japanese|russian|serbian|slovenian|spanish|spanisch|swedish|thai|turkish|bl|cz|de|es|fr|ger|heb|hu|hun|it(a| 19|20\d\d)|jap|ko|kor|nl|pl|se)[ \-\._]/i', $this->releaseName)) { - $this->tmpCat = Category::MUSIC_FOREIGN; - return true; - } - return false; - } + /** + * @return bool + */ + public function isMusicForeign(): bool + { + if ($this->categorizeForeign && preg_match('/[ \-\._](brazilian|chinese|croatian|danish|deutsch|dutch|estonian|flemish|finnish|french|german|greek|hebrew|icelandic|italian|ita|latin|mandarin|nordic|norwegian|polish|portuguese|japenese|japanese|russian|serbian|slovenian|spanish|spanisch|swedish|thai|turkish|bl|cz|de|es|fr|ger|heb|hu|hun|it(a| 19|20\d\d)|jap|ko|kor|nl|pl|se)[ \-\._]/i', $this->releaseName)) { + $this->tmpCat = Category::MUSIC_FOREIGN; - /** - * @return bool - */ - public function isAudiobook(): bool - { - if ($this->categorizeForeign) { - if (stripos($this->releaseName, 'Audiobook') !== false) { - $this->tmpCat = Category::MUSIC_FOREIGN; - return true; - } - } - return false; - } + return true; + } - /** - * @return bool - */ - public function isMusicVideo(): bool - { - if (preg_match('/(720P|x264)\-(19|20)\d\d\-[a-z0-9]{1,12}/i', $this->releaseName)) { - if ($this->isMusicForeign()) { - return true; - } - $this->tmpCat = Category::MUSIC_VIDEO; - return true; - } - if (preg_match('/[a-z0-9]{1,12}\-(19|20)\d\d\-(720P|x264)/i', $this->releaseName)) { - if ($this->isMusicForeign()) { - return true; - } - $this->tmpCat = Category::MUSIC_VIDEO; - return true; + return false; + } - } - return false; - } + /** + * @return bool + */ + public function isAudiobook(): bool + { + if ($this->categorizeForeign) { + if (stripos($this->releaseName, 'Audiobook') !== false) { + $this->tmpCat = Category::MUSIC_FOREIGN; - /** - * @return bool - */ - public function isMusicLossless(): bool - { - if (preg_match('/\[(19|20)\d\d\][-._ ]\[FLAC\]|(\(|\[)flac(\)|\])|FLAC\-(19|20)\d\d\-[a-z0-9]{1,12}|\.flac"|(19|20)\d\d\sFLAC|[-._ ]FLAC.+(19|20)\d\d[-._ ]| FLAC$/i', $this->releaseName)) { - if ($this->isMusicForeign()) { - return true; - } - $this->tmpCat = Category::MUSIC_LOSSLESS; - return true; - } - return false; - } + return true; + } + } - /** - * @return bool - */ - public function isMusicMP3(): bool - { - if (preg_match('/[a-z0-9]{1,12}\-(19|20)\d\d\-[a-z0-9]{1,12}|[\.\-\(\[_ ]\d{2,3}k[\.\-\)\]_ ]|\((192|256|320)\)|(320|cd|eac|vbr).+mp3|(cd|eac|mp3|vbr).+320|FIH\_INT|\s\dCDs|[-._ ]MP3[-._ ]|MP3\-\d{3}kbps|\.(m3u|mp3)"|NMR\s\d{2,3}\skbps|\(320\)\.|\-\((Bootleg|Promo)\)|\.mp3$|\-\sMP3\s(19|20)\d\d|\(vbr\)|rip(192|256|320)|[-._ ](CDR|SBD|WEB).+(19|20)\d\d/i', $this->releaseName)) { - if ($this->isMusicForeign()) { - return true; - } - $this->tmpCat = Category::MUSIC_MP3; - return true; - } - if (preg_match('/\s(19|20)\d\d\s([a-z0-9]{3}|[a-z]{2,})$|\-(19|20)\d\d\-(C4|MTD)(\s|\.)|[-._ ]FM.+MP3[-._ ]|-web-(19|20)\d\d(\.|\s|$)|[-._ ](SAT|SBD|WEB).+(19|20)\d\d([-._ ]|$)|[-._ ](19|20)\d\d.+(SAT|WEB)([-._ ]|$)| MP3$/i', $this->releaseName)) { - if ($this->isMusicForeign()) { - return true; - } - $this->tmpCat = Category::MUSIC_MP3; - return true; - } - return false; - } + return false; + } - /** - * @return bool - */ - public function isMusicOther(): bool - { - if (preg_match('/(19|20)\d\d\-(C4)$|[-._ ]\d?CD[-._ ](19|20)\d\d|\(\d\-?CD\)|\-\dcd\-|\d[-._ ]Albums|Albums.+(EP)|Bonus.+Tracks|Box.+?CD.+SET|Discography|D\.O\.M|Greatest\sSongs|Live.+(Bootleg|Remastered)|Music.+Vol|(\(|\[|\s)NMR(\)|\]|\s)|Promo.+CD|Reggaeton|Tiesto.+Club|Vinyl\s2496|\WV\.A\.|^\(VA\s|^VA[-._ ]/i', $this->releaseName)) { - switch (true) { + /** + * @return bool + */ + public function isMusicVideo(): bool + { + if (preg_match('/(720P|x264)\-(19|20)\d\d\-[a-z0-9]{1,12}/i', $this->releaseName)) { + if ($this->isMusicForeign()) { + return true; + } + $this->tmpCat = Category::MUSIC_VIDEO; + + return true; + } + if (preg_match('/[a-z0-9]{1,12}\-(19|20)\d\d\-(720P|x264)/i', $this->releaseName)) { + if ($this->isMusicForeign()) { + return true; + } + $this->tmpCat = Category::MUSIC_VIDEO; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isMusicLossless(): bool + { + if (preg_match('/\[(19|20)\d\d\][-._ ]\[FLAC\]|(\(|\[)flac(\)|\])|FLAC\-(19|20)\d\d\-[a-z0-9]{1,12}|\.flac"|(19|20)\d\d\sFLAC|[-._ ]FLAC.+(19|20)\d\d[-._ ]| FLAC$/i', $this->releaseName)) { + if ($this->isMusicForeign()) { + return true; + } + $this->tmpCat = Category::MUSIC_LOSSLESS; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isMusicMP3(): bool + { + if (preg_match('/[a-z0-9]{1,12}\-(19|20)\d\d\-[a-z0-9]{1,12}|[\.\-\(\[_ ]\d{2,3}k[\.\-\)\]_ ]|\((192|256|320)\)|(320|cd|eac|vbr).+mp3|(cd|eac|mp3|vbr).+320|FIH\_INT|\s\dCDs|[-._ ]MP3[-._ ]|MP3\-\d{3}kbps|\.(m3u|mp3)"|NMR\s\d{2,3}\skbps|\(320\)\.|\-\((Bootleg|Promo)\)|\.mp3$|\-\sMP3\s(19|20)\d\d|\(vbr\)|rip(192|256|320)|[-._ ](CDR|SBD|WEB).+(19|20)\d\d/i', $this->releaseName)) { + if ($this->isMusicForeign()) { + return true; + } + $this->tmpCat = Category::MUSIC_MP3; + + return true; + } + if (preg_match('/\s(19|20)\d\d\s([a-z0-9]{3}|[a-z]{2,})$|\-(19|20)\d\d\-(C4|MTD)(\s|\.)|[-._ ]FM.+MP3[-._ ]|-web-(19|20)\d\d(\.|\s|$)|[-._ ](SAT|SBD|WEB).+(19|20)\d\d([-._ ]|$)|[-._ ](19|20)\d\d.+(SAT|WEB)([-._ ]|$)| MP3$/i', $this->releaseName)) { + if ($this->isMusicForeign()) { + return true; + } + $this->tmpCat = Category::MUSIC_MP3; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isMusicOther(): bool + { + if (preg_match('/(19|20)\d\d\-(C4)$|[-._ ]\d?CD[-._ ](19|20)\d\d|\(\d\-?CD\)|\-\dcd\-|\d[-._ ]Albums|Albums.+(EP)|Bonus.+Tracks|Box.+?CD.+SET|Discography|D\.O\.M|Greatest\sSongs|Live.+(Bootleg|Remastered)|Music.+Vol|(\(|\[|\s)NMR(\)|\]|\s)|Promo.+CD|Reggaeton|Tiesto.+Club|Vinyl\s2496|\WV\.A\.|^\(VA\s|^VA[-._ ]/i', $this->releaseName)) { + switch (true) { case $this->isMusicForeign(): break; default: $this->tmpCat = Category::MUSIC_OTHER; break; } - return true; - } - if (preg_match('/\(pure_fm\)|-+\(?(2lp|cd[ms]([-_ .][a-z]{2})?|cover|ep|ltd_ed|mix|original|ost|.*?(edit(ion)?|remix(es)?|vinyl)|web)\)?-+((19|20)\d\d|you$)/i', $this->releaseName)) { - $this->tmpCat = Category::MUSIC_OTHER; - return true; - } - return false; - } - // Books. + return true; + } + if (preg_match('/\(pure_fm\)|-+\(?(2lp|cd[ms]([-_ .][a-z]{2})?|cover|ep|ltd_ed|mix|original|ost|.*?(edit(ion)?|remix(es)?|vinyl)|web)\)?-+((19|20)\d\d|you$)/i', $this->releaseName)) { + $this->tmpCat = Category::MUSIC_OTHER; - /** - * @return bool|null - */ - public function isBook(): ?bool - { - switch (true) { + return true; + } + + return false; + } + + // Books. + + /** + * @return bool|null + */ + public function isBook(): ?bool + { + switch (true) { case preg_match('/AVI[-._ ]PDF|\.exe|Full[-._ ]Video/i', $this->releaseName): return false; case $this->isComic(): @@ -1623,31 +1748,32 @@ class Categorize extends Category default: return false; } - } + } - /** - * @return bool|null - */ - public function isBookForeign(): ?bool - { - switch (true) { + /** + * @return bool|null + */ + public function isBookForeign(): ?bool + { + switch (true) { case $this->categorizeForeign === false: return false; case preg_match('/[ \-\._](brazilian|chinese|croatian|danish|deutsch|dutch|estonian|flemish|finnish|french|german|greek|hebrew|icelandic|italian|ita|latin|mandarin|nordic|norwegian|polish|portuguese|japenese|japanese|russian|serbian|slovenian|spanish|spanisch|swedish|thai|turkish)[-._ ]/i', $this->releaseName): $this->tmpCat = Category::BOOKS_FOREIGN; + return true; default: return false; } - } + } - /** - * @return bool - */ - public function isComic(): bool - { - switch (true) { - case !preg_match('/[\. ](cbr|cbz)|[\( ]c2c|cbr|cbz[\) ]|comix|^\(comic|[\.\-_\(\[ ]comics?[-._ ]|comic.+book|covers.+digital|DC.+(Adventures|Universe)|digital.+(son|zone)|Graphic.+Novel|[\.\-_h ]manga|Total[-._ ]Marvel/i', $this->releaseName): + /** + * @return bool + */ + public function isComic(): bool + { + switch (true) { + case ! preg_match('/[\. ](cbr|cbz)|[\( ]c2c|cbr|cbz[\) ]|comix|^\(comic|[\.\-_\(\[ ]comics?[-._ ]|comic.+book|covers.+digital|DC.+(Adventures|Universe)|digital.+(son|zone)|Graphic.+Novel|[\.\-_h ]manga|Total[-._ ]Marvel/i', $this->releaseName): return false; case $this->isBookForeign(): break; @@ -1655,16 +1781,17 @@ class Categorize extends Category $this->tmpCat = Category::BOOKS_COMICS; break; } - return true; - } - /** - * @return bool - */ - public function isTechnicalBook(): bool - { - switch (true) { - case !preg_match('/^\(?(atz|bb|css|c ?t|Drawing|Gabler|IOS|Iphone|Lynda|Manning|Medic(al|ine)|MIT|No[-._ ]Starch|Packt|Peachpit|Pragmatic|Revista|Servo|SmartBooks|Spektrum|Strata|Sybex|Syngress|Vieweg|Wiley|Woods|Wrox)[-._ ]|[-._ ](Ajax|CSS|DIY|Javascript|(My|Postgre)?SQL|XNA)[-._ ]|3DS\.\-_ ]Max|Academic|Adobe|Algebra|Analysis|Appleworks|Archaeology|Bitdefender|Birkhauser|Britannica|[-._ ]C\+\+|C[-._ ](\+\+|Sharp|Plus)|Chemistry|Circuits|Cook(book|ing)|(Beginners?|Complete|Communications|Definitive|Essential|Hackers?|Practical|Professionals?)[-._ ]Guide|Developer|Diagnostic|Disassembl(er|ing|y)|Debugg(er|ing)|Dreamweaver|Economics|Education|Electronics|Enc(i|y)clopedia|Engineer(ing|s)|Essays|Exercizes|For.+Beginners|Focal[-._ ]Press|For[-._ ]Dummies|FreeBSD|Fundamentals[-._ ]of[-._ ]|(Galileo|Island)[-._ ]Press|Geography|Grammar|Guide[-._ ](For|To)|Hacking|Google|Handboo?k|How[-._ ](It|To)|Intoduction[-._ ]to|Iphone|jQuery|Lessons[-._ ]In|Learning|LibreOffice|Linux|Manual|Marketing|Masonry|Mathematic(al|s)?|Medical|Microsoft|National[-._ ]Academies|Nero[-._ ]\d+|OReilly|OS[-._ ]X[-._ ]|Official[-._ ]Guide|Open(GL|Office)|Pediatric|Periodic.+Table|Photoshop|Physics|Power(PC|Point|Shell)|Programm(ers?|ier||ing)|Raspberry.+Pi|Remedies|Service\s?Manual|SitePoint|Sketching|Statistics|Stock.+Market|Students|Theory|Training|Tutsplus|Ubuntu|Understanding[-._ ](and|Of|The)|Visual[-._ ]Studio|Textbook|VMWare|wii?max|Windows[-._ ](8|7|Vista|XP)|^Wood[-._ ]|Woodwork|WordPress|Work(book|shop)|Youtube/i', $this->releaseName): + return true; + } + + /** + * @return bool + */ + public function isTechnicalBook(): bool + { + switch (true) { + case ! preg_match('/^\(?(atz|bb|css|c ?t|Drawing|Gabler|IOS|Iphone|Lynda|Manning|Medic(al|ine)|MIT|No[-._ ]Starch|Packt|Peachpit|Pragmatic|Revista|Servo|SmartBooks|Spektrum|Strata|Sybex|Syngress|Vieweg|Wiley|Woods|Wrox)[-._ ]|[-._ ](Ajax|CSS|DIY|Javascript|(My|Postgre)?SQL|XNA)[-._ ]|3DS\.\-_ ]Max|Academic|Adobe|Algebra|Analysis|Appleworks|Archaeology|Bitdefender|Birkhauser|Britannica|[-._ ]C\+\+|C[-._ ](\+\+|Sharp|Plus)|Chemistry|Circuits|Cook(book|ing)|(Beginners?|Complete|Communications|Definitive|Essential|Hackers?|Practical|Professionals?)[-._ ]Guide|Developer|Diagnostic|Disassembl(er|ing|y)|Debugg(er|ing)|Dreamweaver|Economics|Education|Electronics|Enc(i|y)clopedia|Engineer(ing|s)|Essays|Exercizes|For.+Beginners|Focal[-._ ]Press|For[-._ ]Dummies|FreeBSD|Fundamentals[-._ ]of[-._ ]|(Galileo|Island)[-._ ]Press|Geography|Grammar|Guide[-._ ](For|To)|Hacking|Google|Handboo?k|How[-._ ](It|To)|Intoduction[-._ ]to|Iphone|jQuery|Lessons[-._ ]In|Learning|LibreOffice|Linux|Manual|Marketing|Masonry|Mathematic(al|s)?|Medical|Microsoft|National[-._ ]Academies|Nero[-._ ]\d+|OReilly|OS[-._ ]X[-._ ]|Official[-._ ]Guide|Open(GL|Office)|Pediatric|Periodic.+Table|Photoshop|Physics|Power(PC|Point|Shell)|Programm(ers?|ier||ing)|Raspberry.+Pi|Remedies|Service\s?Manual|SitePoint|Sketching|Statistics|Stock.+Market|Students|Theory|Training|Tutsplus|Ubuntu|Understanding[-._ ](and|Of|The)|Visual[-._ ]Studio|Textbook|VMWare|wii?max|Windows[-._ ](8|7|Vista|XP)|^Wood[-._ ]|Woodwork|WordPress|Work(book|shop)|Youtube/i', $this->releaseName): return false; case $this->isBookForeign(): break; @@ -1672,16 +1799,17 @@ class Categorize extends Category $this->tmpCat = Category::BOOKS_TECHNICAL; break; } - return true; - } - /** - * @return bool - */ - public function isMagazine(): bool - { - switch (true) { - case !preg_match('/[a-z\-\._ ][-._ ](January|February|March|April|May|June|July|August|September|October|November|December)[-._ ](\d{1,2},)?20\d\d[-._ ]|^\(.+[ .]\d{1,2}[ .]20\d\d[ .].+\.scr|[-._ ](Catalogue|FHM|NUTS|Pictorial|Tatler|XXX)[-._ ]|^\(?(Allehanda|Club|Computer([a-z0-9]+)?|Connect \d+|Corriere|ct|Diario|Digit(al)?|Esquire|FHM|Gadgets|Galileo|Glam|GQ|Infosat|Inked|Instyle|io|Kicker|Liberation|New Scientist|NGV|Nuts|Popular|Professional|Reise|Sette(tv)?|Springer|Stuff|Studentlitteratur|Vegetarian|Vegetable|Videomarkt|Wired)[-._ ]|Brady(.+)?Games|Catalog|Columbus.+Dispatch|Correspondenten|Corriere[-._ ]Della[-._ ]Sera|Cosmopolitan|Dagbladet|Digital[-._ ]Guide|Economist|Eload ?24|ExtraTime|Fatto[-._ ]Quotidiano|Flight[-._ ](International|Journal)|Finanzwoche|France.+Football|Foto.+Video|Games?(Master|Markt|tar|TM)|Gardening|Gazzetta|Globe[-._ ]And[-._ ]Mail|Guitar|Heimkino|Hustler|La.+(Lettura|Rblica|Stampa)|Le[-._ ](Monde|Temps)|Les[-._ ]Echos|e?Magazin(es?)?|Mac(life|welt)|Marie.+Claire|Maxim|Men.+(Health|Fitness)|Motocross|Motorcycle|Mountain[-._ ]Bike|MusikWoche|National[-._ ]Geographic|New[-._ ]Yorker|PC([-._ ](Gamer|Welt|World)|Games|Go|Tip)|Penthouse|Photograph(er|ic)|Playboy|Posten|Quotidiano|(Golf|Readers?).+Digest|SFX[-._ ]UK|Recipe(.+Guide|s)|SkyNews|Sport[-._ ]?Week|Strategy.+Guide|TabletPC|Tattoo[-._ ]Life|The[-._ ]Guardian|Tageszeitung|Tid(bits|ning)|Top[-._ ]Gear[-._ ]|Total[-._ ]Guitar|Travel[-._ ]Guides?|Tribune[-._ ]De[-._ ]|US[-._ ]Weekly|USA[-._ ]Today|TruePDF|Vogue|Verlag|Warcraft|Web.+Designer|What[-._ ]Car|Zeitung/i', $this->releaseName): + return true; + } + + /** + * @return bool + */ + public function isMagazine(): bool + { + switch (true) { + case ! preg_match('/[a-z\-\._ ][-._ ](January|February|March|April|May|June|July|August|September|October|November|December)[-._ ](\d{1,2},)?20\d\d[-._ ]|^\(.+[ .]\d{1,2}[ .]20\d\d[ .].+\.scr|[-._ ](Catalogue|FHM|NUTS|Pictorial|Tatler|XXX)[-._ ]|^\(?(Allehanda|Club|Computer([a-z0-9]+)?|Connect \d+|Corriere|ct|Diario|Digit(al)?|Esquire|FHM|Gadgets|Galileo|Glam|GQ|Infosat|Inked|Instyle|io|Kicker|Liberation|New Scientist|NGV|Nuts|Popular|Professional|Reise|Sette(tv)?|Springer|Stuff|Studentlitteratur|Vegetarian|Vegetable|Videomarkt|Wired)[-._ ]|Brady(.+)?Games|Catalog|Columbus.+Dispatch|Correspondenten|Corriere[-._ ]Della[-._ ]Sera|Cosmopolitan|Dagbladet|Digital[-._ ]Guide|Economist|Eload ?24|ExtraTime|Fatto[-._ ]Quotidiano|Flight[-._ ](International|Journal)|Finanzwoche|France.+Football|Foto.+Video|Games?(Master|Markt|tar|TM)|Gardening|Gazzetta|Globe[-._ ]And[-._ ]Mail|Guitar|Heimkino|Hustler|La.+(Lettura|Rblica|Stampa)|Le[-._ ](Monde|Temps)|Les[-._ ]Echos|e?Magazin(es?)?|Mac(life|welt)|Marie.+Claire|Maxim|Men.+(Health|Fitness)|Motocross|Motorcycle|Mountain[-._ ]Bike|MusikWoche|National[-._ ]Geographic|New[-._ ]Yorker|PC([-._ ](Gamer|Welt|World)|Games|Go|Tip)|Penthouse|Photograph(er|ic)|Playboy|Posten|Quotidiano|(Golf|Readers?).+Digest|SFX[-._ ]UK|Recipe(.+Guide|s)|SkyNews|Sport[-._ ]?Week|Strategy.+Guide|TabletPC|Tattoo[-._ ]Life|The[-._ ]Guardian|Tageszeitung|Tid(bits|ning)|Top[-._ ]Gear[-._ ]|Total[-._ ]Guitar|Travel[-._ ]Guides?|Tribune[-._ ]De[-._ ]|US[-._ ]Weekly|USA[-._ ]Today|TruePDF|Vogue|Verlag|Warcraft|Web.+Designer|What[-._ ]Car|Zeitung/i', $this->releaseName): return false; case $this->isBookForeign(): break; @@ -1689,28 +1817,31 @@ class Categorize extends Category $this->tmpCat = Category::BOOKS_MAGAZINES; break; } - return true; - } - /** - * @return bool - */ - public function isBookOther(): bool - { - if (preg_match('/"\d\d-\d\d-20\d\d\./i', $this->releaseName)) { - $this->tmpCat = Category::BOOKS_UNKNOWN; - return true; - } - return false; - } + return true; + } - /** - * @return bool - */ - public function isEBook(): bool - { - switch (true) { - case !preg_match('/^ePub|[-._ ](Ebook|E?\-book|\) WW|Publishing)|[\.\-_\(\[ ](azw|epub|html|mobi|pdf|rtf|tif|txt)[\.\-_\)\] ]|[\. ](azw|doc|epub|mobi|pdf)(?![\w .])|\.ebook-\w$/i', $this->releaseName): + /** + * @return bool + */ + public function isBookOther(): bool + { + if (preg_match('/"\d\d-\d\d-20\d\d\./i', $this->releaseName)) { + $this->tmpCat = Category::BOOKS_UNKNOWN; + + return true; + } + + return false; + } + + /** + * @return bool + */ + public function isEBook(): bool + { + switch (true) { + case ! preg_match('/^ePub|[-._ ](Ebook|E?\-book|\) WW|Publishing)|[\.\-_\(\[ ](azw|epub|html|mobi|pdf|rtf|tif|txt)[\.\-_\)\] ]|[\. ](azw|doc|epub|mobi|pdf)(?![\w .])|\.ebook-\w$/i', $this->releaseName): return false; case $this->isBookForeign(): break; @@ -1718,17 +1849,18 @@ class Categorize extends Category $this->tmpCat = Category::BOOKS_EBOOK; break; } - return true; - } - // Misc, all hash/misc go in other misc. + return true; + } - /** - * @return bool - */ - public function isMisc(): bool - { - switch (true) { + // Misc, all hash/misc go in other misc. + + /** + * @return bool + */ + public function isMisc(): bool + { + switch (true) { case preg_match('/[^a-z0-9]((480|720|1080)[ip]|s\d{1,3}[-._ ]?[ed]\d{1,3}([ex]\d{1,3}|[-.\w ]))[^a-z0-9]/i', $this->releaseName): return false; case preg_match('/[a-f0-9]{32,64}/i', $this->releaseName): @@ -1741,22 +1873,25 @@ class Categorize extends Category default: return false; } - return true; - } - /** - * @param string $regex Regex to use for match - * @param string $fromName Poster that needs to be matched by regex - * @param string $category Category to set if there is a match - * - * @return bool - */ - public function checkPoster($regex, $fromName, $category): bool - { - if (preg_match($regex, $fromName)) { - $this->tmpCat = $category; - return true; - } - return false; - } + return true; + } + + /** + * @param string $regex Regex to use for match + * @param string $fromName Poster that needs to be matched by regex + * @param string $category Category to set if there is a match + * + * @return bool + */ + public function checkPoster($regex, $fromName, $category): bool + { + if (preg_match($regex, $fromName)) { + $this->tmpCat = $category; + + return true; + } + + return false; + } } diff --git a/nntmux/Category.php b/nntmux/Category.php index 4093b79bf..35d614111 100755 --- a/nntmux/Category.php +++ b/nntmux/Category.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; use nntmux\db\DB; @@ -8,89 +9,88 @@ use nntmux\db\DB; */ class Category { + /** + * Category constants. + * Do NOT use the values, as they may change, always use the constant - that's what it's for. + */ + const OTHER_MISC = '0010'; + const OTHER_HASHED = '0020'; + const GAME_NDS = '1010'; + const GAME_PSP = '1020'; + const GAME_WII = '1030'; + const GAME_XBOX = '1040'; + const GAME_XBOX360 = '1050'; + const GAME_WIIWARE = '1060'; + const GAME_XBOX360DLC = '1070'; + const GAME_PS3 = '1080'; + const GAME_OTHER = '1999'; + const GAME_3DS = '1110'; + const GAME_PSVITA = '1120'; + const GAME_WIIU = '1130'; + const GAME_XBOXONE = '1140'; + const GAME_PS4 = '1180'; + const MOVIE_FOREIGN = '2010'; + const MOVIE_OTHER = '2999'; + const MOVIE_SD = '2030'; + const MOVIE_HD = '2040'; + const MOVIE_UHD = '2045'; + const MOVIE_3D = '2050'; + const MOVIE_BLURAY = '2060'; + const MOVIE_DVD = '2070'; + const MOVIE_WEBDL = '2080'; + const MUSIC_MP3 = '3010'; + const MUSIC_VIDEO = '3020'; + const MUSIC_AUDIOBOOK = '3030'; + const MUSIC_LOSSLESS = '3040'; + const MUSIC_OTHER = '3999'; + const MUSIC_FOREIGN = '3060'; + const PC_0DAY = '4010'; + const PC_ISO = '4020'; + const PC_MAC = '4030'; + const PC_PHONE_OTHER = '4040'; + const PC_GAMES = '4050'; + const PC_PHONE_IOS = '4060'; + const PC_PHONE_ANDROID = '4070'; + const TV_WEBDL = '5010'; + const TV_FOREIGN = '5020'; + const TV_SD = '5030'; + const TV_HD = '5040'; + const TV_UHD = '5045'; + const TV_OTHER = '5999'; + const TV_SPORT = '5060'; + const TV_ANIME = '5070'; + const TV_DOCU = '5080'; + const XXX_DVD = '6010'; + const XXX_WMV = '6020'; + const XXX_XVID = '6030'; + const XXX_X264 = '6040'; + const XXX_CLIPHD = '6041'; + const XXX_CLIPSD = '6042'; + const XXX_UHD = '6045'; + const XXX_PACK = '6050'; + const XXX_IMAGESET = '6060'; + const XXX_OTHER = '6999'; + const XXX_SD = '6080'; + const XXX_WEBDL = '6090'; + const BOOKS_MAGAZINES = '7010'; + const BOOKS_EBOOK = '7020'; + const BOOKS_COMICS = '7030'; + const BOOKS_TECHNICAL = '7040'; + const BOOKS_FOREIGN = '7060'; + const BOOKS_UNKNOWN = '7999'; + const OTHER_ROOT = '0000'; + const GAME_ROOT = '1000'; + const MOVIE_ROOT = '2000'; + const MUSIC_ROOT = '3000'; + const PC_ROOT = '4000'; + const TV_ROOT = '5000'; + const XXX_ROOT = '6000'; + const BOOKS_ROOT = '7000'; + const STATUS_INACTIVE = 0; + const STATUS_ACTIVE = 1; + const STATUS_DISABLED = 2; - /** - * Category constants. - * Do NOT use the values, as they may change, always use the constant - that's what it's for. - */ - const OTHER_MISC = '0010'; - const OTHER_HASHED = '0020'; - const GAME_NDS = '1010'; - const GAME_PSP = '1020'; - const GAME_WII = '1030'; - const GAME_XBOX = '1040'; - const GAME_XBOX360 = '1050'; - const GAME_WIIWARE = '1060'; - const GAME_XBOX360DLC = '1070'; - const GAME_PS3 = '1080'; - const GAME_OTHER = '1999'; - const GAME_3DS = '1110'; - const GAME_PSVITA = '1120'; - const GAME_WIIU = '1130'; - const GAME_XBOXONE = '1140'; - const GAME_PS4 = '1180'; - const MOVIE_FOREIGN = '2010'; - const MOVIE_OTHER = '2999'; - const MOVIE_SD = '2030'; - const MOVIE_HD = '2040'; - const MOVIE_UHD = '2045'; - const MOVIE_3D = '2050'; - const MOVIE_BLURAY = '2060'; - const MOVIE_DVD = '2070'; - const MOVIE_WEBDL = '2080'; - const MUSIC_MP3 = '3010'; - const MUSIC_VIDEO = '3020'; - const MUSIC_AUDIOBOOK = '3030'; - const MUSIC_LOSSLESS = '3040'; - const MUSIC_OTHER = '3999'; - const MUSIC_FOREIGN = '3060'; - const PC_0DAY = '4010'; - const PC_ISO = '4020'; - const PC_MAC = '4030'; - const PC_PHONE_OTHER = '4040'; - const PC_GAMES = '4050'; - const PC_PHONE_IOS = '4060'; - const PC_PHONE_ANDROID = '4070'; - const TV_WEBDL = '5010'; - const TV_FOREIGN = '5020'; - const TV_SD = '5030'; - const TV_HD = '5040'; - const TV_UHD = '5045'; - const TV_OTHER = '5999'; - const TV_SPORT = '5060'; - const TV_ANIME = '5070'; - const TV_DOCU = '5080'; - const XXX_DVD = '6010'; - const XXX_WMV = '6020'; - const XXX_XVID = '6030'; - const XXX_X264 = '6040'; - const XXX_CLIPHD = '6041'; - const XXX_CLIPSD = '6042'; - const XXX_UHD = '6045'; - const XXX_PACK = '6050'; - const XXX_IMAGESET = '6060'; - const XXX_OTHER = '6999'; - const XXX_SD = '6080'; - const XXX_WEBDL = '6090'; - const BOOKS_MAGAZINES = '7010'; - const BOOKS_EBOOK = '7020'; - const BOOKS_COMICS = '7030'; - const BOOKS_TECHNICAL = '7040'; - const BOOKS_FOREIGN = '7060'; - const BOOKS_UNKNOWN = '7999'; - const OTHER_ROOT = '0000'; - const GAME_ROOT = '1000'; - const MOVIE_ROOT = '2000'; - const MUSIC_ROOT = '3000'; - const PC_ROOT = '4000'; - const TV_ROOT = '5000'; - const XXX_ROOT = '6000'; - const BOOKS_ROOT = '7000'; - const STATUS_INACTIVE = 0; - const STATUS_ACTIVE = 1; - const STATUS_DISABLED = 2; - - const OTHERS_GROUP = + const OTHERS_GROUP = [ self::BOOKS_UNKNOWN, self::GAME_OTHER, @@ -100,93 +100,91 @@ class Category self::TV_OTHER, self::OTHER_HASHED, self::XXX_OTHER, - self::OTHER_MISC - ] - ; + self::OTHER_MISC, + ]; - private $tmpCat = 0; + private $tmpCat = 0; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * Construct. - * - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Construct. + * + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + } - /** - * Parse category search constraints - * - * @param array|string $cat - * - * @return string $catsrch - */ - public function getCategorySearch(array $cat = []): string - { - $categories = []; + /** + * Parse category search constraints. + * + * @param array|string $cat + * + * @return string $catsrch + */ + public function getCategorySearch(array $cat = []): string + { + $categories = []; - // If multiple categories were sent in a single array position, slice and add them - if (strpos($cat[0], ',') !== false) { - $tmpcats = explode(',', $cat[0]); - // Reset the category to the first comma separated value in the string - $cat[0] = $tmpcats[0]; - // Add the remaining categories in the string to the original array - foreach (array_slice($tmpcats, 1) AS $tmpcat) { - $cat[] = $tmpcat; - } - } + // If multiple categories were sent in a single array position, slice and add them + if (strpos($cat[0], ',') !== false) { + $tmpcats = explode(',', $cat[0]); + // Reset the category to the first comma separated value in the string + $cat[0] = $tmpcats[0]; + // Add the remaining categories in the string to the original array + foreach (array_slice($tmpcats, 1) as $tmpcat) { + $cat[] = $tmpcat; + } + } - foreach ($cat as $category) { - if ($category !== -1 && $this->isParent($category)) { - foreach ($this->getChildren($category) as $child) { - $categories[] = $child['id']; - } - } else if ($category > 0) { - $categories[] = $category; - } - } + foreach ($cat as $category) { + if ($category !== -1 && $this->isParent($category)) { + foreach ($this->getChildren($category) as $child) { + $categories[] = $child['id']; + } + } elseif ($category > 0) { + $categories[] = $category; + } + } - $catCount = count($categories); + $catCount = count($categories); - switch ($catCount) { + switch ($catCount) { //No category constraint case 0: $catsrch = ' AND 1=1 '; break; // One category constraint case 1: - $catsrch = $categories[0] !== -1 ? ' AND r.categories_id = ' . $categories[0] : ''; + $catsrch = $categories[0] !== -1 ? ' AND r.categories_id = '.$categories[0] : ''; break; // Multiple category constraints default: - $catsrch = ' AND r.categories_id IN (' . implode(', ', $categories) . ') '; + $catsrch = ' AND r.categories_id IN ('.implode(', ', $categories).') '; break; } - return $catsrch; - } + return $catsrch; + } - - /** - * Returns a concatenated list of other categories - * - * @return string - */ - public static function getCategoryOthersGroup(): string - { - return implode(',', + /** + * Returns a concatenated list of other categories. + * + * @return string + */ + public static function getCategoryOthersGroup(): string + { + return implode(',', [ self::BOOKS_UNKNOWN, self::GAME_OTHER, @@ -197,115 +195,116 @@ class Category self::OTHER_HASHED, self::XXX_OTHER, self::OTHER_MISC, - self::OTHER_HASHED + self::OTHER_HASHED, ] ); - } + } - /** - * @param $category - * - * @return mixed - */ - public static function getCategoryValue($category) - { - return constant('self::' . $category); - } + /** + * @param $category + * + * @return mixed + */ + public static function getCategoryValue($category) + { + return constant('self::'.$category); + } - /** - * Check if category is parent. - * - * @param $cid - * - * @return bool - */ - public function isParent($cid): bool - { - $ret = $this->pdo->query( + /** + * Check if category is parent. + * + * @param $cid + * + * @return bool + */ + public function isParent($cid): bool + { + $ret = $this->pdo->query( sprintf('SELECT id FROM categories WHERE id = %d AND parentid IS NULL', $cid), true, NN_CACHE_EXPIRY_LONG ); - return isset($ret[0]['id']); - } - /** - * @param bool $activeonly - * - * @return array - */ - public function getFlat($activeonly = false): array - { - $act = ''; - if ($activeonly) { - $act = sprintf(' WHERE c.status = %d ', Category::STATUS_ACTIVE); - } - return $this->pdo->query('SELECT c.*, (SELECT title FROM categories WHERE id=c.parentid) AS parentName FROM categories c ' . $act . ' ORDER BY c.id'); - } + return isset($ret[0]['id']); + } - /** - * Get children of a parent category. - * - * @param $cid - * - * @return array - */ - public function getChildren($cid): array - { - return $this->pdo->query( + /** + * @param bool $activeonly + * + * @return array + */ + public function getFlat($activeonly = false): array + { + $act = ''; + if ($activeonly) { + $act = sprintf(' WHERE c.status = %d ', self::STATUS_ACTIVE); + } + + return $this->pdo->query('SELECT c.*, (SELECT title FROM categories WHERE id=c.parentid) AS parentName FROM categories c '.$act.' ORDER BY c.id'); + } + + /** + * Get children of a parent category. + * + * @param $cid + * + * @return array + */ + public function getChildren($cid): array + { + return $this->pdo->query( sprintf('SELECT c.* FROM categories c WHERE parentid = %d', $cid), true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * Get names of enabled parent categories. - * @return array - */ - public function getEnabledParentNames(): array - { - return $this->pdo->query( + /** + * Get names of enabled parent categories. + * @return array + */ + public function getEnabledParentNames(): array + { + return $this->pdo->query( 'SELECT title FROM categories WHERE parentid IS NULL AND status = 1', true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * Returns category ID's for site disabled categories. - * - * @return array - */ - public function getDisabledIDs(): array - { - return $this->pdo->query( + /** + * Returns category ID's for site disabled categories. + * + * @return array + */ + public function getDisabledIDs(): array + { + return $this->pdo->query( 'SELECT id FROM categories WHERE status = 2 OR parentid IN (SELECT id FROM categories WHERE status = 2 AND parentid IS NULL)', true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * Get a category row by its id. - * - * @param $id - * - * @return array|bool - */ - public function getById($id) - { + /** + * Get a category row by its id. + * + * @param $id + * + * @return array|bool + */ + public function getById($id) + { + return $this->pdo->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 categories c left outer join categories cp on cp.id = c.parentid where c.id = %d", $id)); + } - return $this->pdo->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 categories c left outer join categories cp on cp.id = c.parentid where c.id = %d", $id)); - } - - /** - * Get multiple categories. - * - * @param array $ids - * - * @return array|bool - */ - public function getByIds($ids) - { - if (count($ids) > 0) { - return $this->pdo->query( + /** + * Get multiple categories. + * + * @param array $ids + * + * @return array|bool + */ + public function getByIds($ids) + { + if (count($ids) > 0) { + return $this->pdo->query( sprintf( "SELECT CONCAT(cp.title, ' > ',c.title) AS title FROM categories c @@ -313,20 +312,20 @@ class Category WHERE c.id IN (%s)", implode(',', $ids) ), true, NN_CACHE_EXPIRY_LONG ); - } + } - return false; - } + return false; + } - /** - * Return the parent and category name from the supplied categoryID. - * @param $ID - * - * @return string - */ - public function getNameByID($ID): string - { - $cat = $this->pdo->queryOneRow( + /** + * Return the parent and category name from the supplied categoryID. + * @param $ID + * + * @return string + */ + public function getNameByID($ID): string + { + $cat = $this->pdo->queryOneRow( sprintf(' SELECT c.title AS ctitle, cp.title AS ptitle FROM categories c @@ -335,131 +334,133 @@ class Category $ID ) ); - return $cat['ptitle'] . ' -> ' . $cat['ctitle']; - } - /** - * Update a category. - * - * @param $id - * @param $status - * @param $desc - * @param $disablepreview - * @param $minsize - * @param $maxsize - * - * @return bool|\PDOStatement - */ - public function update($id, $status, $desc, $disablepreview, $minsize, $maxsize) - { - return $this->pdo->queryExec(sprintf('UPDATE categories SET disablepreview = %d, status = %d, minsizetoformrelease = %d, maxsizetoformrelease = %d, description = %s WHERE id = %d', $disablepreview, $status, $minsize, $maxsize, $this->pdo->escapeString($desc), $id)); - } + return $cat['ptitle'].' -> '.$cat['ctitle']; + } - /** - * @param array $excludedcats - * - * @param array $roleexcludedcats - * - * @return array - */ - public function getForMenu(array $excludedcats = [], array $roleexcludedcats = []): array - { - $ret = []; + /** + * Update a category. + * + * @param $id + * @param $status + * @param $desc + * @param $disablepreview + * @param $minsize + * @param $maxsize + * + * @return bool|\PDOStatement + */ + public function update($id, $status, $desc, $disablepreview, $minsize, $maxsize) + { + return $this->pdo->queryExec(sprintf('UPDATE categories SET disablepreview = %d, status = %d, minsizetoformrelease = %d, maxsizetoformrelease = %d, description = %s WHERE id = %d', $disablepreview, $status, $minsize, $maxsize, $this->pdo->escapeString($desc), $id)); + } - $exccatlist = ''; - if (count($excludedcats) > 0 && count($roleexcludedcats) == 0) { - $exccatlist = ' AND id NOT IN (' . implode(',', $excludedcats) . ')'; - } elseif (count($excludedcats) > 0 && count($roleexcludedcats) > 0) { - $exccatlist = ' AND id NOT IN (' . implode(',', $excludedcats) . ',' . implode(',', $roleexcludedcats) . ')'; - } elseif (count($excludedcats) === 0 && count($roleexcludedcats) > 0) { - $exccatlist = ' AND id NOT IN (' . implode(',', $roleexcludedcats) . ')'; - } + /** + * @param array $excludedcats + * + * @param array $roleexcludedcats + * + * @return array + */ + public function getForMenu(array $excludedcats = [], array $roleexcludedcats = []): array + { + $ret = []; - $arr = $this->pdo->query( + $exccatlist = ''; + if (count($excludedcats) > 0 && count($roleexcludedcats) == 0) { + $exccatlist = ' AND id NOT IN ('.implode(',', $excludedcats).')'; + } elseif (count($excludedcats) > 0 && count($roleexcludedcats) > 0) { + $exccatlist = ' AND id NOT IN ('.implode(',', $excludedcats).','.implode(',', $roleexcludedcats).')'; + } elseif (count($excludedcats) === 0 && count($roleexcludedcats) > 0) { + $exccatlist = ' AND id NOT IN ('.implode(',', $roleexcludedcats).')'; + } + + $arr = $this->pdo->query( sprintf('SELECT * FROM categories WHERE status = %d %s', self::STATUS_ACTIVE, $exccatlist), true, NN_CACHE_EXPIRY_LONG ); - foreach($arr as $key => $val) { - if($val['id'] === '0') { - $item = $arr[$key]; - unset($arr[$key]); - $arr[] = $item; - break; - } - } + foreach ($arr as $key => $val) { + if ($val['id'] === '0') { + $item = $arr[$key]; + unset($arr[$key]); + $arr[] = $item; + break; + } + } - foreach ($arr as $a) { - if (empty($a['parentid'])) { - $ret[] = $a; - } - } + foreach ($arr as $a) { + if (empty($a['parentid'])) { + $ret[] = $a; + } + } - foreach ($ret as $key => $parent) { - $subcatlist = []; - $subcatnames = []; - foreach ($arr as $a) { - if ($a['parentid'] === $parent['id']) { - $subcatlist[] = $a; - $subcatnames[] = $a['title']; - } - } + foreach ($ret as $key => $parent) { + $subcatlist = []; + $subcatnames = []; + foreach ($arr as $a) { + if ($a['parentid'] === $parent['id']) { + $subcatlist[] = $a; + $subcatnames[] = $a['title']; + } + } - if (count($subcatlist) > 0) { - array_multisort($subcatnames, SORT_ASC, $subcatlist); - $ret[$key]['subcatlist'] = $subcatlist; - } else { - unset($ret[$key]); - } - } - return $ret; - } + if (count($subcatlist) > 0) { + array_multisort($subcatnames, SORT_ASC, $subcatlist); + $ret[$key]['subcatlist'] = $subcatlist; + } else { + unset($ret[$key]); + } + } - /** - * Return a list of categories for use in a dropdown. - * - * @param bool $blnIncludeNoneSelected - * - * @return array - */ - public function getForSelect($blnIncludeNoneSelected = true): array - { - $categories = $this->getCategories(); - $temp_array = []; + return $ret; + } - if ($blnIncludeNoneSelected) { - $temp_array[-1] = '--Please Select--'; - } + /** + * Return a list of categories for use in a dropdown. + * + * @param bool $blnIncludeNoneSelected + * + * @return array + */ + public function getForSelect($blnIncludeNoneSelected = true): array + { + $categories = $this->getCategories(); + $temp_array = []; - foreach ($categories as $category) { - $temp_array[$category['id']] = $category['title']; - } + if ($blnIncludeNoneSelected) { + $temp_array[-1] = '--Please Select--'; + } - return $temp_array; - } + foreach ($categories as $category) { + $temp_array[$category['id']] = $category['title']; + } - /** - * Get array of categories in DB. - * - * @param bool $activeonly - * @param array $excludedcats - * - * @return array - */ - public function getCategories($activeonly = false, array $excludedcats = []): array - { - return $this->pdo->query( + return $temp_array; + } + + /** + * Get array of categories in DB. + * + * @param bool $activeonly + * @param array $excludedcats + * + * @return array + */ + public function getCategories($activeonly = false, array $excludedcats = []): array + { + return $this->pdo->query( "SELECT c.id, CONCAT(cp.title, ' > ',c.title) AS title, cp.id AS parentid, c.status FROM categories c - INNER JOIN categories cp ON cp.id = c.parentid " . + INNER JOIN categories cp ON cp.id = c.parentid ". ($activeonly ? sprintf( ' WHERE c.status = %d %s ', self::STATUS_ACTIVE, - (count($excludedcats) > 0 ? ' AND c.id NOT IN (' . implode(',', $excludedcats) . ')' : '') + (count($excludedcats) > 0 ? ' AND c.id NOT IN ('.implode(',', $excludedcats).')' : '') ) : '' - ) . + ). ' ORDER BY c.id' ); - } + } } diff --git a/nntmux/CollectionsCleaning.php b/nntmux/CollectionsCleaning.php index 3748e119c..dadc17b2b 100755 --- a/nntmux/CollectionsCleaning.php +++ b/nntmux/CollectionsCleaning.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; use nntmux\db\DB; @@ -10,121 +11,121 @@ use nntmux\db\DB; */ class CollectionsCleaning { - /** - * Used for matching endings in article subjects. - * @const - * @string - */ - const REGEX_END = '[-_\s]{0,3}yEnc$/ui'; + /** + * Used for matching endings in article subjects. + * @const + * @string + */ + const REGEX_END = '[-_\s]{0,3}yEnc$/ui'; - /** - * Used for matching file extension endings in article subjects. - * @const - * @string - */ - const REGEX_FILE_EXTENSIONS = '([-_](proof|sample|thumbs?))*(\.part\d*(\.rar)?|\.rar|\.7z)?(\d{1,3}\.rev"|\.vol\d+\+\d+.+?"|\.[A-Za-z0-9]{2,4}"|")'; + /** + * Used for matching file extension endings in article subjects. + * @const + * @string + */ + const REGEX_FILE_EXTENSIONS = '([-_](proof|sample|thumbs?))*(\.part\d*(\.rar)?|\.rar|\.7z)?(\d{1,3}\.rev"|\.vol\d+\+\d+.+?"|\.[A-Za-z0-9]{2,4}"|")'; - /** - * Used for matching size strings in article subjects. - * @example ' - 365.15 KB - ' - * @const - * @string - */ - const REGEX_SUBJECT_SIZE = '[-_\s]{0,3}\d+([.,]\d+)? [kKmMgG][bB][-_\s]{0,3}'; + /** + * Used for matching size strings in article subjects. + * @example ' - 365.15 KB - ' + * @const + * @string + */ + const REGEX_SUBJECT_SIZE = '[-_\s]{0,3}\d+([.,]\d+)? [kKmMgG][bB][-_\s]{0,3}'; - /** - * Collection subject failed to match any regular expression - */ - const REGEX_NO_MATCH = 0; + /** + * Collection subject failed to match any regular expression. + */ + const REGEX_NO_MATCH = 0; - /** - * Collection subject matched the Generic regular expression - */ - const REGEX_GENERIC_MATCH = -10; + /** + * Collection subject matched the Generic regular expression. + */ + const REGEX_GENERIC_MATCH = -10; - /** - * Collection subject matched the Music generic regular expression - */ - const REGEX_MUSIC_MATCH = -20; + /** + * Collection subject matched the Music generic regular expression. + */ + const REGEX_MUSIC_MATCH = -20; - /** - * @var string - */ - public $e0; + /** + * @var string + */ + public $e0; - /** - * @var string - */ - public $e1; + /** + * @var string + */ + public $e1; - /** - * @var string - */ - public $e2; + /** + * @var string + */ + public $e2; - /** - * @var string - */ - public $groupName = ''; + /** + * @var string + */ + public $groupName = ''; - /** - * @var string - */ - public $subject = ''; + /** + * @var string + */ + public $subject = ''; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var Regexes - */ - protected $_regexes; + /** + * @var Regexes + */ + protected $_regexes; - /** - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - // Extensions. - $this->e0 = self::REGEX_FILE_EXTENSIONS; - $this->e1 = self::REGEX_FILE_EXTENSIONS . self::REGEX_END; - $this->e2 = self::REGEX_FILE_EXTENSIONS . self::REGEX_SUBJECT_SIZE . self::REGEX_END; + /** + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + // Extensions. + $this->e0 = self::REGEX_FILE_EXTENSIONS; + $this->e1 = self::REGEX_FILE_EXTENSIONS.self::REGEX_END; + $this->e2 = self::REGEX_FILE_EXTENSIONS.self::REGEX_SUBJECT_SIZE.self::REGEX_END; - $defaults = [ + $defaults = [ 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->_regexes = new Regexes(['Settings' => $this->pdo, 'Table_Name' => 'collection_regexes']); - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->_regexes = new Regexes(['Settings' => $this->pdo, 'Table_Name' => 'collection_regexes']); + } - /** - * Cleans a usenet subject returning a string that can be used to "merge" files together, a pretty subject, a categoryID and the name status. - * - * @param string $subject Subject to parse. - * @param string $groupName Group to work in. - * - * @return array The ID of the Regex Matched and the cleaned collection name - * @throws \Exception - */ - public function collectionsCleaner($subject, $groupName): ?array - { - $this->subject = $subject; - $this->groupName = $groupName; + /** + * Cleans a usenet subject returning a string that can be used to "merge" files together, a pretty subject, a categoryID and the name status. + * + * @param string $subject Subject to parse. + * @param string $groupName Group to work in. + * + * @return array The ID of the Regex Matched and the cleaned collection name + * @throws \Exception + */ + public function collectionsCleaner($subject, $groupName): ?array + { + $this->subject = $subject; + $this->groupName = $groupName; - // Try DB regex first. - $potentialString = $this->_regexes->tryRegex($subject, $groupName); - if ($potentialString) { - return [ + // Try DB regex first. + $potentialString = $this->_regexes->tryRegex($subject, $groupName); + if ($potentialString) { + return [ 'id' => $this->_regexes->matchedRegex, - 'name' => $potentialString + 'name' => $potentialString, ]; - } + } - switch ($groupName) { + switch ($groupName) { /* case 'alt.binaries.this.is.an.example': return $this->_example_method_name(); @@ -133,98 +134,99 @@ class CollectionsCleaning default: return $this->generic(); } - } + } - /** - * Cleans usenet subject before inserting, used for collectionhash. If no regexes matched on collectionsCleaner. - * - * @return array|null - */ - protected function generic(): ?array - { - // For non music groups. - if (!preg_match('/\.(flac|lossless|mp3|music|sounds)/', $this->groupName)) { - // File/part count. - $cleanSubject = preg_replace('/((( \(\d\d\) -|(\d\d)? - \d\d\.|\d{4} \d\d -) | - \d\d-| \d\d\. [a-z]).+| \d\d of \d\d| \dof\d)\.mp3"?|(\)|\(|\[|\s)\d{1,5}(\/|(\s|_)of(\s|_)|-)\d{1,5}(\)|\]|\s|$|:)|\(\d{1,3}\|\d{1,3}\)|[^\d]{4}-\d{1,3}-\d{1,3}\.|\s\d{1,3}\sof\s\d{1,3}\.|\s\d{1,3}\/\d{1,3}|\d{1,3}of\d{1,3}\.|^\d{1,3}\/\d{1,3}\s|\d{1,3} - of \d{1,3}/i', ' ', $this->subject); - // File extensions. - $cleanSubject = preg_replace('/' . $this->e0 . '/i', ' ', $cleanSubject); - // File extensions - If it was not in quotes. - $cleanSubject = preg_replace('/(-? [a-z0-9]+-?|\(?\d{4}\)?(_|-)[a-z0-9]+)\.jpg"?| [a-z0-9]+\.mu3"?|((\d{1,3})?\.part(\d{1,5})?|\d{1,5} ?|sample|- Partie \d+)?\.(7z|\d{3}(?=(\s|"))|avi|diz|docx?|epub|idx|iso|jpg|m3u|m4a|mds|mkv|mobi|mp4|nfo|nzb|par(\s?2|")|pdf|rar|rev|rtf|r\d\d|sfv|srs|srr|sub|txt|vol.+(par2)|xls|zip|z{2,3})"?|(\s|(\d{2,3})?-)\d{2,3}\.mp3|\d{2,3}\.pdf|\.part\d{1,4}\./i', ' ', $cleanSubject); - // File Sizes - Non unique ones. - $cleanSubject = preg_replace('/\d{1,3}(,|\.|\/)\d{1,3}\s(k|m|g)b|(\])?\s\d+KB\s(yENC)?|"?\s\d+\sbytes?|[- ]?\d+(\.|,)?\d+\s(g|k|m)?B\s-?(\s?yenc)?|\s\(d{1,3},\d{1,3}\s{K,M,G}B\)\s|yEnc \d+k$|{\d+ yEnc bytes}|yEnc \d+ |\(\d+ ?(k|m|g)?b(ytes)?\) yEnc$/i', ' ', $cleanSubject); - // Random stuff. - $cleanSubject = preg_replace('/AutoRarPar\d{1,5}|\(\d+\)( | )yEnc|\d+(Amateur|Classic)| \d{4,}[a-z]{4,} |part\d+/i', ' ', $cleanSubject); - // Multi spaces. - return [ + /** + * Cleans usenet subject before inserting, used for collectionhash. If no regexes matched on collectionsCleaner. + * + * @return array|null + */ + protected function generic(): ?array + { + // For non music groups. + if (! preg_match('/\.(flac|lossless|mp3|music|sounds)/', $this->groupName)) { + // File/part count. + $cleanSubject = preg_replace('/((( \(\d\d\) -|(\d\d)? - \d\d\.|\d{4} \d\d -) | - \d\d-| \d\d\. [a-z]).+| \d\d of \d\d| \dof\d)\.mp3"?|(\)|\(|\[|\s)\d{1,5}(\/|(\s|_)of(\s|_)|-)\d{1,5}(\)|\]|\s|$|:)|\(\d{1,3}\|\d{1,3}\)|[^\d]{4}-\d{1,3}-\d{1,3}\.|\s\d{1,3}\sof\s\d{1,3}\.|\s\d{1,3}\/\d{1,3}|\d{1,3}of\d{1,3}\.|^\d{1,3}\/\d{1,3}\s|\d{1,3} - of \d{1,3}/i', ' ', $this->subject); + // File extensions. + $cleanSubject = preg_replace('/'.$this->e0.'/i', ' ', $cleanSubject); + // File extensions - If it was not in quotes. + $cleanSubject = preg_replace('/(-? [a-z0-9]+-?|\(?\d{4}\)?(_|-)[a-z0-9]+)\.jpg"?| [a-z0-9]+\.mu3"?|((\d{1,3})?\.part(\d{1,5})?|\d{1,5} ?|sample|- Partie \d+)?\.(7z|\d{3}(?=(\s|"))|avi|diz|docx?|epub|idx|iso|jpg|m3u|m4a|mds|mkv|mobi|mp4|nfo|nzb|par(\s?2|")|pdf|rar|rev|rtf|r\d\d|sfv|srs|srr|sub|txt|vol.+(par2)|xls|zip|z{2,3})"?|(\s|(\d{2,3})?-)\d{2,3}\.mp3|\d{2,3}\.pdf|\.part\d{1,4}\./i', ' ', $cleanSubject); + // File Sizes - Non unique ones. + $cleanSubject = preg_replace('/\d{1,3}(,|\.|\/)\d{1,3}\s(k|m|g)b|(\])?\s\d+KB\s(yENC)?|"?\s\d+\sbytes?|[- ]?\d+(\.|,)?\d+\s(g|k|m)?B\s-?(\s?yenc)?|\s\(d{1,3},\d{1,3}\s{K,M,G}B\)\s|yEnc \d+k$|{\d+ yEnc bytes}|yEnc \d+ |\(\d+ ?(k|m|g)?b(ytes)?\) yEnc$/i', ' ', $cleanSubject); + // Random stuff. + $cleanSubject = preg_replace('/AutoRarPar\d{1,5}|\(\d+\)( | )yEnc|\d+(Amateur|Classic)| \d{4,}[a-z]{4,} |part\d+/i', ' ', $cleanSubject); + // Multi spaces. + return [ 'id' => self::REGEX_GENERIC_MATCH, - 'name' => utf8_encode(trim(preg_replace('/\s\s+/', ' ', $cleanSubject))) + 'name' => utf8_encode(trim(preg_replace('/\s\s+/', ' ', $cleanSubject))), ]; - } // Music groups. - else { - // Try some music group regexes. - $musicSubject = $this->musicSubject(); - if ($musicSubject !== false) { - return [ + } // Music groups. + else { + // Try some music group regexes. + $musicSubject = $this->musicSubject(); + if ($musicSubject !== false) { + return [ 'id' => self::REGEX_MUSIC_MATCH, - 'name' => $musicSubject + 'name' => $musicSubject, ]; - // Parts/files - } else { - $cleanSubject = preg_replace('/((( \(\d\d\) -|(\d\d)? - \d\d\.|\d{4} \d\d -) | - \d\d-| \d\d\. [a-z]).+| \d\d of \d\d| \dof\d)\.mp3"?|(\(|\[|\s)\d{1,4}(\/|(\s|_)of(\s|_)|-)\d{1,4}(\)|\]|\s|$|:)|\(\d{1,3}\|\d{1,3}\)|-\d{1,3}-\d{1,3}\.|\s\d{1,3}\sof\s\d{1,3}\.|\s\d{1,3}\/\d{1,3}|\d{1,3}of\d{1,3}\.|^\d{1,3}\/\d{1,3}\s|\d{1,3} - of \d{1,3}/i', ' ', $this->subject); - } - // Anything between the quotes. Too much variance within the quotes, so remove it completely. - $cleanSubject = preg_replace('/".+"/i', ' ', $cleanSubject); - // File extensions - If it was not in quotes. - $cleanSubject = preg_replace('/(-? [a-z0-9]+-?|\(?\d{4}\)?(_|-)[a-z0-9]+)\.jpg"?| [a-z0-9]+\.mu3"?|((\d{1,3})?\.part(\d{1,5})?|\d{1,5} ?|sample|- Partie \d+)?\.(7z|\d{3}(?=(\s|"))|avi|diz|docx?|epub|idx|iso|jpg|m3u|m4a|mds|mkv|mobi|mp4|nfo|nzb|par(\s?2|")|pdf|rar|rev|rtf|r\d\d|sfv|srs|srr|sub|txt|vol.+(par2)|xls|zip|z{2,3})"?|(\s|(\d{2,3})?-)\d{2,3}\.mp3|\d{2,3}\.pdf|\.part\d{1,4}\./i', ' ', $cleanSubject); - // File Sizes - Non unique ones. - $cleanSubject = preg_replace('/\d{1,3}(,|\.|\/)\d{1,3}\s(k|m|g)b|(\])?\s\d+KB\s(yENC)?|"?\s\d+\sbytes?|[- ]?\d+[.,]?\d+\s(g|k|m)?B\s-?(\s?yenc)?|\s\(d{1,3},\d{1,3}\s{K,M,G}B\)\s|yEnc \d+k$|{\d+ yEnc bytes}|yEnc \d+ |\(\d+ ?(k|m|g)?b(ytes)?\) yEnc$/i', ' ', $cleanSubject); - // Random stuff. - $cleanSubject = preg_replace('/AutoRarPar\d{1,5}|\(\d+\)( | )yEnc|\d+(Amateur|Classic)| \d{4,}[a-z]{4,} |part\d+/i', ' ', $cleanSubject); - // Multi spaces. - $cleanSubject = utf8_encode(trim(preg_replace('/\s\s+/i', ' ', $cleanSubject))); - // If the subject is too similar to another because it is so short, try to extract info from the subject. - if (strlen($cleanSubject) <= 10 || preg_match('/^[-a-z0-9$ ]{1,7}yEnc$/i', $cleanSubject)) { - $x = ''; - if (preg_match('/.*("[A-Z0-9]+).*?"/i', $this->subject, $match)) { - $x = $match[1]; - } - if (preg_match_all('/[^A-Z0-9]/i', $this->subject, $match1)) { - $start = 0; - foreach ($match1[0] as $add) { - if ($start > 2) { - break; - } - $x .= $add; - $start++; - } - } - $newName = preg_replace('/".+?"/', '', $this->subject); - $newName = preg_replace('/[a-z0-9]|' . $this->e0 . '/i', '', $newName); - return [ - 'id' => self::REGEX_MUSIC_MATCH, - 'name' => $cleanSubject . $newName . $x - ]; - } else { - return [ - 'id' => self::REGEX_MUSIC_MATCH, - 'name' => $cleanSubject - ]; - } - } - } + // Parts/files + } else { + $cleanSubject = preg_replace('/((( \(\d\d\) -|(\d\d)? - \d\d\.|\d{4} \d\d -) | - \d\d-| \d\d\. [a-z]).+| \d\d of \d\d| \dof\d)\.mp3"?|(\(|\[|\s)\d{1,4}(\/|(\s|_)of(\s|_)|-)\d{1,4}(\)|\]|\s|$|:)|\(\d{1,3}\|\d{1,3}\)|-\d{1,3}-\d{1,3}\.|\s\d{1,3}\sof\s\d{1,3}\.|\s\d{1,3}\/\d{1,3}|\d{1,3}of\d{1,3}\.|^\d{1,3}\/\d{1,3}\s|\d{1,3} - of \d{1,3}/i', ' ', $this->subject); + } + // Anything between the quotes. Too much variance within the quotes, so remove it completely. + $cleanSubject = preg_replace('/".+"/i', ' ', $cleanSubject); + // File extensions - If it was not in quotes. + $cleanSubject = preg_replace('/(-? [a-z0-9]+-?|\(?\d{4}\)?(_|-)[a-z0-9]+)\.jpg"?| [a-z0-9]+\.mu3"?|((\d{1,3})?\.part(\d{1,5})?|\d{1,5} ?|sample|- Partie \d+)?\.(7z|\d{3}(?=(\s|"))|avi|diz|docx?|epub|idx|iso|jpg|m3u|m4a|mds|mkv|mobi|mp4|nfo|nzb|par(\s?2|")|pdf|rar|rev|rtf|r\d\d|sfv|srs|srr|sub|txt|vol.+(par2)|xls|zip|z{2,3})"?|(\s|(\d{2,3})?-)\d{2,3}\.mp3|\d{2,3}\.pdf|\.part\d{1,4}\./i', ' ', $cleanSubject); + // File Sizes - Non unique ones. + $cleanSubject = preg_replace('/\d{1,3}(,|\.|\/)\d{1,3}\s(k|m|g)b|(\])?\s\d+KB\s(yENC)?|"?\s\d+\sbytes?|[- ]?\d+[.,]?\d+\s(g|k|m)?B\s-?(\s?yenc)?|\s\(d{1,3},\d{1,3}\s{K,M,G}B\)\s|yEnc \d+k$|{\d+ yEnc bytes}|yEnc \d+ |\(\d+ ?(k|m|g)?b(ytes)?\) yEnc$/i', ' ', $cleanSubject); + // Random stuff. + $cleanSubject = preg_replace('/AutoRarPar\d{1,5}|\(\d+\)( | )yEnc|\d+(Amateur|Classic)| \d{4,}[a-z]{4,} |part\d+/i', ' ', $cleanSubject); + // Multi spaces. + $cleanSubject = utf8_encode(trim(preg_replace('/\s\s+/i', ' ', $cleanSubject))); + // If the subject is too similar to another because it is so short, try to extract info from the subject. + if (strlen($cleanSubject) <= 10 || preg_match('/^[-a-z0-9$ ]{1,7}yEnc$/i', $cleanSubject)) { + $x = ''; + if (preg_match('/.*("[A-Z0-9]+).*?"/i', $this->subject, $match)) { + $x = $match[1]; + } + if (preg_match_all('/[^A-Z0-9]/i', $this->subject, $match1)) { + $start = 0; + foreach ($match1[0] as $add) { + if ($start > 2) { + break; + } + $x .= $add; + $start++; + } + } + $newName = preg_replace('/".+?"/', '', $this->subject); + $newName = preg_replace('/[a-z0-9]|'.$this->e0.'/i', '', $newName); - /** - * Generic regexes for music groups. - * - * @return bool - */ - protected function musicSubject() - { - //Broderick_Smith-Unknown_Country-2009-404 "00-broderick_smith-unknown_country-2009.sfv" yEnc - if (preg_match('/^(\w{10,}-[a-zA-Z0-9]+ ")\d\d-.+?" yEnc$/', $this->subject, $match)) { - return $match[1]; - } + return [ + 'id' => self::REGEX_MUSIC_MATCH, + 'name' => $cleanSubject.$newName.$x, + ]; + } else { + return [ + 'id' => self::REGEX_MUSIC_MATCH, + 'name' => $cleanSubject, + ]; + } + } + } - return false; - } + /** + * Generic regexes for music groups. + * + * @return bool + */ + protected function musicSubject() + { + //Broderick_Smith-Unknown_Country-2009-404 "00-broderick_smith-unknown_country-2009.sfv" yEnc + if (preg_match('/^(\w{10,}-[a-zA-Z0-9]+ ")\d\d-.+?" yEnc$/', $this->subject, $match)) { + return $match[1]; + } + + return false; + } } diff --git a/nntmux/ColorCLI.php b/nntmux/ColorCLI.php index 2ff19d6b9..0ddd98ceb 100755 --- a/nntmux/ColorCLI.php +++ b/nntmux/ColorCLI.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; // Original taken from https://gist.github.com/donatj/1315354 by Jesse Donat. @@ -6,7 +7,7 @@ namespace nntmux; class ColorCLI { - private static $foreground_colors = [ + private static $foreground_colors = [ 'Black' => '30', 'Blue' => '34', 'Green' => '32', @@ -16,8 +17,8 @@ class ColorCLI 'Yellow' => '33', 'Gray' => '37', ]; - // Feel free to add any other colors that you like here. - private static $colors256 = [ + // Feel free to add any other colors that you like here. + private static $colors256 = [ 'Gray' => '008', 'Red' => '009', 'Green' => '010', 'Yellow' => '011', 'Blue' => '012', 'Purple' => '013', @@ -143,212 +144,227 @@ class ColorCLI 'Grey28' => '252', 'Grey29' => '253', 'Grey30' => '254', 'Grey31' => '255', ]; - private static $background_colors = [ + private static $background_colors = [ 'Black' => '40', 'Red' => '41', 'Green' => '42', 'Yellow' => '43', 'Blue' => '44', 'Purple' => '45', 'Cyan' => '46', 'White' => '47', ]; - private static $options = [ + private static $options = [ 'Norm' => '0', 'Bold' => '1', 'Dim' => '2', 'Uline' => '4', 'Blink' => '5', 'Rev' => '7', 'Hidden' => '8', 'Crossout' => '9', ]; - /** - * @param int $count - */ - public static function bell($count = 1): void - { - echo str_repeat("\007", $count); - } + /** + * @param int $count + */ + public static function bell($count = 1): void + { + echo str_repeat("\007", $count); + } - /** - * @param $fg - * @param string $opt - * @param string $bg - * @return string - */ - public static function setColor($fg, $opt = 'None', $bg = 'None'): string - { - $colored_string = "\033[" . self::$foreground_colors[$fg]; - if (isset(self::$options[$opt])) { - $colored_string .= ';' . self::$options[$opt]; - } - if (isset(self::$background_colors[$bg])) { - $colored_string .= ';' . self::$background_colors[$bg]; - } - $colored_string .= 'm'; - return $colored_string; - } + /** + * @param $fg + * @param string $opt + * @param string $bg + * @return string + */ + public static function setColor($fg, $opt = 'None', $bg = 'None'): string + { + $colored_string = "\033[".self::$foreground_colors[$fg]; + if (isset(self::$options[$opt])) { + $colored_string .= ';'.self::$options[$opt]; + } + if (isset(self::$background_colors[$bg])) { + $colored_string .= ';'.self::$background_colors[$bg]; + } + $colored_string .= 'm'; - /** - * @param $fg - * @param string $opt - * @param string $bg - * @return string - */ - public static function set256($fg, $opt = 'None', $bg = 'None'): string - { - $colored_string = "\033[38;5;" . self::$colors256[$fg]; - if ($opt !== 'Norm' && isset(self::$options[$opt])) { - $colored_string .= ';' . self::$options[$opt]; - } - if (isset(self::$background_colors[$bg])) { - $colored_string .= ';48;5;' . self::$colors256[$bg]; - } - $colored_string .= 'm'; - return $colored_string; - } + return $colored_string; + } - /** - * @param $str - * @return string - */ - public static function debug($str): string - { - $debugstring = "\033[" . self::$foreground_colors['Gray'] . "mDebug: $str\033[0m\n"; - return $debugstring; - } + /** + * @param $fg + * @param string $opt + * @param string $bg + * @return string + */ + public static function set256($fg, $opt = 'None', $bg = 'None'): string + { + $colored_string = "\033[38;5;".self::$colors256[$fg]; + if ($opt !== 'Norm' && isset(self::$options[$opt])) { + $colored_string .= ';'.self::$options[$opt]; + } + if (isset(self::$background_colors[$bg])) { + $colored_string .= ';48;5;'.self::$colors256[$bg]; + } + $colored_string .= 'm'; - /** - * @param $str - * @return string - */ - public static function info($str): string - { - $infostring = "\033[" . self::$foreground_colors['Purple'] . "mInfo: $str\033[0m\n"; - return $infostring; - } + return $colored_string; + } - /** - * @param $str - * @return string - */ - public static function notice($str): string - { - $noticstring = "\033[38;5;" . self::$colors256['Blue'] . "mNotice: $str\033[0m\n"; - return $noticstring; - } + /** + * @param $str + * @return string + */ + public static function debug($str): string + { + $debugstring = "\033[".self::$foreground_colors['Gray']."mDebug: $str\033[0m\n"; - /** - * @param $str - * @return string - */ - public static function warning($str): string - { - $warnstring = "\033[" . self::$foreground_colors['Yellow'] . "mWarning: $str\033[0m\n"; - return $warnstring; - } + return $debugstring; + } - /** - * @param $str - * @return string - */ - public static function error($str): string - { - $errorstring = "\033[" . self::$foreground_colors['Red'] . "mError: $str\033[0m\n"; - return $errorstring; - } + /** + * @param $str + * @return string + */ + public static function info($str): string + { + $infostring = "\033[".self::$foreground_colors['Purple']."mInfo: $str\033[0m\n"; - /** - * @param $str - * @return string - */ - public static function primary($str): string - { - $str = "\033[38;5;" . self::$colors256['Green'] . "m$str\033[0m\n"; - return $str; - } + return $infostring; + } - /** - * @param $str - * @return string - */ - public static function header($str): string - { - $str = "\033[38;5;" . self::$colors256['Yellow'] . "m$str\033[0m\n"; - return $str; - } + /** + * @param $str + * @return string + */ + public static function notice($str): string + { + $noticstring = "\033[38;5;".self::$colors256['Blue']."mNotice: $str\033[0m\n"; - /** - * @param $str - * @return string - */ - public static function alternate($str): string - { - $str = "\033[38;5;" . self::$colors256['DeepPink1'] . "m$str\033[0m\n"; - return $str; - } + return $noticstring; + } - /** - * @param $str - * @return string - */ - public static function tmuxOrange($str): string - { - $str = "\033[38;5;" . self::$colors256['Orange'] . "m$str\033[0m\n"; - return $str; - } + /** + * @param $str + * @return string + */ + public static function warning($str): string + { + $warnstring = "\033[".self::$foreground_colors['Yellow']."mWarning: $str\033[0m\n"; - /** - * @param $str - * @return string - */ - public static function primaryOver($str): string - { - $str = "\033[38;5;" . self::$colors256['Green'] . "m$str\033[0m"; - return $str; - } + return $warnstring; + } - /** - * @param $str - * @return string - */ - public static function headerOver($str): string - { - $str = "\033[38;5;" . self::$colors256['Yellow'] . "m$str\033[0m"; - return $str; - } + /** + * @param $str + * @return string + */ + public static function error($str): string + { + $errorstring = "\033[".self::$foreground_colors['Red']."mError: $str\033[0m\n"; - /** - * @param $str - * @return string - */ - public static function alternateOver($str): string - { - $str = "\033[38;5;" . self::$colors256['DeepPink1'] . "m$str\033[0m"; - return $str; - } + return $errorstring; + } - /** - * @param $str - * @return string - */ - public static function warningOver($str): string - { - $str = "\033[38;5;" . self::$colors256['Red'] . "m$str\033[0m"; - return $str; - } + /** + * @param $str + * @return string + */ + public static function primary($str): string + { + $str = "\033[38;5;".self::$colors256['Green']."m$str\033[0m\n"; - /** - * @return string - */ - public static function rsetColor(): string - { - return "\033[0m"; - } + return $str; + } - /** - * Echo message to CLI. - * - * @param string $message The message. - * @param bool $nl Add a new line? - * @void - */ - public static function doEcho($message, $nl = false): void - { - echo $message . ($nl ? PHP_EOL : ''); - } + /** + * @param $str + * @return string + */ + public static function header($str): string + { + $str = "\033[38;5;".self::$colors256['Yellow']."m$str\033[0m\n"; + + return $str; + } + + /** + * @param $str + * @return string + */ + public static function alternate($str): string + { + $str = "\033[38;5;".self::$colors256['DeepPink1']."m$str\033[0m\n"; + + return $str; + } + + /** + * @param $str + * @return string + */ + public static function tmuxOrange($str): string + { + $str = "\033[38;5;".self::$colors256['Orange']."m$str\033[0m\n"; + + return $str; + } + + /** + * @param $str + * @return string + */ + public static function primaryOver($str): string + { + $str = "\033[38;5;".self::$colors256['Green']."m$str\033[0m"; + + return $str; + } + + /** + * @param $str + * @return string + */ + public static function headerOver($str): string + { + $str = "\033[38;5;".self::$colors256['Yellow']."m$str\033[0m"; + + return $str; + } + + /** + * @param $str + * @return string + */ + public static function alternateOver($str): string + { + $str = "\033[38;5;".self::$colors256['DeepPink1']."m$str\033[0m"; + + return $str; + } + + /** + * @param $str + * @return string + */ + public static function warningOver($str): string + { + $str = "\033[38;5;".self::$colors256['Red']."m$str\033[0m"; + + return $str; + } + + /** + * @return string + */ + public static function rsetColor(): string + { + return "\033[0m"; + } + + /** + * Echo message to CLI. + * + * @param string $message The message. + * @param bool $nl Add a new line? + * @void + */ + public static function doEcho($message, $nl = false): void + { + echo $message.($nl ? PHP_EOL : ''); + } } diff --git a/nntmux/Console.php b/nntmux/Console.php index 8d257a8dd..23f87df3a 100755 --- a/nntmux/Console.php +++ b/nntmux/Console.php @@ -1,169 +1,170 @@ <?php + namespace nntmux; -use ApaiIO\Request\GuzzleRequest; -use ApaiIO\ResponseTransformer\XmlToSimpleXmlObject; -use App\Models\Settings; -use GuzzleHttp\Client; use nntmux\db\DB; -use ApaiIO\Configuration\GenericConfiguration; -use ApaiIO\Operations\Search; use ApaiIO\ApaiIO; - +use GuzzleHttp\Client; +use App\Models\Settings; +use ApaiIO\Operations\Search; +use ApaiIO\Request\GuzzleRequest; +use ApaiIO\Configuration\GenericConfiguration; +use ApaiIO\ResponseTransformer\XmlToSimpleXmlObject; /** - * Class Console + * Class Console. */ class Console { - const CONS_UPROC = 0; // Release has not been processed. - const CONS_NTFND = -2; + const CONS_UPROC = 0; // Release has not been processed. + const CONS_NTFND = -2; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var bool - */ - public $echooutput; + /** + * @var bool + */ + public $echooutput; - /** - * @var array|bool|string - */ - public $pubkey; + /** + * @var array|bool|string + */ + public $pubkey; - /** - * @var array|bool|string - */ - public $privkey; + /** + * @var array|bool|string + */ + public $privkey; - /** - * @var array|bool|string - */ - public $asstag; + /** + * @var array|bool|string + */ + public $asstag; - /** - * @var array|bool|int|string - */ - public $gameqty; + /** + * @var array|bool|int|string + */ + public $gameqty; - /** - * @var array|bool|int|string - */ - public $sleeptime; + /** + * @var array|bool|int|string + */ + public $sleeptime; - /** - * @var string - */ - public $imgSavePath; + /** + * @var string + */ + public $imgSavePath; - /** - * @var string - */ - public $renamed; + /** + * @var string + */ + public $renamed; - /** - * @var array|bool|int|string - */ - public $catWhere; + /** + * @var array|bool|int|string + */ + public $catWhere; - /** - * Store names of failed Amazon lookup items - * @var array - */ - public $failCache; + /** + * Store names of failed Amazon lookup items. + * @var array + */ + public $failCache; - /** - * @param array $options Class instances / Echo to cli. - */ - public function __construct(array $options =[]) - { - $defaults = [ + /** + * @param array $options Class instances / Echo to cli. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->pubkey = Settings::value('APIs..amazonpubkey'); - $this->privkey = Settings::value('APIs..amazonprivkey'); - $this->asstag = Settings::value('APIs..amazonassociatetag'); - $this->gameqty = (Settings::value('..maxgamesprocessed') != '') ? Settings::value('..maxgamesprocessed') : 150; - $this->sleeptime = (Settings::value('..amazonsleep') != '') ? Settings::value('..amazonsleep') : 1000; - $this->imgSavePath = NN_COVERS . 'console' . DS; - $this->renamed = Settings::value('..lookupgames') == 2 ? 'AND isrenamed = 1' : ''; - $this->catWhere = 'PARTITION (console)'; + $this->pubkey = Settings::value('APIs..amazonpubkey'); + $this->privkey = Settings::value('APIs..amazonprivkey'); + $this->asstag = Settings::value('APIs..amazonassociatetag'); + $this->gameqty = (Settings::value('..maxgamesprocessed') != '') ? Settings::value('..maxgamesprocessed') : 150; + $this->sleeptime = (Settings::value('..amazonsleep') != '') ? Settings::value('..amazonsleep') : 1000; + $this->imgSavePath = NN_COVERS.'console'.DS; + $this->renamed = Settings::value('..lookupgames') == 2 ? 'AND isrenamed = 1' : ''; + $this->catWhere = 'PARTITION (console)'; - $this->failCache =[]; - } + $this->failCache = []; + } - public function getConsoleInfo($id) - { - return $this->pdo->queryOneRow( + public function getConsoleInfo($id) + { + return $this->pdo->queryOneRow( sprintf( 'SELECT consoleinfo.*, genres.title AS genres FROM consoleinfo LEFT OUTER JOIN genres ON genres.id = consoleinfo.genres_id WHERE consoleinfo.id = %d', $id ) ); - } + } - public function getConsoleInfoByName($title, $platform) - { - //only used to get a count of words - $searchwords = $searchsql = ''; - $ft = $this->pdo->queryDirect("SHOW INDEX FROM consoleinfo WHERE key_name = 'ix_consoleinfo_title_platform_ft'"); - if ($ft->rowCount() !== 2) { - $searchsql .= sprintf(" title %s AND platform %s'", $this->pdo->likeString($title, true, true), $this->pdo->likeString($platform, true, true)); - } else { - $title = preg_replace('/( - | -|\(.+\)|\(|\))/', ' ', $title); - $title = preg_replace('/[^\w ]+/', '', $title); - $title = trim(preg_replace('/\s\s+/i', ' ', $title)); - $title = trim($title); - $words = explode(' ', $title); + public function getConsoleInfoByName($title, $platform) + { + //only used to get a count of words + $searchwords = $searchsql = ''; + $ft = $this->pdo->queryDirect("SHOW INDEX FROM consoleinfo WHERE key_name = 'ix_consoleinfo_title_platform_ft'"); + if ($ft->rowCount() !== 2) { + $searchsql .= sprintf(" title %s AND platform %s'", $this->pdo->likeString($title, true, true), $this->pdo->likeString($platform, true, true)); + } else { + $title = preg_replace('/( - | -|\(.+\)|\(|\))/', ' ', $title); + $title = preg_replace('/[^\w ]+/', '', $title); + $title = trim(preg_replace('/\s\s+/i', ' ', $title)); + $title = trim($title); + $words = explode(' ', $title); - foreach ($words as $word) { - $word = trim(rtrim(trim($word), '-')); - if ($word !== '' && $word !== '-') { - $word = '+' . $word; - $searchwords .= sprintf('%s ', $word); - } - } - $searchwords = trim($searchwords); - $searchsql .= sprintf(' MATCH(title, platform) AGAINST(%s IN BOOLEAN MODE) AND platform = %s', $this->pdo->escapeString($searchwords), $this->pdo->escapeString($platform)); - } - return $this->pdo->queryOneRow(sprintf('SELECT * FROM consoleinfo WHERE %s', $searchsql)); - } + foreach ($words as $word) { + $word = trim(rtrim(trim($word), '-')); + if ($word !== '' && $word !== '-') { + $word = '+'.$word; + $searchwords .= sprintf('%s ', $word); + } + } + $searchwords = trim($searchwords); + $searchsql .= sprintf(' MATCH(title, platform) AGAINST(%s IN BOOLEAN MODE) AND platform = %s', $this->pdo->escapeString($searchwords), $this->pdo->escapeString($platform)); + } - /** - * @param $cat - * @param $start - * @param $num - * @param $orderby - * @param array $excludedcats - * - * @return array - */ - public function getConsoleRange($cat, $start, $num, $orderby, $excludedcats = []) - { - $browseby = $this->getBrowseBy(); + return $this->pdo->queryOneRow(sprintf('SELECT * FROM consoleinfo WHERE %s', $searchsql)); + } - $catsrch = ''; - if (count($cat) > 0 && $cat[0] != -1) { - $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); - } + /** + * @param $cat + * @param $start + * @param $num + * @param $orderby + * @param array $excludedcats + * + * @return array + */ + public function getConsoleRange($cat, $start, $num, $orderby, $excludedcats = []) + { + $browseby = $this->getBrowseBy(); - $exccatlist = ""; - if (count($excludedcats) > 0) { - $exccatlist = ' AND r.categories_id NOT IN (' . implode(',', $excludedcats) . ')'; - } + $catsrch = ''; + if (count($cat) > 0 && $cat[0] != -1) { + $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); + } - $order = $this->getConsoleOrder($orderby); + $exccatlist = ''; + if (count($excludedcats) > 0) { + $exccatlist = ' AND r.categories_id NOT IN ('.implode(',', $excludedcats).')'; + } - $consoles = $this->pdo->queryCalc( + $order = $this->getConsoleOrder($orderby); + + $consoles = $this->pdo->queryCalc( sprintf(" SELECT SQL_CALC_FOUND_ROWS con.id, @@ -183,20 +184,20 @@ class Console $exccatlist, $order[0], $order[1], - ($start === false ? '' : ' LIMIT ' . $num . ' OFFSET ' . $start) + ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start) ), true, NN_CACHE_EXPIRY_MEDIUM ); - $consoleIDs = $releaseIDs = false; + $consoleIDs = $releaseIDs = false; - if (is_array($consoles['result'])) { - foreach ($consoles['result'] AS $console => $id) { - $consoleIDs[] = $id['id']; - $releaseIDs[] = $id['grp_release_id']; - } - } + if (is_array($consoles['result'])) { + foreach ($consoles['result'] as $console => $id) { + $consoleIDs[] = $id['id']; + $releaseIDs[] = $id['grp_release_id']; + } + } - $return = $this->pdo->query( + $return = $this->pdo->query( sprintf(" SELECT GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id, @@ -236,17 +237,18 @@ class Console $order[1] ), true, NN_CACHE_EXPIRY_MEDIUM ); - if (!empty($return)) { - $return[0]['_totalcount'] = $consoles['total'] ?? 0; - } - return $return; - } + if (! empty($return)) { + $return[0]['_totalcount'] = $consoles['total'] ?? 0; + } - public function getConsoleOrder($orderby) - { - $order = ($orderby == '') ? 'r.postdate' : $orderby; - $orderArr = explode("_", $order); - switch ($orderArr[0]) { + return $return; + } + + public function getConsoleOrder($orderby) + { + $order = ($orderby == '') ? 'r.postdate' : $orderby; + $orderArr = explode('_', $order); + switch ($orderArr[0]) { case 'title': $orderfield = 'con.title'; break; @@ -273,55 +275,58 @@ class Console $orderfield = 'r.postdate'; break; } - $ordersort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc'; - return array($orderfield, $ordersort); - } + $ordersort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc'; - public function getConsoleOrdering() - { - return array('title_asc', 'title_desc', 'posted_asc', 'posted_desc', 'size_asc', 'size_desc', 'files_asc', 'files_desc', 'stats_asc', 'stats_desc', 'platform_asc', 'platform_desc', 'releasedate_asc', 'releasedate_desc', 'genre_asc', 'genre_desc'); - } + return [$orderfield, $ordersort]; + } - public function getBrowseByOptions() - { - return array('platform' => 'platform', 'title' => 'title', 'genre' => 'genres_id'); - } + public function getConsoleOrdering() + { + return ['title_asc', 'title_desc', 'posted_asc', 'posted_desc', 'size_asc', 'size_desc', 'files_asc', 'files_desc', 'stats_asc', 'stats_desc', 'platform_asc', 'platform_desc', 'releasedate_asc', 'releasedate_desc', 'genre_asc', 'genre_desc']; + } - public function getBrowseBy() - { - $browseby = ' '; - $browsebyArr = $this->getBrowseByOptions(); - foreach ($browsebyArr as $bbk => $bbv) { - if (isset($_REQUEST[$bbk]) && !empty($_REQUEST[$bbk])) { - $bbs = stripslashes($_REQUEST[$bbk]); - $browseby .= 'AND con.' . $bbv . ' ' . $this->pdo->likeString($bbs, true, true); - } - } - return $browseby; - } + public function getBrowseByOptions() + { + return ['platform' => 'platform', 'title' => 'title', 'genre' => 'genres_id']; + } - public function makeFieldLinks($data, $field) - { - $tmpArr = explode(', ', $data[$field]); - $newArr =[]; - $i = 0; - foreach ($tmpArr as $ta) { - if (trim($ta) == '') { - continue; - } - // Only use first 6. - if ($i > 5) { - break; - } - $newArr[] = '<a href="' . WWW_TOP . '/console?' . $field . '=' . urlencode($ta) . '" title="' . $ta . '">' . $ta . '</a>'; - $i++; - } - return implode(', ', $newArr); - } + public function getBrowseBy() + { + $browseby = ' '; + $browsebyArr = $this->getBrowseByOptions(); + foreach ($browsebyArr as $bbk => $bbv) { + if (isset($_REQUEST[$bbk]) && ! empty($_REQUEST[$bbk])) { + $bbs = stripslashes($_REQUEST[$bbk]); + $browseby .= 'AND con.'.$bbv.' '.$this->pdo->likeString($bbs, true, true); + } + } - public function update($id, $title, $asin, $url, $salesrank, $platform, $publisher, $releasedate, $esrb, $cover, $genreID, $review = 'review') - { - $this->pdo->queryExec( + return $browseby; + } + + public function makeFieldLinks($data, $field) + { + $tmpArr = explode(', ', $data[$field]); + $newArr = []; + $i = 0; + foreach ($tmpArr as $ta) { + if (trim($ta) == '') { + continue; + } + // Only use first 6. + if ($i > 5) { + break; + } + $newArr[] = '<a href="'.WWW_TOP.'/console?'.$field.'='.urlencode($ta).'" title="'.$ta.'">'.$ta.'</a>'; + $i++; + } + + return implode(', ', $newArr); + } + + public function update($id, $title, $asin, $url, $salesrank, $platform, $publisher, $releasedate, $esrb, $cover, $genreID, $review = 'review') + { + $this->pdo->queryExec( sprintf(' UPDATE consoleinfo SET @@ -342,217 +347,217 @@ class Console $id ) ); - } + } - public function updateConsoleInfo($gameInfo) - { - $consoleId = self::CONS_NTFND; + public function updateConsoleInfo($gameInfo) + { + $consoleId = self::CONS_NTFND; - $amaz = $this->fetchAmazonProperties($gameInfo['title'], $gameInfo['node']); + $amaz = $this->fetchAmazonProperties($gameInfo['title'], $gameInfo['node']); - if ($amaz) { + if ($amaz) { + $gameInfo['platform'] = $this->_replacePlatform($gameInfo['platform']); - $gameInfo['platform'] = $this->_replacePlatform($gameInfo['platform']); + $con = $this->_setConBeforeMatch($amaz, $gameInfo); - $con = $this->_setConBeforeMatch($amaz, $gameInfo); + // Basically the XBLA names contain crap, this is to reduce the title down far enough to be usable. + if (stripos('xbla', $gameInfo['platform']) !== false) { + $gameInfo['title'] = substr($gameInfo['title'], 0, 10); + $con['substr'] = $gameInfo['title']; + } - // Basically the XBLA names contain crap, this is to reduce the title down far enough to be usable. - if (stripos('xbla', $gameInfo['platform']) !== false) { - $gameInfo['title'] = substr($gameInfo['title'], 0, 10); - $con['substr'] = $gameInfo['title']; - } + if ($this->_matchConToGameInfo($gameInfo, $con) === true) { + $con += $this->_setConAfterMatch($amaz); + $con += $this->_matchGenre($amaz); - if ($this->_matchConToGameInfo($gameInfo, $con) === true) { + // Set covers properties + $con['coverurl'] = (string) $amaz->Items->Item->LargeImage->URL; - $con += $this->_setConAfterMatch($amaz); - $con += $this->_matchGenre($amaz); + if ($con['coverurl'] != '') { + $con['cover'] = 1; + } else { + $con['cover'] = 0; + } - // Set covers properties - $con['coverurl'] = (string)$amaz->Items->Item->LargeImage->URL; + $consoleId = $this->_updateConsoleTable($con); - if ($con['coverurl'] != '') { - $con['cover'] = 1; - } else { - $con['cover'] = 0; - } - - $consoleId = $this->_updateConsoleTable($con); - - if ($this->echooutput) { - if ($consoleId !== -2) { - ColorCLI::doEcho( - ColorCLI::header('Added/updated game: ') . - ColorCLI::alternateOver(' Title: ') . - ColorCLI::primary($con['title']) . - ColorCLI::alternateOver(' Platform: ') . - ColorCLI::primary($con['platform']) . - ColorCLI::alternateOver(' Genre: ') . + if ($this->echooutput) { + if ($consoleId !== -2) { + ColorCLI::doEcho( + ColorCLI::header('Added/updated game: '). + ColorCLI::alternateOver(' Title: '). + ColorCLI::primary($con['title']). + ColorCLI::alternateOver(' Platform: '). + ColorCLI::primary($con['platform']). + ColorCLI::alternateOver(' Genre: '). ColorCLI::primary($con['consolegenre']) ); - } - } - } - } - return $consoleId; - } + } + } + } + } - protected function _matchConToGameInfo($gameInfo =[], $con =[]) - { - $matched = false; + return $consoleId; + } - // This actual compares the two strings and outputs a percentage value. - $titlepercent = $platformpercent = ''; + protected function _matchConToGameInfo($gameInfo = [], $con = []) + { + $matched = false; - //Remove import tags from console title for match - $con['title'] = trim(preg_replace('/(\[|\().{2,} import(\]|\))$/i', '', $con['title'])); + // This actual compares the two strings and outputs a percentage value. + $titlepercent = $platformpercent = ''; - similar_text(strtolower($gameInfo['title']), strtolower($con['title']), $titlepercent); - similar_text(strtolower($gameInfo['platform']), strtolower($con['platform']), $platformpercent); + //Remove import tags from console title for match + $con['title'] = trim(preg_replace('/(\[|\().{2,} import(\]|\))$/i', '', $con['title'])); - if (NN_DEBUG) { - echo(PHP_EOL ."Matched: Title Percentage 1: $titlepercent% between " . $gameInfo['title'] . " and " . $con['title'] . PHP_EOL); - } + similar_text(strtolower($gameInfo['title']), strtolower($con['title']), $titlepercent); + similar_text(strtolower($gameInfo['platform']), strtolower($con['platform']), $platformpercent); - // Since Wii Ware games and XBLA have inconsistent original platforms, as long as title is 50% its ok. - if (preg_match('/wiiware|xbla/i', trim($gameInfo['platform'])) && $titlepercent >= 50) { - $titlepercent = 100; - $platformpercent = 100; - } + if (NN_DEBUG) { + echo PHP_EOL."Matched: Title Percentage 1: $titlepercent% between ".$gameInfo['title'].' and '.$con['title'].PHP_EOL; + } - // If the release is DLC matching will be difficult, so assume anything over 50% is legit. - if (isset($gameInfo['dlc']) && $gameInfo['dlc'] == 1 && $titlepercent >= 50) { - $titlepercent = 100; - $platformpercent = 100; - } + // Since Wii Ware games and XBLA have inconsistent original platforms, as long as title is 50% its ok. + if (preg_match('/wiiware|xbla/i', trim($gameInfo['platform'])) && $titlepercent >= 50) { + $titlepercent = 100; + $platformpercent = 100; + } - if ($titlepercent < 70) { - $gameInfo['title'] .= ' - ' . $gameInfo['platform']; - similar_text(strtolower($gameInfo['title']), strtolower($con['title']), $titlepercent); - } + // If the release is DLC matching will be difficult, so assume anything over 50% is legit. + if (isset($gameInfo['dlc']) && $gameInfo['dlc'] == 1 && $titlepercent >= 50) { + $titlepercent = 100; + $platformpercent = 100; + } - if (NN_DEBUG) { - echo("Matched: Title Percentage 2: $titlepercent% between " . $gameInfo['title'] . " and " . $con['title'] . PHP_EOL); - echo("Matched: Platform Percentage: $platformpercent% between " . $gameInfo['platform'] . " and " . $con['platform'] . PHP_EOL); - } + if ($titlepercent < 70) { + $gameInfo['title'] .= ' - '.$gameInfo['platform']; + similar_text(strtolower($gameInfo['title']), strtolower($con['title']), $titlepercent); + } - // Platform must equal 100%. - if ($platformpercent == 100 && $titlepercent >= 70) { - $matched = true; - } + if (NN_DEBUG) { + echo "Matched: Title Percentage 2: $titlepercent% between ".$gameInfo['title'].' and '.$con['title'].PHP_EOL; + echo "Matched: Platform Percentage: $platformpercent% between ".$gameInfo['platform'].' and '.$con['platform'].PHP_EOL; + } - return $matched; - } + // Platform must equal 100%. + if ($platformpercent == 100 && $titlepercent >= 70) { + $matched = true; + } - protected function _setConBeforeMatch($amaz, $gameInfo) - { - $con =[]; - $con['platform'] = (string)$amaz->Items->Item->ItemAttributes->Platform; - if (empty($con['platform'])) { - $con['platform'] = $gameInfo['platform']; - } + return $matched; + } - if (stripos('Super', $con['platform']) !== false) { - $con['platform'] = 'SNES'; - } + protected function _setConBeforeMatch($amaz, $gameInfo) + { + $con = []; + $con['platform'] = (string) $amaz->Items->Item->ItemAttributes->Platform; + if (empty($con['platform'])) { + $con['platform'] = $gameInfo['platform']; + } - $con['title'] = (string)$amaz->Items->Item->ItemAttributes->Title; - if (empty($con['title'])) { - $con['title'] = $gameInfo['title']; - } + if (stripos('Super', $con['platform']) !== false) { + $con['platform'] = 'SNES'; + } - // Remove Download strings - $dlStrings = array(' [Online Game Code]', ' [Download]', ' [Digital Code]', ' [Digital Download]'); - $con['title'] = str_ireplace($dlStrings, '', $con['title']); - return $con; - } + $con['title'] = (string) $amaz->Items->Item->ItemAttributes->Title; + if (empty($con['title'])) { + $con['title'] = $gameInfo['title']; + } - protected function _setConAfterMatch($amaz) - { - $con =[]; - $con['asin'] = (string)$amaz->Items->Item->ASIN; + // Remove Download strings + $dlStrings = [' [Online Game Code]', ' [Download]', ' [Digital Code]', ' [Digital Download]']; + $con['title'] = str_ireplace($dlStrings, '', $con['title']); - $con['url'] = (string)$amaz->Items->Item->DetailPageURL; - $con['url'] = str_replace("%26tag%3Dws", "%26tag%3Dopensourceins%2D21", $con['url']); + return $con; + } - $con['salesrank'] = (string)$amaz->Items->Item->SalesRank; - if ($con['salesrank'] == "") { - $con['salesrank'] = "null"; - } + protected function _setConAfterMatch($amaz) + { + $con = []; + $con['asin'] = (string) $amaz->Items->Item->ASIN; - $con['publisher'] = (string)$amaz->Items->Item->ItemAttributes->Publisher; - $con['esrb'] = (string)$amaz->Items->Item->ItemAttributes->ESRBAgeRating; - $con['releasedate'] = (string)$amaz->Items->Item->ItemAttributes->ReleaseDate; + $con['url'] = (string) $amaz->Items->Item->DetailPageURL; + $con['url'] = str_replace('%26tag%3Dws', '%26tag%3Dopensourceins%2D21', $con['url']); - if(!isset($con['releasedate'])){ - $con['releasedate'] = ""; - } + $con['salesrank'] = (string) $amaz->Items->Item->SalesRank; + if ($con['salesrank'] == '') { + $con['salesrank'] = 'null'; + } - if ($con['releasedate'] == "''") { - $con['releasedate'] = ""; - } + $con['publisher'] = (string) $amaz->Items->Item->ItemAttributes->Publisher; + $con['esrb'] = (string) $amaz->Items->Item->ItemAttributes->ESRBAgeRating; + $con['releasedate'] = (string) $amaz->Items->Item->ItemAttributes->ReleaseDate; - $con['review'] = ""; - if (isset($amaz->Items->Item->EditorialReviews)) { - $con['review'] = trim(strip_tags((string)$amaz->Items->Item->EditorialReviews->EditorialReview->Content)); - } - return $con; - } + if (! isset($con['releasedate'])) { + $con['releasedate'] = ''; + } - protected function _matchGenre($amaz) - { + if ($con['releasedate'] == "''") { + $con['releasedate'] = ''; + } - $genreName = ''; + $con['review'] = ''; + if (isset($amaz->Items->Item->EditorialReviews)) { + $con['review'] = trim(strip_tags((string) $amaz->Items->Item->EditorialReviews->EditorialReview->Content)); + } - if (isset($amaz->Items->Item->BrowseNodes)) { - //had issues getting this out of the browsenodes obj - //workaround is to get the xml and load that into its own obj - $amazGenresXml = $amaz->Items->Item->BrowseNodes->asXml(); - $amazGenresObj = simplexml_load_string($amazGenresXml); - $amazGenres = $amazGenresObj->xpath("//Name"); + return $con; + } - foreach ($amazGenres as $amazGenre) { - $currName = trim($amazGenre[0]); - if (empty($genreName)) { - $genreMatch = $this->matchBrowseNode($currName); - if ($genreMatch !== false) { - $genreName = $genreMatch; - break; - } - } - } - } + protected function _matchGenre($amaz) + { + $genreName = ''; - if ($genreName == '' && isset($amaz->Items->Item->ItemAttributes->Genre)) { - $a = (string)$amaz->Items->Item->ItemAttributes->Genre; - $b = str_replace('-', ' ', $a); - $tmpGenre = explode(' ', $b); + if (isset($amaz->Items->Item->BrowseNodes)) { + //had issues getting this out of the browsenodes obj + //workaround is to get the xml and load that into its own obj + $amazGenresXml = $amaz->Items->Item->BrowseNodes->asXml(); + $amazGenresObj = simplexml_load_string($amazGenresXml); + $amazGenres = $amazGenresObj->xpath('//Name'); - foreach ($tmpGenre as $tg) { - $genreMatch = $this->matchBrowseNode(ucwords($tg)); - if ($genreMatch !== false) { - $genreName = $genreMatch; - break; - } - } - } + foreach ($amazGenres as $amazGenre) { + $currName = trim($amazGenre[0]); + if (empty($genreName)) { + $genreMatch = $this->matchBrowseNode($currName); + if ($genreMatch !== false) { + $genreName = $genreMatch; + break; + } + } + } + } - if (empty($genreName)) { - $genreName = 'Unknown'; - } + if ($genreName == '' && isset($amaz->Items->Item->ItemAttributes->Genre)) { + $a = (string) $amaz->Items->Item->ItemAttributes->Genre; + $b = str_replace('-', ' ', $a); + $tmpGenre = explode(' ', $b); - $genreKey = $this->_getGenreKey($genreName); + foreach ($tmpGenre as $tg) { + $genreMatch = $this->matchBrowseNode(ucwords($tg)); + if ($genreMatch !== false) { + $genreName = $genreMatch; + break; + } + } + } - return array('consolegenre' => $genreName, 'consolegenreid' => $genreKey); - } + if (empty($genreName)) { + $genreName = 'Unknown'; + } - protected function _getGenreKey($genreName) - { - $genreassoc = $this->_loadGenres(); + $genreKey = $this->_getGenreKey($genreName); - if (in_array(strtolower($genreName), $genreassoc)) { - $genreKey = array_search(strtolower($genreName), $genreassoc); - } else { - $genreKey = $this->pdo->queryInsert( + return ['consolegenre' => $genreName, 'consolegenreid' => $genreKey]; + } + + protected function _getGenreKey($genreName) + { + $genreassoc = $this->_loadGenres(); + + if (in_array(strtolower($genreName), $genreassoc)) { + $genreKey = array_search(strtolower($genreName), $genreassoc); + } else { + $genreKey = $this->pdo->queryInsert( sprintf(' INSERT INTO genres (title, type) VALUES (%s, %d)', @@ -560,33 +565,35 @@ class Console Genres::CONSOLE_TYPE ) ); - } - return $genreKey; - } + } - protected function _loadGenres() - { - $gen = new Genres(['Settings' => $this->pdo]); + return $genreKey; + } - $defaultGenres = $gen->getGenres(Genres::CONSOLE_TYPE); - $genreassoc =[]; - foreach ($defaultGenres as $dg) { - $genreassoc[$dg['id']] = strtolower($dg['title']); - } - return $genreassoc; - } + protected function _loadGenres() + { + $gen = new Genres(['Settings' => $this->pdo]); - /** This function sets the platform retrieved - * from the release to the Amazon equivalent - * - * @param string $platform - * - * - * @return string - */ - protected function _replacePlatform($platform) - { - switch (strtoupper($platform)) { + $defaultGenres = $gen->getGenres(Genres::CONSOLE_TYPE); + $genreassoc = []; + foreach ($defaultGenres as $dg) { + $genreassoc[$dg['id']] = strtolower($dg['title']); + } + + return $genreassoc; + } + + /** This function sets the platform retrieved + * from the release to the Amazon equivalent. + * + * @param string $platform + * + * + * @return string + */ + protected function _replacePlatform($platform) + { + switch (strtoupper($platform)) { case 'X360': case 'XBOX360': @@ -642,14 +649,15 @@ class Console $platform = 'SNES'; break; } - return $platform; - } - protected function _updateConsoleTable($con =[]) - { - $ri = new ReleaseImage($this->pdo); + return $platform; + } - $check = $this->pdo->queryOneRow( + protected function _updateConsoleTable($con = []) + { + $ri = new ReleaseImage($this->pdo); + + $check = $this->pdo->queryOneRow( sprintf(' SELECT id FROM consoleinfo @@ -658,8 +666,8 @@ class Console ) ); - if ($check === false) { - $consoleId = $this->pdo->queryInsert( + if ($check === false) { + $consoleId = $this->pdo->queryInsert( sprintf( 'INSERT INTO consoleinfo (title, asin, url, salesrank, platform, publisher, genres_id, esrb, releasedate, review, cover, createddate, updateddate) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, NOW(), NOW())', @@ -669,79 +677,74 @@ class Console $con['salesrank'], $this->pdo->escapeString($con['platform']), $this->pdo->escapeString($con['publisher']), - ($con['consolegenreid'] == -1 ? "null" : $con['consolegenreid']), + ($con['consolegenreid'] == -1 ? 'null' : $con['consolegenreid']), $this->pdo->escapeString($con['esrb']), - ($con['releasedate'] != "" ? $this->pdo->escapeString($con['releasedate']) : "null"), + ($con['releasedate'] != '' ? $this->pdo->escapeString($con['releasedate']) : 'null'), $this->pdo->escapeString(substr($con['review'], 0, 3000)), $con['cover'] ) ); - if($con['cover'] === 1){ - $con['cover'] = $ri->saveImage($consoleId, $con['coverurl'], $this->imgSavePath, 250, 250); - } - } else { - $consoleId = $check['id']; + if ($con['cover'] === 1) { + $con['cover'] = $ri->saveImage($consoleId, $con['coverurl'], $this->imgSavePath, 250, 250); + } + } else { + $consoleId = $check['id']; - if($con['cover'] === 1){ - $con['cover'] = $ri->saveImage($consoleId, $con['coverurl'], $this->imgSavePath, 250, 250); - } + if ($con['cover'] === 1) { + $con['cover'] = $ri->saveImage($consoleId, $con['coverurl'], $this->imgSavePath, 250, 250); + } - $this->update( + $this->update( $consoleId, $con['title'], $con['asin'], $con['url'], $con['salesrank'], - $con['platform'], $con['publisher'], (isset($con['releasedate']) ? $con['releasedate']: null), $con['esrb'], + $con['platform'], $con['publisher'], (isset($con['releasedate']) ? $con['releasedate'] : null), $con['esrb'], $con['cover'], $con['consolegenreid'], (isset($con['review']) ? $con['review'] : null) ); - } - return $consoleId; - } + } - public function fetchAmazonProperties($title, $node) - { - $conf = new GenericConfiguration(); - $client = new Client(); - $request = new GuzzleRequest($client); + return $consoleId; + } - try { - $conf + public function fetchAmazonProperties($title, $node) + { + $conf = new GenericConfiguration(); + $client = new Client(); + $request = new GuzzleRequest($client); + + try { + $conf ->setCountry('com') ->setAccessKey($this->pubkey) ->setSecretKey($this->privkey) ->setAssociateTag($this->asstag) ->setRequest($request) ->setResponseTransformer(new XmlToSimpleXmlObject()); - } catch (\Exception $e) { - echo $e->getMessage(); - } + } catch (\Exception $e) { + echo $e->getMessage(); + } - $search = new Search(); - $search->setCategory('VideoGames'); - $search->setKeywords($title); - $search->setBrowseNode($node); - $search->setResponseGroup(['Large']); + $search = new Search(); + $search->setCategory('VideoGames'); + $search->setKeywords($title); + $search->setBrowseNode($node); + $search->setResponseGroup(['Large']); - $apaiIo = new ApaiIO($conf); + $apaiIo = new ApaiIO($conf); - $response = $apaiIo->runOperation($search); - if ($response === false) - { - throw new \Exception('Could not connect to Amazon'); - } - else - { - if (isset($response->Items->Item->ItemAttributes->Title)) - { - return $response; - } - else - { - return false; - } - } - } + $response = $apaiIo->runOperation($search); + if ($response === false) { + throw new \Exception('Could not connect to Amazon'); + } else { + if (isset($response->Items->Item->ItemAttributes->Title)) { + return $response; + } else { + return false; + } + } + } - public function processConsoleReleases() - { - $res = $this->pdo->queryDirect( + public function processConsoleReleases() + { + $res = $this->pdo->queryDirect( sprintf(' SELECT searchname, id FROM releases @@ -757,63 +760,61 @@ class Console ) ); - if ($res instanceof \Traversable && $res->rowCount() > 0) { + if ($res instanceof \Traversable && $res->rowCount() > 0) { + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::header('Processing '.$res->rowCount().' console release(s).')); + } - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::header('Processing ' . $res->rowCount() . ' console release(s).')); - } + foreach ($res as $arr) { + $startTime = microtime(true); + $usedAmazon = false; + $gameId = self::CONS_NTFND; + $gameInfo = $this->parseTitle($arr['searchname']); - foreach ($res as $arr) { - $startTime = microtime(true); - $usedAmazon = false; - $gameId = self::CONS_NTFND; - $gameInfo = $this->parseTitle($arr['searchname']); - - if ($gameInfo !== false) { - if ($this->echooutput) { - ColorCLI::doEcho( - ColorCLI::headerOver('Looking up: ') . + if ($gameInfo !== false) { + if ($this->echooutput) { + ColorCLI::doEcho( + ColorCLI::headerOver('Looking up: '). ColorCLI::primary( - $gameInfo['title'] . - ' (' . - $gameInfo['platform'] . ')' + $gameInfo['title']. + ' ('. + $gameInfo['platform'].')' ) ); - } + } - // Check for existing console entry. - $gameCheck = $this->getConsoleInfoByName($gameInfo['title'], $gameInfo['platform']); + // Check for existing console entry. + $gameCheck = $this->getConsoleInfoByName($gameInfo['title'], $gameInfo['platform']); - if ($gameCheck === false && in_array($gameInfo['title'] . $gameInfo['platform'], $this->failCache)) { - // Lookup recently failed, no point trying again - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::headerOver('Cached previous failure. Skipping.') . PHP_EOL); - } - $gameId = -2; - } else if ($gameCheck === false) { - $gameId = $this->updateConsoleInfo($gameInfo); - $usedAmazon = true; - if ($gameId === false) { - $gameId = -2; - $this->failCache[] = $gameInfo['title'] . $gameInfo['platform']; - } - } else { - if ($this->echooutput) { - ColorCLI::doEcho( - ColorCLI::headerOver("Found Local: ") . - ColorCLI::primary("{$gameCheck['title']} - {$gameCheck['platform']}") . + if ($gameCheck === false && in_array($gameInfo['title'].$gameInfo['platform'], $this->failCache)) { + // Lookup recently failed, no point trying again + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::headerOver('Cached previous failure. Skipping.').PHP_EOL); + } + $gameId = -2; + } elseif ($gameCheck === false) { + $gameId = $this->updateConsoleInfo($gameInfo); + $usedAmazon = true; + if ($gameId === false) { + $gameId = -2; + $this->failCache[] = $gameInfo['title'].$gameInfo['platform']; + } + } else { + if ($this->echooutput) { + ColorCLI::doEcho( + ColorCLI::headerOver('Found Local: '). + ColorCLI::primary("{$gameCheck['title']} - {$gameCheck['platform']}"). PHP_EOL ); - } - $gameId = $gameCheck['id']; - } + } + $gameId = $gameCheck['id']; + } + } elseif ($this->echooutput) { + echo '.'; + } - } elseif ($this->echooutput) { - echo '.'; - } - - // Update release. - $this->pdo->queryExec( + // Update release. + $this->pdo->queryExec( sprintf(' UPDATE releases %s @@ -825,97 +826,95 @@ class Console ) ); - // Sleep to not flood amazon. - $diff = floor((microtime(true) - $startTime) * 1000000); - if ($this->sleeptime * 1000 - $diff > 0 && $usedAmazon === true) { - usleep($this->sleeptime * 1000 - $diff); - } - } + // Sleep to not flood amazon. + $diff = floor((microtime(true) - $startTime) * 1000000); + if ($this->sleeptime * 1000 - $diff > 0 && $usedAmazon === true) { + usleep($this->sleeptime * 1000 - $diff); + } + } + } elseif ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::header('No console releases to process.')); + } + } - } else if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::header('No console releases to process.')); - } - } + /** + * @param $releasename + * + * @return array|bool + */ + public function parseTitle($releasename) + { + $releasename = preg_replace('/\sMulti\d?\s/i', '', $releasename); + $result = []; - /** - * @param $releasename - * - * @return array|bool - */ - public function parseTitle($releasename) - { - $releasename = preg_replace('/\sMulti\d?\s/i', '', $releasename); - $result =[]; + // Get name of the game from name of release. + if (preg_match('/^(.+((abgx360EFNet|EFNet\sFULL|FULL\sabgxEFNet|abgx\sFULL|abgxbox360EFNet)\s|illuminatenboard\sorg|Place2(hom|us)e.net|united-forums? co uk|\(\d+\)))?(?P<title>.*?)[\.\-_ ](v\.?\d\.\d|PAL|NTSC|EUR|USA|JP|ASIA|JAP|JPN|AUS|MULTI(\.?\d{1,2})?|PATCHED|FULLDVD|DVD5|DVD9|DVDRIP|PROPER|REPACK|RETAIL|DEMO|DISTRIBUTION|REGIONFREE|[\. ]RF[\. ]?|READ\.?NFO|NFOFIX|PSX(2PSP)?|PS[2-4]|PSP|PSVITA|WIIU|WII|X\-?BOX|XBLA|X360|3DS|NDS|N64|NGC)/i', $releasename, $matches)) { + $title = $matches['title']; - // Get name of the game from name of release. - if (preg_match('/^(.+((abgx360EFNet|EFNet\sFULL|FULL\sabgxEFNet|abgx\sFULL|abgxbox360EFNet)\s|illuminatenboard\sorg|Place2(hom|us)e.net|united-forums? co uk|\(\d+\)))?(?P<title>.*?)[\.\-_ ](v\.?\d\.\d|PAL|NTSC|EUR|USA|JP|ASIA|JAP|JPN|AUS|MULTI(\.?\d{1,2})?|PATCHED|FULLDVD|DVD5|DVD9|DVDRIP|PROPER|REPACK|RETAIL|DEMO|DISTRIBUTION|REGIONFREE|[\. ]RF[\. ]?|READ\.?NFO|NFOFIX|PSX(2PSP)?|PS[2-4]|PSP|PSVITA|WIIU|WII|X\-?BOX|XBLA|X360|3DS|NDS|N64|NGC)/i', $releasename, $matches)) { - $title = $matches['title']; + // Replace dots, underscores, or brackets with spaces. + $result['title'] = str_replace(['.', '_', '%20', '[', ']'], ' ', $title); + $result['title'] = str_replace([' RF ', '.RF.', '-RF-', '_RF_'], ' ', $result['title']); + //Remove format tags from release title for match + $result['title'] = trim(preg_replace('/PAL|MULTI(\d)?|NTSC-?J?|\(JAPAN\)/i', '', $result['title'])); + //Remove disc tags from release title for match + $result['title'] = trim(preg_replace('/Dis[ck] \d.*$/i', '', $result['title'])); - // Replace dots, underscores, or brackets with spaces. - $result['title'] = str_replace(['.','_','%20', '[', ']'], ' ', $title); - $result['title'] = str_replace([' RF ', '.RF.', '-RF-', '_RF_'], ' ', $result['title']); - //Remove format tags from release title for match - $result['title'] = trim(preg_replace('/PAL|MULTI(\d)?|NTSC-?J?|\(JAPAN\)/i', '', $result['title'])); - //Remove disc tags from release title for match - $result['title'] = trim(preg_replace('/Dis[ck] \d.*$/i', '', $result['title'])); + // Needed to add code to handle DLC Properly. + if (stripos('dlc', $result['title']) !== false) { + $result['dlc'] = '1'; + if (stripos('Rock Band Network', $result['title']) !== false) { + $result['title'] = 'Rock Band'; + } elseif (strpos('-', $result['title']) !== false) { + $dlc = explode('-', $result['title']); + $result['title'] = $dlc[0]; + } elseif (preg_match('/(.*? .*?) /i', $result['title'], $dlc)) { + $result['title'] = $dlc[0]; + } + } + } else { + $title = ''; + } - // Needed to add code to handle DLC Properly. - if (stripos('dlc', $result['title']) !== false) { - $result['dlc'] = '1'; - if (stripos('Rock Band Network', $result['title']) !== false) { - $result['title'] = 'Rock Band'; - } else if (strpos('-', $result['title']) !== false) { - $dlc = explode("-", $result['title']); - $result['title'] = $dlc[0]; - } else if (preg_match('/(.*? .*?) /i', $result['title'], $dlc)) { - $result['title'] = $dlc[0]; - } - } + // Get the platform of the release. + if (preg_match('/[\.\-_ ](?P<platform>XBLA|WiiWARE|N64|SNES|NES|PS[2-4]|PS 3|PSX(2PSP)?|PSP|WIIU|WII|XBOX360|XBOXONE|X\-?BOX|X360|3DS|NDS|N?GC)/i', $releasename, $matches)) { + $platform = $matches['platform']; - } else { - $title = ''; - } + if (preg_match('/^N?GC$/i', $platform)) { + $platform = 'NGC'; + } - // Get the platform of the release. - if (preg_match('/[\.\-_ ](?P<platform>XBLA|WiiWARE|N64|SNES|NES|PS[2-4]|PS 3|PSX(2PSP)?|PSP|WIIU|WII|XBOX360|XBOXONE|X\-?BOX|X360|3DS|NDS|N?GC)/i', $releasename, $matches)) { - $platform = $matches['platform']; + if (stripos('PSX2PSP', $platform) === 0) { + $platform = 'PSX'; + } - if (preg_match('/^N?GC$/i', $platform)) { - $platform = 'NGC'; - } + if (! empty($title) && stripos('XBLA', $platform) === 0) { + if (stripos('dlc', $title) !== false) { + $platform = 'XBOX360'; + } + } - if (stripos('PSX2PSP', $platform) === 0) { - $platform = 'PSX'; - } + $browseNode = $this->getBrowseNode($platform); + $result['platform'] = $platform; + $result['node'] = $browseNode; + } + $result['release'] = $releasename; + array_map('trim', $result); - if (!empty($title) && stripos('XBLA', $platform) === 0) { - if (stripos('dlc', $title) !== false) { - $platform = 'XBOX360'; - } - } + /* Make sure we got a title and platform otherwise the resulting lookup will probably be shit. + Other option is to pass the $release->categories_id here if we don't find a platform but that + would require an extra lookup to determine the name. In either case we should have a title at the minimum. */ - $browseNode = $this->getBrowseNode($platform); - $result['platform'] = $platform; - $result['node'] = $browseNode; - } - $result['release'] = $releasename; - array_map('trim', $result); + return (isset($result['title']) && ! empty($result['title']) && isset($result['platform'])) ? $result : false; + } - /* Make sure we got a title and platform otherwise the resulting lookup will probably be shit. - Other option is to pass the $release->categories_id here if we don't find a platform but that - would require an extra lookup to determine the name. In either case we should have a title at the minimum. */ - - return (isset($result['title']) && !empty($result['title']) && isset($result['platform'])) ? $result : false; - } - - /** - * @param $platform - * - * @return string - */ - public function getBrowseNode($platform) - { - switch ($platform) { + /** + * @param $platform + * + * @return string + */ + public function getBrowseNode($platform) + { + switch ($platform) { case 'PS2': $nodeId = '301712'; break; @@ -977,20 +976,20 @@ class Console break; } - return $nodeId; - } + return $nodeId; + } - /** - * @param $nodeName - * - * @return bool|string - */ - public function matchBrowseNode($nodeName) - { - $str = ''; + /** + * @param $nodeName + * + * @return bool|string + */ + public function matchBrowseNode($nodeName) + { + $str = ''; - //music nodes above mp3 download nodes - switch ($nodeName) { + //music nodes above mp3 download nodes + switch ($nodeName) { case 'Action_shooter': case 'Action_Games': case 'Action_games': @@ -1056,8 +1055,6 @@ class Console break; } - return ($str != '') ? $str : false; - } - - + return ($str != '') ? $str : false; + } } diff --git a/nntmux/ConsoleTools.php b/nntmux/ConsoleTools.php index b91ee0a23..e8aa2e15d 100755 --- a/nntmux/ConsoleTools.php +++ b/nntmux/ConsoleTools.php @@ -1,172 +1,174 @@ <?php + namespace nntmux; /** - * Class ConsoleTools + * Class ConsoleTools. */ class ConsoleTools { + /** + * @var ColorCLI + */ + public $cli; - /** - * @var ColorCLI - */ - public $cli; + /** + * @var int + */ + public $lastMessageLength; - /** - * @var int - */ - public $lastMessageLength; - - /** - * Construct. - * - * @param array $options - */ - public function __construct(array $options = []) - { - $defaults = [ - 'ColorCLI' => null + /** + * Construct. + * + * @param array $options + */ + public function __construct(array $options = []) + { + $defaults = [ + 'ColorCLI' => null, ]; - $options += $defaults; + $options += $defaults; - $this->cli = ($options['ColorCLI'] instanceof ColorCLI ? $options['ColorCLI'] : new ColorCLI()); + $this->cli = ($options['ColorCLI'] instanceof ColorCLI ? $options['ColorCLI'] : new ColorCLI()); - $this->lastMessageLength = 0; - } + $this->lastMessageLength = 0; + } - /** - * @param string $message - * @param bool $reset - */ - public function overWriteHeader($message, $reset = false): void - { - if ($reset) { - $this->lastMessageLength = 0; - } + /** + * @param string $message + * @param bool $reset + */ + public function overWriteHeader($message, $reset = false): void + { + if ($reset) { + $this->lastMessageLength = 0; + } - echo str_repeat(chr(8), $this->lastMessageLength); - echo str_repeat(' ', $this->lastMessageLength); - echo str_repeat(chr(8), $this->lastMessageLength); + echo str_repeat(chr(8), $this->lastMessageLength); + echo str_repeat(' ', $this->lastMessageLength); + echo str_repeat(chr(8), $this->lastMessageLength); - $this->lastMessageLength = strlen($message); - echo ColorCLI::headerOver($message); - } + $this->lastMessageLength = strlen($message); + echo ColorCLI::headerOver($message); + } - /** - * @param string $message - * @param bool $reset - */ - public function overWritePrimary($message, $reset = false): void - { - if ($reset) { - $this->lastMessageLength = 0; - } + /** + * @param string $message + * @param bool $reset + */ + public function overWritePrimary($message, $reset = false): void + { + if ($reset) { + $this->lastMessageLength = 0; + } - echo str_repeat(chr(8), $this->lastMessageLength); - echo str_repeat(' ', $this->lastMessageLength); - echo str_repeat(chr(8), $this->lastMessageLength); + echo str_repeat(chr(8), $this->lastMessageLength); + echo str_repeat(' ', $this->lastMessageLength); + echo str_repeat(chr(8), $this->lastMessageLength); - $this->lastMessageLength = strlen($message); - echo ColorCLI::primaryOver($message); - } + $this->lastMessageLength = strlen($message); + echo ColorCLI::primaryOver($message); + } - /** - * @param string $message - * @param bool $reset - */ - public function overWrite($message, $reset = false): void - { - if ($reset) { - $this->lastMessageLength = 0; - } + /** + * @param string $message + * @param bool $reset + */ + public function overWrite($message, $reset = false): void + { + if ($reset) { + $this->lastMessageLength = 0; + } - echo str_repeat(chr(8), $this->lastMessageLength); - echo str_repeat(' ', $this->lastMessageLength); - echo str_repeat(chr(8), $this->lastMessageLength); + echo str_repeat(chr(8), $this->lastMessageLength); + echo str_repeat(' ', $this->lastMessageLength); + echo str_repeat(chr(8), $this->lastMessageLength); - $this->lastMessageLength = strlen($message); - echo $message; - } + $this->lastMessageLength = strlen($message); + echo $message; + } - /** - * @param string $message - */ - public function appendWrite($message): void - { - echo $message; - $this->lastMessageLength += strlen($message); - } + /** + * @param string $message + */ + public function appendWrite($message): void + { + echo $message; + $this->lastMessageLength += strlen($message); + } - /** - * @param int $cur - * @param int $total - * - * @return string - */ - public function percentString($cur, $total): string - { - $percent = 100 * $cur / $total; - $formatString = '% ' . strlen($total) . 'd/%d (% 2d%%)'; - return sprintf($formatString, $cur, $total, $percent); - } + /** + * @param int $cur + * @param int $total + * + * @return string + */ + public function percentString($cur, $total): string + { + $percent = 100 * $cur / $total; + $formatString = '% '.strlen($total).'d/%d (% 2d%%)'; - /** - * @param int $first - * @param int $last - * @param int $total - * - * @return string - */ - public function percentString2($first, $last, $total): string - { - $percent1 = 100 * ($first - 1) / $total; - $percent2 = 100 * $last / $total; - $formatString = '% ' . strlen($total) . 'd-% ' . strlen($total) . 'd/%d (% 2d%%-% 3d%%)'; - return sprintf($formatString, $first, $last, $total, $percent1, $percent2); - } + return sprintf($formatString, $cur, $total, $percent); + } - /** - * Convert seconds to minutes or hours, appending type at the end. - * - * @param int $seconds - * - * @return string - */ - public function convertTime($seconds): string - { + /** + * @param int $first + * @param int $last + * @param int $total + * + * @return string + */ + public function percentString2($first, $last, $total): string + { + $percent1 = 100 * ($first - 1) / $total; + $percent2 = 100 * $last / $total; + $formatString = '% '.strlen($total).'d-% '.strlen($total).'d/%d (% 2d%%-% 3d%%)'; - if ($seconds > 3600) { - return round($seconds / 3600) . ' hour(s)'; - } - if ($seconds > 60) { - return round($seconds / 60) . ' minute(s)'; - } - return $seconds . ' second(s)'; - } + return sprintf($formatString, $first, $last, $total, $percent1, $percent2); + } - /** - * Convert seconds to a timer, 00h:00m:00s - * - * @param int $seconds - * - * @return string - */ - public function convertTimer($seconds): string - { - return ' ' . sprintf('%02dh:%02dm:%02ds', floor($seconds / 3600), floor(($seconds / 60) % 60), $seconds % 60); - } + /** + * Convert seconds to minutes or hours, appending type at the end. + * + * @param int $seconds + * + * @return string + */ + public function convertTime($seconds): string + { + if ($seconds > 3600) { + return round($seconds / 3600).' hour(s)'; + } + if ($seconds > 60) { + return round($seconds / 60).' minute(s)'; + } - /** - * Sleep for x seconds, printing timer on screen. - * - * @param int $seconds - */ - public function showSleep($seconds): void - { - for ($i = $seconds; $i >= 0; $i--) { - $this->overWriteHeader('Sleeping for ' . $i . ' seconds.'); - sleep(1); - } - echo PHP_EOL; - } + return $seconds.' second(s)'; + } + + /** + * Convert seconds to a timer, 00h:00m:00s. + * + * @param int $seconds + * + * @return string + */ + public function convertTimer($seconds): string + { + return ' '.sprintf('%02dh:%02dm:%02ds', floor($seconds / 3600), floor(($seconds / 60) % 60), $seconds % 60); + } + + /** + * Sleep for x seconds, printing timer on screen. + * + * @param int $seconds + */ + public function showSleep($seconds): void + { + for ($i = $seconds; $i >= 0; $i--) { + $this->overWriteHeader('Sleeping for '.$i.' seconds.'); + sleep(1); + } + echo PHP_EOL; + } } diff --git a/nntmux/Content.php b/nntmux/Content.php index 8e48c15c3..cf29336af 100755 --- a/nntmux/Content.php +++ b/nntmux/Content.php @@ -1,19 +1,19 @@ <?php + namespace nntmux; class Content { - public $id = ''; - public $title = ''; - public $url = ''; - public $body = ''; - public $metadescription = ''; - public $metakeywords = ''; - public $contenttype = ''; - public $showinmenu = ''; - public $status = ''; - public $ordinal = ''; - public $createddate = ''; - public $role = ''; - + public $id = ''; + public $title = ''; + public $url = ''; + public $body = ''; + public $metadescription = ''; + public $metakeywords = ''; + public $contenttype = ''; + public $showinmenu = ''; + public $status = ''; + public $ordinal = ''; + public $createddate = ''; + public $role = ''; } diff --git a/nntmux/Contents.php b/nntmux/Contents.php index 6d49e140d..09917e0ee 100755 --- a/nntmux/Contents.php +++ b/nntmux/Contents.php @@ -1,334 +1,337 @@ <?php + namespace nntmux; use nntmux\db\DB; class Contents { - const TYPEUSEFUL = 1; - const TYPEARTICLE = 2; - const TYPEINDEX = 3; + const TYPEUSEFUL = 1; + const TYPEARTICLE = 2; + const TYPEINDEX = 3; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + } - /** - * @return array|bool - */ - public function get() - { - $arr = []; - $rows = $this->data_get(); - if ($rows === false) { - return false; - } + /** + * @return array|bool + */ + public function get() + { + $arr = []; + $rows = $this->data_get(); + if ($rows === false) { + return false; + } - foreach ($rows as $row) { - $arr[] = $this->row2Object($row); - } + foreach ($rows as $row) { + $arr[] = $this->row2Object($row); + } - return $arr; - } + return $arr; + } - /** - * @return array|bool - */ - public function getAll() - { - $arr = []; - $rows = $this->data_getAll(); - if ($rows === false) { - return false; - } + /** + * @return array|bool + */ + public function getAll() + { + $arr = []; + $rows = $this->data_getAll(); + if ($rows === false) { + return false; + } - foreach ($rows as $row) { - $arr[] = $this->row2Object($row); - } + foreach ($rows as $row) { + $arr[] = $this->row2Object($row); + } - return $arr; - } + return $arr; + } - /** - * Convert get all but from to object. - * - * @return array|bool - */ - public function getAllButFront() - { - $arr = []; - $rows = $this->data_getAllButFront(); - if ($rows === false) { - return false; - } + /** + * Convert get all but from to object. + * + * @return array|bool + */ + public function getAllButFront() + { + $arr = []; + $rows = $this->data_getAllButFront(); + if ($rows === false) { + return false; + } - foreach ($rows as $row) { - $arr[] = $this->row2Object($row); - } + foreach ($rows as $row) { + $arr[] = $this->row2Object($row); + } - return $arr; - } + return $arr; + } - /** - * @return array|bool - */ - public function getFrontPage() - { - $arr = []; - $rows = $this->data_getFrontPage(); - if ($rows === false) { - return false; - } + /** + * @return array|bool + */ + public function getFrontPage() + { + $arr = []; + $rows = $this->data_getFrontPage(); + if ($rows === false) { + return false; + } - foreach ($rows as $row) { - $arr[] = $this->row2Object($row); - } + foreach ($rows as $row) { + $arr[] = $this->row2Object($row); + } - return $arr; - } + return $arr; + } - /** - * @param $id - * @param $role - * - * @return array|bool - */ - public function getForMenuByTypeAndRole($id, $role) - { + /** + * @param $id + * @param $role + * + * @return array|bool + */ + public function getForMenuByTypeAndRole($id, $role) + { + $arr = []; + $rows = $this->data_getForMenuByTypeAndRole($id, $role); + if ($rows === false) { + return false; + } - $arr = []; - $rows = $this->data_getForMenuByTypeAndRole($id, $role); - if ($rows === false) { - return false; - } + foreach ($rows as $row) { + $arr[] = $this->row2Object($row); + } - foreach ($rows as $row) { - $arr[] = $this->row2Object($row); - } + return $arr; + } - return $arr; - } + /** + * @return bool|Content + */ + public function getIndex() + { + $row = $this->data_getIndex(); + if ($row === false) { + return false; + } - /** - * @return bool|Content - */ - public function getIndex() - { - $row = $this->data_getIndex(); - if ($row === false) { - return false; - } + return $this->row2Object($row); + } - return $this->row2Object($row); - } + /** + * @param $id + * @param $role + * + * @return bool|Content + */ + public function getByID($id, $role) + { + $row = $this->data_getByID($id, $role); + if ($row === false) { + return false; + } - /** - * @param $id - * @param $role - * - * @return bool|Content - */ - public function getByID($id, $role) - { - $row = $this->data_getByID($id, $role); - if ($row === false) { - return false; - } + return $this->row2Object($row); + } - return $this->row2Object($row); - } + /** + * @param $content + * + * @return mixed + */ + public function validate($content) + { + if ($content->url[0] !== '/') { + $content->url = '/'.$content->url; + } - /** - * @param $content - * - * @return mixed - */ - public function validate($content) - { - if ($content->url[0] !== '/') { - $content->url = '/' . $content->url; - } + if (substr($content->url, strlen($content->url) - 1) !== '/') { + $content->url .= '/'; + } - if (substr($content->url, strlen($content->url) - 1) !== '/') { - $content->url .= '/'; - } + return $content; + } - return $content; - } + /** + * @param $form + * + * @return false|int|string + */ + public function add($form) + { + $content = $this->row2Object($form); + $content = $this->validate($content); + if ($content->ordinal === 1) { + $this->pdo->queryDirect('UPDATE content SET ordinal = ordinal + 1 WHERE ordinal > 0'); + } - /** - * @param $form - * - * @return false|int|string - */ - public function add($form) - { - $content = $this->row2Object($form); - $content = $this->validate($content); - if ($content->ordinal === 1) { - $this->pdo->queryDirect('UPDATE content SET ordinal = ordinal + 1 WHERE ordinal > 0'); - } - return $this->data_add($content); - } + return $this->data_add($content); + } - /** - * @param $id - * - * @return bool|\PDOStatement - */ - public function delete($id) - { - return $this->pdo->queryExec(sprintf('DELETE FROM content WHERE id = %d', $id)); - } + /** + * @param $id + * + * @return bool|\PDOStatement + */ + public function delete($id) + { + return $this->pdo->queryExec(sprintf('DELETE FROM content WHERE id = %d', $id)); + } - /** - * @param $form - * - * @return mixed|Content - */ - public function update($form) - { - $content = $this->row2Object($form); - $content = $this->validate($content); - $this->data_update($content); + /** + * @param $form + * + * @return mixed|Content + */ + public function update($form) + { + $content = $this->row2Object($form); + $content = $this->validate($content); + $this->data_update($content); - return $content; - } + return $content; + } - /** - * @param $row - * @param string $prefix - * - * @return Content - */ - public function row2Object($row, $prefix = '') - { - $obj = new Content(); - if (isset($row[$prefix . 'id'])) { - $obj->id = $row[$prefix . 'id']; - } - $obj->title = $row[$prefix . 'title']; - $obj->url = $row[$prefix . 'url']; - $obj->body = $row[$prefix . 'body']; - $obj->metadescription = $row[$prefix . 'metadescription']; - $obj->metakeywords = $row[$prefix . 'metakeywords']; - $obj->contenttype = $row[$prefix . 'contenttype']; - $obj->showinmenu = $row[$prefix . 'showinmenu']; - $obj->status = $row[$prefix . 'status']; - $obj->ordinal = $row[$prefix . 'ordinal']; - if (isset($row[$prefix . 'createddate'])) { - $obj->createddate = $row[$prefix . 'createddate']; - } - $obj->role = $row[$prefix . 'role']; - return $obj; - } + /** + * @param $row + * @param string $prefix + * + * @return Content + */ + public function row2Object($row, $prefix = '') + { + $obj = new Content(); + if (isset($row[$prefix.'id'])) { + $obj->id = $row[$prefix.'id']; + } + $obj->title = $row[$prefix.'title']; + $obj->url = $row[$prefix.'url']; + $obj->body = $row[$prefix.'body']; + $obj->metadescription = $row[$prefix.'metadescription']; + $obj->metakeywords = $row[$prefix.'metakeywords']; + $obj->contenttype = $row[$prefix.'contenttype']; + $obj->showinmenu = $row[$prefix.'showinmenu']; + $obj->status = $row[$prefix.'status']; + $obj->ordinal = $row[$prefix.'ordinal']; + if (isset($row[$prefix.'createddate'])) { + $obj->createddate = $row[$prefix.'createddate']; + } + $obj->role = $row[$prefix.'role']; - /** - * @param $content - * - * @return bool|\PDOStatement - */ - public function data_update($content) - { - return $this->pdo->queryExec(sprintf('UPDATE content SET role = %d, title = %s, url = %s, body = %s, metadescription = %s, metakeywords = %s, contenttype = %d, showinmenu = %d, status = %d, ordinal = %d WHERE id = %d', $content->role, $this->pdo->escapeString($content->title), $this->pdo->escapeString($content->url), $this->pdo->escapeString($content->body), $this->pdo->escapeString($content->metadescription), $this->pdo->escapeString($content->metakeywords), $content->contenttype, $content->showinmenu, $content->status, $content->ordinal, $content->id)); - } + return $obj; + } - /** - * @param $content - * - * @return false|int|string - */ - public function data_add($content) - { - return $this->pdo->queryInsert(sprintf('INSERT INTO content (role, title, url, body, metadescription, metakeywords, contenttype, showinmenu, status, ordinal) values (%d, %s, %s, %s, %s, %s, %d, %d, %d, %d )', $content->role, $this->pdo->escapeString($content->title), $this->pdo->escapeString($content->url), $this->pdo->escapeString($content->body), $this->pdo->escapeString($content->metadescription), $this->pdo->escapeString($content->metakeywords), $content->contenttype, $content->showinmenu, $content->status, $content->ordinal)); - } + /** + * @param $content + * + * @return bool|\PDOStatement + */ + public function data_update($content) + { + return $this->pdo->queryExec(sprintf('UPDATE content SET role = %d, title = %s, url = %s, body = %s, metadescription = %s, metakeywords = %s, contenttype = %d, showinmenu = %d, status = %d, ordinal = %d WHERE id = %d', $content->role, $this->pdo->escapeString($content->title), $this->pdo->escapeString($content->url), $this->pdo->escapeString($content->body), $this->pdo->escapeString($content->metadescription), $this->pdo->escapeString($content->metakeywords), $content->contenttype, $content->showinmenu, $content->status, $content->ordinal, $content->id)); + } - /** - * @return array - */ - public function data_get(): array - { - return $this->pdo->query(sprintf('SELECT * FROM content WHERE status = 1 ORDER BY contenttype, COALESCE(ordinal, 1000000)')); - } + /** + * @param $content + * + * @return false|int|string + */ + public function data_add($content) + { + return $this->pdo->queryInsert(sprintf('INSERT INTO content (role, title, url, body, metadescription, metakeywords, contenttype, showinmenu, status, ordinal) values (%d, %s, %s, %s, %s, %s, %d, %d, %d, %d )', $content->role, $this->pdo->escapeString($content->title), $this->pdo->escapeString($content->url), $this->pdo->escapeString($content->body), $this->pdo->escapeString($content->metadescription), $this->pdo->escapeString($content->metakeywords), $content->contenttype, $content->showinmenu, $content->status, $content->ordinal)); + } - /** - * @return array - */ - public function data_getAll(): array - { - return $this->pdo->query(sprintf('SELECT * FROM content ORDER BY contenttype, COALESCE(ordinal, 1000000)')); - } + /** + * @return array + */ + public function data_get(): array + { + return $this->pdo->query(sprintf('SELECT * FROM content WHERE status = 1 ORDER BY contenttype, COALESCE(ordinal, 1000000)')); + } - /** - * Get all but front page. - * - * @return array - */ - public function data_getAllButFront(): array - { - return $this->pdo->query(sprintf('SELECT * FROM content WHERE id != 1 ORDER BY contenttype, COALESCE(ordinal, 1000000)')); - } + /** + * @return array + */ + public function data_getAll(): array + { + return $this->pdo->query(sprintf('SELECT * FROM content ORDER BY contenttype, COALESCE(ordinal, 1000000)')); + } - /** - * @param $id - * @param $role - * - * @return array|bool - */ - public function data_getByID($id, $role) - { - if ($role === Users::ROLE_ADMIN) { - $role = ''; - } else { - $role = sprintf('AND (role = %d OR role = 0)', $role); - } + /** + * Get all but front page. + * + * @return array + */ + public function data_getAllButFront(): array + { + return $this->pdo->query(sprintf('SELECT * FROM content WHERE id != 1 ORDER BY contenttype, COALESCE(ordinal, 1000000)')); + } - return $this->pdo->queryOneRow(sprintf('SELECT * FROM content WHERE id = %d %s', $id, $role)); - } + /** + * @param $id + * @param $role + * + * @return array|bool + */ + public function data_getByID($id, $role) + { + if ($role === Users::ROLE_ADMIN) { + $role = ''; + } else { + $role = sprintf('AND (role = %d OR role = 0)', $role); + } - /** - * @return array - */ - public function data_getFrontPage(): array - { - return $this->pdo->query(sprintf('SELECT * FROM content WHERE status = 1 AND contenttype = %d ORDER BY ordinal ASC, COALESCE(ordinal, 1000000), id', Contents::TYPEINDEX)); - } + return $this->pdo->queryOneRow(sprintf('SELECT * FROM content WHERE id = %d %s', $id, $role)); + } - /** - * @return array|bool - */ - public function data_getIndex() - { - return $this->pdo->queryOneRow(sprintf('SELECT * FROM content WHERE status = 1 AND contenttype = %d', Contents::TYPEINDEX)); - } + /** + * @return array + */ + public function data_getFrontPage(): array + { + return $this->pdo->query(sprintf('SELECT * FROM content WHERE status = 1 AND contenttype = %d ORDER BY ordinal ASC, COALESCE(ordinal, 1000000), id', self::TYPEINDEX)); + } - /** - * @param $id - * @param $role - * - * @return array - */ - public function data_getForMenuByTypeAndRole($id, $role): array - { - if ($role === Users::ROLE_ADMIN) { - $role = ''; - } else { - $role = sprintf('AND (role = %d OR role = 0)', $role); - } - return $this->pdo->query(sprintf('SELECT * FROM content WHERE showinmenu = 1 AND status = 1 AND contenttype = %d %s ', $id, $role)); - } + /** + * @return array|bool + */ + public function data_getIndex() + { + return $this->pdo->queryOneRow(sprintf('SELECT * FROM content WHERE status = 1 AND contenttype = %d', self::TYPEINDEX)); + } + + /** + * @param $id + * @param $role + * + * @return array + */ + public function data_getForMenuByTypeAndRole($id, $role): array + { + if ($role === Users::ROLE_ADMIN) { + $role = ''; + } else { + $role = sprintf('AND (role = %d OR role = 0)', $role); + } + + return $this->pdo->query(sprintf('SELECT * FROM content WHERE showinmenu = 1 AND status = 1 AND contenttype = %d %s ', $id, $role)); + } } diff --git a/nntmux/CouchPotato.php b/nntmux/CouchPotato.php index 91ece0719..10267bfe6 100755 --- a/nntmux/CouchPotato.php +++ b/nntmux/CouchPotato.php @@ -22,61 +22,60 @@ namespace nntmux; use GuzzleHttp\Client; -use nntmux\utility\Utility; /** - * Class CouchPotato + * Class CouchPotato. */ class CouchPotato { - /** - * URL to the CP server. - * @var string|array|bool - */ - public $cpurl = ''; + /** + * URL to the CP server. + * @var string|array|bool + */ + public $cpurl = ''; - /** - * The CP key. - * @var string|array|bool - */ - public $cpapi = ''; + /** + * The CP key. + * @var string|array|bool + */ + public $cpapi = ''; - /** - * Imdb ID - * @var string - */ - public $imdbid = ''; + /** + * Imdb ID. + * @var string + */ + public $imdbid = ''; - /** - * Construct. - * - * @param \BasePage $page - */ - public function __construct(&$page) - { - $this->cpurl = !empty($page->userdata['cp_url']) ? $page->userdata['cp_url'] : ''; - $this->cpapi = !empty($page->userdata['cp_api']) ? $page->userdata['cp_api'] : ''; - } + /** + * Construct. + * + * @param \BasePage $page + */ + public function __construct(&$page) + { + $this->cpurl = ! empty($page->userdata['cp_url']) ? $page->userdata['cp_url'] : ''; + $this->cpapi = ! empty($page->userdata['cp_api']) ? $page->userdata['cp_api'] : ''; + } - /** - * Send a movie to CouchPotato. - * - * @param string $id - * - * @return bool|mixed - * @throws \RuntimeException - */ - public function sendToCouchPotato($id) - { - $this->imdbid = $id; + /** + * Send a movie to CouchPotato. + * + * @param string $id + * + * @return bool|mixed + * @throws \RuntimeException + */ + public function sendToCouchPotato($id) + { + $this->imdbid = $id; - return (new Client(['verify' => false]))->get( - $this->cpurl . - '/api/' . - $this->cpapi . - '/movie.add/?identifier=tt' . + return (new Client(['verify' => false]))->get( + $this->cpurl. + '/api/'. + $this->cpapi. + '/movie.add/?identifier=tt'. $this->imdbid )->getBody()->getContents(); - } + } } diff --git a/nntmux/DnzbFailures.php b/nntmux/DnzbFailures.php index 670f05cb7..be2220610 100755 --- a/nntmux/DnzbFailures.php +++ b/nntmux/DnzbFailures.php @@ -1,104 +1,104 @@ <?php + namespace nntmux; - -use App\Models\DnzbFailure; use nntmux\db\DB; - +use App\Models\DnzbFailure; /** - * Class DnzbFailures + * Class DnzbFailures. */ class DnzbFailures { - const FAILED = 1; - /** - * @var DB - */ - public $pdo; + const FAILED = 1; + /** + * @var DB + */ + public $pdo; - /** - * @var ReleaseComments - */ - public $rc; + /** + * @var ReleaseComments + */ + public $rc; - /** - * @var array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ - 'Settings' => null + /** + * @var array Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ + 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->rc = new ReleaseComments(['Settings' => $this->pdo]); - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->rc = new ReleaseComments(['Settings' => $this->pdo]); + } - /** - * Read failed downloads count for requested release_id - * - * - * @param $relId - * - * @return bool|mixed - */ - public function getFailedCount($relId) - { - $result = DnzbFailure::query()->where('release_id', $relId)->value('failed'); - if (!empty($result)) { - return $result; - } - return false; - } + /** + * Read failed downloads count for requested release_id. + * + * + * @param $relId + * + * @return bool|mixed + */ + public function getFailedCount($relId) + { + $result = DnzbFailure::query()->where('release_id', $relId)->value('failed'); + if (! empty($result)) { + return $result; + } - /** - * @return int - */ - public function getCount(): int - { - return DnzbFailure::query()->count('release_id'); - } + return false; + } - /** - * Get a range of releases. used in admin manage list - * - * @param $start - * @param $num - * - * @return array - */ - public function getFailedRange($start, $num): array - { - if ($start === false) { - $limit = ''; - } else { - $limit = ' LIMIT ' . $start . ',' . $num; - } + /** + * @return int + */ + public function getCount(): int + { + return DnzbFailure::query()->count('release_id'); + } - return $this->pdo->query(" + /** + * Get a range of releases. used in admin manage list. + * + * @param $start + * @param $num + * + * @return array + */ + public function getFailedRange($start, $num): array + { + if ($start === false) { + $limit = ''; + } else { + $limit = ' LIMIT '.$start.','.$num; + } + + return $this->pdo->query(" SELECT r.*, CONCAT(cp.title, ' > ', c.title) AS category_name FROM releases r RIGHT JOIN dnzb_failures df ON df.release_id = r.id LEFT OUTER JOIN categories c ON c.id = r.categories_id LEFT OUTER JOIN categories cp ON cp.id = c.parentid - ORDER BY postdate DESC" . $limit + ORDER BY postdate DESC".$limit ); - } + } - /** - * Retrieve alternate release with same or similar searchname - * - * @param string $guid - * @param string $userid - * - * @return string|array - * @throws \Exception - */ - public function getAlternate($guid, $userid) - { - $rel = $this->pdo->queryOneRow( + /** + * Retrieve alternate release with same or similar searchname. + * + * @param string $guid + * @param string $userid + * + * @return string|array + * @throws \Exception + */ + public function getAlternate($guid, $userid) + { + $rel = $this->pdo->queryOneRow( sprintf(' SELECT id, searchname, categories_id FROM releases @@ -107,14 +107,13 @@ class DnzbFailures ) ); - if ($rel === false) { - return false; - } + if ($rel === false) { + return false; + } - DnzbFailure::query()->updateOrCreate(['release_id' => $rel['id'], 'users_id' => $userid], ['release_id' => $rel['id'], 'users_id' => $userid, 'failed' => 'failed + 1']); + DnzbFailure::query()->updateOrCreate(['release_id' => $rel['id'], 'users_id' => $userid], ['release_id' => $rel['id'], 'users_id' => $userid, 'failed' => 'failed + 1']); - - $alternate = $this->pdo->queryOneRow( + $alternate = $this->pdo->queryOneRow( sprintf(' SELECT r.guid FROM releases r @@ -130,6 +129,6 @@ class DnzbFailures ) ); - return $alternate; - } + return $alternate; + } } diff --git a/nntmux/Forum.php b/nntmux/Forum.php index 6bebb4993..d1b6c0652 100755 --- a/nntmux/Forum.php +++ b/nntmux/Forum.php @@ -1,92 +1,93 @@ <?php + namespace nntmux; use nntmux\db\DB; class Forum { - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ - 'Settings' => null + /** + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ + 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + } - /** - * Add post to forum - * - * @param $parentid - * @param $userid - * @param $subject - * @param $message - * @param int $locked - * @param int $sticky - * @param int $replies - * - * @return bool|int - */ - public function add($parentid, $userid, $subject, $message, $locked = 0, $sticky = 0, $replies = 0) - { - if ($message === '') { - return -1; - } + /** + * Add post to forum. + * + * @param $parentid + * @param $userid + * @param $subject + * @param $message + * @param int $locked + * @param int $sticky + * @param int $replies + * + * @return bool|int + */ + public function add($parentid, $userid, $subject, $message, $locked = 0, $sticky = 0, $replies = 0) + { + if ($message === '') { + return -1; + } - if ($parentid !== 0) { - $par = $this->getParent($parentid); - if ($par === false) { - return -1; - } + if ($parentid !== 0) { + $par = $this->getParent($parentid); + if ($par === false) { + return -1; + } - $this->pdo->queryExec(sprintf('UPDATE forumpost SET replies = replies + 1, updateddate = NOW() WHERE id = %d', $parentid)); - } + $this->pdo->queryExec(sprintf('UPDATE forumpost SET replies = replies + 1, updateddate = NOW() WHERE id = %d', $parentid)); + } - return $this->pdo->queryInsert( + return $this->pdo->queryInsert( sprintf(' INSERT INTO forumpost (forumid, parentid, users_id, subject, message, locked, sticky, replies, createddate, updateddate) VALUES (1, %d, %d, %s, %s, %d, %d, %d, NOW(), NOW())', $parentid, $userid, $this->pdo->escapeString($subject), $this->pdo->escapeString($message), $locked, $sticky, $replies ) ); - } + } - /** - * Get parent of the forum post - * - * @param $parent - * - * @return array|bool - */ - public function getParent($parent) - { - return $this->pdo->queryOneRow( + /** + * Get parent of the forum post. + * + * @param $parent + * + * @return array|bool + */ + public function getParent($parent) + { + return $this->pdo->queryOneRow( sprintf( 'SELECT f.*, u.username FROM forumpost f LEFT OUTER JOIN users u ON u.id = f.users_id WHERE f.id = %d', $parent ) ); - } + } - /** - * Get forum posts for a parent category - * - * @param $parent - * - * @return array - */ - public function getPosts($parent): array - { - return $this->pdo->query( + /** + * Get forum posts for a parent category. + * + * @param $parent + * + * @return array + */ + public function getPosts($parent): array + { + return $this->pdo->query( sprintf(' SELECT f.*, u.username, ur.name AS rolename FROM forumpost f @@ -99,42 +100,43 @@ class Forum $parent ) ); - } + } - /** - * Get post from forum - * - * @param $id - * - * @return array|bool - */ - public function getPost($id) - { - return $this->pdo->queryOneRow(sprintf('SELECT * FROM forumpost WHERE id = %d', $id)); - } + /** + * Get post from forum. + * + * @param $id + * + * @return array|bool + */ + public function getPost($id) + { + return $this->pdo->queryOneRow(sprintf('SELECT * FROM forumpost WHERE id = %d', $id)); + } - /** - * Get count of posts for parent forum - * - * @return int - */ - public function getBrowseCount(): int - { - $res = $this->pdo->queryOneRow(sprintf('SELECT COUNT(id) AS num FROM forumpost WHERE parentid = 0')); - return ($res === false ? 0 : $res['num']); - } + /** + * Get count of posts for parent forum. + * + * @return int + */ + public function getBrowseCount(): int + { + $res = $this->pdo->queryOneRow(sprintf('SELECT COUNT(id) AS num FROM forumpost WHERE parentid = 0')); - /** - * Get browse range for forum - * - * @param $start - * @param $num - * - * @return array - */ - public function getBrowseRange($start, $num): array - { - return $this->pdo->query( + return $res === false ? 0 : $res['num']; + } + + /** + * Get browse range for forum. + * + * @param $start + * @param $num + * + * @return array + */ + public function getBrowseRange($start, $num): array + { + return $this->pdo->query( sprintf(' SELECT f.*, u.username, ur.name AS rolename FROM forumpost f @@ -142,97 +144,98 @@ class Forum LEFT JOIN user_roles ur ON ur.id = u.role WHERE f.parentid = 0 ORDER BY f.updateddate DESC %s', - ($start === false ? '' : (' LIMIT ' . $num . ' OFFSET ' . $start)) + ($start === false ? '' : (' LIMIT '.$num.' OFFSET '.$start)) ) ); - } + } - /** - * Delete parent category from forum - * - * @param $parent - */ - public function deleteParent($parent): void - { - $this->pdo->queryExec(sprintf('DELETE FROM forumpost WHERE id = %d OR parentid = %d', $parent, $parent)); - } + /** + * Delete parent category from forum. + * + * @param $parent + */ + public function deleteParent($parent): void + { + $this->pdo->queryExec(sprintf('DELETE FROM forumpost WHERE id = %d OR parentid = %d', $parent, $parent)); + } - /** - * Delete post from forum - * - * @param $id - */ - public function deletePost($id): void - { - $post = $this->getPost($id); - if ($post) { - if ((int)$post['parentid'] === 0) { - $this->deleteParent($id); - } else { - $this->pdo->queryExec(sprintf('DELETE FROM forumpost WHERE id = %d', $id)); - } - } - } + /** + * Delete post from forum. + * + * @param $id + */ + public function deletePost($id): void + { + $post = $this->getPost($id); + if ($post) { + if ((int) $post['parentid'] === 0) { + $this->deleteParent($id); + } else { + $this->pdo->queryExec(sprintf('DELETE FROM forumpost WHERE id = %d', $id)); + } + } + } - /** - * Delete user from forum - * - * @param $id - */ - public function deleteUser($id): void - { - $this->pdo->queryExec(sprintf('DELETE FROM forumpost WHERE users_id = %d', $id)); - } + /** + * Delete user from forum. + * + * @param $id + */ + public function deleteUser($id): void + { + $this->pdo->queryExec(sprintf('DELETE FROM forumpost WHERE users_id = %d', $id)); + } - /** - * Get count of posts for user - * - * @param $uid - * - * @return int - */ - public function getCountForUser($uid): int - { - $res = $this->pdo->queryOneRow(sprintf('SELECT COUNT(id) AS num FROM forumpost WHERE users_id = %d', $uid)); - return ($res === false ? 0 : $res['num']); - } + /** + * Get count of posts for user. + * + * @param $uid + * + * @return int + */ + public function getCountForUser($uid): int + { + $res = $this->pdo->queryOneRow(sprintf('SELECT COUNT(id) AS num FROM forumpost WHERE users_id = %d', $uid)); - /** - * Get range of posts for user - * - * @param $uid - * @param $start - * @param $num - * - * @return array - */ - public function getForUserRange($uid, $start, $num): array - { - return $this->pdo->query( + return $res === false ? 0 : $res['num']; + } + + /** + * Get range of posts for user. + * + * @param $uid + * @param $start + * @param $num + * + * @return array + */ + public function getForUserRange($uid, $start, $num): array + { + return $this->pdo->query( sprintf(' SELECT forumpost.*, users.username FROM forumpost LEFT OUTER JOIN users ON users.id = forumpost.users_id WHERE users_id = %d ORDER BY forumpost.createddate DESC %s', - ($start === false ? '' : (' LIMIT ' . $num . ' OFFSET ' . $start)), + ($start === false ? '' : (' LIMIT '.$num.' OFFSET '.$start)), $uid ) ); - } + } - /** - * Edit forum post for user - * - * @param $id - * @param $message - * @param $uid - */ - public function editPost($id, $message, $uid): void - { - $post = $this->getPost($id); - if ($post) { - $this->pdo->queryExec(sprintf(' + /** + * Edit forum post for user. + * + * @param $id + * @param $message + * @param $uid + */ + public function editPost($id, $message, $uid): void + { + $post = $this->getPost($id); + if ($post) { + $this->pdo->queryExec(sprintf(' UPDATE forumpost SET message = %s WHERE id = %d @@ -242,18 +245,18 @@ class Forum $uid ) ); - } - } + } + } - /** - * Lock forum topic - * - * @param $id - * @param $lock - */ - public function lockUnlockTopic($id, $lock): void - { - $this->pdo->queryExec(sprintf(' + /** + * Lock forum topic. + * + * @param $id + * @param $lock + */ + public function lockUnlockTopic($id, $lock): void + { + $this->pdo->queryExec(sprintf(' UPDATE forumpost SET locked = %d WHERE id = %d @@ -263,5 +266,5 @@ class Forum $id ) ); - } + } } diff --git a/nntmux/Games.php b/nntmux/Games.php index 6bc6a8b43..8cade65cd 100755 --- a/nntmux/Games.php +++ b/nntmux/Games.php @@ -1,143 +1,143 @@ <?php + namespace nntmux; -use App\Models\Settings; -use DBorsatto\GiantBomb\Config; -use DBorsatto\GiantBomb\Client; use nntmux\db\DB; - +use App\Models\Settings; +use DBorsatto\GiantBomb\Client; +use DBorsatto\GiantBomb\Config; class Games { - const GAME_MATCH_PERCENTAGE = 85; + const GAME_MATCH_PERCENTAGE = 85; - const GAMES_TITLE_PARSE_REGEX = - '#(?P<title>[\w\s\.]+)(-(?P<relgrp>FLT|RELOADED|SKIDROW|PROPHET|RAZOR1911|CORE|REFLEX))?\s?(\s*(\(?(' . - '(?P<reltype>PROPER|MULTI\d|RETAIL|CRACK(FIX)?|ISO|(RE)?(RIP|PACK))|(?P<year>(19|20)\d{2})|V\s?' . + const GAMES_TITLE_PARSE_REGEX = + '#(?P<title>[\w\s\.]+)(-(?P<relgrp>FLT|RELOADED|SKIDROW|PROPHET|RAZOR1911|CORE|REFLEX))?\s?(\s*(\(?('. + '(?P<reltype>PROPER|MULTI\d|RETAIL|CRACK(FIX)?|ISO|(RE)?(RIP|PACK))|(?P<year>(19|20)\d{2})|V\s?'. '(?P<version>(\d+\.)+\d+)|(-\s)?(?P=relgrp))\)?)\s?)*\s?(\.\w{2,4})?#i'; -/** - * @var bool - */ - public $echoOutput; + /** + * @var bool + */ + public $echoOutput; - /** - * @var array|bool|int|string - */ - public $gameQty; + /** + * @var array|bool|int|string + */ + public $gameQty; - /** - * @var string - */ - public $imgSavePath; + /** + * @var string + */ + public $imgSavePath; - /** - * @var int - */ - public $matchPercentage; + /** + * @var int + */ + public $matchPercentage; - /** - * @var bool - */ - public $maxHitRequest; + /** + * @var bool + */ + public $maxHitRequest; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var array|bool|string - */ - public $publicKey; + /** + * @var array|bool|string + */ + public $publicKey; - /** - * @var string - */ - public $renamed; + /** + * @var string + */ + public $renamed; - /** - * @var array|bool|int|string - */ - public $sleepTime; + /** + * @var array|bool|int|string + */ + public $sleepTime; - /** - * @var string - */ - protected $_classUsed; + /** + * @var string + */ + protected $_classUsed; - /** - * @var string - */ - protected $_gameID; + /** + * @var string + */ + protected $_gameID; - /** - * @var array|bool - */ - protected $_gameResults; + /** + * @var array|bool + */ + protected $_gameResults; - /** - * @var Steam - */ - protected $_getGame; + /** + * @var Steam + */ + protected $_getGame; - /** - * @var int - */ - protected $_resultsFound = 0; + /** + * @var int + */ + protected $_resultsFound = 0; - /** - * @var array|bool|int|string - */ - public $catWhere; - /** - * @var Config - */ - protected $config; + /** + * @var array|bool|int|string + */ + public $catWhere; + /** + * @var Config + */ + protected $config; - /** - * @var Client - */ - protected $giantBomb; + /** + * @var Client + */ + protected $giantBomb; - /** - * @param array $options Class instances / Echo to cli. - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances / Echo to cli. + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'ColorCLI' => null, 'Settings' => null, ]; - $options += $defaults; - $this->echoOutput = ($options['Echo'] && NN_ECHOCLI); + $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->publicKey = Settings::value('APIs..giantbombkey'); - $this->gameQty = Settings::value('..maxgamesprocessed') !== '' ? Settings::value('..maxgamesprocessed') : 150; - $this->imgSavePath = NN_COVERS . 'games' . DS; - $this->renamed = Settings::value('..lookupgames') === 2 ? 'AND isrenamed = 1' : ''; - $this->matchPercentage = 60; - $this->maxHitRequest = false; - $this->catWhere = 'AND categories_id = ' . Category::PC_GAMES . ' '; - if ($this->publicKey !== '') { - $this->config = new Config($this->publicKey); - $this->giantBomb = new Client($this->config); - } - } + $this->publicKey = Settings::value('APIs..giantbombkey'); + $this->gameQty = Settings::value('..maxgamesprocessed') !== '' ? Settings::value('..maxgamesprocessed') : 150; + $this->imgSavePath = NN_COVERS.'games'.DS; + $this->renamed = Settings::value('..lookupgames') === 2 ? 'AND isrenamed = 1' : ''; + $this->matchPercentage = 60; + $this->maxHitRequest = false; + $this->catWhere = 'AND categories_id = '.Category::PC_GAMES.' '; + if ($this->publicKey !== '') { + $this->config = new Config($this->publicKey); + $this->giantBomb = new Client($this->config); + } + } - /** - * @param $id - * - * @return array|bool - */ - public function getGamesInfoById($id) - { - return $this->pdo->queryOneRow( + /** + * @param $id + * + * @return array|bool + */ + public function getGamesInfoById($id) + { + return $this->pdo->queryOneRow( sprintf(' SELECT gi.*, g.title AS genres FROM gamesinfo gi @@ -146,108 +146,109 @@ class Games $id ) ); - } + } - /** - * @param string $title - * - * @return array|bool - */ - public function getGamesInfoByName($title) - { - $bestMatch = false; + /** + * @param string $title + * + * @return array|bool + */ + public function getGamesInfoByName($title) + { + $bestMatch = false; - if (empty($title)) { - return $bestMatch; - } + if (empty($title)) { + return $bestMatch; + } - $results = $this->pdo->queryDirect(" + $results = $this->pdo->queryDirect(" SELECT * FROM gamesinfo WHERE MATCH(title) AGAINST({$this->pdo->escapeString($title)}) LIMIT 20" ); - if ($results instanceof \Traversable) { - $bestMatchPct = 0; - foreach ($results as $result) { - // If we have an exact string match set best match and break out - if ($result['title'] === $title) { - $bestMatch = $result; - break; - } - similar_text(strtolower($result['title']), strtolower($title), $percent); - // If similar_text reports an exact match set best match and break out - if ($percent === 100) { - $bestMatch = $result; - break; - } - if ($percent >= self::GAME_MATCH_PERCENTAGE && $percent > $bestMatchPct) { - $bestMatch = $result; - $bestMatchPct = $percent; - } - } - } + if ($results instanceof \Traversable) { + $bestMatchPct = 0; + foreach ($results as $result) { + // If we have an exact string match set best match and break out + if ($result['title'] === $title) { + $bestMatch = $result; + break; + } + similar_text(strtolower($result['title']), strtolower($title), $percent); + // If similar_text reports an exact match set best match and break out + if ($percent === 100) { + $bestMatch = $result; + break; + } + if ($percent >= self::GAME_MATCH_PERCENTAGE && $percent > $bestMatchPct) { + $bestMatch = $result; + $bestMatchPct = $percent; + } + } + } - return $bestMatch; - } + return $bestMatch; + } - /** - * @param $start - * @param $num - * - * @return array - */ - public function getRange($start, $num): array - { - return $this->pdo->query( + /** + * @param $start + * @param $num + * + * @return array + */ + public function getRange($start, $num): array + { + return $this->pdo->query( sprintf( 'SELECT gi.*, g.title AS genretitle FROM gamesinfo gi INNER JOIN genres g ON gi.genres_id = g.id ORDER BY createddate DESC %s', - ($start === false ? '' : 'LIMIT ' . $num . ' OFFSET ' . $start) + ($start === false ? '' : 'LIMIT '.$num.' OFFSET '.$start) ) ); - } + } - /** - * @return int - */ - public function getCount(): int - { - $res = $this->pdo->queryOneRow('SELECT COUNT(id) AS num FROM gamesinfo'); - return ($res === false ? 0 : $res['num']); - } + /** + * @return int + */ + public function getCount(): int + { + $res = $this->pdo->queryOneRow('SELECT COUNT(id) AS num FROM gamesinfo'); - /** - * @param $cat - * @param $start - * @param $num - * @param string|array $orderBy - * @param string $maxAge - * @param array $excludedCats - * - * @return array - */ - public function getGamesRange($cat, $start, $num, $orderBy = '', $maxAge = '', array $excludedCats = []): array - { - $browseBy = $this->getBrowseBy(); + return $res === false ? 0 : $res['num']; + } - $catsrch = ''; - if (count($cat) > 0 && $cat[0] !== -1) { - $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); - } + /** + * @param $cat + * @param $start + * @param $num + * @param string|array $orderBy + * @param string $maxAge + * @param array $excludedCats + * + * @return array + */ + public function getGamesRange($cat, $start, $num, $orderBy = '', $maxAge = '', array $excludedCats = []): array + { + $browseBy = $this->getBrowseBy(); - if ($maxAge > 0) { - $maxAge = sprintf(' AND r.postdate > NOW() - INTERVAL %d DAY ', $maxAge); - } + $catsrch = ''; + if (count($cat) > 0 && $cat[0] !== -1) { + $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); + } - $exccatlist = ''; - if (count($excludedCats) > 0) { - $exccatlist = ' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')'; - } + if ($maxAge > 0) { + $maxAge = sprintf(' AND r.postdate > NOW() - INTERVAL %d DAY ', $maxAge); + } - $order = $this->getGamesOrder($orderBy); + $exccatlist = ''; + if (count($excludedCats) > 0) { + $exccatlist = ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')'; + } - $games = $this->pdo->queryCalc( + $order = $this->getGamesOrder($orderBy); + + $games = $this->pdo->queryCalc( sprintf(" SELECT SQL_CALC_FOUND_ROWS gi.id, GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id @@ -267,20 +268,20 @@ class Games $exccatlist, $order[0], $order[1], - ($start === false ? '' : ' LIMIT ' . $num . ' OFFSET ' . $start) + ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start) ), true, NN_CACHE_EXPIRY_MEDIUM ); - $gameIDs = $releaseIDs = false; + $gameIDs = $releaseIDs = false; - if (is_array($games['result'])) { - foreach ($games['result'] AS $game => $id) { - $gameIDs[] = $id['id']; - $releaseIDs[] = $id['grp_release_id']; - } - } + if (is_array($games['result'])) { + foreach ($games['result'] as $game => $id) { + $gameIDs[] = $id['id']; + $releaseIDs[] = $id['grp_release_id']; + } + } - $return = $this->pdo->query( + $return = $this->pdo->query( sprintf(" SELECT GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id, @@ -316,22 +317,23 @@ class Games $order[1] ), true, NN_CACHE_EXPIRY_MEDIUM ); - if (!empty($return)) { - $return[0]['_totalcount'] = $games['total'] ?? 0; - } - return $return; - } + if (! empty($return)) { + $return[0]['_totalcount'] = $games['total'] ?? 0; + } - /** - * @param string|array $orderBy - * - * @return array - */ - public function getGamesOrder($orderBy): array - { - $order = $orderBy === '' ? 'r.postdate' : $orderBy; - $orderArr = explode('_', $order); - switch ($orderArr[0]) { + return $return; + } + + /** + * @param string|array $orderBy + * + * @return array + */ + public function getGamesOrder($orderBy): array + { + $order = $orderBy === '' ? 'r.postdate' : $orderBy; + $orderArr = explode('_', $order); + switch ($orderArr[0]) { case 'title': $orderField = 'gi.title'; break; @@ -355,99 +357,98 @@ class Games $orderField = 'r.postdate'; break; } - $orderSort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc'; + $orderSort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc'; - return [$orderField, $orderSort]; - } + return [$orderField, $orderSort]; + } - /** - * @return array - */ - public function getGamesOrdering(): array - { - return [ + /** + * @return array + */ + public function getGamesOrdering(): array + { + return [ 'title_asc', 'title_desc', 'posted_asc', 'posted_desc', 'size_asc', 'size_desc', 'files_asc', 'files_desc', 'stats_asc', 'stats_desc', - 'releasedate_asc', 'releasedate_desc', 'genre_asc', 'genre_desc' + 'releasedate_asc', 'releasedate_desc', 'genre_asc', 'genre_desc', ]; - } + } - /** - * @return array - */ - public function getBrowseByOptions(): array - { - return ['title' => 'title', 'genre' => 'genres_id', 'year' => 'year']; - } + /** + * @return array + */ + public function getBrowseByOptions(): array + { + return ['title' => 'title', 'genre' => 'genres_id', 'year' => 'year']; + } - /** - * @return string - */ - public function getBrowseBy(): string - { - $browseBy = ' '; - $browseByArr = $this->getBrowseByOptions(); + /** + * @return string + */ + public function getBrowseBy(): string + { + $browseBy = ' '; + $browseByArr = $this->getBrowseByOptions(); - foreach ($browseByArr as $bbk => $bbv) { - if (isset($_REQUEST[$bbk]) && !empty($_REQUEST[$bbk])) { - $bbs = stripslashes($_REQUEST[$bbk]); - if ($bbk === 'year') { - $browseBy .= 'AND YEAR (gi.releasedate) ' . $this->pdo->likeString($bbs, true, true); - } else { - $browseBy .= 'AND gi.' . $bbv . ' ' . $this->pdo->likeString($bbs, true, true); - } - } - } + foreach ($browseByArr as $bbk => $bbv) { + if (isset($_REQUEST[$bbk]) && ! empty($_REQUEST[$bbk])) { + $bbs = stripslashes($_REQUEST[$bbk]); + if ($bbk === 'year') { + $browseBy .= 'AND YEAR (gi.releasedate) '.$this->pdo->likeString($bbs, true, true); + } else { + $browseBy .= 'AND gi.'.$bbv.' '.$this->pdo->likeString($bbs, true, true); + } + } + } - return $browseBy; - } + return $browseBy; + } - /** - * @param $data - * @param $field - * - * @return string - */ - public function makeFieldLinks($data, $field): string - { - $tmpArr = explode(', ', $data[$field]); - $newArr = []; - $i = 0; - foreach ($tmpArr as $ta) { - if (trim($ta) === '') { - continue; - } - // Only use first 6. - if ($i > 5) { - break; - } - $newArr[] = - '<a href="' . WWW_TOP . '/games?' . $field . '=' . urlencode($ta) . '" title="' . - $ta . '">' . $ta . '</a>'; - $i++; - } + /** + * @param $data + * @param $field + * + * @return string + */ + public function makeFieldLinks($data, $field): string + { + $tmpArr = explode(', ', $data[$field]); + $newArr = []; + $i = 0; + foreach ($tmpArr as $ta) { + if (trim($ta) === '') { + continue; + } + // Only use first 6. + if ($i > 5) { + break; + } + $newArr[] = + '<a href="'.WWW_TOP.'/games?'.$field.'='.urlencode($ta).'" title="'. + $ta.'">'.$ta.'</a>'; + $i++; + } - return implode(', ', $newArr); - } + return implode(', ', $newArr); + } - /** - * Updates the game for game-edit.php - * - * @param $id - * @param $title - * @param $asin - * @param $url - * @param $publisher - * @param $releaseDate - * @param $esrb - * @param $cover - * @param $trailerUrl - * @param $genreID - */ - public function update($id, $title, $asin, $url, $publisher, $releaseDate, $esrb, $cover, $trailerUrl, $genreID): void - { - - $this->pdo->queryExec( + /** + * Updates the game for game-edit.php. + * + * @param $id + * @param $title + * @param $asin + * @param $url + * @param $publisher + * @param $releaseDate + * @param $esrb + * @param $cover + * @param $trailerUrl + * @param $genreID + */ + public function update($id, $title, $asin, $url, $publisher, $releaseDate, $esrb, $cover, $trailerUrl, $genreID): void + { + $this->pdo->queryExec( sprintf(' UPDATE gamesinfo SET title = %s, asin = %s, url = %s, publisher = %s, @@ -465,199 +466,198 @@ class Games $id ) ); - } + } - /** - * Process each game, updating game information from Steam and Giantbomb - * - * @param $gameInfo - * - * @return bool - * @throws \RuntimeException - * @throws \InvalidArgumentException - */ - public function updateGamesInfo($gameInfo): bool - { - //wait 10 seconds before proceeding (steam api limit) - sleep(10); - $gen = new Genres(['Settings' => $this->pdo]); - $ri = new ReleaseImage($this->pdo); + /** + * Process each game, updating game information from Steam and Giantbomb. + * + * @param $gameInfo + * + * @return bool + * @throws \RuntimeException + * @throws \InvalidArgumentException + */ + public function updateGamesInfo($gameInfo): bool + { + //wait 10 seconds before proceeding (steam api limit) + sleep(10); + $gen = new Genres(['Settings' => $this->pdo]); + $ri = new ReleaseImage($this->pdo); - $game = []; + $game = []; - // Process Steam first before GiantBomb as Steam has more details - $this->_gameResults = false; - $genreName = ''; - $this->_getGame = new Steam(['DB' => $this->pdo]); - $this->_classUsed = 'Steam'; + // Process Steam first before GiantBomb as Steam has more details + $this->_gameResults = false; + $genreName = ''; + $this->_getGame = new Steam(['DB' => $this->pdo]); + $this->_classUsed = 'Steam'; - $steamGameID = $this->_getGame->search($gameInfo['title']); + $steamGameID = $this->_getGame->search($gameInfo['title']); - if ($steamGameID !== false) { - $this->_gameResults = $this->_getGame->getAll($steamGameID); + if ($steamGameID !== false) { + $this->_gameResults = $this->_getGame->getAll($steamGameID); - if ($this->_gameResults !== false) { - if (empty($this->_gameResults['title'])) { - return false; - } - if (!empty($this->_gameResults['cover'])) { - $game['coverurl'] = (string)$this->_gameResults['cover']; - } + if ($this->_gameResults !== false) { + if (empty($this->_gameResults['title'])) { + return false; + } + if (! empty($this->_gameResults['cover'])) { + $game['coverurl'] = (string) $this->_gameResults['cover']; + } - if (!empty($this->_gameResults['backdrop'])) { - $game['backdropurl'] = (string)$this->_gameResults['backdrop']; - } + if (! empty($this->_gameResults['backdrop'])) { + $game['backdropurl'] = (string) $this->_gameResults['backdrop']; + } - $game['title'] = (string)$this->_gameResults['title']; - $game['asin'] = $this->_gameResults['steamid']; - $game['url'] = (string)$this->_gameResults['directurl']; + $game['title'] = (string) $this->_gameResults['title']; + $game['asin'] = $this->_gameResults['steamid']; + $game['url'] = (string) $this->_gameResults['directurl']; - if (!empty($this->_gameResults['publisher'])) { - $game['publisher'] = (string)$this->_gameResults['publisher']; - } else { - $game['publisher'] = 'Unknown'; - } + if (! empty($this->_gameResults['publisher'])) { + $game['publisher'] = (string) $this->_gameResults['publisher']; + } else { + $game['publisher'] = 'Unknown'; + } - if (!empty($this->_gameResults['rating'])) { - $game['esrb'] = (string)$this->_gameResults['rating']; - } else { - $game['esrb'] = 'Not Rated'; - } + if (! empty($this->_gameResults['rating'])) { + $game['esrb'] = (string) $this->_gameResults['rating']; + } else { + $game['esrb'] = 'Not Rated'; + } - if (!empty($this->_gameResults['releasedate'])) { - $dateReleased = $this->_gameResults['releasedate']; - $date = \DateTime::createFromFormat('M j, Y', $dateReleased); - if ($date instanceof \DateTime) { - $game['releasedate'] = (string)$date->format('Y-m-d'); - } - } + if (! empty($this->_gameResults['releasedate'])) { + $dateReleased = $this->_gameResults['releasedate']; + $date = \DateTime::createFromFormat('M j, Y', $dateReleased); + if ($date instanceof \DateTime) { + $game['releasedate'] = (string) $date->format('Y-m-d'); + } + } - if (!empty($this->_gameResults['description'])) { - $game['review'] = (string)$this->_gameResults['description']; - } + if (! empty($this->_gameResults['description'])) { + $game['review'] = (string) $this->_gameResults['description']; + } - if (!empty($this->_gameResults['genres'])) { - $genres = $this->_gameResults['genres']; - $genreName = $this->_matchGenre($genres); - } - } - } + if (! empty($this->_gameResults['genres'])) { + $genres = $this->_gameResults['genres']; + $genreName = $this->_matchGenre($genres); + } + } + } - if ($this->publicKey !== '') { - if ($steamGameID === false || $this->_gameResults === false) { - $bestMatch = false; - $this->_classUsed = 'GiantBomb'; - $result = $this->giantBomb->search($gameInfo['title'], 'Game'); + if ($this->publicKey !== '') { + if ($steamGameID === false || $this->_gameResults === false) { + $bestMatch = false; + $this->_classUsed = 'GiantBomb'; + $result = $this->giantBomb->search($gameInfo['title'], 'Game'); - if (!is_object($result)) { - foreach ($result as $res) { - similar_text(strtolower($gameInfo['title']), strtolower($res->name), $percent1); - similar_text(strtolower($gameInfo['title']), strtolower($res->aliases), $percent2); - if ($percent1 >= self::GAME_MATCH_PERCENTAGE || $percent2 >= self::GAME_MATCH_PERCENTAGE) { - $bestMatch = $res->id; - } - } + if (! is_object($result)) { + foreach ($result as $res) { + similar_text(strtolower($gameInfo['title']), strtolower($res->name), $percent1); + similar_text(strtolower($gameInfo['title']), strtolower($res->aliases), $percent2); + if ($percent1 >= self::GAME_MATCH_PERCENTAGE || $percent2 >= self::GAME_MATCH_PERCENTAGE) { + $bestMatch = $res->id; + } + } - if ($bestMatch !== false) { - $this->_gameResults = $this->giantBomb->findOne('Game', '3030-' . $bestMatch); + if ($bestMatch !== false) { + $this->_gameResults = $this->giantBomb->findOne('Game', '3030-'.$bestMatch); - if (!empty($this->_gameResults->image['medium_url'])) { - $game['coverurl'] = (string)$this->_gameResults->image['medium_url']; - } + if (! empty($this->_gameResults->image['medium_url'])) { + $game['coverurl'] = (string) $this->_gameResults->image['medium_url']; + } - if (!empty($this->_gameResults->image['screen_url'])) { - $game['backdropurl'] = (string)$this->_gameResults->image['screen_url']; - } + if (! empty($this->_gameResults->image['screen_url'])) { + $game['backdropurl'] = (string) $this->_gameResults->image['screen_url']; + } - $game['title'] = (string)$this->_gameResults->get('name'); - $game['asin'] = $this->_gameResults->get('id'); - if (!empty($this->_gameResults->get('site_detail_url'))) { - $game['url'] = (string)$this->_gameResults->get('site_detail_url'); - } else { - $game['url'] = ''; - } + $game['title'] = (string) $this->_gameResults->get('name'); + $game['asin'] = $this->_gameResults->get('id'); + if (! empty($this->_gameResults->get('site_detail_url'))) { + $game['url'] = (string) $this->_gameResults->get('site_detail_url'); + } else { + $game['url'] = ''; + } - if ($this->_gameResults->get('publishers') !== '') { - $game['publisher'] = (string)$this->_gameResults->publishers[0]['name']; - } else { - $game['publisher'] = 'Unknown'; - } + if ($this->_gameResults->get('publishers') !== '') { + $game['publisher'] = (string) $this->_gameResults->publishers[0]['name']; + } else { + $game['publisher'] = 'Unknown'; + } + if (! empty($this->_gameResults->original_game_rating[0]['name'])) { + $game['esrb'] = (string) $this->_gameResults->original_game_rating[0]['name']; + } else { + $game['esrb'] = 'Not Rated'; + } - if (!empty($this->_gameResults->original_game_rating[0]['name'])) { - $game['esrb'] = (string)$this->_gameResults->original_game_rating[0]['name']; - } else { - $game['esrb'] = 'Not Rated'; - } + if ($this->_gameResults->original_release_date !== '') { + $dateReleased = $this->_gameResults->original_release_date; + $date = \DateTime::createFromFormat('Y-m-d H:i:s', $dateReleased); + if ($date instanceof \DateTime) { + $game['releasedate'] = (string) $date->format('Y-m-d'); + } + } - if ($this->_gameResults->original_release_date !== '') { - $dateReleased = $this->_gameResults->original_release_date; - $date = \DateTime::createFromFormat('Y-m-d H:i:s', $dateReleased); - if ($date instanceof \DateTime) { - $game['releasedate'] = (string)$date->format('Y-m-d'); - } - } + if ($this->_gameResults->deck !== '') { + $game['review'] = (string) $this->_gameResults->deck; + } + } else { + ColorCLI::doEcho(ColorCLI::notice('GiantBomb returned no valid results')); - if ($this->_gameResults->deck !== '') { - $game['review'] = (string)$this->_gameResults->deck; - } - } else { - ColorCLI::doEcho(ColorCLI::notice('GiantBomb returned no valid results')); + return false; + } + } else { + ColorCLI::doEcho(ColorCLI::notice('GiantBomb found no valid results')); - return false; - } - } else { - ColorCLI::doEcho(ColorCLI::notice('GiantBomb found no valid results')); + return false; + } + } + } - return false; - } - } - } + // Load genres. + $defaultGenres = $gen->getGenres(Genres::GAME_TYPE); + $genreAssoc = []; + foreach ($defaultGenres as $dg) { + $genreAssoc[$dg['id']] = strtolower($dg['title']); + } - // Load genres. - $defaultGenres = $gen->getGenres(Genres::GAME_TYPE); - $genreAssoc = []; - foreach ($defaultGenres as $dg) { - $genreAssoc[$dg['id']] = strtolower($dg['title']); - } + // Prepare database values. + if (isset($game['coverurl'])) { + $game['cover'] = 1; + } else { + $game['cover'] = 0; + } + if (isset($game['backdropurl'])) { + $game['backdrop'] = 1; + } else { + $game['backdrop'] = 0; + } + if (! isset($game['trailer'])) { + $game['trailer'] = 0; + } + if (empty($game['title'])) { + $game['title'] = $gameInfo['title']; + } + if (! isset($game['releasedate'])) { + $game['releasedate'] = ''; + } - // Prepare database values. - if (isset($game['coverurl'])) { - $game['cover'] = 1; - } else { - $game['cover'] = 0; - } - if (isset($game['backdropurl'])) { - $game['backdrop'] = 1; - } else { - $game['backdrop'] = 0; - } - if (!isset($game['trailer'])) { - $game['trailer'] = 0; - } - if (empty($game['title'])) { - $game['title'] = $gameInfo['title']; - } - if(!isset($game['releasedate'])){ - $game['releasedate'] = ''; - } + if ($game['releasedate'] === '') { + $game['releasedate'] = ''; + } + if (! isset($game['review'])) { + $game['review'] = 'No Review'; + } + $game['classused'] = $this->_classUsed; - if ($game['releasedate'] === '') { - $game['releasedate'] = ''; - } - if(!isset($game['review'])){ - $game['review'] = 'No Review'; - } - $game['classused'] = $this->_classUsed; + if (empty($genreName)) { + $genreName = 'Unknown'; + } - if (empty($genreName)) { - $genreName = 'Unknown'; - } - - if (in_array(strtolower($genreName), $genreAssoc, false)) { - $genreKey = array_search(strtolower($genreName), $genreAssoc, false); - } else { - $genreKey = $this->pdo->queryInsert( + if (in_array(strtolower($genreName), $genreAssoc, false)) { + $genreKey = array_search(strtolower($genreName), $genreAssoc, false); + } else { + $genreKey = $this->pdo->queryInsert( sprintf(' INSERT INTO genres (title, type) VALUES (%s, %d)', @@ -665,12 +665,12 @@ class Games Genres::GAME_TYPE ) ); - } + } - $game['gamesgenre'] = $genreName; - $game['gamesgenreID'] = $genreKey; + $game['gamesgenre'] = $genreName; + $game['gamesgenreID'] = $genreKey; - $check = $this->pdo->queryOneRow( + $check = $this->pdo->queryOneRow( sprintf(' SELECT id FROM gamesinfo @@ -678,8 +678,8 @@ class Games $this->pdo->escapeString($game['asin']) ) ); - if ($check === false) { - $gamesId = $this->pdo->queryInsert( + if ($check === false) { + $gamesId = $this->pdo->queryInsert( sprintf(' INSERT INTO gamesinfo (title, asin, url, publisher, genres_id, esrb, releasedate, review, cover, backdrop, trailer, classused, createddate, updateddate) @@ -698,9 +698,9 @@ class Games $this->pdo->escapeString($game['classused']) ) ); - } else { - $gamesId = $check['id']; - $this->pdo->queryExec( + } else { + $gamesId = $check['id']; + $this->pdo->queryExec( sprintf(' UPDATE gamesinfo SET @@ -722,44 +722,43 @@ class Games $gamesId ) ); - } + } - if ($gamesId) { - if ($this->echoOutput) { - ColorCLI::doEcho( - ColorCLI::header('Added/updated game: ') . - ColorCLI::alternateOver(' Title: ') . - ColorCLI::primary($game['title']) . - ColorCLI::alternateOver( ' Source: ') . + if ($gamesId) { + if ($this->echoOutput) { + ColorCLI::doEcho( + ColorCLI::header('Added/updated game: '). + ColorCLI::alternateOver(' Title: '). + ColorCLI::primary($game['title']). + ColorCLI::alternateOver(' Source: '). ColorCLI::primary($this->_classUsed) ); - } - if($game['cover'] === 1){ - $game['cover'] = $ri->saveImage($gamesId, $game['coverurl'], $this->imgSavePath, 250, 250); - } - if($game['backdrop'] === 1){ - $game['backdrop'] = $ri->saveImage($gamesId . '-backdrop', $game['backdropurl'], $this->imgSavePath, 1920, 1024); - } - } else { - if ($this->echoOutput) { - ColorCLI::doEcho( - ColorCLI::headerOver('Nothing to update: ') . - ColorCLI::primary($game['title'] . ' (PC)' ) + } + if ($game['cover'] === 1) { + $game['cover'] = $ri->saveImage($gamesId, $game['coverurl'], $this->imgSavePath, 250, 250); + } + if ($game['backdrop'] === 1) { + $game['backdrop'] = $ri->saveImage($gamesId.'-backdrop', $game['backdropurl'], $this->imgSavePath, 1920, 1024); + } + } else { + if ($this->echoOutput) { + ColorCLI::doEcho( + ColorCLI::headerOver('Nothing to update: '). + ColorCLI::primary($game['title'].' (PC)') ); - } - } + } + } - return $gamesId; - } + return $gamesId; + } - /** - * - * @throws \InvalidArgumentException - * @throws \RuntimeException - */ - public function processGamesReleases(): void - { - $res = $this->pdo->queryDirect( + /** + * @throws \InvalidArgumentException + * @throws \RuntimeException + */ + public function processGamesReleases(): void + { + $res = $this->pdo->queryDirect( sprintf(' SELECT searchname, id FROM releases @@ -773,106 +772,104 @@ class Games ) ); - if ($res instanceof \Traversable && $res->rowCount() > 0) { - if ($this->echoOutput) { - ColorCLI::doEcho(ColorCLI::header('Processing ' . $res->rowCount() . ' games release(s).')); - } + if ($res instanceof \Traversable && $res->rowCount() > 0) { + if ($this->echoOutput) { + ColorCLI::doEcho(ColorCLI::header('Processing '.$res->rowCount().' games release(s).')); + } - foreach ($res as $arr) { + foreach ($res as $arr) { // Reset maxhitrequest - $this->maxHitRequest = false; + $this->maxHitRequest = false; - $gameInfo = $this->parseTitle($arr['searchname']); - if ($gameInfo !== false) { - - if ($this->echoOutput) { - ColorCLI::doEcho( - ColorCLI::headerOver('Looking up: ') . - ColorCLI::primary($gameInfo['title'] . ' (PC)' ) + $gameInfo = $this->parseTitle($arr['searchname']); + if ($gameInfo !== false) { + if ($this->echoOutput) { + ColorCLI::doEcho( + ColorCLI::headerOver('Looking up: '). + ColorCLI::primary($gameInfo['title'].' (PC)') ); - } + } - // Check for existing games entry. - $gameCheck = $this->getGamesInfoByName($gameInfo['title']); + // Check for existing games entry. + $gameCheck = $this->getGamesInfoByName($gameInfo['title']); - if ($gameCheck === false) { - $gameId = $this->updateGamesInfo($gameInfo); - if ($gameId === false) { - $gameId = -2; + if ($gameCheck === false) { + $gameId = $this->updateGamesInfo($gameInfo); + if ($gameId === false) { + $gameId = -2; - // Leave gamesinfo_id 0 to parse again - if($this->maxHitRequest === true){ - $gameId = 0; - } - } + // Leave gamesinfo_id 0 to parse again + if ($this->maxHitRequest === true) { + $gameId = 0; + } + } + } else { + $gameId = $gameCheck['id']; + } + // Update release. + $this->pdo->queryExec(sprintf('UPDATE releases SET gamesinfo_id = %d WHERE id = %d %s', $gameId, $arr['id'], $this->catWhere)); + } else { + // Could not parse release title. + $this->pdo->queryExec(sprintf('UPDATE releases SET gamesinfo_id = %d WHERE id = %d %s', -2, $arr['id'], $this->catWhere)); - } else { - $gameId = $gameCheck['id']; - } - // Update release. - $this->pdo->queryExec(sprintf('UPDATE releases SET gamesinfo_id = %d WHERE id = %d %s', $gameId, $arr['id'], $this->catWhere)); - } else { - // Could not parse release title. - $this->pdo->queryExec(sprintf('UPDATE releases SET gamesinfo_id = %d WHERE id = %d %s', -2, $arr['id'], $this->catWhere)); + if ($this->echoOutput) { + echo '.'; + } + } + } + } else { + if ($this->echoOutput) { + ColorCLI::doEcho(ColorCLI::header('No games releases to process.')); + } + } + } - if ($this->echoOutput) { - echo '.'; - } - } - } - } else { - if ($this->echoOutput) { - ColorCLI::doEcho(ColorCLI::header('No games releases to process.')); - } - } - } - - /** - * Parse the game release title - * - * @param string $releaseName - * - * @return array|bool - */ - public function parseTitle($releaseName) - { + /** + * Parse the game release title. + * + * @param string $releaseName + * + * @return array|bool + */ + public function parseTitle($releaseName) + { // Get name of the game from name of release. - if (preg_match(self::GAMES_TITLE_PARSE_REGEX, preg_replace('/\sMulti\d?\s/i', '', $releaseName), $matches)) { - // Replace dots, underscores, colons, or brackets with spaces. - $result = []; - $result['title'] = str_replace(' RF ', ' ', preg_replace('/(\-|\:|\.|_|\%20|\[|\])/', ' ', $matches['title'])); - // Replace any foreign words at the end of the release - $result['title'] = preg_replace('/(brazilian|chinese|croatian|danish|deutsch|dutch|english|estonian|flemish|finnish|french|german|greek|hebrew|icelandic|italian|latin|nordic|norwegian|polish|portuguese|japenese|japanese|russian|serbian|slovenian|spanish|spanisch|swedish|thai|turkish)$/i', '', $result['title']); - // Remove PC ISO) ( from the beginning bad regex from Games category? - $result['title'] = preg_replace('/^(PC\sISO\)\s\()/i', '', $result['title']); - // Finally remove multiple spaces and trim leading spaces. - $result['title'] = trim(preg_replace('/\s{2,}/', ' ', $result['title'])); - if (empty($result['title'])) { - return false; - } - $result['release'] = $releaseName; + if (preg_match(self::GAMES_TITLE_PARSE_REGEX, preg_replace('/\sMulti\d?\s/i', '', $releaseName), $matches)) { + // Replace dots, underscores, colons, or brackets with spaces. + $result = []; + $result['title'] = str_replace(' RF ', ' ', preg_replace('/(\-|\:|\.|_|\%20|\[|\])/', ' ', $matches['title'])); + // Replace any foreign words at the end of the release + $result['title'] = preg_replace('/(brazilian|chinese|croatian|danish|deutsch|dutch|english|estonian|flemish|finnish|french|german|greek|hebrew|icelandic|italian|latin|nordic|norwegian|polish|portuguese|japenese|japanese|russian|serbian|slovenian|spanish|spanisch|swedish|thai|turkish)$/i', '', $result['title']); + // Remove PC ISO) ( from the beginning bad regex from Games category? + $result['title'] = preg_replace('/^(PC\sISO\)\s\()/i', '', $result['title']); + // Finally remove multiple spaces and trim leading spaces. + $result['title'] = trim(preg_replace('/\s{2,}/', ' ', $result['title'])); + if (empty($result['title'])) { + return false; + } + $result['release'] = $releaseName; - return array_map('trim', $result); - } + return array_map('trim', $result); + } - return false; - } + return false; + } - /** - * See if genre name exists - * - * @param $gameGenre - * - * @return bool|string - */ - public function matchGenreName($gameGenre) - { - $str = ''; + /** + * See if genre name exists. + * + * @param $gameGenre + * + * @return bool|string + */ + public function matchGenreName($gameGenre) + { + $str = ''; - //Game genres - switch ($gameGenre) { + //Game genres + switch ($gameGenre) { case 'Action': case 'Adventure': case 'Arcade': @@ -892,36 +889,36 @@ class Games break; } - return ($str !== '') ? $str : false; - } + return ($str !== '') ? $str : false; + } - /** - * Matches Genres - * - * @param string $genre - * - * @return string - */ - protected function _matchGenre($genre = ''): string - { - $genreName = ''; - $a = str_replace('-', ' ', $genre); - $tmpGenre = explode(',', $a); - if (is_array($tmpGenre)) { - foreach ($tmpGenre as $tg) { - $genreMatch = $this->matchGenreName(ucwords($tg)); - if ($genreMatch !== false) { - $genreName = (string)$genreMatch; - break; - } - } - if(empty($genreName)){ - $genreName = $tmpGenre[0]; - } - } else { - $genreName = $genre; - } + /** + * Matches Genres. + * + * @param string $genre + * + * @return string + */ + protected function _matchGenre($genre = ''): string + { + $genreName = ''; + $a = str_replace('-', ' ', $genre); + $tmpGenre = explode(',', $a); + if (is_array($tmpGenre)) { + foreach ($tmpGenre as $tg) { + $genreMatch = $this->matchGenreName(ucwords($tg)); + if ($genreMatch !== false) { + $genreName = (string) $genreMatch; + break; + } + } + if (empty($genreName)) { + $genreName = $tmpGenre[0]; + } + } else { + $genreName = $genre; + } - return $genreName; - } + return $genreName; + } } diff --git a/nntmux/Genres.php b/nntmux/Genres.php index 0e24a20fd..17e05f58b 100755 --- a/nntmux/Genres.php +++ b/nntmux/Genres.php @@ -1,132 +1,136 @@ <?php + namespace nntmux; use nntmux\db\DB; class Genres { - const CONSOLE_TYPE = Category::GAME_ROOT; - const MUSIC_TYPE = Category::MUSIC_ROOT; - const GAME_TYPE = Category::PC_ROOT; + const CONSOLE_TYPE = Category::GAME_ROOT; + const MUSIC_TYPE = Category::MUSIC_ROOT; + const GAME_TYPE = Category::PC_ROOT; - const STATUS_ENABLED = 0; - const STATUS_DISABLED = 1; + const STATUS_ENABLED = 0; + const STATUS_DISABLED = 1; - /** - * @var \nntmux\db\Settings; - */ - public $pdo; + /** + * @var \nntmux\db\Settings; + */ + public $pdo; - /** - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ - 'Settings' => null + /** + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ + 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + } - public function getGenres($type = '', $activeonly = false) - { - return $this->pdo->query($this->getListQuery($type, $activeonly), true,NN_CACHE_EXPIRY_LONG); - } + public function getGenres($type = '', $activeonly = false) + { + return $this->pdo->query($this->getListQuery($type, $activeonly), true, NN_CACHE_EXPIRY_LONG); + } - private function getListQuery($type = '', $activeonly = false) - { - if (!empty($type)) - $typesql = sprintf(' AND g.type = %d', $type); - else - $typesql = ''; + private function getListQuery($type = '', $activeonly = false) + { + if (! empty($type)) { + $typesql = sprintf(' AND g.type = %d', $type); + } else { + $typesql = ''; + } - if ($activeonly) { - $sql = sprintf(" + if ($activeonly) { + $sql = sprintf(' SELECT g.* FROM genres g INNER JOIN (SELECT DISTINCT genres_id FROM musicinfo) x - ON x.genres_id = g.id %1\$s + ON x.genres_id = g.id %1$s UNION SELECT g.* FROM genres g INNER JOIN (SELECT DISTINCT genres_id FROM consoleinfo) x - ON x.genres_id = g.id %1\$s + ON x.genres_id = g.id %1$s UNION SELECT g.* FROM genres g INNER JOIN (SELECT DISTINCT genres_id FROM gamesinfo) x - ON x.genres_id = g.id %1\$s - ORDER BY title", + ON x.genres_id = g.id %1$s + ORDER BY title', $typesql ); - } else { - $sql = sprintf('SELECT g.* FROM genres g WHERE 1 %s ORDER BY g.title', $typesql); - } + } else { + $sql = sprintf('SELECT g.* FROM genres g WHERE 1 %s ORDER BY g.title', $typesql); + } - return $sql; - } + return $sql; + } - public function getRange($type = '', $activeonly = false, $start, $num) - { - $sql = $this->getListQuery($type, $activeonly); - $sql .= ' LIMIT ' . $num . ' OFFSET ' . $start; + public function getRange($type = '', $activeonly = false, $start, $num) + { + $sql = $this->getListQuery($type, $activeonly); + $sql .= ' LIMIT '.$num.' OFFSET '.$start; - return $this->pdo->query($sql); - } + return $this->pdo->query($sql); + } - public function getCount($type = '', $activeonly = false) - { - if (!empty($type)) - $typesql = sprintf(' AND g.type = %d', $type); - else - $typesql = ''; + public function getCount($type = '', $activeonly = false) + { + if (! empty($type)) { + $typesql = sprintf(' AND g.type = %d', $type); + } else { + $typesql = ''; + } - if ($activeonly) - $sql = sprintf(" + if ($activeonly) { + $sql = sprintf(' SELECT COUNT(id) AS num FROM genres g INNER JOIN (SELECT DISTINCT genres_id FROM musicinfo) x - ON x.genres_id = g.id %1\$s + ON x.genres_id = g.id %1$s + SELECT COUNT(id) AS num FROM genres g INNER JOIN (SELECT DISTINCT genres_id FROM consoleinfo) y - ON y.genres_id = g.id %1\$s + ON y.genres_id = g.id %1$s + SELECT COUNT(id) AS num FROM genres g INNER JOIN (SELECT DISTINCT genres_id FROM gamesinfo) x - ON x.genres_id = g.id %1\$s", + ON x.genres_id = g.id %1$s', $typesql ); - else - $sql = sprintf('SELECT COUNT(g.id) AS num FROM genres g WHERE 1 %s ORDER BY g.title', $typesql); + } else { + $sql = sprintf('SELECT COUNT(g.id) AS num FROM genres g WHERE 1 %s ORDER BY g.title', $typesql); + } - $res = $this->pdo->queryOneRow($sql); + $res = $this->pdo->queryOneRow($sql); - return $res['num']; - } + return $res['num']; + } - public function getById($id) - { - return $this->pdo->queryOneRow(sprintf('SELECT * FROM genres WHERE id = %d', $id)); - } + public function getById($id) + { + return $this->pdo->queryOneRow(sprintf('SELECT * FROM genres WHERE id = %d', $id)); + } - public function update($id, $disabled) - { - return $this->pdo->queryExec(sprintf('UPDATE genres SET disabled = %d WHERE id = %d', $disabled, $id)); - } + public function update($id, $disabled) + { + return $this->pdo->queryExec(sprintf('UPDATE genres SET disabled = %d WHERE id = %d', $disabled, $id)); + } - public function getDisabledIDs() - { - return $this->pdo->query('SELECT id FROM genres WHERE disabled = 1', true, NN_CACHE_EXPIRY_LONG); - } + public function getDisabledIDs() + { + return $this->pdo->query('SELECT id FROM genres WHERE disabled = 1', true, NN_CACHE_EXPIRY_LONG); + } } diff --git a/nntmux/Groups.php b/nntmux/Groups.php index 3649ce551..8035cddf1 100755 --- a/nntmux/Groups.php +++ b/nntmux/Groups.php @@ -1,111 +1,112 @@ <?php + namespace nntmux; use nntmux\db\DB; class Groups { - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var ColorCLI - */ - public $colorCLI; + /** + * @var ColorCLI + */ + public $colorCLI; - /** - * The table names for TPG children - * - * @var array - */ - protected $cbpm; + /** + * The table names for TPG children. + * + * @var array + */ + protected $cbpm; - /** - * @var array - */ - protected $cbppTableNames; + /** + * @var array + */ + protected $cbppTableNames; - /** - * Construct. - * - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Construct. + * + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, - 'ColorCLI' => null + 'ColorCLI' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->colorCLI = ($options['ColorCLI'] instanceof ColorCLI ? $options['ColorCLI'] : new ColorCLI()); - $this->cbpm = ['collections', 'binaries', 'parts', 'missed_parts']; - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->colorCLI = ($options['ColorCLI'] instanceof ColorCLI ? $options['ColorCLI'] : new ColorCLI()); + $this->cbpm = ['collections', 'binaries', 'parts', 'missed_parts']; + } - /** - * Returns an associative array of groups for list selection - * - * @return array - */ - public function getGroupsForSelect() - { - $groups = $this->getActive(); - $temp_array = []; + /** + * Returns an associative array of groups for list selection. + * + * @return array + */ + public function getGroupsForSelect() + { + $groups = $this->getActive(); + $temp_array = []; - $temp_array[-1] = '--Please Select--'; + $temp_array[-1] = '--Please Select--'; - if (is_array($groups)) { - foreach ($groups as $group) { - $temp_array[$group['name']] = $group['name']; - } - } + if (is_array($groups)) { + foreach ($groups as $group) { + $temp_array[$group['name']] = $group['name']; + } + } - return $temp_array; - } + return $temp_array; + } - /** - * Get all properties of a single group by its ID - * - * @param $id - * - * @return array|bool - */ - public function getByID($id) - { - return $this->pdo->queryOneRow(" + /** + * Get all properties of a single group by its ID. + * + * @param $id + * + * @return array|bool + */ + public function getByID($id) + { + return $this->pdo->queryOneRow(" SELECT g.* FROM groups g WHERE g.id = {$id}" ); - } + } - /** - * Get all properties of all groups ordered by name ascending - * - * @return array - */ - public function getActive() - { - return $this->pdo->query( + /** + * Get all properties of all groups ordered by name ascending. + * + * @return array + */ + public function getActive() + { + return $this->pdo->query( 'SELECT g.* FROM groups g WHERE g.active = 1 ORDER BY g.name ASC', true, NN_CACHE_EXPIRY_SHORT ); - } + } - /** - * Get active backfill groups ordered by name ascending - * - * @param string $order The type of operation designating the order - * - * @return array - */ - public function getActiveBackfill($order) - { - switch ($order) { + /** + * Get active backfill groups ordered by name ascending. + * + * @param string $order The type of operation designating the order + * + * @return array + */ + public function getActiveBackfill($order) + { + switch ($order) { case '': case 'normal': $orderBy = 'g.name ASC'; @@ -117,21 +118,21 @@ class Groups return []; } - return $this->pdo->query( + return $this->pdo->query( "SELECT g.* FROM groups g WHERE g.backfill = 1 AND g.last_record != 0 ORDER BY {$orderBy}", true, NN_CACHE_EXPIRY_SHORT ); - } + } - /** - * Get all active group IDs - * - * @return array - */ - public function getActiveIDs() - { - return $this->pdo->query(' + /** + * Get all active group IDs. + * + * @return array + */ + public function getActiveIDs() + { + return $this->pdo->query(' SELECT g.id FROM groups g WHERE g.active = 1 @@ -139,71 +140,71 @@ class Groups true, NN_CACHE_EXPIRY_SHORT ); - } + } - /** - * Get all group columns by Name - * - * @param $grp - * - * @return array|bool - */ - public function getByName($grp) - { - return $this->pdo->queryOneRow(" + /** + * Get all group columns by Name. + * + * @param $grp + * + * @return array|bool + */ + public function getByName($grp) + { + return $this->pdo->queryOneRow(" SELECT g.* FROM groups g WHERE g.name = {$this->pdo->escapeString($grp)}" ); - } + } - /** - * Get a group name using its ID. - * - * @param int|string $id The group ID. - * - * @return string Empty string on failure, groupName on success. - */ - public function getNameByID($id) - { - $res = $this->pdo->queryOneRow(" + /** + * Get a group name using its ID. + * + * @param int|string $id The group ID. + * + * @return string Empty string on failure, groupName on success. + */ + public function getNameByID($id) + { + $res = $this->pdo->queryOneRow(" SELECT g.name FROM groups g WHERE g.id = {$id}" ); - return ($res === false ? '' : $res['name']); - } + return $res === false ? '' : $res['name']; + } - /** - * Get a group ID using its name. - * - * @param string $name The group name. - * - * @return string|int Empty string on failure, groups_id on success. - */ - public function getIDByName($name) - { - $res = $this->pdo->queryOneRow(" + /** + * Get a group ID using its name. + * + * @param string $name The group name. + * + * @return string|int Empty string on failure, groups_id on success. + */ + public function getIDByName($name) + { + $res = $this->pdo->queryOneRow(" SELECT g.id FROM groups g WHERE g.name = {$this->pdo->escapeString($name)}" ); - return ($res === false ? '' : $res['id']); - } + return $res === false ? '' : $res['id']; + } - /** - * Gets a count of all groups in the table limited by parameters - * - * @param string $groupname Constrain query to specific group name - * @param int $active Constrain query to active status - * - * @return mixed - */ - public function getCount($groupname = '', $active = -1) - { - $res = $this->pdo->query( + /** + * Gets a count of all groups in the table limited by parameters. + * + * @param string $groupname Constrain query to specific group name + * @param int $active Constrain query to active status + * + * @return mixed + */ + public function getCount($groupname = '', $active = -1) + { + $res = $this->pdo->query( sprintf(' SELECT COUNT(g.id) AS num FROM groups g @@ -220,22 +221,22 @@ class Groups ), true, NN_CACHE_EXPIRY_MEDIUM ); - return (empty($res) ? 0 : $res[0]['num']); - } + return empty($res) ? 0 : $res[0]['num']; + } - /** - * Gets all groups and associated release counts - * - * @param bool|int $start The offset of the query or false for no offset - * @param int $num The limit of the query - * @param string $groupname The groupname we want if any - * @param int $active The status of the group we want if any - * - * @return mixed - */ - public function getRange($start = false, $num = -1, $groupname = '', $active = -1) - { - return $this->pdo->query( + /** + * Gets all groups and associated release counts. + * + * @param bool|int $start The offset of the query or false for no offset + * @param int $num The limit of the query + * @param string $groupname The groupname we want if any + * @param int $active The status of the group we want if any + * + * @return mixed + */ + public function getRange($start = false, $num = -1, $groupname = '', $active = -1) + { + return $this->pdo->query( sprintf(' SELECT g.*, COALESCE(COUNT(r.id), 0) AS num_releases @@ -254,22 +255,21 @@ class Groups : '' ), $active > -1 ? sprintf('AND g.active = %d', $active) : '', - $start === false ? '' : ' LIMIT ' . $num . ' OFFSET ' . $start + $start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start ), true, NN_CACHE_EXPIRY_SHORT ); - } + } - /** - * Update an existing group. - * - * @param array $group - * - * @return bool - */ - public function update($group) - { - - $minFileString = + /** + * Update an existing group. + * + * @param array $group + * + * @return bool + */ + public function update($group) + { + $minFileString = ( $group['minfilestoformrelease'] == '' ? 'minfilestoformrelease = NULL,' @@ -279,7 +279,7 @@ class Groups ) ); - $minSizeString = + $minSizeString = ( $group['minsizetoformrelease'] == '' ? 'minsizetoformrelease = NULL' @@ -289,7 +289,7 @@ class Groups ) ); - return $this->pdo->queryExec( + return $this->pdo->queryExec( sprintf( 'UPDATE groups SET name = %s, description = %s, backfill_target = %s, first_record = %s, last_record = %s, @@ -307,49 +307,48 @@ class Groups $group['id'] ) ); - } + } - /** - * Checks group name is standard and replaces any shorthand prefixes - * - * @param string $groupName The full name of the usenet group being evaluated - * - * @return string|bool The name of the group replacing shorthand prefix or false if groupname was malformed - */ - public function isValidGroup($groupName) - { - if (preg_match('/^([\w-]+\.)+[\w-]+$/i', $groupName)) { + /** + * Checks group name is standard and replaces any shorthand prefixes. + * + * @param string $groupName The full name of the usenet group being evaluated + * + * @return string|bool The name of the group replacing shorthand prefix or false if groupname was malformed + */ + public function isValidGroup($groupName) + { + if (preg_match('/^([\w-]+\.)+[\w-]+$/i', $groupName)) { + return preg_replace('/^a\.b\./i', 'alt.binaries.', $groupName, 1); + } - return preg_replace('/^a\.b\./i', 'alt.binaries.', $groupName, 1); - } + return false; + } - return false; - } - - /** - * Add a new group. - * - * @param array $group - * - * @return bool - */ - public function add($group) - { - $minFileString = + /** + * Add a new group. + * + * @param array $group + * + * @return bool + */ + public function add($group) + { + $minFileString = ( $group['minfilestoformrelease'] == '' ? 'NULL' : sprintf('%d', $this->formatNumberString($group['minfilestoformrelease'], false)) ); - $minSizeString = + $minSizeString = ( $group['minsizetoformrelease'] == '' ? 'NULL' : sprintf('%d', $this->formatNumberString($group['minsizetoformrelease'], false)) ); - return $this->pdo->queryInsert( + return $this->pdo->queryInsert( sprintf(' INSERT INTO groups (name, description, backfill_target, first_record, last_record, last_updated, @@ -366,179 +365,179 @@ class Groups $minSizeString ) ); - } + } - /** - * Format numeric string when adding/updating groups. - * - * @param string $setting - * @param bool $escape - * - * @return string|int - */ - protected function formatNumberString($setting, $escape = true) - { - $setting = trim($setting); - if ($setting === '0' || !is_numeric($setting)) { - $setting = '0'; - } + /** + * Format numeric string when adding/updating groups. + * + * @param string $setting + * @param bool $escape + * + * @return string|int + */ + protected function formatNumberString($setting, $escape = true) + { + $setting = trim($setting); + if ($setting === '0' || ! is_numeric($setting)) { + $setting = '0'; + } - return ($escape ? $this->pdo->escapeString($setting) : (int)$setting); - } + return $escape ? $this->pdo->escapeString($setting) : (int) $setting; + } - /** - * Delete a group. - * - * @param int|string $id ID of the group. - * - * @return bool - */ - public function delete($id) - { - $this->purge($id); + /** + * Delete a group. + * + * @param int|string $id ID of the group. + * + * @return bool + */ + public function delete($id) + { + $this->purge($id); - return $this->pdo->queryExec(" + return $this->pdo->queryExec(" DELETE g FROM groups g WHERE g.id = {$id}" ); - } + } - /** - * Reset a group. - * - * @param string|int $id The group ID. - * - * @return bool - */ - public function reset($id) - { - // Remove rows from collections / binaries / parts. - (new Binaries(['Groups' => $this, 'Settings' => $this->pdo]))->purgeGroup($id); + /** + * Reset a group. + * + * @param string|int $id The group ID. + * + * @return bool + */ + public function reset($id) + { + // Remove rows from collections / binaries / parts. + (new Binaries(['Groups' => $this, 'Settings' => $this->pdo]))->purgeGroup($id); - // Remove rows from part repair. - $this->pdo->queryExec(" + // Remove rows from part repair. + $this->pdo->queryExec(" DELETE mp FROM missed_parts mp WHERE mp.groups_id = {$id}" ); - foreach ($this->cbpm AS $tablePrefix) { - $this->pdo->queryExec( + foreach ($this->cbpm as $tablePrefix) { + $this->pdo->queryExec( "DROP TABLE IF EXISTS {$tablePrefix}_{$id}" ); - } + } - // Reset the group stats. - return $this->pdo->queryExec(" + // Reset the group stats. + return $this->pdo->queryExec(" UPDATE groups SET backfill_target = 1, first_record = 0, first_record_postdate = NULL, last_record = 0, last_record_postdate = NULL, last_updated = NULL WHERE id = {$id}" ); - } + } - /** - * Reset all groups. - * - * @return bool - */ - public function resetall() - { - foreach ($this->cbpm AS $tablePrefix) { - $this->pdo->queryExec("TRUNCATE TABLE {$tablePrefix}"); - } + /** + * Reset all groups. + * + * @return bool + */ + public function resetall() + { + foreach ($this->cbpm as $tablePrefix) { + $this->pdo->queryExec("TRUNCATE TABLE {$tablePrefix}"); + } - $groups = $this->pdo->queryDirect('SELECT id FROM groups'); + $groups = $this->pdo->queryDirect('SELECT id FROM groups'); - if ($groups instanceof \Traversable) { - foreach ($groups AS $group) { - foreach ($this->cbpm AS $tablePrefix) { - $this->pdo->queryExec("DROP TABLE IF EXISTS {$tablePrefix}_{$group['id']}"); - } - } - } + if ($groups instanceof \Traversable) { + foreach ($groups as $group) { + foreach ($this->cbpm as $tablePrefix) { + $this->pdo->queryExec("DROP TABLE IF EXISTS {$tablePrefix}_{$group['id']}"); + } + } + } - // Reset the group stats. - return $this->pdo->queryExec(' + // Reset the group stats. + return $this->pdo->queryExec(' UPDATE groups SET backfill_target = 1, first_record = 0, first_record_postdate = NULL, last_record = 0, last_record_postdate = NULL, last_updated = NULL, active = 0' ); - } + } - /** - * Purge a single group or all groups. - * - * @param int|string|bool $id The group ID. If false, purge all groups. - */ - public function purge($id = false) - { - if ($id === false) { - $this->resetall(); - } else { - $this->reset($id); - } + /** + * Purge a single group or all groups. + * + * @param int|string|bool $id The group ID. If false, purge all groups. + */ + public function purge($id = false) + { + if ($id === false) { + $this->resetall(); + } else { + $this->reset($id); + } - $res = $this->pdo->queryDirect( + $res = $this->pdo->queryDirect( sprintf(' SELECT r.id, r.guid FROM releases r %s', - ($id === false ? '' : 'WHERE r.groups_id = ' . $id) + ($id === false ? '' : 'WHERE r.groups_id = '.$id) ) ); - if ($res instanceof \Traversable) { - $releases = new Releases(['Settings' => $this->pdo, 'Groups' => $this]); - $nzb = new NZB($this->pdo); - $releaseImage = new ReleaseImage($this->pdo); - foreach ($res AS $row) { - $releases->deleteSingle( + if ($res instanceof \Traversable) { + $releases = new Releases(['Settings' => $this->pdo, 'Groups' => $this]); + $nzb = new NZB($this->pdo); + $releaseImage = new ReleaseImage($this->pdo); + foreach ($res as $row) { + $releases->deleteSingle( [ 'g' => $row['guid'], - 'i' => $row['id'] + 'i' => $row['id'], ], $nzb, $releaseImage ); - } - } - } + } + } + } - /** - * Adds new newsgroups based on a regular expression match against USP available - * - * @param string $groupList - * @param int $active - * @param int $backfill - * - * @return array|string - */ - public function addBulk($groupList, $active = 1, $backfill = 1) - { - if (preg_match('/^\s*$/m', $groupList)) { - $ret = 'No group list provided.'; - } else { - $nntp = new NNTP(['Echo' => false]); - if ($nntp->doConnect() !== true) { - return 'Problem connecting to usenet.'; - } - $groups = $nntp->getGroups(); - $nntp->doQuit(); + /** + * Adds new newsgroups based on a regular expression match against USP available. + * + * @param string $groupList + * @param int $active + * @param int $backfill + * + * @return array|string + */ + public function addBulk($groupList, $active = 1, $backfill = 1) + { + if (preg_match('/^\s*$/m', $groupList)) { + $ret = 'No group list provided.'; + } else { + $nntp = new NNTP(['Echo' => false]); + if ($nntp->doConnect() !== true) { + return 'Problem connecting to usenet.'; + } + $groups = $nntp->getGroups(); + $nntp->doQuit(); - if ($nntp->isError($groups)) { - return 'Problem fetching groups from usenet.'; - } + if ($nntp->isError($groups)) { + return 'Problem fetching groups from usenet.'; + } - $regFilter = '/' . $groupList . '/i'; + $regFilter = '/'.$groupList.'/i'; - $ret = []; + $ret = []; - foreach ($groups as $group) { - if (preg_match($regFilter, $group['group']) > 0) { - $res = $this->getIDByName($group['group']); - if ($res === '') { - $this->add( + foreach ($groups as $group) { + if (preg_match($regFilter, $group['group']) > 0) { + $res = $this->getIDByName($group['group']); + if ($res === '') { + $this->add( [ 'name' => $group['group'], 'active' => $active, @@ -546,107 +545,106 @@ class Groups 'description' => 'Added by bulkAdd', ] ); - $ret[] = ['group' => $group['group'], 'msg' => 'Created']; - } - } - } + $ret[] = ['group' => $group['group'], 'msg' => 'Created']; + } + } + } - if (count($ret) === 0) { - $ret = 'No groups found with your regex, try again!'; - } - } + if (count($ret) === 0) { + $ret = 'No groups found with your regex, try again!'; + } + } - return $ret; - } + return $ret; + } - /** - * Updates the group active/backfill status - * - * @param int $id Which group ID - * @param string $column Which column active/backfill - * @param int $status Which status we are setting - * - * @return string - */ - public function updateGroupStatus($id, $column, $status = 0) - { - $this->pdo->queryExec(" + /** + * Updates the group active/backfill status. + * + * @param int $id Which group ID + * @param string $column Which column active/backfill + * @param int $status Which status we are setting + * + * @return string + */ + public function updateGroupStatus($id, $column, $status = 0) + { + $this->pdo->queryExec(" UPDATE groups SET {$column} = {$status} WHERE id = {$id}" ); - return "Group {$id}: {$column} has been " . (($status === 0) ? 'deactivated' : 'activated') . '.'; - } + return "Group {$id}: {$column} has been ".(($status === 0) ? 'deactivated' : 'activated').'.'; + } - /** - * Get the names of the collections/binaries/parts/part repair tables. - * If TPG is on, try to create new tables for the groups_id, if we fail, log the error and exit. - * - * @param int $groupID ID of the group. - * - * @return array The table names. - */ - public function getCBPTableNames($groupID) - { - $groupKey = $groupID; + /** + * Get the names of the collections/binaries/parts/part repair tables. + * If TPG is on, try to create new tables for the groups_id, if we fail, log the error and exit. + * + * @param int $groupID ID of the group. + * + * @return array The table names. + */ + public function getCBPTableNames($groupID) + { + $groupKey = $groupID; - // Check if buffered and return. Prevents re-querying MySQL when TPG is on. - if (isset($this->cbppTableNames[$groupKey])) { - return $this->cbppTableNames[$groupKey]; - } + // Check if buffered and return. Prevents re-querying MySQL when TPG is on. + if (isset($this->cbppTableNames[$groupKey])) { + return $this->cbppTableNames[$groupKey]; + } - if (NN_ECHOCLI && $this->createNewTPGTables($groupID) === false) { - exit('There is a problem creating new TPG tables for this group ID: ' . $groupID . PHP_EOL); - } + if (NN_ECHOCLI && $this->createNewTPGTables($groupID) === false) { + exit('There is a problem creating new TPG tables for this group ID: '.$groupID.PHP_EOL); + } - $tables = []; - $tables['cname'] = 'collections_' . $groupID; - $tables['bname'] = 'binaries_' . $groupID; - $tables['pname'] = 'parts_' . $groupID; - $tables['prname'] = 'missed_parts_' . $groupID; + $tables = []; + $tables['cname'] = 'collections_'.$groupID; + $tables['bname'] = 'binaries_'.$groupID; + $tables['pname'] = 'parts_'.$groupID; + $tables['prname'] = 'missed_parts_'.$groupID; - // Buffer. - $this->cbppTableNames[$groupKey] = $tables; + // Buffer. + $this->cbppTableNames[$groupKey] = $tables; - return $tables; - } + return $tables; + } - /** - * Check if the tables exist for the groups_id, make new tables for table per group. - * - * @param int $groupID - * - * @return bool - */ - public function createNewTPGTables($groupID) - { - foreach ($this->cbpm as $tablePrefix) { - if ($this->pdo->queryExec( + /** + * Check if the tables exist for the groups_id, make new tables for table per group. + * + * @param int $groupID + * + * @return bool + */ + public function createNewTPGTables($groupID) + { + foreach ($this->cbpm as $tablePrefix) { + if ($this->pdo->queryExec( "CREATE TABLE IF NOT EXISTS {$tablePrefix}_{$groupID} LIKE {$tablePrefix}", true ) === false ) { + return false; + } + } - return false; - } - } + return true; + } - return true; - } - - /** - * Disable group that does not exist on USP server - * - * @param int $id The Group ID to disable - */ - public function disableIfNotExist($id) - { - $this->updateGroupStatus($id, 'active', 0); - ColorCLI::doEcho( + /** + * Disable group that does not exist on USP server. + * + * @param int $id The Group ID to disable + */ + public function disableIfNotExist($id) + { + $this->updateGroupStatus($id, 'active', 0); + ColorCLI::doEcho( ColorCLI::error( 'Group does not exist on server, disabling' ) ); - } + } } diff --git a/nntmux/IRCClient.php b/nntmux/IRCClient.php index b12be2d8b..bd0a0317a 100755 --- a/nntmux/IRCClient.php +++ b/nntmux/IRCClient.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; use nntmux\utility\Utility; @@ -10,657 +11,597 @@ use nntmux\utility\Utility; */ class IRCClient { - /** - * Hostname IRC server used when connecting. - * - * @var string - * @access protected - */ - protected $_remote_host = ''; + /** + * Hostname IRC server used when connecting. + * + * @var string + */ + protected $_remote_host = ''; - /** - * Port number IRC server. - * - * @var int - * @access protected - */ - protected $_remote_port = 6667; + /** + * Port number IRC server. + * + * @var int + */ + protected $_remote_port = 6667; - /** - * Socket transport type for the IRC server. - * - * @var string - * @access protected - */ - protected $_remote_transport = 'tcp'; + /** + * Socket transport type for the IRC server. + * + * @var string + */ + protected $_remote_transport = 'tcp'; + /** + * Hostname the IRC server sent us back. + * + * @var string + */ + protected $_remote_host_received = ''; - /** - * Hostname the IRC server sent us back. - * - * @var string - * @access protected - */ - protected $_remote_host_received = ''; + /** + * String used when creating the stream socket. + * + * @var string + */ + protected $_remote_socket_string = ''; - /** - * String used when creating the stream socket. - * - * @var string - * @access protected - */ - protected $_remote_socket_string = ''; + /** + * Are we using tls/ssl? + * + * @var bool + */ + protected $_remote_tls = false; - /** - * Are we using tls/ssl? - * - * @var bool - * @access protected - */ - protected $_remote_tls = false; + /** + * Time in seconds to timeout on connect. + * + * @var int + */ + protected $_remote_connection_timeout = 30; - /** - * Time in seconds to timeout on connect. - * - * @var int - * @access protected - */ - protected $_remote_connection_timeout = 30; + /** + * Time in seconds before we timeout when sending/receiving a command. + * + * @var int + */ + protected $_socket_timeout = 180; - /** - * Time in seconds before we timeout when sending/receiving a command. - * - * @var int - * @access protected - */ - protected $_socket_timeout = 180; + /** + * How many times to retry when connecting to IRC. + * + * @var int + */ + protected $_reconnectRetries = 3; - /** - * How many times to retry when connecting to IRC. - * - * @var int - * @access protected - */ - protected $_reconnectRetries = 3; + /** + * Seconds to delay when reconnecting fails. + * + * @var int + */ + protected $_reconnectDelay = 5; - /** - * Seconds to delay when reconnecting fails. - * - * @var int - * @access protected - */ - protected $_reconnectDelay = 5; + /** + * Stream socket client. + * + * @var resource + */ + protected $_socket = null; - /** - * Stream socket client. - * - * @var resource - * @access protected - */ - protected $_socket = null; + /** + * Buffer contents. + * + * @var string + */ + protected $_buffer = null; - /** - * Buffer contents. - * - * @var string - * @access protected - */ - protected $_buffer = null; + /** + * When someone types something into a channel, buffer it. + * array( + * 'nickname' => string(The nick name of the person who posted.), + * 'channel' => string(The channel name.), + * 'message' => string(The message the person posted.) + * );. + * + * @note Used with the processChannelMessages() function. + * @var array + */ + protected $_channelData = []; - /** - * When someone types something into a channel, buffer it. - * array( - * 'nickname' => string(The nick name of the person who posted.), - * 'channel' => string(The channel name.), - * 'message' => string(The message the person posted.) - * ); - * - * @note Used with the processChannelMessages() function. - * @var array - * @access protected - */ - protected $_channelData = []; + /** + * Nick name when we log in. + * + * @var string + */ + protected $_nickName; - /** - * Nick name when we log in. - * - * @var string - * @access protected - */ - protected $_nickName; + /** + * User name when we log in. + * + * @var string + */ + protected $_userName; - /** - * User name when we log in. - * - * @var string - * @access protected - */ - protected $_userName; + /** + * "Real" name when we log in. + * + * @var string + */ + protected $_realName; - /** - * "Real" name when we log in. - * - * @var string - * @access protected - */ - protected $_realName; + /** + * Password when we log in. + * + * @var string + */ + protected $_password; - /** - * Password when we log in. - * - * @var string - * @access protected - */ - protected $_password; + /** + * List of channels and passwords to join. + * + * @var array + */ + protected $_channels; - /** - * List of channels and passwords to join. - * - * @var array - * @access protected - */ - protected $_channels; + /** + * Last time we received a ping or sent a ping to the server. + * + * @var int + */ + protected $_lastPing; - /** - * Last time we received a ping or sent a ping to the server. - * - * @var int - * @access protected - */ - protected $_lastPing; + /** + * How many times we've tried to reconnect to IRC. + * + * @var int + */ + protected $_currentRetries = 0; - /** - * How many times we've tried to reconnect to IRC. - * - * @var int - * @access protected - */ - protected $_currentRetries = 0; + /** + * Turns on or off debugging. + * + * @var bool + */ + protected $_debug = true; - /** - * Turns on or off debugging. - * - * @var bool - */ - protected $_debug = true; + /** + * Are we already logged in to IRC? + * + * @var bool + */ + protected $_alreadyLoggedIn = false; - /** - * Are we already logged in to IRC? - * - * @var bool - */ - protected $_alreadyLoggedIn = false; + /** + * Disconnect from IRC. + */ + public function __destruct() + { + $this->quit(); + } - /** - * Disconnect from IRC. - * - * @access public - */ - public function __destruct() - { - $this->quit(); - } + /** + * Time before giving up when trying to read or write to the IRC server. + * The default is fine, it will ping the server if the server does not ping us + * within this time to keep the connection alive. + * + * @param int $timeout Seconds. + */ + public function setSocketTimeout($timeout) + { + if (! is_numeric($timeout)) { + echo 'ERROR: IRC socket timeout must be a number!'.PHP_EOL; + } else { + $this->_socket_timeout = $timeout; + } + } - /** - * Time before giving up when trying to read or write to the IRC server. - * The default is fine, it will ping the server if the server does not ping us - * within this time to keep the connection alive. - * - * @param int $timeout Seconds. - * - * @access public - */ - public function setSocketTimeout($timeout) - { - if (!is_numeric($timeout)) { - echo 'ERROR: IRC socket timeout must be a number!' . PHP_EOL; - } else { - $this->_socket_timeout = $timeout; - } - } + /** + * Amount of time to wait before giving up when connecting. + * + * @param int $timeout Seconds. + */ + public function setConnectionTimeout($timeout) + { + if (! is_numeric($timeout)) { + echo 'ERROR: IRC connection timeout must be a number!'.PHP_EOL; + } else { + $this->_remote_connection_timeout = $timeout; + } + } - /** - * Amount of time to wait before giving up when connecting. - * - * @param int $timeout Seconds. - * - * @access public - */ - public function setConnectionTimeout($timeout) - { - if (!is_numeric($timeout)) { - echo 'ERROR: IRC connection timeout must be a number!' . PHP_EOL; - } else { - $this->_remote_connection_timeout = $timeout; - } - } + /** + * Amount of times to retry before giving up when connecting. + * + * @param int $retries + */ + public function setConnectionRetries($retries) + { + if (! is_numeric($retries)) { + echo 'ERROR: IRC connection retries must be a number!'.PHP_EOL; + } else { + $this->_reconnectRetries = $retries; + } + } - /** - * Amount of times to retry before giving up when connecting. - * - * @param int $retries - * - * @access public - */ - public function setConnectionRetries($retries) - { - if (!is_numeric($retries)) { - echo 'ERROR: IRC connection retries must be a number!' . PHP_EOL; - } else { - $this->_reconnectRetries = $retries; - } - } + /** + * Amount of time to wait between failed connects. + * + * @param int $delay Seconds. + */ + public function setReConnectDelay($delay) + { + if (! is_numeric($delay)) { + echo 'ERROR: IRC reconnect delay must be a number!'.PHP_EOL; + } else { + $this->_reconnectDelay = $delay; + } + } - /** - * Amount of time to wait between failed connects. - * - * @param int $delay Seconds. - * - * @access public - */ - public function setReConnectDelay($delay) - { - if (!is_numeric($delay)) { - echo 'ERROR: IRC reconnect delay must be a number!' . PHP_EOL; - } else { - $this->_reconnectDelay = $delay; - } - } + /** + * Connect to a IRC server. + * + * @param string $hostname Host name of the IRC server (can be a IP or a name). + * @param int $port Port number of the IRC server. + * @param bool $tls Use encryption for the socket transport? (make sure the port is right). + * + * @return bool + */ + public function connect($hostname, $port = 6667, $tls = false) + { + $this->_alreadyLoggedIn = false; + $transport = ($tls === true ? 'tls' : 'tcp'); - /** - * Connect to a IRC server. - * - * @param string $hostname Host name of the IRC server (can be a IP or a name). - * @param int $port Port number of the IRC server. - * @param bool $tls Use encryption for the socket transport? (make sure the port is right). - * - * @return bool - * - * @access public - */ - public function connect($hostname, $port = 6667, $tls = false) - { - $this->_alreadyLoggedIn = false; - $transport = ($tls === true ? 'tls' : 'tcp'); + $socket_string = $transport.'://'.$hostname.':'.$port; + if ($socket_string !== $this->_remote_socket_string || ! $this->_connected()) { + if (! is_string($hostname) || $hostname == '') { + echo 'ERROR: IRC host name must not be empty!'.PHP_EOL; - $socket_string = $transport . '://' . $hostname . ':' . $port; - if ($socket_string !== $this->_remote_socket_string || !$this->_connected()) { - if (!is_string($hostname) || $hostname == '') { - echo 'ERROR: IRC host name must not be empty!' . PHP_EOL; + return false; + } - return false; - } + if (! is_numeric($port)) { + echo 'ERROR: IRC port must be a number!'.PHP_EOL; - if (!is_numeric($port)) { - echo 'ERROR: IRC port must be a number!' . PHP_EOL; + return false; + } - return false; - } + $this->_remote_host = $hostname; + $this->_remote_port = $port; + $this->_remote_transport = $transport; + $this->_remote_tls = $tls; + $this->_remote_socket_string = $socket_string; - $this->_remote_host = $hostname; - $this->_remote_port = $port; - $this->_remote_transport = $transport; - $this->_remote_tls = $tls; - $this->_remote_socket_string = $socket_string; + // Try to connect until we run out of retries. + while ($this->_reconnectRetries >= $this->_currentRetries++) { + $this->_initiateStream(); + if ($this->_connected()) { + break; + } else { + // Sleep between retries. + sleep($this->_reconnectDelay); + } + } + } else { + $this->_alreadyLoggedIn = true; + } - // Try to connect until we run out of retries. - while ($this->_reconnectRetries >= $this->_currentRetries++) { - $this->_initiateStream(); - if ($this->_connected()) { - break; - } else { - // Sleep between retries. - sleep($this->_reconnectDelay); - } - } - } else { - $this->_alreadyLoggedIn = true; - } + // Set last ping time to now. + $this->_lastPing = time(); + // Reset retries. + $this->_currentRetries = $this->_reconnectRetries; - // Set last ping time to now. - $this->_lastPing = time(); - // Reset retries. - $this->_currentRetries = $this->_reconnectRetries; + return $this->_connected(); + } - return $this->_connected(); - } + /** + * Log in to a IRC server. + * + * @param string $nickName The nick name - visible in the channel. + * @param string $userName The user name - visible in the host name. + * @param string $realName The real name - visible in the WhoIs. + * @param null $password The password - some servers require a password. + * + * @return bool + */ + public function login($nickName, $userName, $realName, $password = null) + { + if (! $this->_connected()) { + echo 'ERROR: You must connect to IRC first!'.PHP_EOL; - /** - * Log in to a IRC server. - * - * @param string $nickName The nick name - visible in the channel. - * @param string $userName The user name - visible in the host name. - * @param string $realName The real name - visible in the WhoIs. - * @param null $password The password - some servers require a password. - * - * @return bool - * - * @access public - */ - public function login($nickName, $userName, $realName, $password = null) - { - if (!$this->_connected()) { - echo 'ERROR: You must connect to IRC first!' . PHP_EOL; + return false; + } - return false; - } + if (empty($nickName) || empty($userName) || empty($realName)) { + echo 'ERROR: nick/user/real name must not be empty!'.PHP_EOL; - if (empty($nickName) || empty($userName) || empty($realName)) { - echo 'ERROR: nick/user/real name must not be empty!' . PHP_EOL; + return false; + } - return false; - } + $this->_nickName = $nickName; + $this->_userName = $userName; + $this->_realName = $realName; + $this->_password = $password; - $this->_nickName = $nickName; - $this->_userName = $userName; - $this->_realName = $realName; - $this->_password = $password; + if (($password !== null && ! empty($password)) && ! $this->_writeSocket('PASSWORD '.$password)) { + return false; + } - if (($password !== null && !empty($password)) && !$this->_writeSocket('PASSWORD ' . $password)) { - return false; - } + if (! $this->_writeSocket('NICK '.$nickName)) { + return false; + } - if (!$this->_writeSocket('NICK ' . $nickName)) { - return false; - } + if (! $this->_writeSocket('USER '.$userName.' 0 * :'.$realName)) { + return false; + } - if (!$this->_writeSocket('USER ' . $userName . ' 0 * :' . $realName)) { - return false; - } + // Loop over socket buffer until we find "001". + while (true) { + $this->_readSocket(); - // Loop over socket buffer until we find "001". - while (true) { - $this->_readSocket(); + // We got pinged, reply with a pong. + if (preg_match('/^PING\s*:(.+?)$/', $this->_buffer, $matches)) { + $this->_pong($matches[1]); + } elseif (preg_match('/^:(.*?)\s+(\d+).*?(:.+?)?$/', $this->_buffer, $matches)) { + // We found 001, which means we are logged in. + if ($matches[2] == 001) { + $this->_remote_host_received = $matches[1]; + break; - // We got pinged, reply with a pong. - if (preg_match('/^PING\s*:(.+?)$/', $this->_buffer, $matches)) { - $this->_pong($matches[1]); + // We got 464, which means we need to send a password. + } elseif ($matches[2] == 464) { + // Before the lower check, set the password : username:password + $tempPass = $userName.':'.$password; - } else if (preg_match('/^:(.*?)\s+(\d+).*?(:.+?)?$/', $this->_buffer, $matches)) { - // We found 001, which means we are logged in. - if ($matches[2] == 001) { - $this->_remote_host_received = $matches[1]; - break; + // Check if the user has his password in this format: username/server:password + if (preg_match('/^.+?\/.+?:.+?$/', $password)) { + $tempPass = $password; + } - // We got 464, which means we need to send a password. - } else if ($matches[2] == 464) { - // Before the lower check, set the password : username:password - $tempPass = $userName . ':' . $password; + if ($password !== null && ! $this->_writeSocket('PASS '.$tempPass)) { + return false; + } elseif (isset($matches[3]) && strpos(strtolower($matches[3]), 'invalid password')) { + echo 'Invalid password or username for ('.$this->_remote_host.').'; - // Check if the user has his password in this format: username/server:password - if (preg_match('/^.+?\/.+?:.+?$/', $password)) { - $tempPass = $password; - } + return false; + } + } + //ERROR :Closing Link: kevin123[100.100.100.100] (This server is full.) + } elseif (preg_match('/^ERROR\s*:/', $this->_buffer)) { + echo $this->_buffer.PHP_EOL; - if ($password !== null && !$this->_writeSocket('PASS ' . $tempPass)) { - return false; - } else if (isset($matches[3]) && strpos(strtolower($matches[3]), 'invalid password')) { - echo 'Invalid password or username for (' . $this->_remote_host . ').'; + return false; + } + } - return false; - } - } - //ERROR :Closing Link: kevin123[100.100.100.100] (This server is full.) - } else if (preg_match('/^ERROR\s*:/', $this->_buffer)) { - echo $this->_buffer . PHP_EOL; + return true; + } - return false; - } - } + /** + * Quit from IRC. + * + * @param string $message Optional disconnect message. + * + * @return bool + */ + public function quit($message = null) + { + if ($this->_connected()) { + $this->_writeSocket('QUIT'.($message === null ? '' : ' :'.$message)); + } + $this->_closeStream(); - return true; - } + return $this->_connected(); + } - /** - * Quit from IRC. - * - * @param string $message Optional disconnect message. - * - * @return bool - * - * @access public - */ - public function quit($message = null) - { - if ($this->_connected()) { - $this->_writeSocket('QUIT' . ($message === null ? '' : ' :' . $message)); - } - $this->_closeStream(); + /** + * Read the incoming buffer in a loop. + */ + public function readIncoming() + { + while (true) { + $this->_readSocket(); - return $this->_connected(); - } + // If the server pings us, return it a pong. + if (preg_match('/^PING\s*:(.+?)$/', $this->_buffer, $matches)) { + if ($matches[1] === $this->_remote_host_received) { + $this->_pong($matches[1]); + } - /** - * Read the incoming buffer in a loop. - * - * @access public - */ - public function readIncoming() - { - while (true) { - - $this->_readSocket(); - - // If the server pings us, return it a pong. - if (preg_match('/^PING\s*:(.+?)$/', $this->_buffer, $matches)) { - if ($matches[1] === $this->_remote_host_received) { - $this->_pong($matches[1]); - } - - // Check for a channel message. - } else if (preg_match('/^:(?P<nickname>.+?)\!.+?\s+PRIVMSG\s+(?P<channel>#.+?)\s+:\s*(?P<message>.+?)\s*$/', + // Check for a channel message. + } elseif (preg_match('/^:(?P<nickname>.+?)\!.+?\s+PRIVMSG\s+(?P<channel>#.+?)\s+:\s*(?P<message>.+?)\s*$/', $this->_stripControlCharacters($this->_buffer), $matches ) ) { - - $this->_channelData = - array( + $this->_channelData = + [ 'nickname' => $matches['nickname'], 'channel' => $matches['channel'], - 'message' => $matches['message'] - ); + 'message' => $matches['message'], + ]; - $this->processChannelMessages(); - } + $this->processChannelMessages(); + } - // Ping the server if it has not sent us a ping in a while. - if ((time() - $this->_lastPing) > ($this->_socket_timeout / 2)) { - $this->_ping($this->_remote_host_received); - } - } - } + // Ping the server if it has not sent us a ping in a while. + if ((time() - $this->_lastPing) > ($this->_socket_timeout / 2)) { + $this->_ping($this->_remote_host_received); + } + } + } - /** - * Join a channel or multiple channels. - * - * @param array $channels Array of channels with their passwords (null if the channel doesn't need a password). - * array( '#exampleChannel' => 'thePassword', '#exampleChan2' => null ); - * - * @return bool - * - * @access public - */ - public function joinChannels($channels = []) - { - $this->_channels = $channels; + /** + * Join a channel or multiple channels. + * + * @param array $channels Array of channels with their passwords (null if the channel doesn't need a password). + * array( '#exampleChannel' => 'thePassword', '#exampleChan2' => null ); + * + * @return bool + */ + public function joinChannels($channels = []) + { + $this->_channels = $channels; - if (!$this->_connected()) { - echo 'ERROR: You must connect to IRC first!' . PHP_EOL; + if (! $this->_connected()) { + echo 'ERROR: You must connect to IRC first!'.PHP_EOL; - return false; - } + return false; + } - if (!empty($channels)) { - foreach ($channels as $channel => $password) { - $this->_joinChannel($channel, $password); - } - } + if (! empty($channels)) { + foreach ($channels as $channel => $password) { + $this->_joinChannel($channel, $password); + } + } - return false; - } + return false; + } - /** - * Implementation. - * Extended classes will use this function to parse the messages in the channel using $this->_channelData. - * - * @access protected - */ - protected function processChannelMessages() - { - } + /** + * Implementation. + * Extended classes will use this function to parse the messages in the channel using $this->_channelData. + */ + protected function processChannelMessages() + { + } - /** - * Join a channel. - * - * @param string $channel - * @param string $password - * - * @access protected. - */ - protected function _joinChannel($channel, $password) - { - $this->_writeSocket('JOIN ' . $channel . ($password === null ? '' : ' ' . $password)); - } + /** + * Join a channel. + * + * @param string $channel + * @param string $password + */ + protected function _joinChannel($channel, $password) + { + $this->_writeSocket('JOIN '.$channel.($password === null ? '' : ' '.$password)); + } - /** - * Send PONG to a host. - * - * @param string $host - * - * @access protected - */ - protected function _pong($host) - { - if ($this->_writeSocket('PONG ' . $host) === false) { - $this->_reconnect(); - } + /** + * Send PONG to a host. + * + * @param string $host + */ + protected function _pong($host) + { + if ($this->_writeSocket('PONG '.$host) === false) { + $this->_reconnect(); + } - // If we got a ping from the IRC server, set the last ping time to now. - if ($host === $this->_remote_host_received) { - $this->_lastPing = time(); - } - } + // If we got a ping from the IRC server, set the last ping time to now. + if ($host === $this->_remote_host_received) { + $this->_lastPing = time(); + } + } - /** - * Send PING to a host. - * - * @param string $host - * - * @access protected - */ - protected function _ping($host) - { - $pong = $this->_writeSocket('PING ' . $host); + /** + * Send PING to a host. + * + * @param string $host + */ + protected function _ping($host) + { + $pong = $this->_writeSocket('PING '.$host); - // Check if there's a connection error. - if ($pong === false || ((time() - $this->_lastPing) > ($this->_socket_timeout / 2) && !preg_match('/^PONG/', $this->_buffer))) { - $this->_reconnect(); - } + // Check if there's a connection error. + if ($pong === false || ((time() - $this->_lastPing) > ($this->_socket_timeout / 2) && ! preg_match('/^PONG/', $this->_buffer))) { + $this->_reconnect(); + } - // If sent a ping from the IRC server, set the last ping time to now. - if ($host === $this->_remote_host_received) { - $this->_lastPing = time(); - } - } + // If sent a ping from the IRC server, set the last ping time to now. + if ($host === $this->_remote_host_received) { + $this->_lastPing = time(); + } + } - /** - * Attempt to reconnect to IRC. - * - * @access protected - */ - protected function _reconnect() - { - if (!$this->connect($this->_remote_host, $this->_remote_port, $this->_remote_tls)) { - exit('FATAL: Could not reconnect to (' . $this->_remote_host . ') after (' . $this->_reconnectRetries . ') tries.' . PHP_EOL); - } + /** + * Attempt to reconnect to IRC. + */ + protected function _reconnect() + { + if (! $this->connect($this->_remote_host, $this->_remote_port, $this->_remote_tls)) { + exit('FATAL: Could not reconnect to ('.$this->_remote_host.') after ('.$this->_reconnectRetries.') tries.'.PHP_EOL); + } - if ($this->_alreadyLoggedIn === false) { - if (!$this->login($this->_nickName, $this->_userName, $this->_realName, $this->_password)) { - exit('FATAL: Could not log in to (' . $this->_remote_host . ')!' . PHP_EOL); - } + if ($this->_alreadyLoggedIn === false) { + if (! $this->login($this->_nickName, $this->_userName, $this->_realName, $this->_password)) { + exit('FATAL: Could not log in to ('.$this->_remote_host.')!'.PHP_EOL); + } - $this->joinChannels($this->_channels); - } - } + $this->joinChannels($this->_channels); + } + } - /** - * Read response from the IRC server. - * - * @access protected - */ - protected function _readSocket() - { - $buffer = ''; - do { - stream_set_timeout($this->_socket, $this->_socket_timeout); - $buffer .= fgets($this->_socket, 1024); - } while (!empty($buffer) && !preg_match('/\v+$/', $buffer)); - $this->_buffer = trim($buffer); + /** + * Read response from the IRC server. + */ + protected function _readSocket() + { + $buffer = ''; + do { + stream_set_timeout($this->_socket, $this->_socket_timeout); + $buffer .= fgets($this->_socket, 1024); + } while (! empty($buffer) && ! preg_match('/\v+$/', $buffer)); + $this->_buffer = trim($buffer); - if ($this->_debug && $this->_buffer !== '') { - echo 'RECV ' . $this->_buffer . PHP_EOL; - } - } + if ($this->_debug && $this->_buffer !== '') { + echo 'RECV '.$this->_buffer.PHP_EOL; + } + } - /** - * Send a command to the IRC server. - * - * @param string $command - * - * @return bool - * - * @access protected - */ - protected function _writeSocket($command) - { - $command .= "\r\n"; - for ($written = 0; $written < strlen($command); $written += $fWrite) { - stream_set_timeout($this->_socket, $this->_socket_timeout); - $fWrite = $this->_writeSocketChar(substr($command, $written)); + /** + * Send a command to the IRC server. + * + * @param string $command + * + * @return bool + */ + protected function _writeSocket($command) + { + $command .= "\r\n"; + for ($written = 0; $written < strlen($command); $written += $fWrite) { + stream_set_timeout($this->_socket, $this->_socket_timeout); + $fWrite = $this->_writeSocketChar(substr($command, $written)); - // http://www.php.net/manual/en/function.fwrite.php#96951 | fwrite can return 0 causing an infinite loop. - if ($fWrite === false || $fWrite <= 0) { + // http://www.php.net/manual/en/function.fwrite.php#96951 | fwrite can return 0 causing an infinite loop. + if ($fWrite === false || $fWrite <= 0) { // If it failed, try a second time. - $fWrite = $this->_writeSocketChar(substr($command, $written)); - if ($fWrite === false || $fWrite <= 0) { - echo 'ERROR: Could no write to socket! (the IRC server might have closed the connection)' . PHP_EOL; + $fWrite = $this->_writeSocketChar(substr($command, $written)); + if ($fWrite === false || $fWrite <= 0) { + echo 'ERROR: Could no write to socket! (the IRC server might have closed the connection)'.PHP_EOL; - return false; - } - } - } + return false; + } + } + } - if ($this->_debug) { - echo 'SEND :' . $command; - } + if ($this->_debug) { + echo 'SEND :'.$command; + } - return true; - } + return true; + } - /** - * Write a single character to the socket. - * - * @param string (char) $character A single character. - * - * @return int|bool Number of bytes written or false. - */ - protected function _writeSocketChar($character) - { - return @fwrite($this->_socket, $character); - } + /** + * Write a single character to the socket. + * + * @param string (char) $character A single character. + * + * @return int|bool Number of bytes written or false. + */ + protected function _writeSocketChar($character) + { + return @fwrite($this->_socket, $character); + } - /** - * Initiate stream socket to IRC server. - * - * @access protected - */ - protected function _initiateStream() - { - $this->_closeStream(); + /** + * Initiate stream socket to IRC server. + */ + protected function _initiateStream() + { + $this->_closeStream(); - $socket = stream_socket_client( + $socket = stream_socket_client( $this->_remote_socket_string, $error_number, $error_string, @@ -669,59 +610,53 @@ class IRCClient stream_context_create(Utility::streamSslContextOptions(true)) ); - if ($socket === false) { - echo 'ERROR: ' . $error_string . ' (' . $error_number . ')' . PHP_EOL; - } else { - $this->_socket = $socket; - } - } + if ($socket === false) { + echo 'ERROR: '.$error_string.' ('.$error_number.')'.PHP_EOL; + } else { + $this->_socket = $socket; + } + } - /** - * Close the socket. - * - * @access protected - */ - protected function _closeStream() - { - if (!is_null($this->_socket)) { - $this->_socket = null; - } - } + /** + * Close the socket. + */ + protected function _closeStream() + { + if (! is_null($this->_socket)) { + $this->_socket = null; + } + } - /** - * Check if we are connected to the IRC server. - * - * @return bool - * - * @access protected - */ - protected function _connected() - { - return (is_resource($this->_socket) && !feof($this->_socket)); - } + /** + * Check if we are connected to the IRC server. + * + * @return bool + */ + protected function _connected() + { + return is_resource($this->_socket) && ! feof($this->_socket); + } - /** - * Strips control characters from a IRC message. - * - * @param string $text - * - * @return string - * - * @access protected - */ - protected function _stripControlCharacters($text) - { - return preg_replace( - array( + /** + * Strips control characters from a IRC message. + * + * @param string $text + * + * @return string + */ + protected function _stripControlCharacters($text) + { + return preg_replace( + [ '/(\x03(?:\d{1,2}(?:,\d{1,2})?)?)/', // Color code '/\x02/', // Bold '/\x0F/', // Escaped '/\x16/', // Italic '/\x1F/', // Underline - '/\x12/' // Device control 2 - ), + '/\x12/', // Device control 2 + ], '', $text ); - } + } } diff --git a/nntmux/IRCScraper.php b/nntmux/IRCScraper.php index 5b367eaab..2ba9d4047 100755 --- a/nntmux/IRCScraper.php +++ b/nntmux/IRCScraper.php @@ -1,84 +1,77 @@ <?php + namespace nntmux; + use nntmux\db\DB; /** - * Class IRCScraper + * Class IRCScraper. */ class IRCScraper extends IRCClient { - /** - * Regex to ignore categories. - * @var string|bool - */ - protected $_categoryIgnoreRegex; + /** + * Regex to ignore categories. + * @var string|bool + */ + protected $_categoryIgnoreRegex; - /** - * Array of current pre info. - * @var array - * @access protected - */ - protected $_curPre; + /** + * Array of current pre info. + * @var array + */ + protected $_curPre; - /** - * List of groups and their id's - * @var array - * @access protected - */ - protected $_groupList; + /** + * List of groups and their id's. + * @var array + */ + protected $_groupList; - /** - * Array of ignored channels. - * @var array - */ - protected $_ignoredChannels; + /** + * Array of ignored channels. + * @var array + */ + protected $_ignoredChannels; - /** - * Is this pre nuked or un nuked? - * @var bool - * @access protected - */ - protected $_nuked; + /** + * Is this pre nuked or un nuked? + * @var bool + */ + protected $_nuked; - /** - * Array of old pre info. - * @var array|bool - * @access protected - */ - protected $_oldPre; + /** + * Array of old pre info. + * @var array|bool + */ + protected $_oldPre; - /** - * @var \nntmux\db\DB - * @access protected - */ - protected $_pdo; + /** + * @var \nntmux\db\DB + */ + protected $_pdo; - /** - * Run this in silent mode (no text output). - * @var bool - * @access protected - */ - protected $_silent; + /** + * Run this in silent mode (no text output). + * @var bool + */ + protected $_silent; - /** - * Regex to ignore PRE titles. - * @var string|bool - */ - protected $_titleIgnoreRegex; + /** + * Regex to ignore PRE titles. + * @var string|bool + */ + protected $_titleIgnoreRegex; - /** - * Construct - * - * @param bool $silent Run this in silent mode (no text output). - * @param bool $debug Turn on debug? Shows sent/received socket buffer messages. - * - * @access public - */ - public function __construct(&$silent, &$debug) - { - if (defined('SCRAPE_IRC_SOURCE_IGNORE')) { - $this->_ignoredChannels = unserialize(SCRAPE_IRC_SOURCE_IGNORE, ['allowed_classes' => - ['#a.b.cd.image', + /** + * Construct. + * + * @param bool $silent Run this in silent mode (no text output). + * @param bool $debug Turn on debug? Shows sent/received socket buffer messages. + */ + public function __construct(&$silent, &$debug) + { + if (defined('SCRAPE_IRC_SOURCE_IGNORE')) { + $this->_ignoredChannels = unserialize(SCRAPE_IRC_SOURCE_IGNORE, ['allowed_classes' => ['#a.b.cd.image', '#a.b.console.ps3', '#a.b.dvd', '#a.b.erotica', @@ -97,12 +90,12 @@ class IRCScraper extends IRCClient '#pre@corrupt', '#scnzb', '#tvnzb', - 'srrdb' - ] + 'srrdb', + ], ] ); - } else { - $this->_ignoredChannels = [ + } else { + $this->_ignoredChannels = [ '#a.b.cd.image' => false, '#a.b.console.ps3' => false, '#a.b.dvd' => false, @@ -122,131 +115,126 @@ class IRCScraper extends IRCClient '#pre@corrupt' => false, '#scnzb' => false, '#tvnzb' => false, - 'srrdb' => false + 'srrdb' => false, ]; - } + } - $this->_categoryIgnoreRegex = false; - if (defined('SCRAPE_IRC_CATEGORY_IGNORE') && SCRAPE_IRC_CATEGORY_IGNORE !== '') { - $this->_categoryIgnoreRegex = SCRAPE_IRC_CATEGORY_IGNORE; - } + $this->_categoryIgnoreRegex = false; + if (defined('SCRAPE_IRC_CATEGORY_IGNORE') && SCRAPE_IRC_CATEGORY_IGNORE !== '') { + $this->_categoryIgnoreRegex = SCRAPE_IRC_CATEGORY_IGNORE; + } - $this->_titleIgnoreRegex = false; - if (defined('SCRAPE_IRC_TITLE_IGNORE') && SCRAPE_IRC_TITLE_IGNORE !== '') { - $this->_titleIgnoreRegex = SCRAPE_IRC_TITLE_IGNORE; - } + $this->_titleIgnoreRegex = false; + if (defined('SCRAPE_IRC_TITLE_IGNORE') && SCRAPE_IRC_TITLE_IGNORE !== '') { + $this->_titleIgnoreRegex = SCRAPE_IRC_TITLE_IGNORE; + } - $this->_pdo = new DB(); - $this->_groupList = []; - $this->_silent = $silent; - $this->_debug = $debug; - $this->_resetPreVariables(); - $this->_startScraping(); - } + $this->_pdo = new DB(); + $this->_groupList = []; + $this->_silent = $silent; + $this->_debug = $debug; + $this->_resetPreVariables(); + $this->_startScraping(); + } - public function __destruct() - { - parent::__destruct(); - } + public function __destruct() + { + parent::__destruct(); + } - /** - * Main method for scraping. - * - * @access protected - */ - protected function _startScraping() - { + /** + * Main method for scraping. + */ + protected function _startScraping() + { // Connect to IRC. - if ($this->connect(SCRAPE_IRC_SERVER, SCRAPE_IRC_PORT, SCRAPE_IRC_TLS) === false) { - exit ( - 'Error connecting to (' . - SCRAPE_IRC_SERVER . - ':' . - SCRAPE_IRC_PORT . - '). Please verify your server information and try again.' . + if ($this->connect(SCRAPE_IRC_SERVER, SCRAPE_IRC_PORT, SCRAPE_IRC_TLS) === false) { + exit( + 'Error connecting to ('. + SCRAPE_IRC_SERVER. + ':'. + SCRAPE_IRC_PORT. + '). Please verify your server information and try again.'. PHP_EOL ); - } + } - // Login to IRC. - if ($this->login(SCRAPE_IRC_NICKNAME, SCRAPE_IRC_REALNAME, SCRAPE_IRC_USERNAME, SCRAPE_IRC_PASSWORD) === false) { - exit('Error logging in to: (' . - SCRAPE_IRC_SERVER . ':' . SCRAPE_IRC_PORT . ') nickname: (' . SCRAPE_IRC_NICKNAME . - '). Verify your connection information, you might also be banned from this server or there might have been a connection issue.' . + // Login to IRC. + if ($this->login(SCRAPE_IRC_NICKNAME, SCRAPE_IRC_REALNAME, SCRAPE_IRC_USERNAME, SCRAPE_IRC_PASSWORD) === false) { + exit('Error logging in to: ('. + SCRAPE_IRC_SERVER.':'.SCRAPE_IRC_PORT.') nickname: ('.SCRAPE_IRC_NICKNAME. + '). Verify your connection information, you might also be banned from this server or there might have been a connection issue.'. PHP_EOL ); - } + } - // Join channels. - $channels = defined('SCRAPE_IRC_CHANNELS') ? unserialize(SCRAPE_IRC_CHANNELS, ['allowed_classes' => ['#PreNNTmux', '#nZEDbPRE', '#nZEDbPRE2']]) : ['#PreNNTmux' => null]; - $this->joinChannels($channels); + // Join channels. + $channels = defined('SCRAPE_IRC_CHANNELS') ? unserialize(SCRAPE_IRC_CHANNELS, ['allowed_classes' => ['#PreNNTmux', '#nZEDbPRE', '#nZEDbPRE2']]) : ['#PreNNTmux' => null]; + $this->joinChannels($channels); - if (!$this->_silent) { - echo - '[' . - date('r') . - '] [Scraping of IRC channels for (' . - SCRAPE_IRC_SERVER . - ':' . - SCRAPE_IRC_PORT . - ') (' . - SCRAPE_IRC_NICKNAME . - ') started.]' . + if (! $this->_silent) { + echo + '['. + date('r'). + '] [Scraping of IRC channels for ('. + SCRAPE_IRC_SERVER. + ':'. + SCRAPE_IRC_PORT. + ') ('. + SCRAPE_IRC_NICKNAME. + ') started.]'. PHP_EOL; - } + } - // Scan incoming IRC messages. - $this->readIncoming(); - } + // Scan incoming IRC messages. + $this->readIncoming(); + } - /** - * Process bot messages, insert/update PREs. - * - * @access protected - */ - protected function processChannelMessages() - { - if (preg_match( - '/^(NEW|UPD|NUK): \[DT: (?P<time>.+?)\]\s?\[TT: (?P<title>.+?)\]\s?\[SC: (?P<source>.+?)\]\s?\[CT: (?P<category>.+?)\]\s?\[RQ: (?P<req>.+?)\]' . + /** + * Process bot messages, insert/update PREs. + */ + protected function processChannelMessages() + { + if (preg_match( + '/^(NEW|UPD|NUK): \[DT: (?P<time>.+?)\]\s?\[TT: (?P<title>.+?)\]\s?\[SC: (?P<source>.+?)\]\s?\[CT: (?P<category>.+?)\]\s?\[RQ: (?P<req>.+?)\]'. '\s?\[SZ: (?P<size>.+?)\]\s?\[FL: (?P<files>.+?)\]\s?(\[FN: (?P<filename>.+?)\]\s?)?(\[(?P<nuked>(UN|MOD|RE|OLD)?NUKED?): (?P<reason>.+?)\])?$/i', $this->_channelData['message'], $matches)) { + if (isset($this->_ignoredChannels[$matches['source']]) && $this->_ignoredChannels[$matches['source']] === true) { + return; + } - if (isset($this->_ignoredChannels[$matches['source']]) && $this->_ignoredChannels[$matches['source']] === true) { - return; - } + if ($this->_categoryIgnoreRegex !== false && preg_match((string) $this->_categoryIgnoreRegex, $matches['category'])) { + return; + } - if ($this->_categoryIgnoreRegex !== false && preg_match((string)$this->_categoryIgnoreRegex, $matches['category'])) { - return; - } + if ($this->_titleIgnoreRegex !== false && preg_match((string) $this->_titleIgnoreRegex, $matches['title'])) { + return; + } - if ($this->_titleIgnoreRegex !== false && preg_match((string)$this->_titleIgnoreRegex, $matches['title'])) { - return; - } + $this->_curPre['predate'] = $this->_pdo->from_unixtime(strtotime($matches['time'].' UTC')); + $this->_curPre['title'] = $matches['title']; + $this->_curPre['source'] = $matches['source']; + if ($matches['category'] !== 'N/A') { + $this->_curPre['category'] = $matches['category']; + } + if ($matches['req'] !== 'N/A' && preg_match('/^(?P<req>\d+):(?P<group>.+)$/i', $matches['req'], $matches2)) { + $this->_curPre['reqid'] = $matches2['req']; + $this->_curPre['group_id'] = $this->_getGroupID($matches2['group']); + } + if ($matches['size'] !== 'N/A') { + $this->_curPre['size'] = $matches['size']; + } + if ($matches['files'] !== 'N/A') { + $this->_curPre['files'] = substr($matches['files'], 0, 50); + } - $this->_curPre['predate'] = $this->_pdo->from_unixtime(strtotime($matches['time'] . ' UTC')); - $this->_curPre['title'] = $matches['title']; - $this->_curPre['source'] = $matches['source']; - if ($matches['category'] !== 'N/A') { - $this->_curPre['category'] = $matches['category']; - } - if ($matches['req'] !== 'N/A' && preg_match('/^(?P<req>\d+):(?P<group>.+)$/i', $matches['req'], $matches2)) { - $this->_curPre['reqid'] = $matches2['req']; - $this->_curPre['group_id'] = $this->_getGroupID($matches2['group']); - } - if ($matches['size'] !== 'N/A') { - $this->_curPre['size'] = $matches['size']; - } - if ($matches['files'] !== 'N/A') { - $this->_curPre['files'] = substr($matches['files'], 0, 50); - } + if (isset($matches['filename']) && $matches['filename'] !== 'N/A') { + $this->_curPre['filename'] = $matches['filename']; + } - if (isset($matches['filename']) && $matches['filename'] !== 'N/A') { - $this->_curPre['filename'] = $matches['filename']; - } - - if (isset($matches['nuked'])) { - switch ($matches['nuked']) { + if (isset($matches['nuked'])) { + switch ($matches['nuked']) { case 'NUKED': $this->_curPre['nuked'] = PreDb::PRE_NUKED; break; @@ -263,134 +251,125 @@ class IRCScraper extends IRCClient $this->_curPre['nuked'] = PreDb::PRE_OLDNUKE; break; } - $this->_curPre['reason'] = (isset($matches['reason']) ? substr($matches['reason'], 0, 255) : ''); - } - $this->_checkForDupe(); - } - } + $this->_curPre['reason'] = (isset($matches['reason']) ? substr($matches['reason'], 0, 255) : ''); + } + $this->_checkForDupe(); + } + } - /** - * Check if we already have the PRE, update if we have it, insert if not. - * - * @access protected - */ - protected function _checkForDupe() - { - $this->_oldPre = $this->_pdo->queryOneRow(sprintf('SELECT category, size FROM predb WHERE title = %s', $this->_pdo->escapeString($this->_curPre['title']))); - if ($this->_oldPre === false) { - $this->_insertNewPre(); - } else { - $this->_updatePre(); - } - $this->_resetPreVariables(); - } + /** + * Check if we already have the PRE, update if we have it, insert if not. + */ + protected function _checkForDupe() + { + $this->_oldPre = $this->_pdo->queryOneRow(sprintf('SELECT category, size FROM predb WHERE title = %s', $this->_pdo->escapeString($this->_curPre['title']))); + if ($this->_oldPre === false) { + $this->_insertNewPre(); + } else { + $this->_updatePre(); + } + $this->_resetPreVariables(); + } - /** - * Insert new PRE into the DB. - * - * @access protected - */ - protected function _insertNewPre() - { - if (empty($this->_curPre['title'])) { - return; - } + /** + * Insert new PRE into the DB. + */ + protected function _insertNewPre() + { + if (empty($this->_curPre['title'])) { + return; + } - $query = 'INSERT INTO predb ('; + $query = 'INSERT INTO predb ('; - $query .= (!empty($this->_curPre['size']) ? 'size, ' : ''); - $query .= (!empty($this->_curPre['category']) ? 'category, ' : ''); - $query .= (!empty($this->_curPre['source']) ? 'source, ' : ''); - $query .= (!empty($this->_curPre['reason']) ? 'nukereason, ' : ''); - $query .= (!empty($this->_curPre['files']) ? 'files, ' : ''); - $query .= (!empty($this->_curPre['reqid']) ? 'requestid, ' : ''); - $query .= (!empty($this->_curPre['group_id']) ? 'groups_id, ' : ''); - $query .= (!empty($this->_curPre['nuked']) ? 'nuked, ' : ''); - $query .= (!empty($this->_curPre['filename']) ? 'filename, ' : ''); + $query .= (! empty($this->_curPre['size']) ? 'size, ' : ''); + $query .= (! empty($this->_curPre['category']) ? 'category, ' : ''); + $query .= (! empty($this->_curPre['source']) ? 'source, ' : ''); + $query .= (! empty($this->_curPre['reason']) ? 'nukereason, ' : ''); + $query .= (! empty($this->_curPre['files']) ? 'files, ' : ''); + $query .= (! empty($this->_curPre['reqid']) ? 'requestid, ' : ''); + $query .= (! empty($this->_curPre['group_id']) ? 'groups_id, ' : ''); + $query .= (! empty($this->_curPre['nuked']) ? 'nuked, ' : ''); + $query .= (! empty($this->_curPre['filename']) ? 'filename, ' : ''); - $query .= 'predate, title) VALUES ('; + $query .= 'predate, title) VALUES ('; - $query .= (!empty($this->_curPre['size']) ? $this->_pdo->escapeString($this->_curPre['size']) . ', ' : ''); - $query .= (!empty($this->_curPre['category']) ? $this->_pdo->escapeString($this->_curPre['category']) . ', ' : ''); - $query .= (!empty($this->_curPre['source']) ? $this->_pdo->escapeString($this->_curPre['source']) . ', ' : ''); - $query .= (!empty($this->_curPre['reason']) ? $this->_pdo->escapeString($this->_curPre['reason']) . ', ' : ''); - $query .= (!empty($this->_curPre['files']) ? $this->_pdo->escapeString($this->_curPre['files']) . ', ' : ''); - $query .= (!empty($this->_curPre['reqid']) ? $this->_curPre['reqid'] . ', ' : ''); - $query .= (!empty($this->_curPre['group_id']) ? $this->_curPre['group_id'] . ', ' : ''); - $query .= (!empty($this->_curPre['nuked']) ? $this->_curPre['nuked'] . ', ' : ''); - $query .= (!empty($this->_curPre['filename']) ? $this->_pdo->escapeString($this->_curPre['filename']) . ', ' : ''); - $query .= (!empty($this->_curPre['predate']) ? $this->_curPre['predate'] . ', ' : 'NOW(), '); + $query .= (! empty($this->_curPre['size']) ? $this->_pdo->escapeString($this->_curPre['size']).', ' : ''); + $query .= (! empty($this->_curPre['category']) ? $this->_pdo->escapeString($this->_curPre['category']).', ' : ''); + $query .= (! empty($this->_curPre['source']) ? $this->_pdo->escapeString($this->_curPre['source']).', ' : ''); + $query .= (! empty($this->_curPre['reason']) ? $this->_pdo->escapeString($this->_curPre['reason']).', ' : ''); + $query .= (! empty($this->_curPre['files']) ? $this->_pdo->escapeString($this->_curPre['files']).', ' : ''); + $query .= (! empty($this->_curPre['reqid']) ? $this->_curPre['reqid'].', ' : ''); + $query .= (! empty($this->_curPre['group_id']) ? $this->_curPre['group_id'].', ' : ''); + $query .= (! empty($this->_curPre['nuked']) ? $this->_curPre['nuked'].', ' : ''); + $query .= (! empty($this->_curPre['filename']) ? $this->_pdo->escapeString($this->_curPre['filename']).', ' : ''); + $query .= (! empty($this->_curPre['predate']) ? $this->_curPre['predate'].', ' : 'NOW(), '); - $query .= '%s)'; + $query .= '%s)'; - $this->_pdo->ping(true); + $this->_pdo->ping(true); - $this->_pdo->queryExec( + $this->_pdo->queryExec( sprintf( $query, $this->_pdo->escapeString($this->_curPre['title']) ) ); - $this->_doEcho(true); - } + $this->_doEcho(true); + } - /** - * Updates PRE data in the DB. - * - * @access protected - */ - protected function _updatePre() - { - if (empty($this->_curPre['title'])) { - return; - } + /** + * Updates PRE data in the DB. + */ + protected function _updatePre() + { + if (empty($this->_curPre['title'])) { + return; + } - $query = 'UPDATE predb SET '; + $query = 'UPDATE predb SET '; - $query .= (!empty($this->_curPre['size']) ? 'size = ' . $this->_pdo->escapeString($this->_curPre['size']) . ', ' : ''); - $query .= (!empty($this->_curPre['source']) ? 'source = ' . $this->_pdo->escapeString($this->_curPre['source']) . ', ' : ''); - $query .= (!empty($this->_curPre['files']) ? 'files = ' . $this->_pdo->escapeString($this->_curPre['files']) . ', ' : ''); - $query .= (!empty($this->_curPre['reason']) ? 'nukereason = ' . $this->_pdo->escapeString($this->_curPre['reason']) . ', ' : ''); - $query .= (!empty($this->_curPre['reqid']) ? 'requestid = ' . $this->_curPre['reqid'] . ', ' : ''); - $query .= (!empty($this->_curPre['group_id']) ? 'groups_id = ' . $this->_curPre['group_id'] . ', ' : ''); - $query .= (!empty($this->_curPre['predate']) ? 'predate = ' . $this->_curPre['predate'] . ', ' : ''); - $query .= (!empty($this->_curPre['nuked']) ? 'nuked = ' . $this->_curPre['nuked'] . ', ' : ''); - $query .= (!empty($this->_curPre['filename']) ? 'filename = ' . $this->_pdo->escapeString($this->_curPre['filename']) . ', ' : ''); - $query .= ( - (empty($this->_oldPre['category']) && !empty($this->_curPre['category'])) - ? 'category = ' . $this->_pdo->escapeString($this->_curPre['category']) . ', ' + $query .= (! empty($this->_curPre['size']) ? 'size = '.$this->_pdo->escapeString($this->_curPre['size']).', ' : ''); + $query .= (! empty($this->_curPre['source']) ? 'source = '.$this->_pdo->escapeString($this->_curPre['source']).', ' : ''); + $query .= (! empty($this->_curPre['files']) ? 'files = '.$this->_pdo->escapeString($this->_curPre['files']).', ' : ''); + $query .= (! empty($this->_curPre['reason']) ? 'nukereason = '.$this->_pdo->escapeString($this->_curPre['reason']).', ' : ''); + $query .= (! empty($this->_curPre['reqid']) ? 'requestid = '.$this->_curPre['reqid'].', ' : ''); + $query .= (! empty($this->_curPre['group_id']) ? 'groups_id = '.$this->_curPre['group_id'].', ' : ''); + $query .= (! empty($this->_curPre['predate']) ? 'predate = '.$this->_curPre['predate'].', ' : ''); + $query .= (! empty($this->_curPre['nuked']) ? 'nuked = '.$this->_curPre['nuked'].', ' : ''); + $query .= (! empty($this->_curPre['filename']) ? 'filename = '.$this->_pdo->escapeString($this->_curPre['filename']).', ' : ''); + $query .= ( + (empty($this->_oldPre['category']) && ! empty($this->_curPre['category'])) + ? 'category = '.$this->_pdo->escapeString($this->_curPre['category']).', ' : '' ); - if ($query === 'UPDATE predb SET '){ - return; - } + if ($query === 'UPDATE predb SET ') { + return; + } - $query .= 'title = ' . $this->_pdo->escapeString($this->_curPre['title']); - $query .= ' WHERE title = ' . $this->_pdo->escapeString($this->_curPre['title']); + $query .= 'title = '.$this->_pdo->escapeString($this->_curPre['title']); + $query .= ' WHERE title = '.$this->_pdo->escapeString($this->_curPre['title']); - $this->_pdo->ping(true); + $this->_pdo->ping(true); - $this->_pdo->queryExec($query); + $this->_pdo->queryExec($query); - $this->_doEcho(false); - } + $this->_doEcho(false); + } - /** - * Echo new or update pre to CLI. - * - * @param bool $new - * - * @access protected - */ - protected function _doEcho($new = true) - { - if (!$this->_silent) { - - $nukeString = ''; - if ($this->_nuked !== false) { - switch((int)$this->_curPre['nuked']) { + /** + * Echo new or update pre to CLI. + * + * @param bool $new + */ + protected function _doEcho($new = true) + { + if (! $this->_silent) { + $nukeString = ''; + if ($this->_nuked !== false) { + switch ((int) $this->_curPre['nuked']) { case PreDb::PRE_NUKED: $nukeString = '[ NUKED ] '; break; @@ -409,59 +388,56 @@ class IRCScraper extends IRCClient default: break; } - $nukeString .= '[' . $this->_curPre['reason'] . '] '; - } + $nukeString .= '['.$this->_curPre['reason'].'] '; + } - echo - '[' . - date('r') . - ($new ? '] [ Added Pre ] [' : '] [Updated Pre] [') . - $this->_curPre['source'] . - '] ' . - $nukeString . - '[' . - $this->_curPre['title'] . - ']' . - (!empty($this->_curPre['category']) - ? ' [' . $this->_curPre['category'] . ']' - : (!empty($this->_oldPre['category']) - ? ' [' . $this->_oldPre['category'] . ']' + echo + '['. + date('r'). + ($new ? '] [ Added Pre ] [' : '] [Updated Pre] ['). + $this->_curPre['source']. + '] '. + $nukeString. + '['. + $this->_curPre['title']. + ']'. + (! empty($this->_curPre['category']) + ? ' ['.$this->_curPre['category'].']' + : (! empty($this->_oldPre['category']) + ? ' ['.$this->_oldPre['category'].']' : '' ) - ) . - (!empty($this->_curPre['size']) ? ' [' . $this->_curPre['size'] . ']' : '') . + ). + (! empty($this->_curPre['size']) ? ' ['.$this->_curPre['size'].']' : ''). PHP_EOL; - } - } + } + } - /** - * Get a group id for a group name. - * - * @param string $groupName - * - * @return mixed - * - * @access protected - */ - protected function _getGroupID($groupName) - { - if (!isset($this->_groupList[$groupName])) { - $group = $this->_pdo->queryOneRow(sprintf('SELECT id FROM groups WHERE name = %s', $this->_pdo->escapeString($groupName))); - $this->_groupList[$groupName] = $group['id']; - } - return $this->_groupList[$groupName]; - } + /** + * Get a group id for a group name. + * + * @param string $groupName + * + * @return mixed + */ + protected function _getGroupID($groupName) + { + if (! isset($this->_groupList[$groupName])) { + $group = $this->_pdo->queryOneRow(sprintf('SELECT id FROM groups WHERE name = %s', $this->_pdo->escapeString($groupName))); + $this->_groupList[$groupName] = $group['id']; + } - /** - * After updating or inserting new PRE, reset these. - * - * @access protected - */ - protected function _resetPreVariables() - { - $this->_nuked = false; - $this->_oldPre = []; - $this->_curPre = + return $this->_groupList[$groupName]; + } + + /** + * After updating or inserting new PRE, reset these. + */ + protected function _resetPreVariables() + { + $this->_nuked = false; + $this->_oldPre = []; + $this->_curPre = [ 'title' => '', 'size' => '', @@ -473,7 +449,7 @@ class IRCScraper extends IRCClient 'nuked' => '', 'reason' => '', 'files' => '', - 'filename' => '' + 'filename' => '', ]; - } + } } diff --git a/nntmux/Install.php b/nntmux/Install.php index 087b92ebe..b1971de54 100755 --- a/nntmux/Install.php +++ b/nntmux/Install.php @@ -1,185 +1,187 @@ <?php + namespace nntmux; class Install { - public $DB_SYSTEM; - public $DB_TYPE; - public $DB_HOST = "127.0.0.1"; - public $DB_PORT; - public $DB_SOCKET; - public $DB_USER; - public $DB_PASSWORD; - public $DB_NAME = "nntmux"; - public $NNTP_USERNAME; - public $NNTP_PASSWORD; - public $NNTP_SERVER; - public $NNTP_PORT; - public $NNTP_SSLENABLED; - public $NNTP_SOCKET_TIMEOUT; - public $NNTP_USERNAME_A; - public $NNTP_PASSWORD_A; - public $NNTP_SERVER_A; - public $NNTP_PORT_A; - public $NNTP_SSLENABLED_A; - public $NNTP_SOCKET_TIMEOUT_A; - public $COVERS_PATH; - public $CONFIG_PATH; - public $coverPathCheck = false; - public $SMARTY_DIR; - public $DB_DIR; - public $INSTALL_DIR; - public $ADMIN_USER; - public $ADMIN_FNAME; - public $ADMIN_LNAME; - public $ADMIN_PASS; - public $ADMIN_EMAIL; - public $NZB_PATH; - public $TMP_PATH; - public $UNRAR_PATH; - public $WWW_TOP; - public $COMPILED_CONFIG; - public $doCheck = false; - public $sha1Check; - public $cryptCheck; - public $iconvCheck; - public $PDOCheck; - public $gdCheck; - public $curlCheck; - public $cacheCheck; - public $animeCoversCheck; - public $audioCoversCheck; - public $audiosampleCoversCheck; - public $bookCoversCheck; - public $consoleCoversCheck; - public $movieCoversCheck; - public $musicCoversCheck; - public $previewCoversCheck; - public $sampleCoversCheck; - public $videoCoversCheck; - public $configCheck; - public $lockCheck; - public $pearCheck; - public $schemaCheck; + public $DB_SYSTEM; + public $DB_TYPE; + public $DB_HOST = '127.0.0.1'; + public $DB_PORT; + public $DB_SOCKET; + public $DB_USER; + public $DB_PASSWORD; + public $DB_NAME = 'nntmux'; + public $NNTP_USERNAME; + public $NNTP_PASSWORD; + public $NNTP_SERVER; + public $NNTP_PORT; + public $NNTP_SSLENABLED; + public $NNTP_SOCKET_TIMEOUT; + public $NNTP_USERNAME_A; + public $NNTP_PASSWORD_A; + public $NNTP_SERVER_A; + public $NNTP_PORT_A; + public $NNTP_SSLENABLED_A; + public $NNTP_SOCKET_TIMEOUT_A; + public $COVERS_PATH; + public $CONFIG_PATH; + public $coverPathCheck = false; + public $SMARTY_DIR; + public $DB_DIR; + public $INSTALL_DIR; + public $ADMIN_USER; + public $ADMIN_FNAME; + public $ADMIN_LNAME; + public $ADMIN_PASS; + public $ADMIN_EMAIL; + public $NZB_PATH; + public $TMP_PATH; + public $UNRAR_PATH; + public $WWW_TOP; + public $COMPILED_CONFIG; + public $doCheck = false; + public $sha1Check; + public $cryptCheck; + public $iconvCheck; + public $PDOCheck; + public $gdCheck; + public $curlCheck; + public $cacheCheck; + public $animeCoversCheck; + public $audioCoversCheck; + public $audiosampleCoversCheck; + public $bookCoversCheck; + public $consoleCoversCheck; + public $movieCoversCheck; + public $musicCoversCheck; + public $previewCoversCheck; + public $sampleCoversCheck; + public $videoCoversCheck; + public $configCheck; + public $lockCheck; + public $pearCheck; + public $schemaCheck; - /** - * @var bool Is the PHP version higher than NN_MINIMUM_PHP_VERSION? - */ - public $phpCheck; - public $minPhpVersion = NN_MINIMUM_PHP_VERSION; + /** + * @var bool Is the PHP version higher than NN_MINIMUM_PHP_VERSION? + */ + public $phpCheck; + public $minPhpVersion = NN_MINIMUM_PHP_VERSION; - public $timelimitCheck; - public $memlimitCheck; - public $rewriteCheck; - public $opensslCheck; - public $exifCheck; - public $timezoneCheck; - public $dbConnCheck; - public $dbNameCheck; - public $dbCreateCheck; - public $emessage; - public $nntpCheck; - public $adminCheck; - public $nzbPathCheck; - public $saveConfigCheck; - public $saveLockCheck; - public $error = false; + public $timelimitCheck; + public $memlimitCheck; + public $rewriteCheck; + public $opensslCheck; + public $exifCheck; + public $timezoneCheck; + public $dbConnCheck; + public $dbNameCheck; + public $dbCreateCheck; + public $emessage; + public $nntpCheck; + public $adminCheck; + public $nzbPathCheck; + public $saveConfigCheck; + public $saveLockCheck; + public $error = false; - // Step 3 (openssl) properties. - public $NN_SSL_CAFILE; - public $NN_SSL_CAPATH; - public $NN_SSL_VERIFY_PEER; - public $NN_SSL_VERIFY_HOST; - public $NN_SSL_ALLOW_SELF_SIGNED; + // Step 3 (openssl) properties. + public $NN_SSL_CAFILE; + public $NN_SSL_CAPATH; + public $NN_SSL_VERIFY_PEER; + public $NN_SSL_VERIFY_HOST; + public $NN_SSL_ALLOW_SELF_SIGNED; - // Does the sessions save path have RW permissions? - public $sessionsPathPermissions; + // Does the sessions save path have RW permissions? + public $sessionsPathPermissions; - public function __construct() - { - $this->CONFIG_PATH = NN_CONFIGS; - $this->COVERS_PATH = NN_RES . 'covers' . DS; - $this->DB_DIR = NN_RES . 'db' . DS . 'schema' . DS; - $this->SMARTY_COMPILED_TEMPLATES = NN_RES . 'smarty' . DS . 'templates_c' . DS; - $this->INSTALL_DIR = NN_WWW . 'install'; - $this->NZB_PATH = NN_RES . 'nzb' . DS; - $this->TMP_PATH = NN_RES . 'tmp' . DS; - $this->UNRAR_PATH = $this->TMP_PATH . 'unrar' . DS; - $this->WWW_TOP = NN_WWW; - } + public function __construct() + { + $this->CONFIG_PATH = NN_CONFIGS; + $this->COVERS_PATH = NN_RES.'covers'.DS; + $this->DB_DIR = NN_RES.'db'.DS.'schema'.DS; + $this->SMARTY_COMPILED_TEMPLATES = NN_RES.'smarty'.DS.'templates_c'.DS; + $this->INSTALL_DIR = NN_WWW.'install'; + $this->NZB_PATH = NN_RES.'nzb'.DS; + $this->TMP_PATH = NN_RES.'tmp'.DS; + $this->UNRAR_PATH = $this->TMP_PATH.'unrar'.DS; + $this->WWW_TOP = NN_WWW; + } - public function setSession() - { - $_SESSION['cfg'] = serialize($this); - } + public function setSession() + { + $_SESSION['cfg'] = serialize($this); + } - public function getSession() - { - $tmpCfg = unserialize($_SESSION['cfg']); - $tmpCfg->error = false; - $tmpCfg->doCheck = false; - return $tmpCfg; - } + public function getSession() + { + $tmpCfg = unserialize($_SESSION['cfg']); + $tmpCfg->error = false; + $tmpCfg->doCheck = false; - public function isInitialized() - { - return (isset($_SESSION['cfg']) && is_object(unserialize($_SESSION['cfg']))); - } + return $tmpCfg; + } - public function isLocked() - { - return (file_exists($this->INSTALL_DIR . '/install.lock') ? true : false); - } + public function isInitialized() + { + return isset($_SESSION['cfg']) && is_object(unserialize($_SESSION['cfg'])); + } - public function setConfig($tmpCfg) - { - preg_match_all('/define\((.*?)\)/i', $tmpCfg, $matches); - $defines = $matches[1]; - foreach ($defines as $define) { - $define = str_replace('\'', '', $define); - list($defName, $defVal) = explode(',', $define); - $this->{$defName} = trim($defVal); - } - } + public function isLocked() + { + return file_exists($this->INSTALL_DIR.'/install.lock') ? true : false; + } - public function saveConfig() - { - $tmpCfg = file_get_contents($this->INSTALL_DIR . DS . 'config.php.tpl'); - $tmpCfg = str_replace('%%DB_SYSTEM%%', $this->DB_SYSTEM, $tmpCfg); - $tmpCfg = str_replace('%%DB_HOST%%', $this->DB_HOST, $tmpCfg); - $tmpCfg = str_replace('%%DB_PORT%%', $this->DB_PORT, $tmpCfg); - $tmpCfg = str_replace('%%DB_SOCKET%%', $this->DB_SOCKET, $tmpCfg); - $tmpCfg = str_replace('%%DB_USER%%', $this->DB_USER, $tmpCfg); - $tmpCfg = str_replace('%%DB_PASSWORD%%', $this->DB_PASSWORD, $tmpCfg); - $tmpCfg = str_replace('%%DB_NAME%%', $this->DB_NAME, $tmpCfg); + public function setConfig($tmpCfg) + { + preg_match_all('/define\((.*?)\)/i', $tmpCfg, $matches); + $defines = $matches[1]; + foreach ($defines as $define) { + $define = str_replace('\'', '', $define); + list($defName, $defVal) = explode(',', $define); + $this->{$defName} = trim($defVal); + } + } - $tmpCfg = str_replace('%%NNTP_USERNAME%%', $this->NNTP_USERNAME, $tmpCfg); - $tmpCfg = str_replace('%%NNTP_PASSWORD%%', $this->NNTP_PASSWORD, $tmpCfg); - $tmpCfg = str_replace('%%NNTP_SERVER%%', $this->NNTP_SERVER, $tmpCfg); - $tmpCfg = str_replace('%%NNTP_PORT%%', $this->NNTP_PORT, $tmpCfg); - $tmpCfg = str_replace('%%NNTP_SSLENABLED%%', ($this->NNTP_SSLENABLED ? "true" : "false"), $tmpCfg); - $tmpCfg = str_replace('%%NNTP_SOCKET_TIMEOUT%%', $this->NNTP_SOCKET_TIMEOUT, $tmpCfg); + public function saveConfig() + { + $tmpCfg = file_get_contents($this->INSTALL_DIR.DS.'config.php.tpl'); + $tmpCfg = str_replace('%%DB_SYSTEM%%', $this->DB_SYSTEM, $tmpCfg); + $tmpCfg = str_replace('%%DB_HOST%%', $this->DB_HOST, $tmpCfg); + $tmpCfg = str_replace('%%DB_PORT%%', $this->DB_PORT, $tmpCfg); + $tmpCfg = str_replace('%%DB_SOCKET%%', $this->DB_SOCKET, $tmpCfg); + $tmpCfg = str_replace('%%DB_USER%%', $this->DB_USER, $tmpCfg); + $tmpCfg = str_replace('%%DB_PASSWORD%%', $this->DB_PASSWORD, $tmpCfg); + $tmpCfg = str_replace('%%DB_NAME%%', $this->DB_NAME, $tmpCfg); - $tmpCfg = str_replace('%%NNTP_USERNAME_A%%', $this->NNTP_USERNAME_A, $tmpCfg); - $tmpCfg = str_replace('%%NNTP_PASSWORD_A%%', $this->NNTP_PASSWORD_A, $tmpCfg); - $tmpCfg = str_replace('%%NNTP_SERVER_A%%', $this->NNTP_SERVER_A, $tmpCfg); - $tmpCfg = str_replace('%%NNTP_PORT_A%%', $this->NNTP_PORT_A, $tmpCfg); - $tmpCfg = str_replace('%%NNTP_SSLENABLED_A%%', ($this->NNTP_SSLENABLED_A ? "true" : "false"), $tmpCfg); - $tmpCfg = str_replace('%%NNTP_SOCKET_TIMEOUT_A%%', $this->NNTP_SOCKET_TIMEOUT_A, $tmpCfg); + $tmpCfg = str_replace('%%NNTP_USERNAME%%', $this->NNTP_USERNAME, $tmpCfg); + $tmpCfg = str_replace('%%NNTP_PASSWORD%%', $this->NNTP_PASSWORD, $tmpCfg); + $tmpCfg = str_replace('%%NNTP_SERVER%%', $this->NNTP_SERVER, $tmpCfg); + $tmpCfg = str_replace('%%NNTP_PORT%%', $this->NNTP_PORT, $tmpCfg); + $tmpCfg = str_replace('%%NNTP_SSLENABLED%%', ($this->NNTP_SSLENABLED ? 'true' : 'false'), $tmpCfg); + $tmpCfg = str_replace('%%NNTP_SOCKET_TIMEOUT%%', $this->NNTP_SOCKET_TIMEOUT, $tmpCfg); - $tmpCfg = str_replace('%%NN_SSL_CAFILE%%', $this->NN_SSL_CAFILE, $tmpCfg); - $tmpCfg = str_replace('%%NN_SSL_CAPATH%%', $this->NN_SSL_CAPATH, $tmpCfg); - $tmpCfg = str_replace('%%NN_SSL_VERIFY_PEER%%', $this->NN_SSL_VERIFY_PEER, $tmpCfg); - $tmpCfg = str_replace('%%NN_SSL_VERIFY_HOST%%', $this->NN_SSL_VERIFY_HOST, $tmpCfg); - $tmpCfg = str_replace('%%NN_SSL_ALLOW_SELF_SIGNED%%', $this->NN_SSL_ALLOW_SELF_SIGNED, $tmpCfg); + $tmpCfg = str_replace('%%NNTP_USERNAME_A%%', $this->NNTP_USERNAME_A, $tmpCfg); + $tmpCfg = str_replace('%%NNTP_PASSWORD_A%%', $this->NNTP_PASSWORD_A, $tmpCfg); + $tmpCfg = str_replace('%%NNTP_SERVER_A%%', $this->NNTP_SERVER_A, $tmpCfg); + $tmpCfg = str_replace('%%NNTP_PORT_A%%', $this->NNTP_PORT_A, $tmpCfg); + $tmpCfg = str_replace('%%NNTP_SSLENABLED_A%%', ($this->NNTP_SSLENABLED_A ? 'true' : 'false'), $tmpCfg); + $tmpCfg = str_replace('%%NNTP_SOCKET_TIMEOUT_A%%', $this->NNTP_SOCKET_TIMEOUT_A, $tmpCfg); - $this->COMPILED_CONFIG = $tmpCfg; - return @file_put_contents(NN_CONFIGS . DS . 'config.php', $tmpCfg); - } + $tmpCfg = str_replace('%%NN_SSL_CAFILE%%', $this->NN_SSL_CAFILE, $tmpCfg); + $tmpCfg = str_replace('%%NN_SSL_CAPATH%%', $this->NN_SSL_CAPATH, $tmpCfg); + $tmpCfg = str_replace('%%NN_SSL_VERIFY_PEER%%', $this->NN_SSL_VERIFY_PEER, $tmpCfg); + $tmpCfg = str_replace('%%NN_SSL_VERIFY_HOST%%', $this->NN_SSL_VERIFY_HOST, $tmpCfg); + $tmpCfg = str_replace('%%NN_SSL_ALLOW_SELF_SIGNED%%', $this->NN_SSL_ALLOW_SELF_SIGNED, $tmpCfg); - public function saveInstallLock() - { - return @file_put_contents($this->INSTALL_DIR . DS . 'install.lock', ''); - } + $this->COMPILED_CONFIG = $tmpCfg; + return @file_put_contents(NN_CONFIGS.DS.'config.php', $tmpCfg); + } + + public function saveInstallLock() + { + return @file_put_contents($this->INSTALL_DIR.DS.'install.lock', ''); + } } diff --git a/nntmux/Logger.php b/nntmux/Logger.php index 974a94879..d108fbccd 100755 --- a/nntmux/Logger.php +++ b/nntmux/Logger.php @@ -1,16 +1,17 @@ <?php + namespace nntmux; -use Monolog\Formatter\LineFormatter; use Monolog\Logger as Monolog; use Monolog\Handler\StreamHandler; use Monolog\Processor\GitProcessor; -use Monolog\Processor\IntrospectionProcessor; +use Monolog\Formatter\LineFormatter; use Monolog\Processor\MemoryUsageProcessor; +use Monolog\Processor\IntrospectionProcessor; /** * Show log message to CLI/Web and log it to a file. - * Turn these on in automated.config.php + * Turn these on in automated.config.php. * * @example usage: * @@ -19,392 +20,363 @@ use Monolog\Processor\MemoryUsageProcessor; */ class Logger { - // You can use these constants when using the start method. - const LOG_FATAL = 1; // Fatal error, the program exited. - const LOG_ERROR = 2; // Recoverable error. + // You can use these constants when using the start method. + const LOG_FATAL = 1; // Fatal error, the program exited. + const LOG_ERROR = 2; // Recoverable error. const LOG_WARNING = 3; // Warnings. - const LOG_NOTICE = 4; // Notices. - const LOG_INFO = 5; // Info message, not important. - const LOG_SQL = 6; // Full SQL query when it fails. + const LOG_NOTICE = 4; // Notices. + const LOG_INFO = 5; // Info message, not important. + const LOG_SQL = 6; // Full SQL query when it fails. /** * Name of class we are currently logging. * @var string - * @access private */ - private $class; + private $class; - /** - * Name of method we are currently logging. - * @var string - * @access private - */ - private $method; + /** + * Name of method we are currently logging. + * @var string + */ + private $method; - /** - * The log message. - * @var string - * @access private - */ - private $logMessage = ''; + /** + * The log message. + * @var string + */ + private $logMessage = ''; - /** - * Severity level. - * @var string - * @access private - */ - private $severity = ''; + /** + * Severity level. + * @var string + */ + private $severity = ''; - /** - * @var Monolog - */ - private $logger; + /** + * @var Monolog + */ + private $logger; - /** - * @var LineFormatter - */ - private $formatter; + /** + * @var LineFormatter + */ + private $formatter; - /** - * @var bool - */ - private $outputCLI; + /** + * @var bool + */ + private $outputCLI; - /** - * Is this the windows O/S? - * @var bool - * @access private - */ - private $isWindows; + /** + * Is this the windows O/S? + * @var bool + */ + private $isWindows; - /** - * Unix time instance was created. - * @var int - * @access private - */ - private $timeStart; + /** + * Unix time instance was created. + * @var int + */ + private $timeStart; - /** - * How many old logs can we have max in the logs folder. - * (per log type, ex.: debug can have x logs, not_yEnc can have x logs, etc) - * @var int - * @access private - */ - private $maxLogs; + /** + * How many old logs can we have max in the logs folder. + * (per log type, ex.: debug can have x logs, not_yEnc can have x logs, etc). + * @var int + */ + private $maxLogs; - /** - * Max log size in MegaBytes. - * @var int - * @access private - */ - private $maxLogSize; + /** + * Max log size in MegaBytes. + * @var int + */ + private $maxLogSize; - /** - * Current name of the log file. - * @var string - * @access private - */ - private $currentLogName; + /** + * Current name of the log file. + * @var string + */ + private $currentLogName; - /** - * Current folder to store log files. - * @var string - * @access private - */ - private $currentLogFolder; + /** + * Current folder to store log files. + * @var string + */ + private $currentLogFolder; - /** - * Show memory usage in log/cli out? - * @var bool - * @access private - */ - private $showMemoryUsage; + /** + * Show memory usage in log/cli out? + * @var bool + */ + private $showMemoryUsage; - /** - * Show CPU load in log/cli out? - * @var bool - * @access private - */ - private $showCPULoad; + /** + * Show CPU load in log/cli out? + * @var bool + */ + private $showCPULoad; - /** - * Show running time of script on log/cli out? - * @var bool - * @access private - */ - private $showRunningTime; + /** + * Show running time of script on log/cli out? + * @var bool + */ + private $showRunningTime; - /** - * Show resource usages on log/cli out?. - * @var bool - * @access private - */ - private $showResourceUsage; + /** + * Show resource usages on log/cli out?. + * @var bool + */ + private $showResourceUsage; - /** - * Constructor. - * - * @param array $options (Optional) Class instances. - * (Optional) Folder to store log files in. - * (Optional) Filename of log, must be alphanumeric (a-z 0-9) and contain no file extensions. - * - * @access public - * @throws LoggerException - * @throws \Exception - * @throws \InvalidArgumentException - */ - public function __construct(array $options = []) - { - if (!NN_LOGGING && !NN_DEBUG) { - return; - } + /** + * Constructor. + * + * @param array $options (Optional) Class instances. + * (Optional) Folder to store log files in. + * (Optional) Filename of log, must be alphanumeric (a-z 0-9) and contain no file extensions. + * + * @throws LoggerException + * @throws \Exception + * @throws \InvalidArgumentException + */ + public function __construct(array $options = []) + { + if (! NN_LOGGING && ! NN_DEBUG) { + return; + } - $defaults = [ + $defaults = [ 'ColorCLI' => null, 'LogFolder' => '', - 'LogFileName' => '' + 'LogFileName' => '', ]; - $options += $defaults; + $options += $defaults; - $this->getSettings(); + $this->getSettings(); - $this->currentLogFolder = ( - !empty($options['LogFolder']) + $this->currentLogFolder = ( + ! empty($options['LogFolder']) ? $options['LogFolder'] : $this->currentLogFolder ); - $this->currentLogName = ( - !empty($options['LogFileName']) + $this->currentLogName = ( + ! empty($options['LogFileName']) ? $options['LogFileName'] : $this->currentLogName - ) . '.log'; + ).'.log'; - $this->outputCLI = (strtolower(PHP_SAPI) === 'cli'); - $this->isWindows = stripos(PHP_OS, 'win') === 0; - $this->timeStart = time(); + $this->outputCLI = (strtolower(PHP_SAPI) === 'cli'); + $this->isWindows = stripos(PHP_OS, 'win') === 0; + $this->timeStart = time(); - $this->logger = new Monolog('nntmux'); - $this->formatter = new LineFormatter(null, 'd/M/Y H:i', false, true); - $this->introspection = new IntrospectionProcessor(); - $this->gitprocessor = new GitProcessor(); - $this->memoryUsage = new MemoryUsageProcessor(); - $this->streamHandler = new StreamHandler($this->currentLogFolder . $this->currentLogName, Monolog::DEBUG); - $this->streamHandler->setFormatter($this->formatter); - $this->logger->pushHandler($this->streamHandler); - $this->logger->pushProcessor($this->introspection); - $this->logger->pushProcessor($this->gitprocessor); - if ($this->showMemoryUsage === true) { - $this->logger->pushProcessor($this->memoryUsage); - } + $this->logger = new Monolog('nntmux'); + $this->formatter = new LineFormatter(null, 'd/M/Y H:i', false, true); + $this->introspection = new IntrospectionProcessor(); + $this->gitprocessor = new GitProcessor(); + $this->memoryUsage = new MemoryUsageProcessor(); + $this->streamHandler = new StreamHandler($this->currentLogFolder.$this->currentLogName, Monolog::DEBUG); + $this->streamHandler->setFormatter($this->formatter); + $this->logger->pushHandler($this->streamHandler); + $this->logger->pushProcessor($this->introspection); + $this->logger->pushProcessor($this->gitprocessor); + if ($this->showMemoryUsage === true) { + $this->logger->pushProcessor($this->memoryUsage); + } + } - } + /** + * Public method for logging and/or echoing log messages. + * + * @param string $class The name of the class. + * @param string $method The method this is coming from. + * @param string $message The message to log/echo. + * @param int $severity How severe is this message? + * 1 Fatal - The program had to stop (exit). + * 2 Error - Something went very wrong but we recovered. + * 3 Warning - Not an error, but something we can probably fix. + * 4 Notice - User errors - the user did not enable any groups for example. + * 5 Info - General info, like we logged in to usenet for example. + * 6 Query - Failed SQL queries. (the full query). + */ + public function log($class, $method, $message, $severity) + { + // Check if echo debugging or logging is on. + if (! NN_DEBUG && ! NN_LOGGING) { + return; + } - /** - * Public method for logging and/or echoing log messages. - * - * @param string $class The name of the class. - * @param string $method The method this is coming from. - * @param string $message The message to log/echo. - * @param int $severity How severe is this message? - * 1 Fatal - The program had to stop (exit). - * 2 Error - Something went very wrong but we recovered. - * 3 Warning - Not an error, but something we can probably fix. - * 4 Notice - User errors - the user did not enable any groups for example. - * 5 Info - General info, like we logged in to usenet for example. - * 6 Query - Failed SQL queries. (the full query). - * - * @access public - */ - public function log($class, $method, $message, $severity) - { - // Check if echo debugging or logging is on. - if (!NN_DEBUG && !NN_LOGGING) { - return; - } + $this->severity = $severity; + // Check the severity of the message, if disabled return, if enabled create part of the log message. + if (! $this->checkSeverity()) { + return; + } - $this->severity = $severity; - // Check the severity of the message, if disabled return, if enabled create part of the log message. - if (!$this->checkSeverity()) { - return; - } + $this->class = $class; + $this->method = $method; + $this->logMessage = $message; - $this->class = $class; - $this->method = $method; - $this->logMessage = $message; + $this->formLogMessage(); + $this->echoMessage(); + $this->logMessage(); + } - $this->formLogMessage(); - $this->echoMessage(); - $this->logMessage(); - } + /** + * Get resource usage string. + * + * @return bool|string + */ + public function getResUsage() + { + if (! $this->isWindows) { + $usage = getrusage(); - /** - * Get resource usage string. - * - * @return bool|string - * - * @access public - */ - public function getResUsage() - { - if (!$this->isWindows) { - $usage = getrusage(); + return + 'USR: '.$this->formatTimeString($usage['ru_utime.tv_sec']). + ' SYS: '.$this->formatTimeString($usage['ru_stime.tv_sec']). + ' FAULTS: '.$usage['ru_majflt']. + ' SWAPS: '.$usage['ru_nswap']; + } - return - 'USR: ' . $this->formatTimeString($usage['ru_utime.tv_sec']) . - ' SYS: ' . $this->formatTimeString($usage['ru_stime.tv_sec']) . - ' FAULTS: ' . $usage['ru_majflt'] . - ' SWAPS: ' . $usage['ru_nswap']; - } - return false; - } + return false; + } - /** - * Get system load. - * - * @return string|bool - * - * @access public - */ - public function getSystemLoad() - { - if (!$this->isWindows) { - $string = ''; - // Fix for single digits (2) or single float (2.1). - foreach(sys_getloadavg() as $load) { - $strLen = strlen($load); - if ($strLen === 1) { - $string .= $load . '.00,'; - } elseif ($strLen === 3) { - $string .= str_pad($load, 4, '0', STR_PAD_RIGHT) . ','; - } else { - $string .= $load . ','; - } - } - return substr($string, 0, -1); - } - return false; - } + /** + * Get system load. + * + * @return string|bool + */ + public function getSystemLoad() + { + if (! $this->isWindows) { + $string = ''; + // Fix for single digits (2) or single float (2.1). + foreach (sys_getloadavg() as $load) { + $strLen = strlen($load); + if ($strLen === 1) { + $string .= $load.'.00,'; + } elseif ($strLen === 3) { + $string .= str_pad($load, 4, '0', STR_PAD_RIGHT).','; + } else { + $string .= $load.','; + } + } - /** - * Changes the location of the log file. - * - * @param string $folder Folder where the log should be stored. - * @param string $fileName Name of the file (must be alphanumeric and contain no file extensions). - * - * @access public - * @throws \nntmux\LoggerException - */ - public function changeLogFileLocation($folder, $fileName) - { - $this->currentLogFolder = $folder; - $this->currentLogName = $fileName; - } + return substr($string, 0, -1); + } - /** - * Get the log folder, log name and full path to the default log. - * - * @return array - * @access public - * @static - */ - public static function getDefaultLogPaths() - { - $defaultLogName = (defined('NN_LOGGING_LOG_NAME') ? NN_LOGGING_LOG_NAME : 'nntmux'); - $defaultLogName = (ctype_alnum($defaultLogName) ? $defaultLogName : 'nntmux'); - $defaultLogFolder = (defined('NN_LOGGING_LOG_FOLDER') && is_dir(NN_LOGGING_LOG_FOLDER) ? NN_LOGGING_LOG_FOLDER : NN_LOGS); - $defaultLogFolder = (in_array(substr($defaultLogFolder, -1), ['/', '\\'], false) ? $defaultLogFolder : $defaultLogFolder . DS); - return [ + return false; + } + + /** + * Changes the location of the log file. + * + * @param string $folder Folder where the log should be stored. + * @param string $fileName Name of the file (must be alphanumeric and contain no file extensions). + * + * @throws \nntmux\LoggerException + */ + public function changeLogFileLocation($folder, $fileName) + { + $this->currentLogFolder = $folder; + $this->currentLogName = $fileName; + } + + /** + * Get the log folder, log name and full path to the default log. + * + * @return array + * @static + */ + public static function getDefaultLogPaths() + { + $defaultLogName = (defined('NN_LOGGING_LOG_NAME') ? NN_LOGGING_LOG_NAME : 'nntmux'); + $defaultLogName = (ctype_alnum($defaultLogName) ? $defaultLogName : 'nntmux'); + $defaultLogFolder = (defined('NN_LOGGING_LOG_FOLDER') && is_dir(NN_LOGGING_LOG_FOLDER) ? NN_LOGGING_LOG_FOLDER : NN_LOGS); + $defaultLogFolder = (in_array(substr($defaultLogFolder, -1), ['/', '\\'], false) ? $defaultLogFolder : $defaultLogFolder.DS); + + return [ 'LogFolder' => $defaultLogFolder, 'LogName' => $defaultLogName, - 'LogPath' => $defaultLogFolder . $defaultLogName . '.log' + 'LogPath' => $defaultLogFolder.$defaultLogName.'.log', ]; - } + } + /** + * Get/set all settings. + */ + private function getSettings() + { + $this->maxLogs = (defined('NN_LOGGING_MAX_LOGS') ? NN_LOGGING_MAX_LOGS : 20); + $this->maxLogs = ($this->maxLogs < 1 ? 20 : $this->maxLogs); + $this->maxLogSize = (defined('NN_LOGGING_MAX_SIZE') ? NN_LOGGING_MAX_SIZE : 30); + $this->maxLogSize = ($this->maxLogSize < 1 ? 30 : $this->maxLogSize); + $this->showMemoryUsage = (bool) (defined('NN_LOGGING_LOG_MEMORY_USAGE') ? NN_LOGGING_LOG_MEMORY_USAGE : true); + $this->showCPULoad = (bool) (defined('NN_LOGGING_LOG_CPU_LOAD') ? NN_LOGGING_LOG_CPU_LOAD : true); + $this->showRunningTime = (bool) (defined('NN_LOGGING_LOG_RUNNING_TIME') ? NN_LOGGING_LOG_RUNNING_TIME : true); + $this->showResourceUsage = (bool) (defined('NN_LOGGING_LOG_RESOURCE_USAGE') ? NN_LOGGING_LOG_RESOURCE_USAGE : false); + $paths = self::getDefaultLogPaths(); + $this->currentLogName = $paths['LogName']; + $this->currentLogFolder = $paths['LogFolder']; + } - /** - * Get/set all settings. - * @access private - */ - private function getSettings() - { - $this->maxLogs = (defined('NN_LOGGING_MAX_LOGS') ? NN_LOGGING_MAX_LOGS : 20); - $this->maxLogs = ($this->maxLogs < 1 ? 20 : $this->maxLogs); - $this->maxLogSize = (defined('NN_LOGGING_MAX_SIZE') ? NN_LOGGING_MAX_SIZE : 30); - $this->maxLogSize = ($this->maxLogSize < 1 ? 30 : $this->maxLogSize); - $this->showMemoryUsage = (bool)(defined('NN_LOGGING_LOG_MEMORY_USAGE') ? NN_LOGGING_LOG_MEMORY_USAGE : true); - $this->showCPULoad = (bool)(defined('NN_LOGGING_LOG_CPU_LOAD') ? NN_LOGGING_LOG_CPU_LOAD : true); - $this->showRunningTime = (bool)(defined('NN_LOGGING_LOG_RUNNING_TIME') ? NN_LOGGING_LOG_RUNNING_TIME : true); - $this->showResourceUsage = (bool)(defined('NN_LOGGING_LOG_RESOURCE_USAGE') ? NN_LOGGING_LOG_RESOURCE_USAGE : false); - $paths = self::getDefaultLogPaths(); - $this->currentLogName = $paths['LogName']; - $this->currentLogFolder = $paths['LogFolder']; - } + /** + * Log message to file. + */ + private function logMessage() + { + // Check if debug logging is on. + if (! NN_LOGGING) { + return; + } + $this->logger->debug($this->logMessage); + } - /** - * Log message to file. - * - * @access private - */ - private function logMessage() - { - // Check if debug logging is on. - if (!NN_LOGGING) { - return; - } + /** + * Echo log message to CLI or web. + */ + private function echoMessage() + { + if (! NN_DEBUG) { + return; + } - $this->logger->debug($this->logMessage); - } + // Check if this is CLI or web. + if ($this->outputCLI) { + ColorCLI::doEcho(ColorCLI::debug($this->logMessage)); + } else { + echo '<pre>'.$this->logMessage.'</pre><br />'; + } + } - /** - * Echo log message to CLI or web. - * - * @access private - */ - private function echoMessage() - { - if (!NN_DEBUG) { - return; - } + /** + * Creates the message object for the log message. + */ + private function formLogMessage() + { + $pid = getmypid(); - // Check if this is CLI or web. - if ($this->outputCLI) { - ColorCLI::doEcho(ColorCLI::debug($this->logMessage)); - } else { - echo '<pre>' . $this->logMessage . '</pre><br />'; - } - } - - /** - * Creates the message object for the log message. - * - * @access private - */ - private function formLogMessage() - { - $pid = getmypid(); - - $this->logMessage = + $this->logMessage = // The severity. - $this->severity . + $this->severity. // Average system load. - (($this->showCPULoad && !$this->isWindows) ? ' [' . $this->getSystemLoad() . ']' : '') . + (($this->showCPULoad && ! $this->isWindows) ? ' ['.$this->getSystemLoad().']' : ''). // Script running time. - ($this->showRunningTime ? ' [' . $this->formatTimeString(time() - $this->timeStart) . ']' : '') . + ($this->showRunningTime ? ' ['.$this->formatTimeString(time() - $this->timeStart).']' : ''). // Resource usage (user time, system time, major page faults, memory swaps). - (($this->showResourceUsage && !$this->isWindows) ? ' [' . $this->getResUsage() . ']' : '') . + (($this->showResourceUsage && ! $this->isWindows) ? ' ['.$this->getResUsage().']' : ''). // Running process id. - ($pid ? ' [PID:' . $pid . ']' : '') . + ($pid ? ' [PID:'.$pid.']' : ''). // The class/function. - ' [' . $this->class . '.' . $this->method . ']' . + ' ['.$this->class.'.'.$this->method.']'. - ' [' . + ' ['. // Now reformat the log message, first stripping leading spaces. trim( @@ -415,87 +387,96 @@ class Logger // Removing new lines and carriage returns. str_replace(["\n", '\n', "\r", '\r'], ' ', $this->logMessage) ) - ) . + ). ']'; - return $this->logMessage; - } - /** - * Convert seconds to hours minutes seconds string. - * - * @param int $seconds - * - * @return string - * - * @access private - */ - private function formatTimeString($seconds) - { - $time = ''; - if ($seconds > 3600) { - $time .= str_pad(round(($seconds % 86400) / 3600), 2, '0', STR_PAD_LEFT) . 'H:'; - } else { - $time .= '00H:'; - } - if ($seconds > 60) { - $time .= str_pad(round(($seconds % 3600) / 60), 2 , '0', STR_PAD_LEFT) . 'M:'; - } else { - $time .= '00M:'; - } - $time .= str_pad($seconds % 60, 2 , '0', STR_PAD_LEFT) . 'S'; - return $time; - } + return $this->logMessage; + } - /** - * Check if the user wants to echo or log this message, form part of the log message at the same time. - * - * @return bool - * - * @access private - */ - private function checkSeverity() - { - switch ($this->severity) { + /** + * Convert seconds to hours minutes seconds string. + * + * @param int $seconds + * + * @return string + */ + private function formatTimeString($seconds) + { + $time = ''; + if ($seconds > 3600) { + $time .= str_pad(round(($seconds % 86400) / 3600), 2, '0', STR_PAD_LEFT).'H:'; + } else { + $time .= '00H:'; + } + if ($seconds > 60) { + $time .= str_pad(round(($seconds % 3600) / 60), 2, '0', STR_PAD_LEFT).'M:'; + } else { + $time .= '00M:'; + } + $time .= str_pad($seconds % 60, 2, '0', STR_PAD_LEFT).'S'; + + return $time; + } + + /** + * Check if the user wants to echo or log this message, form part of the log message at the same time. + * + * @return bool + */ + private function checkSeverity() + { + switch ($this->severity) { case self::LOG_FATAL: if (NN_LOGFATAL) { - $this->severity = '[FATAL] '; - return true; + $this->severity = '[FATAL] '; + + return true; } + return false; case self::LOG_ERROR: if (NN_LOGERROR) { - $this->severity = '[ERROR] '; - return true; + $this->severity = '[ERROR] '; + + return true; } + return false; case self::LOG_WARNING: if (NN_LOGWARNING) { - $this->severity = '[WARN] '; - return true; + $this->severity = '[WARN] '; + + return true; } + return false; case self::LOG_NOTICE: if (NN_LOGNOTICE) { - $this->severity = '[NOTICE]'; - return true; + $this->severity = '[NOTICE]'; + + return true; } + return false; case self::LOG_INFO: if (NN_LOGINFO) { - $this->severity = '[INFO] '; - return true; + $this->severity = '[INFO] '; + + return true; } + return false; case self::LOG_SQL: if (NN_LOGQUERIES) { - $this->severity = '[SQL] '; - return true; + $this->severity = '[SQL] '; + + return true; } + return false; default: return false; } - } - + } } diff --git a/nntmux/LoggerException.php b/nntmux/LoggerException.php index 6c50fc578..ec8dfab3c 100755 --- a/nntmux/LoggerException.php +++ b/nntmux/LoggerException.php @@ -19,10 +19,9 @@ * @author niel * @copyright 2015 nZEDb */ -namespace nntmux; +namespace nntmux; class LoggerException extends \Exception { - } diff --git a/nntmux/Logging.php b/nntmux/Logging.php index 70d4b644f..a67450938 100755 --- a/nntmux/Logging.php +++ b/nntmux/Logging.php @@ -1,113 +1,103 @@ <?php + namespace nntmux; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; /** - * Logs/Reports stuff + * Logs/Reports stuff. */ class Logging { - /** - * @var string If windows "\r\n" if unix "\n". - * @access private - */ - private $newLine; + /** + * @var string If windows "\r\n" if unix "\n". + */ + private $newLine; - /** - * @var DB Class instance. - * @access public - */ - public $pdo; + /** + * @var DB Class instance. + */ + public $pdo; - /** - * @var ColorCLI - * @access public - */ - public $colorCLI; + /** + * @var ColorCLI + */ + public $colorCLI; - /** - * Constructor. - * - * @param array $options - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Constructor. + * + * @param array $options + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->newLine = PHP_EOL; - } + $this->newLine = PHP_EOL; + } - /** - * Get all rows from logging table. - * - * @return array - * - * @access public - */ - public function get(): array - { - return $this->pdo->query('SELECT * FROM logging'); - } + /** + * Get all rows from logging table. + * + * @return array + */ + public function get(): array + { + return $this->pdo->query('SELECT * FROM logging'); + } - /** - * Log bad login attempts. - * - * @param string $username - * @param string $host - * - * @return void - * @throws \Exception - * - * @access public - */ - public function LogBadPasswd($username = '', $host = ''): void - { - // If logggingopt is = 0, then we do nothing, 0 = logging off. - $loggingOpt = Settings::value('site.main.loggingopt'); - $logFile = Settings::value('site.main.logfile'); - if ((int)$loggingOpt === 1) { - $this->pdo->queryInsert(sprintf('INSERT INTO logging (time, username, host) VALUES (NOW(), %s, %s)', + /** + * Log bad login attempts. + * + * @param string $username + * @param string $host + * + * @return void + * @throws \Exception + */ + public function LogBadPasswd($username = '', $host = ''): void + { + // If logggingopt is = 0, then we do nothing, 0 = logging off. + $loggingOpt = Settings::value('site.main.loggingopt'); + $logFile = Settings::value('site.main.logfile'); + if ((int) $loggingOpt === 1) { + $this->pdo->queryInsert(sprintf('INSERT INTO logging (time, username, host) VALUES (NOW(), %s, %s)', $this->pdo->escapeString($username), $this->pdo->escapeString($host))); - } else if ((int)$loggingOpt === 2) { - $this->pdo->queryInsert(sprintf('INSERT INTO logging (time, username, host) VALUES (NOW(), %s, %s)', + } elseif ((int) $loggingOpt === 2) { + $this->pdo->queryInsert(sprintf('INSERT INTO logging (time, username, host) VALUES (NOW(), %s, %s)', $this->pdo->escapeString($username), $this->pdo->escapeString($host))); - $logData = date('M d H:i:s ') . 'Login Failed for ' . $username . ' from ' . $host . '.' . + $logData = date('M d H:i:s ').'Login Failed for '.$username.' from '.$host.'.'. $this->newLine; - if ($logFile !== null) { - file_put_contents($logFile, $logData, FILE_APPEND); - } - } else if ((int)$loggingOpt === 3) { - $logData = date('M d H:i:s ') . 'Login Failed for ' . $username . ' from ' . $host . '.' . $this->newLine; - if ($logFile !== null) { - file_put_contents($logFile, $logData, FILE_APPEND); - } - } - } + if ($logFile !== null) { + file_put_contents($logFile, $logData, FILE_APPEND); + } + } elseif ((int) $loggingOpt === 3) { + $logData = date('M d H:i:s ').'Login Failed for '.$username.' from '.$host.'.'.$this->newLine; + if ($logFile !== null) { + file_put_contents($logFile, $logData, FILE_APPEND); + } + } + } - /** - * @return array - * - * @access public - */ - public function getTopCombined(): array - { - return $this->pdo->query('SELECT MAX(time) AS time, username, host, COUNT(host) AS count FROM logging GROUP BY host, username ORDER BY count DESC LIMIT 10'); - } + /** + * @return array + */ + public function getTopCombined(): array + { + return $this->pdo->query('SELECT MAX(time) AS time, username, host, COUNT(host) AS count FROM logging GROUP BY host, username ORDER BY count DESC LIMIT 10'); + } - /** - * @return array - * - * @access public - */ - public function getTopIPs(): array - { - return $this->pdo->query('SELECT MAX(time) AS time, host, COUNT(host) AS count FROM logging GROUP BY host ORDER BY count DESC LIMIT 10'); - } + /** + * @return array + */ + public function getTopIPs(): array + { + return $this->pdo->query('SELECT MAX(time) AS time, host, COUNT(host) AS count FROM logging GROUP BY host ORDER BY count DESC LIMIT 10'); + } } diff --git a/nntmux/Menu.php b/nntmux/Menu.php index 12eac0771..257a5bfcc 100755 --- a/nntmux/Menu.php +++ b/nntmux/Menu.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; use nntmux\db\DB; @@ -8,72 +9,73 @@ use nntmux\db\DB; */ class Menu { - /** - * @var \nntmux\db\DB - */ - public $pdo; + /** + * @var \nntmux\db\DB + */ + public $pdo; - /** - * @param \nntmux\db\DB $settings - */ - public function __construct($settings = null) - { - $this->pdo = ($settings instanceof DB ? $settings : new DB()); - } + /** + * @param \nntmux\db\DB $settings + */ + public function __construct($settings = null) + { + $this->pdo = ($settings instanceof DB ? $settings : new DB()); + } - /** - * @param $role - * @param $serverurl - * - * @return array - */ - public function get($role, $serverurl) - { - $guest = ''; - if ($role !== Users::ROLE_GUEST) { - $guest = sprintf(' AND role != %d ', Users::ROLE_GUEST); - } + /** + * @param $role + * @param $serverurl + * + * @return array + */ + public function get($role, $serverurl) + { + $guest = ''; + if ($role !== Users::ROLE_GUEST) { + $guest = sprintf(' AND role != %d ', Users::ROLE_GUEST); + } - if ($role !== Users::ROLE_ADMIN) { - $guest .= sprintf(' AND role != %d ', Users::ROLE_ADMIN); - } + if ($role !== Users::ROLE_ADMIN) { + $guest .= sprintf(' AND role != %d ', Users::ROLE_ADMIN); + } - $data = $this->pdo->query(sprintf('SELECT * FROM menu WHERE role <= %d %s ORDER BY ordinal', $role, $guest)); + $data = $this->pdo->query(sprintf('SELECT * FROM menu WHERE role <= %d %s ORDER BY ordinal', $role, $guest)); - $ret = []; - foreach ($data as $d) { - if (stripos($d['href'], 'http') === false) { - $d['href'] = $serverurl . $d['href']; - $ret[] = $d; - } else { - $ret[] = $d; - } - } - return $ret; - } + $ret = []; + foreach ($data as $d) { + if (stripos($d['href'], 'http') === false) { + $d['href'] = $serverurl.$d['href']; + $ret[] = $d; + } else { + $ret[] = $d; + } + } - public function getAll() - { - return $this->pdo->query('SELECT * FROM menu ORDER BY role, ordinal'); - } + return $ret; + } - public function getById($id) - { - return $this->pdo->queryOneRow(sprintf('SELECT * FROM menu WHERE id = %d', $id)); - } + public function getAll() + { + return $this->pdo->query('SELECT * FROM menu ORDER BY role, ordinal'); + } - public function delete($id) - { - return $this->pdo->queryExec(sprintf('DELETE FROM menu WHERE id = %d', $id)); - } + public function getById($id) + { + return $this->pdo->queryOneRow(sprintf('SELECT * FROM menu WHERE id = %d', $id)); + } - public function add($menu) - { - return $this->pdo->queryInsert(sprintf('INSERT INTO menu (href, title, tooltip, role, ordinal, menueval, newwindow ) VALUES (%s, %s, %s, %d, %d, %s, %d)', $this->pdo->escapeString($menu['href']), $this->pdo->escapeString($menu['title']), $this->pdo->escapeString($menu['tooltip']), $menu['role'], $menu['ordinal'], $this->pdo->escapeString($menu['menueval']), $menu['newwindow'])); - } + public function delete($id) + { + return $this->pdo->queryExec(sprintf('DELETE FROM menu WHERE id = %d', $id)); + } - public function update($menu) - { - return $this->pdo->queryExec(sprintf('UPDATE menu SET href = %s, title = %s, tooltip = %s, role = %d, ordinal = %d, menueval = %s, newwindow = %d WHERE id = %d', $this->pdo->escapeString($menu['href']), $this->pdo->escapeString($menu['title']), $this->pdo->escapeString($menu['tooltip']), $menu['role'], $menu['ordinal'], $this->pdo->escapeString($menu['menueval']), $menu['newwindow'], $menu['id'])); - } + public function add($menu) + { + return $this->pdo->queryInsert(sprintf('INSERT INTO menu (href, title, tooltip, role, ordinal, menueval, newwindow ) VALUES (%s, %s, %s, %d, %d, %s, %d)', $this->pdo->escapeString($menu['href']), $this->pdo->escapeString($menu['title']), $this->pdo->escapeString($menu['tooltip']), $menu['role'], $menu['ordinal'], $this->pdo->escapeString($menu['menueval']), $menu['newwindow'])); + } + + public function update($menu) + { + return $this->pdo->queryExec(sprintf('UPDATE menu SET href = %s, title = %s, tooltip = %s, role = %d, ordinal = %d, menueval = %s, newwindow = %d WHERE id = %d', $this->pdo->escapeString($menu['href']), $this->pdo->escapeString($menu['title']), $this->pdo->escapeString($menu['tooltip']), $menu['role'], $menu['ordinal'], $this->pdo->escapeString($menu['menueval']), $menu['newwindow'], $menu['id'])); + } } diff --git a/nntmux/MiscSorter.php b/nntmux/MiscSorter.php index b5e77a67b..2084dfa17 100755 --- a/nntmux/MiscSorter.php +++ b/nntmux/MiscSorter.php @@ -1,105 +1,105 @@ <?php + namespace nntmux; -use ApaiIO\ResponseTransformer\XmlToSimpleXmlObject; -use App\Models\Settings; use nntmux\db\DB; -use ApaiIO\Configuration\GenericConfiguration; use ApaiIO\ApaiIO; +use App\Models\Settings; use ApaiIO\Operations\Lookup; - +use ApaiIO\Configuration\GenericConfiguration; +use ApaiIO\ResponseTransformer\XmlToSimpleXmlObject; /** - * Class MiscSorter + * Class MiscSorter. */ class MiscSorter { - - const PROC_SORTER_NONE = 0; //Release has not been run through MiscSorter before + const PROC_SORTER_NONE = 0; //Release has not been run through MiscSorter before const PROC_SORTER_DONE = 1; //Release has been processed by MiscSorter /** * @var int */ - private $qty; + private $qty; - /** - * @var bool - */ - private $echooutput; + /** + * @var bool + */ + private $echooutput; - /** - * @var bool - */ - private $debugging; + /** + * @var bool + */ + private $debugging; - /** - * @var DB - */ - private $pdo; + /** + * @var DB + */ + private $pdo; - /** - * @var Movie - */ - private $movie; + /** + * @var Movie + */ + private $movie; - /** - * @var Music - */ - private $music; + /** + * @var Music + */ + private $music; - /** - * @var array|bool|string - */ - public $pubkey; + /** + * @var array|bool|string + */ + public $pubkey; - /** - * @var array|bool|string - */ - public $privkey; + /** + * @var array|bool|string + */ + public $privkey; - /** - * @var array|bool|string - */ - public $asstag; + /** + * @var array|bool|string + */ + public $asstag; - /** - * @var Books - */ - private $book; + /** + * @var Books + */ + private $book; - /** - * @param bool $echooutput - * @param $pdo - * - * @throws \Exception - */ - public function __construct($echooutput = false, &$pdo) - { - $this->echooutput = (NN_ECHOCLI && $echooutput); + /** + * @param bool $echooutput + * @param $pdo + * + * @throws \Exception + */ + public function __construct($echooutput = false, &$pdo) + { + $this->echooutput = (NN_ECHOCLI && $echooutput); - $this->pdo = ($pdo instanceof DB ? $pdo : new DB()); - $this->movie = new Movie(['Echo' => $this->echooutput, 'Settings' => $this->pdo]); - $this->music = new Music(['Echo' => $this->echooutput, 'Settings' => $this->pdo]); - $this->book = new Books(['Echo' => $this->echooutput, 'Settings' => $this->pdo]); - $this->pubkey = Settings::value('APIs..amazonpubkey'); - $this->privkey = Settings::value('APIs..amazonprivkey'); - $this->asstag = Settings::value('APIs..amazonassociatetag'); - } + $this->pdo = ($pdo instanceof DB ? $pdo : new DB()); + $this->movie = new Movie(['Echo' => $this->echooutput, 'Settings' => $this->pdo]); + $this->music = new Music(['Echo' => $this->echooutput, 'Settings' => $this->pdo]); + $this->book = new Books(['Echo' => $this->echooutput, 'Settings' => $this->pdo]); + $this->pubkey = Settings::value('APIs..amazonpubkey'); + $this->privkey = Settings::value('APIs..amazonprivkey'); + $this->asstag = Settings::value('APIs..amazonassociatetag'); + } - // Main function that determines which operation(s) should be run based on the releases NFO file - /** - * @param int|string $category - * @param int $id - * - * @return bool - */ - public function nfosorter($category, $id) - { - $idarr = ($id !== '' ? sprintf('AND r.id = %d', $id) : ''); - $cat = ($category === '' ? sprintf('AND r.categories_id = %d', Category::OTHER_MISC) : sprintf('AND r.categories_id = %d', $category)); + // Main function that determines which operation(s) should be run based on the releases NFO file - $res = $this->pdo->queryDirect( + /** + * @param int|string $category + * @param int $id + * + * @return bool + */ + public function nfosorter($category, $id) + { + $idarr = ($id !== '' ? sprintf('AND r.id = %d', $id) : ''); + $cat = ($category === '' ? sprintf('AND r.categories_id = %d', Category::OTHER_MISC) : sprintf('AND r.categories_id = %d', $category)); + + $res = $this->pdo->queryDirect( sprintf(' SELECT UNCOMPRESS(rn.nfo) AS nfo, r.id, r.name, r.searchname @@ -114,188 +114,186 @@ class MiscSorter ) ); - if ($res instanceof \Traversable) { + if ($res instanceof \Traversable) { + foreach ($res as $row) { + if (strlen($row['nfo']) > 100) { + $nfo = utf8_decode($row['nfo']); - foreach ($res as $row) { + unset($row['nfo']); + $matches = $this->_sortTypeFromNFO($nfo); - if (strlen($row['nfo']) > 100) { + array_shift($matches); + $matches = $this->doarray($matches); - $nfo = utf8_decode($row['nfo']); + foreach ($matches as $m) { + $case = (isset($m) ? str_replace(' ', '', $m) : ''); - unset($row['nfo']); - $matches = $this->_sortTypeFromNFO($nfo); + if (in_array($m, ['os', 'platform', 'console'], false) && preg_match('/(?:\bos\b(?: type)??|platform|console)[ \.\:\}]+(\w+?).??(\w*?)/iU', $nfo, $set)) { + if (is_array($set)) { + if (isset($set[1])) { + $case = strtolower($set[1]); + } elseif (isset($set[2]) && strlen($set[2]) > 0 && (stripos($set[2], 'mac') !== false || stripos($set[2], 'osx') !== false)) { + $case = strtolower($set[2]); + } else { + $case = str_replace(' ', '', $m); + } + } + } - array_shift($matches); - $matches = $this->doarray($matches); + $pos = $this->nfopos($this->_cleanStrForPos($nfo), $this->_cleanStrForPos($m)); - foreach ($matches as $m) { + if ($pos !== false && $pos > 0.55 && $case !== 'imdb') { + break; + } - $case = (isset($m) ? str_replace(' ', '', $m) : ''); + if ($ret = $this->matchnfo($case, $nfo, $row)) { + return $ret; + } + } + } + } + } + $this->_setProcSorter(self::PROC_SORTER_DONE, $id); - if (in_array($m, ['os', 'platform', 'console'], false) && preg_match('/(?:\bos\b(?: type)??|platform|console)[ \.\:\}]+(\w+?).??(\w*?)/iU', $nfo, $set)) { - if (is_array($set)) { - if (isset($set[1])) { - $case = strtolower($set[1]); - } else if (isset($set[2]) && strlen($set[2]) > 0 && (stripos($set[2], 'mac') !== false || stripos($set[2], 'osx') !== false)) { - $case = strtolower($set[2]); - } else { - $case = str_replace(' ', '', $m); - } - } - } + return false; + } - $pos = $this->nfopos($this->_cleanStrForPos($nfo), $this->_cleanStrForPos($m)); + /** + * @param $nfo + * @param $str + * + * @return bool|float|int + */ + private function nfopos($nfo, $str) + { + $pos = stripos($nfo, $str); + if ($pos !== false) { + return $pos / strlen($nfo); + } - if ($pos !== false && $pos > 0.55 && $case !== 'imdb') { - break; - } + return false; + } - if ($ret = $this->matchnfo($case, $nfo, $row)) { - return $ret; - } - } - } - } - } - $this->_setProcSorter(self::PROC_SORTER_DONE, $id); - return false; - } + /** + * @param $str + * + * @return mixed + */ + private function _cleanStrForPos($str) + { + $str = str_replace([' ', ' ', '\t', '_', '.', '?'], ' ', $str); + $str = preg_replace('/^\s+?/Umi', '', $str); - /** - * @param $nfo - * @param $str - * - * @return bool|float|int - */ - private function nfopos($nfo, $str) - { - $pos = stripos($nfo, $str); - if ($pos !== false) { - return $pos / strlen($nfo); - } + return $str; + } - return false; + /** + * @param $matches + * + * @return array + */ + private function doarray($matches): array + { + $r = []; + $i = 0; - } + $matches = array_count_values($matches); + $matches = array_change_key_case($matches, CASE_LOWER); - /** - * @param $str - * - * @return mixed - */ - private function _cleanStrForPos($str) - { - $str = str_replace([' ', ' ', '\t', '_', '.', '?'], ' ', $str); - $str = preg_replace('/^\s+?/Umi', '', $str); - return $str; - } + foreach ($matches as $m => $v) { + $x = -1; - /** - * @param $matches - * - * @return array - */ - private function doarray($matches): array - { - $r = []; - $i = 0; + if (strlen($m) < 50) { + $str = preg_replace("/\s/iU", '', $m); - $matches = array_count_values($matches); - $matches = array_change_key_case($matches, CASE_LOWER); + $m = strtolower($str); - foreach ($matches as $m => $v) { - $x = -1; + $x = 0; - if (strlen($m) < 50) { - $str = preg_replace("/\s/iU", '', $m); + if ($m === 'imdb') { + $x = -11; + } elseif ($m === 'anidb.net') { + $x = -10; + } elseif ($m === 'upc') { + $x = -9; + } elseif ($m === 'amazon.') { + $x = -8; + } elseif ($m === 'asin' || $m === 'isbn') { + $x = -7; + } elseif ($m === 'tvrage') { + $x = -6; + } elseif ($m === 'audiobook') { + $x = -5; + } elseif ($m === 'os') { + $x = -4; + } elseif (in_array($m, ['mac', 'macintosh', 'dmg', 'macos', 'macosx', 'osx'], false)) { + $x = -3; + } elseif ($m === 'itunes.apple.com/') { + $x = -2; + } elseif (in_array($m, ['documentaries', 'documentary', 'doku'], false)) { + $x = -1; + } elseif (preg_match('/sport|deportes|nhl|nfl|\bnba/i', $m)) { + $x = 1000; + } elseif (preg_match('/avi|xvid|divx|mkv/i', $m)) { + $x = 1001; + } elseif (preg_match('/\.(?:rar|001)/i', $m)) { + $x = 1002; + } elseif (stripos($m, 'pdf') !== false) { + $x = 1003; + } + } - $m = strtolower($str); + if ($x !== -1) { + if ($x === 0) { + $r[$i++] = $m; + } elseif (isset($r[$x])) { + $r[$x + random_int(0, 100) / 100] = $m; + } else { + $r[$x] = $m; + } + } + } + ksort($r); + $r = array_values($r); - $x = 0; + return $r; + } - if ($m === 'imdb') { - $x = -11; - } else if ($m ==='anidb.net') { - $x = -10; - } else if ($m === 'upc') { - $x = -9; - } else if ($m === 'amazon.') { - $x = -8; - } else if ($m === 'asin' || $m === 'isbn') { - $x = -7; - } else if ($m === 'tvrage') { - $x = -6; - } else if ($m === 'audiobook') { - $x = -5; - } else if ($m === 'os') { - $x = -4; - } else if (in_array($m, ['mac', 'macintosh', 'dmg', 'macos', 'macosx', 'osx'], false)) { - $x = -3; - } else if ($m === 'itunes.apple.com/') { - $x = -2; - } else if (in_array($m, ['documentaries', 'documentary', 'doku'], false)) { - $x = -1; - } else if (preg_match('/sport|deportes|nhl|nfl|\bnba/i', $m)) { - $x = 1000; - } else if (preg_match('/avi|xvid|divx|mkv/i', $m)) { - $x = 1001; - } else if (preg_match('/\.(?:rar|001)/i', $m)) { - $x = 1002; - } else if (stripos($m, 'pdf') !== false) { - $x = 1003; - } - } + /** + * This function cleans the release name before updating. + * + * @param string $name + * @return string $name + */ + private function cleanname($name): string + { + do { + $original = $name; + $name = preg_replace('/[\{\[\(]\d+[ \.\-\/]+\d+[\]\}\)]/iU', ' ', $name); + $name = preg_replace('/[\x01-\x1f\!\?\[\{\}\]\/\:\|]+/iU', ' ', $name); + $name = str_replace(' ', ' ', $name); + $name = preg_replace('/^[\s\.]+|[\s\.]{2,}$/iU', '', $name); + $name = str_replace(' - - ', ' - ', $name); + $name = preg_replace('/^[\s\-\_\.]/iU', '', $name); + $name = trim($name); + } while ($original !== $name); - if ($x !== -1) { - if ($x === 0) { - $r[$i++] = $m; - } else if (isset($r[$x])) { - $r[$x + random_int(0, 100) / 100] = $m; - } else { - $r[$x] = $m; - } - } - } - ksort($r); - $r = array_values($r); - return $r; - } + return mb_strimwidth($name, 0, 255); + } - /** - * This function cleans the release name before updating - * - * @param string $name - * @return string $name - */ - private function cleanname($name): string - { - do { - $original = $name; - $name = preg_replace('/[\{\[\(]\d+[ \.\-\/]+\d+[\]\}\)]/iU', ' ', $name); - $name = preg_replace('/[\x01-\x1f\!\?\[\{\}\]\/\:\|]+/iU', ' ', $name); - $name = str_replace(' ', ' ', $name); - $name = preg_replace('/^[\s\.]+|[\s\.]{2,}$/iU', '', $name); - $name = str_replace(' - - ', ' - ', $name); - $name = preg_replace('/^[\s\-\_\.]/iU', '', $name); - $name = trim($name); - } while ($original !== $name); + /** + * @param int $id + * @param string $name + * @param int $typeid + * @param string $type + * + * @return bool + */ + private function dodbupdate($id = 0, $name = '', $typeid = 0, $type = ''): bool + { + $nameChanged = false; - return mb_strimwidth($name, 0, 255); - } - - /** - * @param int $id - * @param string $name - * @param int $typeid - * @param string $type - * - * @return bool - */ - private function dodbupdate($id = 0, $name = '', $typeid = 0, $type = ''): bool - { - $nameChanged = false; - - $release = $this->pdo->queryOneRow( + $release = $this->pdo->queryOneRow( sprintf(' SELECT r.id AS releases_id, r.searchname AS searchname, r.name AS name, r.fromname, r.categories_id, r.groups_id @@ -305,15 +303,15 @@ class MiscSorter ) ); - if ($release !== false && is_array($release) && $name !== '' && $name !== $release['searchname'] && strlen($name) >= 10) { - (new NameFixer(['Settings' => $this->pdo]))->updateRelease($release, $name, $type, true, 'sorter ', 1, 1); - $nameChanged = true; - } else { - $this->_setProcSorter(self::PROC_SORTER_DONE, $id); - } + if ($release !== false && is_array($release) && $name !== '' && $name !== $release['searchname'] && strlen($name) >= 10) { + (new NameFixer(['Settings' => $this->pdo]))->updateRelease($release, $name, $type, true, 'sorter ', 1, 1); + $nameChanged = true; + } else { + $this->_setProcSorter(self::PROC_SORTER_DONE, $id); + } - if ($type !== '' && in_array($type, ['bookinfo_id', 'consoleinfo_id', 'imdbid', 'musicinfo_id'], false)) { - $this->pdo->queryExec( + if ($type !== '' && in_array($type, ['bookinfo_id', 'consoleinfo_id', 'imdbid', 'musicinfo_id'], false)) { + $this->pdo->queryExec( sprintf(' UPDATE releases SET %s = %d @@ -323,149 +321,151 @@ class MiscSorter $id ) ); - } - return $nameChanged; - } + } - /** - * @param string $nfo - * @param int $id - * - * @return bool - */ - private function doOS($nfo = '', $id = 0): bool - { - $ok = false; - $tmp = []; + return $nameChanged; + } - $nfo = preg_replace('/[^\x09-\x80]|\?/', '', $nfo); - $nfo = preg_replace('/[\x01-\x09\x0e-\x20]/', ' ', $nfo); + /** + * @param string $nfo + * @param int $id + * + * @return bool + */ + private function doOS($nfo = '', $id = 0): bool + { + $ok = false; + $tmp = []; - $cleanNfo = $this->_cleanStrForPos($nfo); + $nfo = preg_replace('/[^\x09-\x80]|\?/', '', $nfo); + $nfo = preg_replace('/[\x01-\x09\x0e-\x20]/', ' ', $nfo); - $pattern = '/(?<!fine[ \-\.])(?:\btitle|\bname|release)\b(?![ \-\.]type|[ \-\.]info(?:rmation)?|[ \-\.]date|[ \-\.]name|[ \-\.]notes)(?:[\-\:\.\}\[\s]+?) ?([a-z0-9\.\- \(\)\']+?)/Ui'; - $set = $this->_doOSpregSplit($pattern, $cleanNfo); + $cleanNfo = $this->_cleanStrForPos($nfo); - if (!isset($set[1]) || strlen($set[1]) < 3) { - $pattern = '/(?:(?:presents?|p +r +e +s +e +n +t +s)(?:[^a-z0-9]+?))([a-z0-9 \.\-\_\']+?)/Ui'; - $set = $this->_doOSpregSplit($pattern, $cleanNfo); - } + $pattern = '/(?<!fine[ \-\.])(?:\btitle|\bname|release)\b(?![ \-\.]type|[ \-\.]info(?:rmation)?|[ \-\.]date|[ \-\.]name|[ \-\.]notes)(?:[\-\:\.\}\[\s]+?) ?([a-z0-9\.\- \(\)\']+?)/Ui'; + $set = $this->_doOSpregSplit($pattern, $cleanNfo); - if (isset($set[1])) { - if (preg_match('/^(.+)(\(c\)|\xA9)/i', $set[1], $tmp)) { - $set[1] = $tmp[1]; - } - if (strlen($set[1]) < 128 && !preg_match('/(another)? *(fine)? *release/i', $set[1])) { - $ok = $this->dodbupdate($id, $this->cleanname($set[1]), null, "app"); - } - } + if (! isset($set[1]) || strlen($set[1]) < 3) { + $pattern = '/(?:(?:presents?|p +r +e +s +e +n +t +s)(?:[^a-z0-9]+?))([a-z0-9 \.\-\_\']+?)/Ui'; + $set = $this->_doOSpregSplit($pattern, $cleanNfo); + } - return $ok; - } + if (isset($set[1])) { + if (preg_match('/^(.+)(\(c\)|\xA9)/i', $set[1], $tmp)) { + $set[1] = $tmp[1]; + } + if (strlen($set[1]) < 128 && ! preg_match('/(another)? *(fine)? *release/i', $set[1])) { + $ok = $this->dodbupdate($id, $this->cleanname($set[1]), null, 'app'); + } + } - /** - * @param string $pattern - * @param string $nfo - * - * @return array - */ - private function _doOSpregSplit($pattern = '', $nfo = ''): array - { - return preg_split($pattern, $nfo, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); - } + return $ok; + } - /** - * @param string $nfo - * @param int $imdb - * @param string $name - * - * @return string - */ - private function moviename($nfo = '', $imdb = 0, $name = ''): string - { - $tmp = []; + /** + * @param string $pattern + * @param string $nfo + * + * @return array + */ + private function _doOSpregSplit($pattern = '', $nfo = ''): array + { + return preg_split($pattern, $nfo, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + } - $qual = $this->_getVideoQuality($nfo); + /** + * @param string $nfo + * @param int $imdb + * @param string $name + * + * @return string + */ + private function moviename($nfo = '', $imdb = 0, $name = ''): string + { + $tmp = []; - //Clean up the name - $name = preg_replace('/[a-f0-9]{10,}/i', ' ', $name); - $name = str_replace('\\', ' ', $name); + $qual = $this->_getVideoQuality($nfo); - $name1 = str_replace([' ', '--', '\_\_'], ' ', trim($name)); + //Clean up the name + $name = preg_replace('/[a-f0-9]{10,}/i', ' ', $name); + $name = str_replace('\\', ' ', $name); - if ($imdb > 0) { - $movie = $this->movie->getMovieInfo($imdb); - if ($movie !== false) { - $name2 = ''; - $word = '/' . $movie['title'] . ' ' . $movie['year'] . '/i'; - $tmp[] = preg_split($word, $name1); - if ($tmp instanceof \Traversable) { - foreach ($tmp as $t) { - $name2 .= ' ' . $t[1]; - } - } - $name1 = $name2; - } - } + $name1 = str_replace([' ', '--', '\_\_'], ' ', trim($name)); - $retName = (isset($movie) && $qual !== false ? $movie['title'] . '.' . $movie['year'] . '.' . $name1 . '.' . $qual : $name1); - return trim($retName); - } + if ($imdb > 0) { + $movie = $this->movie->getMovieInfo($imdb); + if ($movie !== false) { + $name2 = ''; + $word = '/'.$movie['title'].' '.$movie['year'].'/i'; + $tmp[] = preg_split($word, $name1); + if ($tmp instanceof \Traversable) { + foreach ($tmp as $t) { + $name2 .= ' '.$t[1]; + } + } + $name1 = $name2; + } + } - /** - * @param string $nfo - * - * @return bool|mixed - */ - private function _getVideoQuality($nfo = '') - { - $qualities = ['(:?..)?tv', '480[ip]?', '640[ip]?', '720[ip]?', '1080[ip]?', 'ac3', 'audio_ts', 'avi', 'bd[\- ]?rip', 'bd25', 'bd50', + $retName = (isset($movie) && $qual !== false ? $movie['title'].'.'.$movie['year'].'.'.$name1.'.'.$qual : $name1); + + return trim($retName); + } + + /** + * @param string $nfo + * + * @return bool|mixed + */ + private function _getVideoQuality($nfo = '') + { + $qualities = ['(:?..)?tv', '480[ip]?', '640[ip]?', '720[ip]?', '1080[ip]?', 'ac3', 'audio_ts', 'avi', 'bd[\- ]?rip', 'bd25', 'bd50', 'bdmv', 'blu ?ray', 'br[\- ]?disk', 'br[\- ]?rip', 'cam', 'cam[\- ]?rip', 'dc', 'directors.?cut', 'divx\d?', 'dts', 'dvd', 'dvd[\- ]?r', 'dvd[\- ]?rip', 'dvd[\- ]?scr', 'extended', 'hd', 'hd[\- ]?tv', 'h264', 'hd[\- ]?cam', 'hd[\- ]?ts', 'iso', 'm2ts', 'mkv', 'mpeg(:?\-\d)?', 'mpg', 'ntsc', 'pal', 'proper', 'ppv', 'ppv[\- ]?rip', 'r\d{1}', 'repack', 'repacked', 'scr', 'screener', 'tc', 'telecine', 'telesync', 'ts', - 'tv[\- ]?rip', 'unrated', 'vhs( ?rip)?', 'video_ts', 'video ts', 'x264', 'xvid', 'web[\- ]?rip']; + 'tv[\- ]?rip', 'unrated', 'vhs( ?rip)?', 'video_ts', 'video ts', 'x264', 'xvid', 'web[\- ]?rip', ]; - foreach ($qualities as $quality) { - if (stripos($nfo, $quality) !== false) { - return $quality; - } - } - return false; - } + foreach ($qualities as $quality) { + if (stripos($nfo, $quality) !== false) { + return $quality; + } + } - /** - * @param string $name - * @param int $id - * @param string $nfo - * @param $q - * @param string $region - * @param bool $case - * @param string $row - * - * @return bool - */ - private function doAmazon($name = '', $id = 0, $nfo = "", $q, $region = 'com', $case = false, $row = ''): bool - { - $conf = new GenericConfiguration(); - try { - $conf + return false; + } + + /** + * @param string $name + * @param int $id + * @param string $nfo + * @param $q + * @param string $region + * @param bool $case + * @param string $row + * + * @return bool + */ + private function doAmazon($name = '', $id = 0, $nfo = '', $q, $region = 'com', $case = false, $row = ''): bool + { + $conf = new GenericConfiguration(); + try { + $conf ->setCountry($region) ->setAccessKey($this->pubkey) ->setSecretKey($this->privkey) ->setAssociateTag($this->asstag) ->setResponseTransformer(new XmlToSimpleXmlObject()); - } catch (\Exception $e) { - echo $e->getMessage(); - } + } catch (\Exception $e) { + echo $e->getMessage(); + } - $amalookup = new Lookup(); + $amalookup = new Lookup(); - $apaiIo = new ApaiIO($conf); - $ok = false; + $apaiIo = new ApaiIO($conf); + $ok = false; - try { - - switch ($case) { + try { + switch ($case) { case 'upc': $amalookup->getName(); $amalookup->setItemId(trim($q)); @@ -491,14 +491,13 @@ class MiscSorter default: $response = false; } + } catch (\Exception $e) { + echo 'Caught exception: ', $e->getMessage().PHP_EOL; + } - } catch (\Exception $e) { - echo 'Caught exception: ', $e->getMessage() . PHP_EOL; - } - - if (isset($response, $response->Items->Item)) { - $type = $response->Items->Item->ItemAttributes->ProductGroup; - switch ($type) { + if (isset($response, $response->Items->Item)) { + $type = $response->Items->Item->ItemAttributes->ProductGroup; + switch ($type) { case 'Audible': case 'Book': case 'eBooks': @@ -519,60 +518,60 @@ class MiscSorter $ok = $this->_doAmazonVG($response, $id); break; default: - echo PHP_EOL . ColorCLI::error("Amazon category $type could not be parsed for " . $name) . PHP_EOL; + echo PHP_EOL.ColorCLI::error("Amazon category $type could not be parsed for ".$name).PHP_EOL; } - } + } - return $ok; - } + return $ok; + } - /** - * Main switch for determining operation type after parsing the NFO file - * - * - * @param array $response - * @param int $id - * - * @return bool - * @throws \Exception - */ - private function _doAmazonBooks(array $response = [], $id = 0): bool - { - $audiobook = false; - $v = (string)$response->Items->Item->ItemAttributes->Format; - if (stripos($v, 'audiobook') !== false) { - $audiobook = true; - } - $new = (string)$response->Items->Item->ItemAttributes->Author; - $name = $new . ' - ' . (string)$response->Items->Item->ItemAttributes->Title; + /** + * Main switch for determining operation type after parsing the NFO file. + * + * + * @param array $response + * @param int $id + * + * @return bool + * @throws \Exception + */ + private function _doAmazonBooks(array $response = [], $id = 0): bool + { + $audiobook = false; + $v = (string) $response->Items->Item->ItemAttributes->Format; + if (stripos($v, 'audiobook') !== false) { + $audiobook = true; + } + $new = (string) $response->Items->Item->ItemAttributes->Author; + $name = $new.' - '.(string) $response->Items->Item->ItemAttributes->Title; - $rel = $this->_doAmazonLocal('bookinfo', (string)$response->Items->Item->ASIN); + $rel = $this->_doAmazonLocal('bookinfo', (string) $response->Items->Item->ASIN); - if (count($rel) === 0) { - $bookId = $this->book->updateBookInfo('', $response); - unset($book); - } else { - $bookId = $rel['id']; - } + if (count($rel) === 0) { + $bookId = $this->book->updateBookInfo('', $response); + unset($book); + } else { + $bookId = $rel['id']; + } - if ($audiobook) { - $ok = $this->dodbupdate($id, $name, $bookId, 'bookinfo_id'); - } else { - $ok = $this->dodbupdate($id, $name, $bookId, 'bookinfo_id'); - } + if ($audiobook) { + $ok = $this->dodbupdate($id, $name, $bookId, 'bookinfo_id'); + } else { + $ok = $this->dodbupdate($id, $name, $bookId, 'bookinfo_id'); + } - return $ok; - } + return $ok; + } - /** - * @param string $table - * @param string $asin - * - * @return array|bool - */ - private function _doAmazonLocal($table = '', $asin = '') - { - return $this->pdo->queryOneRow( + /** + * @param string $table + * @param string $asin + * + * @return array|bool + */ + private function _doAmazonLocal($table = '', $asin = '') + { + return $this->pdo->queryOneRow( sprintf(' SELECT id FROM %s @@ -581,95 +580,94 @@ class MiscSorter $this->pdo->escapeString($asin) ) ); - } + } + /** + * @param array $response + * @param int $id + * + * @return bool + */ + private function _doAmazonMusic($response = [], $id = 0) + { + $new = (string) $response->Items->Item->ItemAttributes->Artist; + if ($new !== '') { + $new .= ' - '; + } + $name = $new.(string) $response->Items->Item->ItemAttributes->Title; - /** - * @param array $response - * @param int $id - * - * @return bool - */ - private function _doAmazonMusic($response = [], $id = 0) - { - $new = (string)$response->Items->Item->ItemAttributes->Artist; - if ($new !== '') { - $new .= ' - '; - } - $name = $new . (string)$response->Items->Item->ItemAttributes->Title; + $rel = $this->_doAmazonLocal('musicinfo', (string) $response->Items->Item->ASIN); - $rel = $this->_doAmazonLocal('musicinfo', (string)$response->Items->Item->ASIN); + if ($rel !== false) { + $ok = $this->dodbupdate($id, $name, $rel['id'], 'musicinfo_id'); + } else { + $musicId = $this->music->updateMusicInfo('', '', $response); + $ok = $this->dodbupdate($id, $name, $musicId, 'musicinfo_id'); + } - if ($rel !== false) { - $ok = $this->dodbupdate($id, $name, $rel['id'], 'musicinfo_id'); - } else { - $musicId = $this->music->updateMusicInfo('', '', $response); - $ok = $this->dodbupdate($id, $name, $musicId, 'musicinfo_id'); - } + return $ok; + } - return $ok; - } + // tries to derive author and title of book from release NFO - // tries to derive author and title of book from release NFO + /** + * @param array $response + * @param int $id + * @param string $nfo + * + * @return bool + */ + private function _doAmazonMovies(array $response = [], $id = 0, $nfo): bool + { + $new = (string) $response->Items->Item->ItemAttributes->Title; + $new = $new.' ('.substr((string) $response->Items->Item->ItemAttributes->ReleaseDate, 0, 4).')'; + $name = $this->moviename($nfo, 0, $new); - /** - * @param array $response - * @param int $id - * @param string $nfo - * - * @return bool - */ - private function _doAmazonMovies(array $response = [], $id = 0, $nfo): bool - { - $new = (string)$response->Items->Item->ItemAttributes->Title; - $new = $new . ' (' . substr((string)$response->Items->Item->ItemAttributes->ReleaseDate, 0, 4) . ')'; - $name = $this->moviename($nfo, 0, $new); + return $this->dodbupdate($id, $name, null, 'amazonMov'); + } - return $this->dodbupdate($id, $name, null, 'amazonMov'); - } + /** + * @param array $response + * @param int $id + * + * @return bool + */ + private function _doAmazonVG($response = [], $id = 0) + { + $name = (string) $response->Items->Item->ItemAttributes->Title; + $name .= '.'.(string) $response->Items->Item->ItemAttributes->Region.'.'; + $name .= '-'.(string) $response->Items->Item->ItemAttributes->Platform; - /** - * @param array $response - * @param int $id - * - * @return bool - */ - private function _doAmazonVG($response = [], $id = 0) - { - $name = (string)$response->Items->Item->ItemAttributes->Title; - $name .= '.' . (string)$response->Items->Item->ItemAttributes->Region . '.'; - $name .= '-' . (string)$response->Items->Item->ItemAttributes->Platform; + $rel = $this->_doAmazonLocal('consoleinfo', (string) $response->Items->Item->ASIN); - $rel = $this->_doAmazonLocal('consoleinfo', (string)$response->Items->Item->ASIN); - - if ($rel !== false) { - $ok = $this->dodbupdate($id, $name, $rel['id'], 'consoleinfo_id'); - } else { - $consoleId = $this->console-> + if ($rel !== false) { + $ok = $this->dodbupdate($id, $name, $rel['id'], 'consoleinfo_id'); + } else { + $consoleId = $this->console-> updateConsoleInfo([ - 'title' => (string)$response->Items->Item->Title, - 'node' => (int)$response->Items->Item->BrowseNodes->BrowseNodeId, - 'platform' => (string)$response->Items->Item->ItemAttributes->Platform + 'title' => (string) $response->Items->Item->Title, + 'node' => (int) $response->Items->Item->BrowseNodes->BrowseNodeId, + 'platform' => (string) $response->Items->Item->ItemAttributes->Platform, ] ); - $ok = $this->dodbupdate($id, $name, $consoleId, 'consoleinfo_id'); - } + $ok = $this->dodbupdate($id, $name, $consoleId, 'consoleinfo_id'); + } - return $ok; - } + return $ok; + } - /** - * @param $case - * @param string $nfo - * @param $row - * - * @return bool - */ - private function matchnfo($case, $nfo, $row) - { - $ok = false; + /** + * @param $case + * @param string $nfo + * @param $row + * + * @return bool + */ + private function matchnfo($case, $nfo, $row) + { + $ok = false; - switch (strtolower($case)) { + switch (strtolower($case)) { case 't r a c k': case 'track': case 'trax': @@ -706,9 +704,9 @@ class MiscSorter case 'game': $set = preg_split('/\>(.*)\</U', $nfo, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); if (isset($set[1])) { - $ok = $this->dodbupdate($row['id'], $this->cleanname($set[1])); + $ok = $this->dodbupdate($row['id'], $this->cleanname($set[1])); } else { - $ok = $this->doOS($nfo, $row['id']); + $ok = $this->doOS($nfo, $row['id']); } break; case 'imdb': @@ -728,130 +726,132 @@ class MiscSorter case 'comix': $ok = $this->dodbupdate($row['id'], $this->cleanname($row['searchname'])); break; - case "asin": - case "isbn": + case 'asin': + case 'isbn': if (preg_match('/(?:isbn|asin)[ \:\.=]*? *?([a-zA-Z0-9\-\.]{8,20}?)/iU', $nfo, $set)) { - $set[1] = str_replace(['-', '.'], '', $set[1]); + $set[1] = str_replace(['-', '.'], '', $set[1]); - if (strlen($set[1]) <= 13) { - $set[2] = $set[1]; - $set[1] = 'com'; - $ok = $this->doAmazon($row['name'], $row['id'], $nfo, $set[2], $set[1], $case, $row); - } + if (strlen($set[1]) <= 13) { + $set[2] = $set[1]; + $set[1] = 'com'; + $ok = $this->doAmazon($row['name'], $row['id'], $nfo, $set[2], $set[1], $case, $row); + } } break; case 'amazon.': if (preg_match('/amazon\.([a-z]*?\.?[a-z]{2,3}?)\/.*\/dp\/([a-zA-Z0-9]{8,10}?)/iU', $nfo, $set)) { - $ok = $this->doAmazon($row['name'], $row['id'], $nfo, $set[2], $set[1], 'asin', $row); + $ok = $this->doAmazon($row['name'], $row['id'], $nfo, $set[2], $set[1], 'asin', $row); } break; case 'upc': if (preg_match('/UPC\:?? *?([a-zA-Z0-9]*?)/iU', $nfo, $set)) { - $set[2] = $set[1]; - $set[1] = 'All'; - $ok = $this->doAmazon($row['name'], $row['id'], $nfo, $set[2], $set[1], $case, $row); + $set[2] = $set[1]; + $set[1] = 'All'; + $ok = $this->doAmazon($row['name'], $row['id'], $nfo, $set[2], $set[1], $case, $row); } break; } - return $ok; - } + return $ok; + } - /** - * Tries to derive artist and title of album/song from release NFO - * - * @param string $nfo - * @param $row - * - * @return bool - */ - private function _matchNfoAudio($nfo, $row): bool - { - if (preg_match('/(a\s?r\s?t\s?i\s?s\s?t|l\s?a\s?b\s?e\s?l|mp3|e\s?n\s?c\s?o\s?d\s?e\s?r|rip|stereo|mono|single charts)/i', $nfo) - && !preg_match('/(\bavi\b|x\.?264|divx|mvk|xvid|install(?!ation)|Setup\.exe|unzip|unrar)/i', $nfo) + /** + * Tries to derive artist and title of album/song from release NFO. + * + * @param string $nfo + * @param $row + * + * @return bool + */ + private function _matchNfoAudio($nfo, $row): bool + { + if (preg_match('/(a\s?r\s?t\s?i\s?s\s?t|l\s?a\s?b\s?e\s?l|mp3|e\s?n\s?c\s?o\s?d\s?e\s?r|rip|stereo|mono|single charts)/i', $nfo) + && ! preg_match('/(\bavi\b|x\.?264|divx|mvk|xvid|install(?!ation)|Setup\.exe|unzip|unrar)/i', $nfo) ) { - $artist = preg_split('/(?:a\s?r\s?t\s?i\s?s\s?t\s?s?\b[^ \.\:]*|a\s?u\s?t\s?h\s?o\s?r\s?s?\b[^ \.\:]*) *?(?!(?:[^\s\.\:\}\]\*\x{2500}-\x{3000}\?] ?){2,}?\b)(?:[\*\?\-\=\|\;\:\.\[\}\]\(\s\x{2500}-\x{3000}\?]+?)[\s\.\>\:\(\)\x{2500}-\x{3000}\?]((?!\:) ?\w.+)(?:\n|$|\s{3}|\.{3})/Uuim', $nfo, 0, PREG_SPLIT_DELIM_CAPTURE); - if(isset($artist[1])) { - $title = preg_split('/(?:t+\s?i+\s?t+\s?l+\s?e+\b|a\s?l\s?b\s?u\s?m\b|r\s?e\s?l\s?e\s?a\s?s\s?e\b) *?(?!(?:[^\s\.\:\}\]\*\x{2500}-\x{3000}\?] ?){2,}?\b)(?:[\*\?\-\=\|\;\:\.\[\}\]\(\s\x{2500}-\x{3000}\?]+?)[\s\.\>\:\(\)\x{2500}-\x{3000}\?]((?!\:) ?\w.+)(?:\n|$|\s{3}|\.{3})/Uuim', $nfo, 0, PREG_SPLIT_DELIM_CAPTURE); - } + $artist = preg_split('/(?:a\s?r\s?t\s?i\s?s\s?t\s?s?\b[^ \.\:]*|a\s?u\s?t\s?h\s?o\s?r\s?s?\b[^ \.\:]*) *?(?!(?:[^\s\.\:\}\]\*\x{2500}-\x{3000}\?] ?){2,}?\b)(?:[\*\?\-\=\|\;\:\.\[\}\]\(\s\x{2500}-\x{3000}\?]+?)[\s\.\>\:\(\)\x{2500}-\x{3000}\?]((?!\:) ?\w.+)(?:\n|$|\s{3}|\.{3})/Uuim', $nfo, 0, PREG_SPLIT_DELIM_CAPTURE); + if (isset($artist[1])) { + $title = preg_split('/(?:t+\s?i+\s?t+\s?l+\s?e+\b|a\s?l\s?b\s?u\s?m\b|r\s?e\s?l\s?e\s?a\s?s\s?e\b) *?(?!(?:[^\s\.\:\}\]\*\x{2500}-\x{3000}\?] ?){2,}?\b)(?:[\*\?\-\=\|\;\:\.\[\}\]\(\s\x{2500}-\x{3000}\?]+?)[\s\.\>\:\(\)\x{2500}-\x{3000}\?]((?!\:) ?\w.+)(?:\n|$|\s{3}|\.{3})/Uuim', $nfo, 0, PREG_SPLIT_DELIM_CAPTURE); + } - if (!isset($title[1], $artist[1])) { - if (preg_match('/presents[\W\. \xb0-\x{3000}]+? ([^\-]+?) \- ([a-z0-9]?(?!\:).+(?:\s\s\s))/iuUm', $nfo, $matches)) { - $artist[1] = $matches[1]; - $title[1] = $matches[2]; - } - if (!isset($matches[2]) && preg_match('/[\h\_\.\:\xb0-\x{3000}]{2,}?([a-z].+) \- (.+?)(?:[\?\s\_\.\:\xb0-\x{3000}]{2,}|$)/Uiu', $nfo, $matches)) { - $pos = $this->nfopos($this->_cleanStrForPos($nfo), $this->_cleanStrForPos($matches[1] . ' - ' . $matches[2])); - if ($pos !== false && $pos < 0.45 && !preg_match('/\:\d\d$/', $matches[2]) && strlen($matches[1]) < 48 && strlen($matches[2]) < 64 + if (! isset($title[1], $artist[1])) { + if (preg_match('/presents[\W\. \xb0-\x{3000}]+? ([^\-]+?) \- ([a-z0-9]?(?!\:).+(?:\s\s\s))/iuUm', $nfo, $matches)) { + $artist[1] = $matches[1]; + $title[1] = $matches[2]; + } + if (! isset($matches[2]) && preg_match('/[\h\_\.\:\xb0-\x{3000}]{2,}?([a-z].+) \- (.+?)(?:[\?\s\_\.\:\xb0-\x{3000}]{2,}|$)/Uiu', $nfo, $matches)) { + $pos = $this->nfopos($this->_cleanStrForPos($nfo), $this->_cleanStrForPos($matches[1].' - '.$matches[2])); + if ($pos !== false && $pos < 0.45 && ! preg_match('/\:\d\d$/', $matches[2]) && strlen($matches[1]) < 48 && strlen($matches[2]) < 64 && strpos('title', $matches[1]) === false && strpos('title', $matches[2]) === false ) { - $artist[1] = $matches[1]; - $title[1] = $matches[2]; - } - } - } - if (empty($artist[1])) { - $artist[1] = $artist[3]; - } - if (isset($title[1],$artist[1])) { - return $this->dodbupdate($row['id'], $this->cleanname($artist[1] . ' - ' . $title[1]), null, 'audioNFO'); - } - } + $artist[1] = $matches[1]; + $title[1] = $matches[2]; + } + } + } + if (empty($artist[1])) { + $artist[1] = $artist[3]; + } + if (isset($title[1],$artist[1])) { + return $this->dodbupdate($row['id'], $this->cleanname($artist[1].' - '.$title[1]), null, 'audioNFO'); + } + } - return false; - } + return false; + } - /** - * Tries to derive the IMDB ID from release - * - * @param string $nfo - * @param $row - * - * @return bool - */ - private function _matchNfoImdb($nfo, $row): bool - { - $imdb = $this->movie->doMovieUpdate($nfo, 'sorter', $row['id']); - if (isset($imdb) && $imdb > 0) { - return $this->dodbupdate($row['id'], $this->moviename($row['id'], $row['searchname']), $imdb, 'imdbid'); - } - return false; - } + /** + * Tries to derive the IMDB ID from release. + * + * @param string $nfo + * @param $row + * + * @return bool + */ + private function _matchNfoImdb($nfo, $row): bool + { + $imdb = $this->movie->doMovieUpdate($nfo, 'sorter', $row['id']); + if (isset($imdb) && $imdb > 0) { + return $this->dodbupdate($row['id'], $this->moviename($row['id'], $row['searchname']), $imdb, 'imdbid'); + } - /** - * Tries to derive author and title of book from release NFO - * - * @param string $nfo - * @param $row - * - * @return bool - */ - private function _matchNfoBook($nfo, $row): bool - { - $author = preg_split('/(?:a\s?u\s?t\s?h\s?o\s?r\b)+? *?(?!(?:[^\s\.\:\}\]\*\xb0-\x{3000}\?] ?){2,}?\b)(?:[\*\?\-\=\|\;\:\.\[\}\]\(\s\xb0-\x{3000}\?]+?)[\s\.\>\:\(\)]((?!\:) ?[a-z0-9\&].+)(?:\s\s\s|$|\.\.\.)/Uuim', $nfo, 0, PREG_SPLIT_DELIM_CAPTURE); - $title = preg_split('/(?:t\s?i\s?t\s?l\s?e\b|b\s?o\s?o\s?k\b)+? *?(?!(?:[^\s\.\:\}\]\*\xb0-\x{3000}\?] ?){2,}?\b)(?:[\*\?\-\=\|\;\:\.\[\}\]\(\s\xb0-\x{3000}\?]+?)[\s\.\>\:\(\)]((?!\:) ?[a-z0-9\&].+)(?:\s\s\s|$|\.\.\.)/Uuim', $nfo, 0, PREG_SPLIT_DELIM_CAPTURE); + return false; + } - if (isset($author[1], $title[1])) { - return $this->dodbupdate($row['id'], Category::MUSIC_AUDIOBOOK, $this->cleanname($author[1] . ' - ' . $title[1])); - } else if (preg_match('/[\h\_\.\:\xb0-\x{3000}]{2,}?([a-z].+) \- (.+)(?:[\s\_\.\:\xb0-\x{3000}]{2,}|$)/iu', $nfo, $matches)) { - $pos = $this->nfopos($this->_cleanStrForPos($nfo), $this->_cleanStrForPos($matches[1] . ' - ' . $matches[2])); - if ($pos !== false && $pos < 0.4 && !preg_match('/\:\d\d$/', $matches[2]) && strlen($matches[1]) < 48 && strlen($matches[2]) < 48 + /** + * Tries to derive author and title of book from release NFO. + * + * @param string $nfo + * @param $row + * + * @return bool + */ + private function _matchNfoBook($nfo, $row): bool + { + $author = preg_split('/(?:a\s?u\s?t\s?h\s?o\s?r\b)+? *?(?!(?:[^\s\.\:\}\]\*\xb0-\x{3000}\?] ?){2,}?\b)(?:[\*\?\-\=\|\;\:\.\[\}\]\(\s\xb0-\x{3000}\?]+?)[\s\.\>\:\(\)]((?!\:) ?[a-z0-9\&].+)(?:\s\s\s|$|\.\.\.)/Uuim', $nfo, 0, PREG_SPLIT_DELIM_CAPTURE); + $title = preg_split('/(?:t\s?i\s?t\s?l\s?e\b|b\s?o\s?o\s?k\b)+? *?(?!(?:[^\s\.\:\}\]\*\xb0-\x{3000}\?] ?){2,}?\b)(?:[\*\?\-\=\|\;\:\.\[\}\]\(\s\xb0-\x{3000}\?]+?)[\s\.\>\:\(\)]((?!\:) ?[a-z0-9\&].+)(?:\s\s\s|$|\.\.\.)/Uuim', $nfo, 0, PREG_SPLIT_DELIM_CAPTURE); + + if (isset($author[1], $title[1])) { + return $this->dodbupdate($row['id'], Category::MUSIC_AUDIOBOOK, $this->cleanname($author[1].' - '.$title[1])); + } elseif (preg_match('/[\h\_\.\:\xb0-\x{3000}]{2,}?([a-z].+) \- (.+)(?:[\s\_\.\:\xb0-\x{3000}]{2,}|$)/iu', $nfo, $matches)) { + $pos = $this->nfopos($this->_cleanStrForPos($nfo), $this->_cleanStrForPos($matches[1].' - '.$matches[2])); + if ($pos !== false && $pos < 0.4 && ! preg_match('/\:\d\d$/', $matches[2]) && strlen($matches[1]) < 48 && strlen($matches[2]) < 48 && strpos('title', $matches[1]) === false && strpos('title', $matches[2]) === false) { - return $this->dodbupdate($row['id'], $this->cleanname($matches[1] . ' - ' . $matches[2]), null, 'bookNFO'); - } - } - return false; - } + return $this->dodbupdate($row['id'], $this->cleanname($matches[1].' - '.$matches[2]), null, 'bookNFO'); + } + } - /** - * Sets the release to its proper status in the database - * - * @param int $status - * @param int $id - */ - private function _setProcSorter($status = 0, $id = 0): void - { - $this->pdo->queryExec( + return false; + } + + /** + * Sets the release to its proper status in the database. + * + * @param int $status + * @param int $id + */ + private function _setProcSorter($status = 0, $id = 0): void + { + $this->pdo->queryExec( sprintf(' UPDATE releases SET proc_sorter = %d @@ -860,27 +860,27 @@ class MiscSorter $id ) ); - } + } - /** - * Derives type of processing to do by preg_splitting NFO file and returning the results of the split - * - * @param string $nfo - * - * @return array - */ - private function _sortTypeFromNFO($nfo = ''): array - { - $pattern = '/.+(\.rar|\.001) [0-9a-f]{6,10}?|(imdb)\.[a-z0-9\.\_\-\/]+?(?:tt|\?)\d+?\/?|(tvrage)\.com\/|(\bASIN)|' . - '(isbn)|(UPC\b)|(comic book)|(comix)|(tv series)|(\bos\b)|(documentaries)|(documentary)|(doku)|(macintosh)|' . - '(dmg)|(mac[ _\.\-]??os[ _\.\-]??x??)|(\bos\b\s??x??)|(\bosx\b)|(\bios\b)|(iphone)|(ipad)|(ipod)|(pdtv)|' . - '(hdtv)|(video streams)|(movie)|(audiobook)|(audible)|(recorded books)|(spoken book)|(speech)|(read by)\:?|' . - '(narrator)\:?|(narrated by)|(dvd)|(ntsc)|(m4v)|(mov\b)|(avi\b)|(xvid)|(divx)|(mkv)|(amazon\.)[a-z]{2,3}.*\/dp\/|' . - '(anidb.net).*aid=|(\blame\b)|(\btrack)|(trax)|(t r a c k)|(music)|(44.1kHz)|video (game)|type:(game)|(game) Type|' . - '(game)[ \.]+|(platform)|(console)|\b(win(?:dows|all|xp)\b)|(\bwin\b)|(m3u)|(flac\b)|(?<!writing )(application)(?! util)|' . - '(plugin)|(\bcrack\b)|(install\b)|(setup)|(magazin)|(x264)|(h264)|(itunes\.apple\.com\/)|(sport)|(deportes)|(nhl)|' . + /** + * Derives type of processing to do by preg_splitting NFO file and returning the results of the split. + * + * @param string $nfo + * + * @return array + */ + private function _sortTypeFromNFO($nfo = ''): array + { + $pattern = '/.+(\.rar|\.001) [0-9a-f]{6,10}?|(imdb)\.[a-z0-9\.\_\-\/]+?(?:tt|\?)\d+?\/?|(tvrage)\.com\/|(\bASIN)|'. + '(isbn)|(UPC\b)|(comic book)|(comix)|(tv series)|(\bos\b)|(documentaries)|(documentary)|(doku)|(macintosh)|'. + '(dmg)|(mac[ _\.\-]??os[ _\.\-]??x??)|(\bos\b\s??x??)|(\bosx\b)|(\bios\b)|(iphone)|(ipad)|(ipod)|(pdtv)|'. + '(hdtv)|(video streams)|(movie)|(audiobook)|(audible)|(recorded books)|(spoken book)|(speech)|(read by)\:?|'. + '(narrator)\:?|(narrated by)|(dvd)|(ntsc)|(m4v)|(mov\b)|(avi\b)|(xvid)|(divx)|(mkv)|(amazon\.)[a-z]{2,3}.*\/dp\/|'. + '(anidb.net).*aid=|(\blame\b)|(\btrack)|(trax)|(t r a c k)|(music)|(44.1kHz)|video (game)|type:(game)|(game) Type|'. + '(game)[ \.]+|(platform)|(console)|\b(win(?:dows|all|xp)\b)|(\bwin\b)|(m3u)|(flac\b)|(?<!writing )(application)(?! util)|'. + '(plugin)|(\bcrack\b)|(install\b)|(setup)|(magazin)|(x264)|(h264)|(itunes\.apple\.com\/)|(sport)|(deportes)|(nhl)|'. '(nfl)|(\bnba)|(ncaa)|(album)|(\bepub\b)|(mobi)|format\W+?[^\r]*(pdf)/iU'; - return preg_split($pattern, $nfo, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); - } + return preg_split($pattern, $nfo, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); + } } diff --git a/nntmux/Movie.php b/nntmux/Movie.php index 8feca2ba2..609a31878 100755 --- a/nntmux/Movie.php +++ b/nntmux/Movie.php @@ -1,234 +1,235 @@ <?php + namespace nntmux; -use App\Models\Settings; +use nntmux\db\DB; +use Tmdb\ApiToken; use aharen\OMDbAPI; use GuzzleHttp\Client; -use GuzzleHttp\Exception\RequestException; -use nntmux\db\DB; -use nntmux\libraries\FanartTV; +use App\Models\Settings; use nntmux\utility\Utility; -use nntmux\processing\tv\TraktTv; -use Tmdb\ApiToken; +use nntmux\libraries\FanartTV; use Tmdb\Client as TmdbClient; +use nntmux\processing\tv\TraktTv; use Tmdb\Exception\TmdbApiException; +use GuzzleHttp\Exception\RequestException; /** - * Class Movie + * Class Movie. */ class Movie { - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * Current title being passed through various sites/api's. - * @var string - */ - protected $currentTitle = ''; + /** + * Current title being passed through various sites/api's. + * @var string + */ + protected $currentTitle = ''; - /** - * Current year of parsed search name. - * @var string - */ - protected $currentYear = ''; + /** + * Current year of parsed search name. + * @var string + */ + protected $currentYear = ''; - /** - * Current release id of parsed search name. - * - * @var string - */ - protected $currentRelID = ''; + /** + * Current release id of parsed search name. + * + * @var string + */ + protected $currentRelID = ''; - /** - * @var Logger - */ - protected $debugging; + /** + * @var Logger + */ + protected $debugging; - /** - * @var bool - */ - protected $debug; + /** + * @var bool + */ + protected $debug; - /** - * Use search engines to find IMDB id's. - * @var bool - */ - protected $searchEngines; + /** + * Use search engines to find IMDB id's. + * @var bool + */ + protected $searchEngines; - /** - * How many times have we hit google this session. - * @var int - */ - protected $googleLimit = 0; + /** + * How many times have we hit google this session. + * @var int + */ + protected $googleLimit = 0; - /** - * If we are temp banned from google, set time we were banned here, try again after 10 minutes. - * @var int - */ - protected $googleBan = 0; + /** + * If we are temp banned from google, set time we were banned here, try again after 10 minutes. + * @var int + */ + protected $googleBan = 0; - /** - * How many times have we hit bing this session. - * - * @var int - */ - protected $bingLimit = 0; + /** + * How many times have we hit bing this session. + * + * @var int + */ + protected $bingLimit = 0; - /** - * How many times have we hit yahoo this session. - * - * @var int - */ - protected $yahooLimit = 0; + /** + * How many times have we hit yahoo this session. + * + * @var int + */ + protected $yahooLimit = 0; - /** - * @var string - */ - protected $showPasswords; + /** + * @var string + */ + protected $showPasswords; - /** - * @var ReleaseImage - */ - protected $releaseImage; + /** + * @var ReleaseImage + */ + protected $releaseImage; - /** - * @var \Tmdb\Client - */ - protected $tmdbclient; + /** + * @var \Tmdb\Client + */ + protected $tmdbclient; - /** - * @var Client - */ - protected $client; + /** + * @var Client + */ + protected $client; - /** - * Language to fetch from IMDB. - * @var string - */ - protected $lookuplanguage; + /** + * Language to fetch from IMDB. + * @var string + */ + protected $lookuplanguage; - /** - * @var FanartTV - */ - public $fanart; + /** + * @var FanartTV + */ + public $fanart; - /** - * @var null|string - */ - public $fanartapikey; + /** + * @var null|string + */ + public $fanartapikey; - /** - * @var null|string - */ - public $omdbapikey; + /** + * @var null|string + */ + public $omdbapikey; - /** - * @var bool - */ - public $imdburl; + /** + * @var bool + */ + public $imdburl; - /** - * @var array|bool|int|string - */ - public $movieqty; + /** + * @var array|bool|int|string + */ + public $movieqty; - /** - * @var bool - */ - public $echooutput; + /** + * @var bool + */ + public $echooutput; - /** - * @var string - */ - public $imgSavePath; + /** + * @var string + */ + public $imgSavePath; - /** - * @var string - */ - public $service; + /** + * @var string + */ + public $service; - /** - * @var array|bool|int|string - */ - public $catWhere; + /** + * @var array|bool|int|string + */ + public $catWhere; - /** - * @param array $options Class instances / Echo to CLI. - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances / Echo to CLI. + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Logger' => null, 'ReleaseImage' => null, 'Settings' => null, 'TMDb' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->releaseImage = ($options['ReleaseImage'] instanceof ReleaseImage ? $options['ReleaseImage'] : new ReleaseImage($this->pdo)); - $this->client = new Client(); - $this->tmdbtoken = new ApiToken(Settings::value('APIs..tmdbkey')); - $this->tmdbclient = new TmdbClient($this->tmdbtoken, [ + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->releaseImage = ($options['ReleaseImage'] instanceof ReleaseImage ? $options['ReleaseImage'] : new ReleaseImage($this->pdo)); + $this->client = new Client(); + $this->tmdbtoken = new ApiToken(Settings::value('APIs..tmdbkey')); + $this->tmdbclient = new TmdbClient($this->tmdbtoken, [ 'cache' => [ - 'enabled' => false - ] + 'enabled' => false, + ], ] ); - $this->fanartapikey = Settings::value('APIs..fanarttvkey'); - $this->fanart = new FanartTV($this->fanartapikey); - $this->omdbapikey = Settings::value('APIs..omdbkey'); + $this->fanartapikey = Settings::value('APIs..fanarttvkey'); + $this->fanart = new FanartTV($this->fanartapikey); + $this->omdbapikey = Settings::value('APIs..omdbkey'); - $this->lookuplanguage = Settings::value('indexer.categorise.imdblanguage') !== '' ? (string)Settings::value('indexer.categorise.imdblanguage') : 'en'; + $this->lookuplanguage = Settings::value('indexer.categorise.imdblanguage') !== '' ? (string) Settings::value('indexer.categorise.imdblanguage') : 'en'; - $this->imdburl = Settings::value('indexer.categorise.imdburl') === 0 ? false : true; - $this->movieqty = Settings::value('..maximdbprocessed') !== '' ? Settings::value('..maximdbprocessed') : 100; - $this->searchEngines = true; - $this->showPasswords = Releases::showPasswords(); + $this->imdburl = Settings::value('indexer.categorise.imdburl') === 0 ? false : true; + $this->movieqty = Settings::value('..maximdbprocessed') !== '' ? Settings::value('..maximdbprocessed') : 100; + $this->searchEngines = true; + $this->showPasswords = Releases::showPasswords(); - $this->debug = NN_DEBUG; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI && $this->pdo->cli); - $this->imgSavePath = NN_COVERS . 'movies' . DS; - $this->service = ''; - $this->catWhere = 'PARTITION (movies)'; + $this->debug = NN_DEBUG; + $this->echooutput = ($options['Echo'] && NN_ECHOCLI && $this->pdo->cli); + $this->imgSavePath = NN_COVERS.'movies'.DS; + $this->service = ''; + $this->catWhere = 'PARTITION (movies)'; - if (NN_DEBUG || NN_LOGGING) { - $this->debug = true; - try { - $this->debugging = new Logger(); - } catch (LoggerException $error) { - $this->_debug = false; - } - } - } + if (NN_DEBUG || NN_LOGGING) { + $this->debug = true; + try { + $this->debugging = new Logger(); + } catch (LoggerException $error) { + $this->_debug = false; + } + } + } - /** - * Get info for a IMDB id. - * - * @param int $imdbId - * - * @return array|bool - */ - public function getMovieInfo($imdbId) - { - return $this->pdo->queryOneRow(sprintf('SELECT * FROM movieinfo WHERE imdbid = %d', $imdbId)); - } + /** + * Get info for a IMDB id. + * + * @param int $imdbId + * + * @return array|bool + */ + public function getMovieInfo($imdbId) + { + return $this->pdo->queryOneRow(sprintf('SELECT * FROM movieinfo WHERE imdbid = %d', $imdbId)); + } - /** - * Get info for multiple IMDB id's. - * - * @param array $imdbIDs - * - * @return array - */ - public function getMovieInfoMultiImdb($imdbIDs): array - { - return $this->pdo->query( + /** + * Get info for multiple IMDB id's. + * + * @param array $imdbIDs + * + * @return array + */ + public function getMovieInfoMultiImdb($imdbIDs): array + { + return $this->pdo->query( sprintf(' SELECT DISTINCT movieinfo.*, releases.imdbid AS relimdb FROM movieinfo @@ -245,30 +246,30 @@ class Movie ) ), true, NN_CACHE_EXPIRY_MEDIUM ); - } + } - /** - * Get movie releases with covers for movie browse page. - * - * @param $cat - * @param $start - * @param $num - * @param $orderBy - * @param $maxAge - * @param array $excludedCats - * - * @return array|bool|\PDOStatement - */ - public function getMovieRange($cat, $start, $num, $orderBy, $maxAge = -1, array $excludedCats = []) - { - $catsrch = ''; - if (count($cat) > 0 && $cat[0] !== -1) { - $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); - } + /** + * Get movie releases with covers for movie browse page. + * + * @param $cat + * @param $start + * @param $num + * @param $orderBy + * @param $maxAge + * @param array $excludedCats + * + * @return array|bool|\PDOStatement + */ + public function getMovieRange($cat, $start, $num, $orderBy, $maxAge = -1, array $excludedCats = []) + { + $catsrch = ''; + if (count($cat) > 0 && $cat[0] !== -1) { + $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); + } - $order = $this->getMovieOrder($orderBy); + $order = $this->getMovieOrder($orderBy); - $movies = $this->pdo->queryCalc( + $movies = $this->pdo->queryCalc( sprintf(" SELECT SQL_CALC_FOUND_ROWS m.imdbid, @@ -284,28 +285,28 @@ class Movie ORDER BY %s %s %s", $this->showPasswords, $this->getBrowseBy(), - (!empty($catsrch) ? $catsrch : ''), + (! empty($catsrch) ? $catsrch : ''), ($maxAge > 0 - ? 'AND r.postdate > NOW() - INTERVAL ' . $maxAge . 'DAY ' + ? 'AND r.postdate > NOW() - INTERVAL '.$maxAge.'DAY ' : '' ), - (count($excludedCats) > 0 ? ' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')' : ''), + (count($excludedCats) > 0 ? ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')' : ''), $order[0], $order[1], - ($start === false ? '' : ' LIMIT ' . $num . ' OFFSET ' . $start) + ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start) ), true, NN_CACHE_EXPIRY_MEDIUM ); - $movieIDs = $releaseIDs = false; + $movieIDs = $releaseIDs = false; - if (is_array($movies['result'])) { - foreach ($movies['result'] AS $movie => $id) { - $movieIDs[] = $id['imdbid']; - $releaseIDs[] = $id['grp_release_id']; - } - } + if (is_array($movies['result'])) { + foreach ($movies['result'] as $movie => $id) { + $movieIDs[] = $id['imdbid']; + $releaseIDs[] = $id['grp_release_id']; + } + } - $sql = sprintf(" + $sql = sprintf(" SELECT GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id, GROUP_CONCAT(r.rarinnerfilecount ORDER BY r.postdate DESC SEPARATOR ',') AS grp_rarinnerfilecount, @@ -338,28 +339,29 @@ class Movie ORDER BY %s %s", (is_array($movieIDs) ? implode(',', $movieIDs) : -1), (is_array($releaseIDs) ? implode(',', $releaseIDs) : -1), - (!empty($catsrch) ? $catsrch : ''), + (! empty($catsrch) ? $catsrch : ''), $order[0], $order[1] ); - $return = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - if (!empty($return)) { - $return[0]['_totalcount'] = $movies['total'] ?? 0; - } - return $return; - } + $return = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); + if (! empty($return)) { + $return[0]['_totalcount'] = $movies['total'] ?? 0; + } - /** - * Get the order type the user requested on the movies page. - * - * @param $orderBy - * - * @return array - */ - protected function getMovieOrder($orderBy): array - { - $orderArr = explode('_', (($orderBy === '') ? 'MAX(r.postdate)' : $orderBy)); - switch ($orderArr[0]) { + return $return; + } + + /** + * Get the order type the user requested on the movies page. + * + * @param $orderBy + * + * @return array + */ + protected function getMovieOrder($orderBy): array + { + $orderArr = explode('_', (($orderBy === '') ? 'MAX(r.postdate)' : $orderBy)); + switch ($orderArr[0]) { case 'title': $orderField = 'm.title'; break; @@ -375,122 +377,126 @@ class Movie break; } - return [$orderField, isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1]) ? $orderArr[1] : 'desc']; - } + return [$orderField, isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1]) ? $orderArr[1] : 'desc']; + } - /** - * Order types for movies page. - * - * @return array - */ - public function getMovieOrdering(): array - { - return ['title_asc', 'title_desc', 'year_asc', 'year_desc', 'rating_asc', 'rating_desc']; - } + /** + * Order types for movies page. + * + * @return array + */ + public function getMovieOrdering(): array + { + return ['title_asc', 'title_desc', 'year_asc', 'year_desc', 'rating_asc', 'rating_desc']; + } - /** - * @return string - */ - protected function getBrowseBy(): string - { - $browseBy = ' '; - $browseByArr = ['title', 'director', 'actors', 'genre', 'rating', 'year', 'imdb']; - foreach ($browseByArr as $bb) { - if (isset($_REQUEST[$bb]) && !empty($_REQUEST[$bb])) { - $bbv = stripslashes($_REQUEST[$bb]); - if ($bb === 'rating') { - $bbv .= '.'; - } - if ($bb === 'imdb') { - $browseBy .= sprintf('AND m.%sid = %d', $bb, $bbv); - } else { - $browseBy .= 'AND m.' . $bb . ' ' . $this->pdo->likeString($bbv, true, true); - } - } - } - return $browseBy; - } + /** + * @return string + */ + protected function getBrowseBy(): string + { + $browseBy = ' '; + $browseByArr = ['title', 'director', 'actors', 'genre', 'rating', 'year', 'imdb']; + foreach ($browseByArr as $bb) { + if (isset($_REQUEST[$bb]) && ! empty($_REQUEST[$bb])) { + $bbv = stripslashes($_REQUEST[$bb]); + if ($bb === 'rating') { + $bbv .= '.'; + } + if ($bb === 'imdb') { + $browseBy .= sprintf('AND m.%sid = %d', $bb, $bbv); + } else { + $browseBy .= 'AND m.'.$bb.' '.$this->pdo->likeString($bbv, true, true); + } + } + } - /** - * @var null|TraktTv - */ - public $traktTv = null; + return $browseBy; + } - /** - * @var OMDbAPI|null - */ - public $omdbApi = null; + /** + * @var null|TraktTv + */ + public $traktTv = null; - /** - * Get trailer using IMDB Id. - * - * @param int $imdbID - * - * @return bool|string - */ - public function getTrailer($imdbID) - { - if (!is_numeric($imdbID)) { - return false; - } + /** + * @var OMDbAPI|null + */ + public $omdbApi = null; - $trailer = $this->pdo->queryOneRow("SELECT trailer FROM movieinfo WHERE imdbid = $imdbID AND trailer != ''"); - if ($trailer) { - return $trailer['trailer']; - } + /** + * Get trailer using IMDB Id. + * + * @param int $imdbID + * + * @return bool|string + */ + public function getTrailer($imdbID) + { + if (! is_numeric($imdbID)) { + return false; + } - if ($this->traktTv === null) { - $this->traktTv = new TraktTv(['Settings' => $this->pdo]); - } + $trailer = $this->pdo->queryOneRow("SELECT trailer FROM movieinfo WHERE imdbid = $imdbID AND trailer != ''"); + if ($trailer) { + return $trailer['trailer']; + } - $data = $this->traktTv->client->movieSummary('tt' . $imdbID, 'full'); - if ($data) { - $this->parseTraktTv($data); - if (!empty($data['trailer'])) { - return $data['trailer']; - } - } + if ($this->traktTv === null) { + $this->traktTv = new TraktTv(['Settings' => $this->pdo]); + } - $trailer = Utility::imdb_trailers($imdbID); - if ($trailer) { - $this->pdo->queryExec( - 'UPDATE movieinfo SET trailer = ' . $this->pdo->escapeString($trailer) . ' WHERE imdbid = ' . $imdbID + $data = $this->traktTv->client->movieSummary('tt'.$imdbID, 'full'); + if ($data) { + $this->parseTraktTv($data); + if (! empty($data['trailer'])) { + return $data['trailer']; + } + } + + $trailer = Utility::imdb_trailers($imdbID); + if ($trailer) { + $this->pdo->queryExec( + 'UPDATE movieinfo SET trailer = '.$this->pdo->escapeString($trailer).' WHERE imdbid = '.$imdbID ); - return $trailer; - } - return false; - } - /** - * Parse trakt info, insert into DB. - * - * @param array $data - * - * @return mixed - */ - public function parseTraktTv(&$data) - { - if (empty($data['ids']['imdb'])) { - return false; - } + return $trailer; + } - if (!empty($data['trailer'])) { - $data['trailer'] = str_ireplace( + return false; + } + + /** + * Parse trakt info, insert into DB. + * + * @param array $data + * + * @return mixed + */ + public function parseTraktTv(&$data) + { + if (empty($data['ids']['imdb'])) { + return false; + } + + if (! empty($data['trailer'])) { + $data['trailer'] = str_ireplace( 'http://', 'https://', str_ireplace('watch?v=', 'embed/', $data['trailer']) ); - return $data['trailer']; - } - $imdbid = (strpos($data['ids']['imdb'], 'tt') === 0) ? substr($data['ids']['imdb'], 2) : $data['ids']['imdb']; - $cover = 0; - if (is_file($this->imgSavePath . $imdbid) . '-cover.jpg') { - $cover = 1; - } else { - $link = $this->checkTraktValue($data['images']['poster']['thumb']); - if ($link) { - $cover = $this->releaseImage->saveImage($imdbid . '-cover', $link, $this->imgSavePath); - } - } - $this->update([ + + return $data['trailer']; + } + $imdbid = (strpos($data['ids']['imdb'], 'tt') === 0) ? substr($data['ids']['imdb'], 2) : $data['ids']['imdb']; + $cover = 0; + if (is_file($this->imgSavePath.$imdbid).'-cover.jpg') { + $cover = 1; + } else { + $link = $this->checkTraktValue($data['images']['poster']['thumb']); + if ($link) { + $cover = $this->releaseImage->saveImage($imdbid.'-cover', $link, $this->imgSavePath); + } + } + $this->update([ 'genres' => $this->checkTraktValue($data['genres']), 'imdbid' => $this->checkTraktValue($imdbid), 'language' => $this->checkTraktValue($data['language']), @@ -501,650 +507,666 @@ class Movie 'tmdbid' => $this->checkTraktValue($data['ids']['tmdb']), 'trailer' => $this->checkTraktValue($data['trailer']), 'cover' => $cover, - 'year' => $this->checkTraktValue($data['year']) + 'year' => $this->checkTraktValue($data['year']), ]); - } + } - /** - * Checks if the value is set and not empty, returns it, else empty string. - * - * @param mixed $value - * - * @return string - */ - private function checkTraktValue($value): string - { - if (is_array($value) && !empty($value)) { - $temp = ''; - foreach($value as $val) { - if (!is_array($val) && !is_object($val)) { - $temp .= (string)$val; - } - } - $value = $temp; - } - return (!empty($value) ? $value : ''); - } + /** + * Checks if the value is set and not empty, returns it, else empty string. + * + * @param mixed $value + * + * @return string + */ + private function checkTraktValue($value): string + { + if (is_array($value) && ! empty($value)) { + $temp = ''; + foreach ($value as $val) { + if (! is_array($val) && ! is_object($val)) { + $temp .= (string) $val; + } + } + $value = $temp; + } - /** - * Create click-able links to IMDB actors/genres/directors/etc.. - * - * @param $data - * @param $field - * - * @return string - */ - public function makeFieldLinks($data, $field): string - { - if (!isset($data[$field]) || $data[$field] === '') { - return ''; - } + return ! empty($value) ? $value : ''; + } - $tmpArr = explode(', ', $data[$field]); - $newArr = []; - $i = 0; - foreach ($tmpArr as $ta) { - if (trim($ta) === '') { - continue; - } - if ($i > 5) { - break; - } //only use first 6 - $newArr[] = '<a href="' . WWW_TOP . '/movies?' . $field . '=' . urlencode($ta) . '" title="' . $ta . '">' . $ta . '</a>'; - $i++; - } - return implode(', ', $newArr); - } + /** + * Create click-able links to IMDB actors/genres/directors/etc.. + * + * @param $data + * @param $field + * + * @return string + */ + public function makeFieldLinks($data, $field): string + { + if (! isset($data[$field]) || $data[$field] === '') { + return ''; + } - /** - * Get array of column keys, for inserting / updating. - * - * @return array - */ - public function getColumnKeys(): array - { - return [ - 'actors','backdrop','cover','director','genre','imdbid','language', - 'plot','rating','tagline','title','tmdbid', 'trailer','type','year' + $tmpArr = explode(', ', $data[$field]); + $newArr = []; + $i = 0; + foreach ($tmpArr as $ta) { + if (trim($ta) === '') { + continue; + } + if ($i > 5) { + break; + } //only use first 6 + $newArr[] = '<a href="'.WWW_TOP.'/movies?'.$field.'='.urlencode($ta).'" title="'.$ta.'">'.$ta.'</a>'; + $i++; + } + + return implode(', ', $newArr); + } + + /** + * Get array of column keys, for inserting / updating. + * + * @return array + */ + public function getColumnKeys(): array + { + return [ + 'actors', 'backdrop', 'cover', 'director', 'genre', 'imdbid', 'language', + 'plot', 'rating', 'tagline', 'title', 'tmdbid', 'trailer', 'type', 'year', ]; - } + } - /** - * Update movie on movie-edit page. - * - * @param array $values Array of keys/values to update. See $validKeys - * - * @return int|bool - */ - public function update(array $values) { - if (!count($values)) { - return false; - } + /** + * Update movie on movie-edit page. + * + * @param array $values Array of keys/values to update. See $validKeys + * + * @return int|bool + */ + public function update(array $values) + { + if (! count($values)) { + return false; + } - $validKeys = $this->getColumnKeys(); + $validKeys = $this->getColumnKeys(); - $query = [ + $query = [ '0' => 'INSERT INTO movieinfo (updateddate, createddate, ', '1' => ' VALUES (NOW(), NOW(), ', - '2' => 'ON DUPLICATE KEY UPDATE updateddate = NOW(), ' + '2' => 'ON DUPLICATE KEY UPDATE updateddate = NOW(), ', ]; - $found = 0; - foreach ($values as $key => $value) { - if (!empty($value) && in_array($key, $validKeys, false)) { - $found++; - $query[0] .= "$key, "; - if (in_array($key, ['genre', 'language'], false)) { - $value = substr($value, 0, 64); - } - $value = $this->pdo->escapeString($value); - $query[1] .= "$value, "; - $query[2] .= "$key = $value, "; - } - } - if (!$found) { - return false; - } - foreach ($query as $key => $value) { - $query[$key] = rtrim($value, ', '); - } + $found = 0; + foreach ($values as $key => $value) { + if (! empty($value) && in_array($key, $validKeys, false)) { + $found++; + $query[0] .= "$key, "; + if (in_array($key, ['genre', 'language'], false)) { + $value = substr($value, 0, 64); + } + $value = $this->pdo->escapeString($value); + $query[1] .= "$value, "; + $query[2] .= "$key = $value, "; + } + } + if (! $found) { + return false; + } + foreach ($query as $key => $value) { + $query[$key] = rtrim($value, ', '); + } - return $this->pdo->queryInsert($query[0] . ') ' . $query[1] . ') ' . $query[2]); - } + return $this->pdo->queryInsert($query[0].') '.$query[1].') '.$query[2]); + } - /** - * Check if a variable is set and not a empty string. - * - * @param $variable - * - * @return bool - */ - protected function checkVariable(&$variable): bool - { - return !empty($variable) ? true : false; - } + /** + * Check if a variable is set and not a empty string. + * + * @param $variable + * + * @return bool + */ + protected function checkVariable(&$variable): bool + { + return ! empty($variable) ? true : false; + } - /** - * Returns a tmdb, imdb or trakt variable, the one that is set. Empty string if both not set. - * - * @param string $variable1 - * @param string $variable2 - * @param string $variable3 - * - * @return array|string - */ - protected function setVariables(&$variable1, &$variable2, &$variable3, &$variable4) - { - if ($this->checkVariable($variable1)) { - return $variable1; - } - if ($this->checkVariable($variable2)) { - return $variable2; - } - if ($this->checkVariable($variable3)) { - return $variable3; - } - if ($this->checkVariable($variable4)) { - return $variable4; - } - return ''; - } + /** + * Returns a tmdb, imdb or trakt variable, the one that is set. Empty string if both not set. + * + * @param string $variable1 + * @param string $variable2 + * @param string $variable3 + * + * @return array|string + */ + protected function setVariables(&$variable1, &$variable2, &$variable3, &$variable4) + { + if ($this->checkVariable($variable1)) { + return $variable1; + } + if ($this->checkVariable($variable2)) { + return $variable2; + } + if ($this->checkVariable($variable3)) { + return $variable3; + } + if ($this->checkVariable($variable4)) { + return $variable4; + } - /** - * Fetch IMDB/TMDB/TRAKT info for the movie. - * - * @param $imdbId - * - * @return bool - */ - public function updateMovieInfo($imdbId): bool - { - if ($this->echooutput && $this->service !== '') { - ColorCLI::doEcho(ColorCLI::primary('Fetching IMDB info from TMDB and/or Trakt using IMDB id: ' . $imdbId)); - } + return ''; + } - // Check TMDB for IMDB info. - $tmdb = $this->fetchTMDBProperties($imdbId); + /** + * Fetch IMDB/TMDB/TRAKT info for the movie. + * + * @param $imdbId + * + * @return bool + */ + public function updateMovieInfo($imdbId): bool + { + if ($this->echooutput && $this->service !== '') { + ColorCLI::doEcho(ColorCLI::primary('Fetching IMDB info from TMDB and/or Trakt using IMDB id: '.$imdbId)); + } - // Check IMDB for movie info. - $imdb = $this->fetchIMDBProperties($imdbId); + // Check TMDB for IMDB info. + $tmdb = $this->fetchTMDBProperties($imdbId); - // Check TRAKT for movie info - $trakt = $this->fetchTraktTVProperties($imdbId); + // Check IMDB for movie info. + $imdb = $this->fetchIMDBProperties($imdbId); - // Check OMDb for movie info - $omdb = $this->fetchOmdbAPIProperties($imdbId); - if (!$imdb && !$tmdb && !$trakt && !$omdb) { - return false; - } + // Check TRAKT for movie info + $trakt = $this->fetchTraktTVProperties($imdbId); - // Check FanArt.tv for cover and background images. - $fanart = $this->fetchFanartTVProperties($imdbId); + // Check OMDb for movie info + $omdb = $this->fetchOmdbAPIProperties($imdbId); + if (! $imdb && ! $tmdb && ! $trakt && ! $omdb) { + return false; + } - $mov = []; + // Check FanArt.tv for cover and background images. + $fanart = $this->fetchFanartTVProperties($imdbId); - $mov['cover'] = $mov['backdrop'] = $mov['banner'] = $movieID = 0; - $mov['type'] = $mov['director'] = $mov['actors'] = $mov['language'] = ''; + $mov = []; - $mov['imdbid'] = $imdbId; - $mov['tmdbid'] = (!isset($tmdb['tmdbid']) || $tmdb['tmdbid'] === '') ? 0 : $tmdb['tmdbid']; + $mov['cover'] = $mov['backdrop'] = $mov['banner'] = $movieID = 0; + $mov['type'] = $mov['director'] = $mov['actors'] = $mov['language'] = ''; - // Prefer Fanart.tv cover over TMDB,TMDB over IMDB and IMDB over OMDB. - if ($this->checkVariable($fanart['cover'])) { - $mov['cover'] = $this->releaseImage->saveImage($imdbId . '-cover', $fanart['cover'], $this->imgSavePath); - } elseif ($this->checkVariable($tmdb['cover'])) { - $mov['cover'] = $this->releaseImage->saveImage($imdbId . '-cover', $tmdb['cover'], $this->imgSavePath); - } elseif ($this->checkVariable($imdb['cover'])) { - $mov['cover'] = $this->releaseImage->saveImage($imdbId . '-cover', $imdb['cover'], $this->imgSavePath); - } elseif ($this->checkVariable($omdb['cover'])) { - $mov['cover'] = $this->releaseImage->saveImage($imdbId . '-cover', $omdb['cover'], $this->imgSavePath); - } + $mov['imdbid'] = $imdbId; + $mov['tmdbid'] = (! isset($tmdb['tmdbid']) || $tmdb['tmdbid'] === '') ? 0 : $tmdb['tmdbid']; - // Backdrops. - if ($this->checkVariable($fanart['backdrop'])) { - $mov['backdrop'] = $this->releaseImage->saveImage($imdbId . '-backdrop', $fanart['backdrop'], $this->imgSavePath, 1920, 1024); - } else if ($this->checkVariable($tmdb['backdrop'])) { - $mov['backdrop'] = $this->releaseImage->saveImage($imdbId . '-backdrop', $tmdb['backdrop'], $this->imgSavePath, 1920, 1024); - } + // Prefer Fanart.tv cover over TMDB,TMDB over IMDB and IMDB over OMDB. + if ($this->checkVariable($fanart['cover'])) { + $mov['cover'] = $this->releaseImage->saveImage($imdbId.'-cover', $fanart['cover'], $this->imgSavePath); + } elseif ($this->checkVariable($tmdb['cover'])) { + $mov['cover'] = $this->releaseImage->saveImage($imdbId.'-cover', $tmdb['cover'], $this->imgSavePath); + } elseif ($this->checkVariable($imdb['cover'])) { + $mov['cover'] = $this->releaseImage->saveImage($imdbId.'-cover', $imdb['cover'], $this->imgSavePath); + } elseif ($this->checkVariable($omdb['cover'])) { + $mov['cover'] = $this->releaseImage->saveImage($imdbId.'-cover', $omdb['cover'], $this->imgSavePath); + } - // Banner - if ($this->checkVariable($fanart['banner'])) { - $mov['banner'] = $this->releaseImage->saveImage($imdbId . '-banner', $fanart['banner'], $this->imgSavePath); - } + // Backdrops. + if ($this->checkVariable($fanart['backdrop'])) { + $mov['backdrop'] = $this->releaseImage->saveImage($imdbId.'-backdrop', $fanart['backdrop'], $this->imgSavePath, 1920, 1024); + } elseif ($this->checkVariable($tmdb['backdrop'])) { + $mov['backdrop'] = $this->releaseImage->saveImage($imdbId.'-backdrop', $tmdb['backdrop'], $this->imgSavePath, 1920, 1024); + } - $mov['title'] = $this->setVariables($imdb['title'] , $tmdb['title'], $trakt['title'], $omdb['title']); - $mov['rating'] = $this->setVariables($imdb['rating'] , $tmdb['rating'], $trakt['rating'], $omdb['rating']); - $mov['plot'] = $this->setVariables($imdb['plot'] , $tmdb['plot'], $trakt['overview'], $omdb['plot']); - $mov['tagline'] = $this->setVariables($imdb['tagline'], $tmdb['tagline'], $trakt['tagline'], $omdb['tagline']); - $mov['year'] = $this->setVariables($imdb['year'] , $tmdb['year'], $trakt['year'], $omdb['year']); - $mov['genre'] = $this->setVariables($imdb['genre'] , $tmdb['genre'], $trakt['genres'], $omdb['genre']); + // Banner + if ($this->checkVariable($fanart['banner'])) { + $mov['banner'] = $this->releaseImage->saveImage($imdbId.'-banner', $fanart['banner'], $this->imgSavePath); + } - if ($this->checkVariable($imdb['type'])) { - $mov['type'] = $imdb['type']; - } + $mov['title'] = $this->setVariables($imdb['title'], $tmdb['title'], $trakt['title'], $omdb['title']); + $mov['rating'] = $this->setVariables($imdb['rating'], $tmdb['rating'], $trakt['rating'], $omdb['rating']); + $mov['plot'] = $this->setVariables($imdb['plot'], $tmdb['plot'], $trakt['overview'], $omdb['plot']); + $mov['tagline'] = $this->setVariables($imdb['tagline'], $tmdb['tagline'], $trakt['tagline'], $omdb['tagline']); + $mov['year'] = $this->setVariables($imdb['year'], $tmdb['year'], $trakt['year'], $omdb['year']); + $mov['genre'] = $this->setVariables($imdb['genre'], $tmdb['genre'], $trakt['genres'], $omdb['genre']); - if ($this->checkVariable($imdb['director'])) { - $mov['director'] = is_array($imdb['director']) ? implode(', ', array_unique($imdb['director'])) : $imdb['director']; - } else if ($this->checkVariable($omdb['director'])) { - $mov['director'] = is_array($omdb['director']) ? implode(', ', array_unique($omdb['director'])) : $omdb['director']; - } + if ($this->checkVariable($imdb['type'])) { + $mov['type'] = $imdb['type']; + } - if ($this->checkVariable($imdb['actors'])) { - $mov['actors'] = is_array($imdb['actors']) ? implode(', ', array_unique($imdb['actors'])) : $imdb['actors']; - } else if ($this->checkVariable($omdb['actors'])) { - $mov['actors'] = is_array($omdb['actors']) ? implode(', ', array_unique($omdb['actors'])) : $omdb['actors']; - } + if ($this->checkVariable($imdb['director'])) { + $mov['director'] = is_array($imdb['director']) ? implode(', ', array_unique($imdb['director'])) : $imdb['director']; + } elseif ($this->checkVariable($omdb['director'])) { + $mov['director'] = is_array($omdb['director']) ? implode(', ', array_unique($omdb['director'])) : $omdb['director']; + } - if ($this->checkVariable($imdb['language'])) { - $mov['language'] = is_array($imdb['language']) ? implode(', ', array_unique($imdb['language'])) : $imdb['language']; - } else if ($this->checkVariable($omdb['language'])) { - $mov['language'] = is_array($imdb['language']) ? implode(', ', array_unique($omdb['language'])) : $omdb['language']; - } + if ($this->checkVariable($imdb['actors'])) { + $mov['actors'] = is_array($imdb['actors']) ? implode(', ', array_unique($imdb['actors'])) : $imdb['actors']; + } elseif ($this->checkVariable($omdb['actors'])) { + $mov['actors'] = is_array($omdb['actors']) ? implode(', ', array_unique($omdb['actors'])) : $omdb['actors']; + } - if (is_array($mov['genre'])) { - $mov['genre'] = implode(', ', array_unique($mov['genre'])); - } + if ($this->checkVariable($imdb['language'])) { + $mov['language'] = is_array($imdb['language']) ? implode(', ', array_unique($imdb['language'])) : $imdb['language']; + } elseif ($this->checkVariable($omdb['language'])) { + $mov['language'] = is_array($imdb['language']) ? implode(', ', array_unique($omdb['language'])) : $omdb['language']; + } - if (is_array($mov['type'])) { - $mov['type'] = implode(', ', array_unique($mov['type'])); - } + if (is_array($mov['genre'])) { + $mov['genre'] = implode(', ', array_unique($mov['genre'])); + } - $mov['title'] = html_entity_decode($mov['title'] , ENT_QUOTES, 'UTF-8'); + if (is_array($mov['type'])) { + $mov['type'] = implode(', ', array_unique($mov['type'])); + } - $mov['title'] = str_replace(['/', '\\'], '', $mov['title']); - $movieID = $this->update([ - 'actors' => html_entity_decode($mov['actors'] , ENT_QUOTES, 'UTF-8'), + $mov['title'] = html_entity_decode($mov['title'], ENT_QUOTES, 'UTF-8'); + + $mov['title'] = str_replace(['/', '\\'], '', $mov['title']); + $movieID = $this->update([ + 'actors' => html_entity_decode($mov['actors'], ENT_QUOTES, 'UTF-8'), 'backdrop' => $mov['backdrop'], 'cover' => $mov['cover'], 'director' => html_entity_decode($mov['director'], ENT_QUOTES, 'UTF-8'), - 'genre' => html_entity_decode($mov['genre'] , ENT_QUOTES, 'UTF-8'), + 'genre' => html_entity_decode($mov['genre'], ENT_QUOTES, 'UTF-8'), 'imdbid' => $mov['imdbid'], 'language' => html_entity_decode($mov['language'], ENT_QUOTES, 'UTF-8'), 'plot' => html_entity_decode(preg_replace('/\s+See full summary »/', ' ', $mov['plot']), ENT_QUOTES, 'UTF-8'), 'rating' => round($mov['rating'], 1), - 'tagline' => html_entity_decode($mov['tagline'] , ENT_QUOTES, 'UTF-8'), + 'tagline' => html_entity_decode($mov['tagline'], ENT_QUOTES, 'UTF-8'), 'title' => $mov['title'], 'tmdbid' => $mov['tmdbid'], 'type' => html_entity_decode(ucwords(preg_replace('/[\.\_]/', ' ', $mov['type'])), ENT_QUOTES, 'UTF-8'), - 'year' => $mov['year'] + 'year' => $mov['year'], ]); - if ($this->echooutput && $this->service !== '') { - ColorCLI::doEcho( - ColorCLI::headerOver(($movieID !== 0 ? 'Added/updated movie: ' : 'Nothing to update for movie: ')) . - ColorCLI::primary($mov['title'] . - ' (' . - $mov['year'] . - ') - ' . + if ($this->echooutput && $this->service !== '') { + ColorCLI::doEcho( + ColorCLI::headerOver(($movieID !== 0 ? 'Added/updated movie: ' : 'Nothing to update for movie: ')). + ColorCLI::primary($mov['title']. + ' ('. + $mov['year']. + ') - '. $mov['imdbid'] ) ); - } + } - return ($movieID === 0 ? false : true); - } + return $movieID === 0 ? false : true; + } - /** - * Fetch FanArt.tv backdrop / cover / title. - * - * @param $imdbId - * - * @return bool|array - */ - protected function fetchFanartTVProperties($imdbId) - { - if ($this->fanartapikey !== '') - { - $art = $this->fanart->getMovieFanart('tt' . $imdbId); + /** + * Fetch FanArt.tv backdrop / cover / title. + * + * @param $imdbId + * + * @return bool|array + */ + protected function fetchFanartTVProperties($imdbId) + { + if ($this->fanartapikey !== '') { + $art = $this->fanart->getMovieFanart('tt'.$imdbId); - if (isset($art) && $art !== false) { - if (isset($art['status']) && $art['status'] === 'error') { - return false; - } - $ret = []; - if ($this->checkVariable($art['moviebackground'][0]['url'])) { - $ret['backdrop'] = $art['moviebackground'][0]['url']; - } else if ($this->checkVariable($art['moviethumb'][0]['url'])) { - $ret['backdrop'] = $art['moviethumb'][0]['url']; - } - if ($this->checkVariable($art['movieposter'][0]['url'])) { - $ret['cover'] = $art['movieposter'][0]['url']; - } - if ($this->checkVariable($art['moviebanner'][0]['url'])) { - $ret['banner'] = $art['moviebanner'][0]['url']; - } + if (isset($art) && $art !== false) { + if (isset($art['status']) && $art['status'] === 'error') { + return false; + } + $ret = []; + if ($this->checkVariable($art['moviebackground'][0]['url'])) { + $ret['backdrop'] = $art['moviebackground'][0]['url']; + } elseif ($this->checkVariable($art['moviethumb'][0]['url'])) { + $ret['backdrop'] = $art['moviethumb'][0]['url']; + } + if ($this->checkVariable($art['movieposter'][0]['url'])) { + $ret['cover'] = $art['movieposter'][0]['url']; + } + if ($this->checkVariable($art['moviebanner'][0]['url'])) { + $ret['banner'] = $art['moviebanner'][0]['url']; + } - if (isset($ret['backdrop'], $ret['cover'])) { - $ret['title'] = $imdbId; - if (isset($art['name'])) { - $ret['title'] = $art['name']; - } - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::alternateOver('Fanart Found ') . ColorCLI::headerOver($ret['title']), true); - } - return $ret; - } - } - } - return false; - } + if (isset($ret['backdrop'], $ret['cover'])) { + $ret['title'] = $imdbId; + if (isset($art['name'])) { + $ret['title'] = $art['name']; + } + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::alternateOver('Fanart Found ').ColorCLI::headerOver($ret['title']), true); + } - /** - * Fetch info for IMDB id from TMDB. - * - * @param $imdbId - * @param bool $text - * - * @return array|bool - */ - public function fetchTMDBProperties($imdbId, $text = false) - { - $lookupId = ($text === false ? 'tt' . $imdbId : $imdbId); + return $ret; + } + } + } - try { - $tmdbLookup = $this->tmdbclient->getMoviesApi()->getMovie($lookupId); - } catch (TmdbApiException $e) { - return false; - } - /*$status = $tmdbLookup['status_code']; - if (!$status || (isset($status) && $status !== 1)) { - return false; - }*/ + return false; + } - $ret = []; - $ret['title'] = $tmdbLookup['original_title']; + /** + * Fetch info for IMDB id from TMDB. + * + * @param $imdbId + * @param bool $text + * + * @return array|bool + */ + public function fetchTMDBProperties($imdbId, $text = false) + { + $lookupId = ($text === false ? 'tt'.$imdbId : $imdbId); - if ($this->currentTitle !== '') { - // Check the similarity. - similar_text($this->currentTitle, $ret['title'], $percent); - if ($percent < 40) { - if ($this->debug) { - $this->debugging->log( + try { + $tmdbLookup = $this->tmdbclient->getMoviesApi()->getMovie($lookupId); + } catch (TmdbApiException $e) { + return false; + } + /*$status = $tmdbLookup['status_code']; + if (!$status || (isset($status) && $status !== 1)) { + return false; + }*/ + + $ret = []; + $ret['title'] = $tmdbLookup['original_title']; + + if ($this->currentTitle !== '') { + // Check the similarity. + similar_text($this->currentTitle, $ret['title'], $percent); + if ($percent < 40) { + if ($this->debug) { + $this->debugging->log( __CLASS__, __FUNCTION__, - 'Found (' . - $ret['title'] . - ') from TMDB, but it\'s only ' . - $percent . - '% similar to (' . - $this->currentTitle . ')', + 'Found ('. + $ret['title']. + ') from TMDB, but it\'s only '. + $percent. + '% similar to ('. + $this->currentTitle.')', Logger::LOG_INFO ); - } - return false; - } - } + } - $ret['tmdbid'] = $tmdbLookup['id']; - $ImdbID = str_replace('tt', '', $tmdbLookup['imdb_id']); - $ret['imdb_id'] = $ImdbID; - $vote = $tmdbLookup['vote_average']; - if (isset($vote)) { - $ret['rating'] = ($vote === 0) ? '' : $vote; - } - $overview = $tmdbLookup['overview']; - if (!empty($overview)) { - $ret['plot'] = $overview; - } - $tagline = $tmdbLookup['tagline']; - if (!empty($tagline)) { - $ret['tagline'] = $tagline; - } - $released = $tmdbLookup['release_date']; - if (!empty($released)) { - $ret['year'] = date('Y', strtotime($released)); - } - $genresa = $tmdbLookup['genres']; - if (!empty($genresa) && count($genresa) > 0) { - $genres = []; - foreach ($genresa as $genre) { - $genres[] = $genre['name']; - } - $ret['genre'] = $genres; - } - $posterp = $tmdbLookup['poster_path']; - if (!empty($posterp)) { - $ret['cover'] = 'http://image.tmdb.org/t/p/w185' . $posterp; - } - $backdrop = $tmdbLookup['backdrop_path']; - if (!empty($backdrop)) { - $ret['backdrop'] = 'http://image.tmdb.org/t/p/original' . $backdrop; - } - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::primaryOver('TMDb Found ') . ColorCLI::headerOver($ret['title']), true); - } - return $ret; - } + return false; + } + } - /** - * @param $imdbId - * - * @return array|bool - */ - protected function fetchIMDBProperties($imdbId) - { - $imdb_regex = [ + $ret['tmdbid'] = $tmdbLookup['id']; + $ImdbID = str_replace('tt', '', $tmdbLookup['imdb_id']); + $ret['imdb_id'] = $ImdbID; + $vote = $tmdbLookup['vote_average']; + if (isset($vote)) { + $ret['rating'] = ($vote === 0) ? '' : $vote; + } + $overview = $tmdbLookup['overview']; + if (! empty($overview)) { + $ret['plot'] = $overview; + } + $tagline = $tmdbLookup['tagline']; + if (! empty($tagline)) { + $ret['tagline'] = $tagline; + } + $released = $tmdbLookup['release_date']; + if (! empty($released)) { + $ret['year'] = date('Y', strtotime($released)); + } + $genresa = $tmdbLookup['genres']; + if (! empty($genresa) && count($genresa) > 0) { + $genres = []; + foreach ($genresa as $genre) { + $genres[] = $genre['name']; + } + $ret['genre'] = $genres; + } + $posterp = $tmdbLookup['poster_path']; + if (! empty($posterp)) { + $ret['cover'] = 'http://image.tmdb.org/t/p/w185'.$posterp; + } + $backdrop = $tmdbLookup['backdrop_path']; + if (! empty($backdrop)) { + $ret['backdrop'] = 'http://image.tmdb.org/t/p/original'.$backdrop; + } + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::primaryOver('TMDb Found ').ColorCLI::headerOver($ret['title']), true); + } + + return $ret; + } + + /** + * @param $imdbId + * + * @return array|bool + */ + protected function fetchIMDBProperties($imdbId) + { + $imdb_regex = [ 'title' => '/<title>(.*?)\s?\(.*?<\/title>/i', 'tagline' => '/taglines:<\/h4>\s([^<]+)/i', 'plot' => '/<p itemprop="description">\s*?(.*?)\s*?<\/p>/i', 'rating' => '/"ratingValue">([\d.]+)<\/span>/i', 'year' => '/<title>.*?\(.*?(\d{4}).*?<\/title>/i', - 'cover' => '/<link rel=\'image_src\' href="(http:\/\/ia\.media-imdb\.com.+\.jpg)">/' + 'cover' => '/<link rel=\'image_src\' href="(http:\/\/ia\.media-imdb\.com.+\.jpg)">/', ]; - $imdb_regex_multi = [ + $imdb_regex_multi = [ 'genre' => '/href="\/genre\/(.*?)\?/i', 'language' => '/<a href="\/language\/.+?\'url\'>(.+?)<\/a>/s', - 'type' => '/<meta property=\'og\:type\' content=\"(.+)\" \/>/i' + 'type' => '/<meta property=\'og\:type\' content=\"(.+)\" \/>/i', ]; - try { - $buffer = + try { + $buffer = $this->client->get( - 'http://' . ($this->imdburl === false ? 'www' : 'akas') . '.imdb.com/title/tt' . $imdbId . '/', + 'http://'.($this->imdburl === false ? 'www' : 'akas').'.imdb.com/title/tt'.$imdbId.'/', ['headers' => [ 'Accept-Language' => ((Settings::value('indexer.categorise.imdblanguage') != '') ? Settings::value('indexer.categorise.imdblanguage') : 'en'), - 'useragent' => 'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) ' . - 'Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10', 'foo=bar' - ] + 'useragent' => 'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) '. + 'Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10', 'foo=bar', + ], ] )->getBody()->getContents(); - } catch (RequestException $e) { - if ($e->hasResponse()) { - if($e->getCode() === 404) { - ColorCLI::doEcho(ColorCLI::notice('Data not available on IMDB server')); - } else if ($e->getCode() === 503) { - ColorCLI::doEcho(ColorCLI::notice('IMDB service unavailable')); - } else { - ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from IMDB, http error reported: ' . $e->getCode())); - } - } - } catch (\RuntimeException $e) { - ColorCLI::doEcho(ColorCLI::notice('Runtime error: ' . $e->getCode())); - } + } catch (RequestException $e) { + if ($e->hasResponse()) { + if ($e->getCode() === 404) { + ColorCLI::doEcho(ColorCLI::notice('Data not available on IMDB server')); + } elseif ($e->getCode() === 503) { + ColorCLI::doEcho(ColorCLI::notice('IMDB service unavailable')); + } else { + ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from IMDB, http error reported: '.$e->getCode())); + } + } + } catch (\RuntimeException $e) { + ColorCLI::doEcho(ColorCLI::notice('Runtime error: '.$e->getCode())); + } - if (isset($buffer) && $buffer !== false) { - $ret = []; - foreach ($imdb_regex as $field => $regex) { - if (preg_match($regex, $buffer, $matches)) { - $match = $matches[1]; - $match1 = strip_tags(trim(rtrim($match))); - $ret[$field] = $match1; - } - } + if (isset($buffer) && $buffer !== false) { + $ret = []; + foreach ($imdb_regex as $field => $regex) { + if (preg_match($regex, $buffer, $matches)) { + $match = $matches[1]; + $match1 = strip_tags(trim(rtrim($match))); + $ret[$field] = $match1; + } + } - $matches = []; - foreach ($imdb_regex_multi as $field => $regex) { - if (preg_match_all($regex, $buffer, $matches)) { - $match2 = $matches[1]; - $match3 = array_map('trim', $match2); - $ret[$field] = $match3; - } - } + $matches = []; + foreach ($imdb_regex_multi as $field => $regex) { + if (preg_match_all($regex, $buffer, $matches)) { + $match2 = $matches[1]; + $match3 = array_map('trim', $match2); + $ret[$field] = $match3; + } + } - if ($this->currentTitle !== '' && isset($ret['title'])) { - // Check the similarity. - similar_text($this->currentTitle, $ret['title'], $percent); - if ($percent < 40) { - if ($this->debug) { - $this->debugging->log( + if ($this->currentTitle !== '' && isset($ret['title'])) { + // Check the similarity. + similar_text($this->currentTitle, $ret['title'], $percent); + if ($percent < 40) { + if ($this->debug) { + $this->debugging->log( __CLASS__, __FUNCTION__, - 'Found (' . - $ret['title'] . - ') from IMDB, but it\'s only ' . - $percent . - '% similar to (' . - $this->currentTitle . ')', + 'Found ('. + $ret['title']. + ') from IMDB, but it\'s only '. + $percent. + '% similar to ('. + $this->currentTitle.')', Logger::LOG_INFO ); - } - return false; - } - } + } - // Actors. - if (preg_match('/<table class="cast_list">(.+?)<\/table>/s', $buffer, $hit)) { - if (preg_match_all('/<span class="itemprop" itemprop="name">\s*(.+?)\s*<\/span>/i', $hit[0], $results, PREG_PATTERN_ORDER)) { - $ret['actors'] = $results[1]; - } - } + return false; + } + } - // Directors. - if (preg_match('/itemprop="directors?".+?<\/div>/s', $buffer, $hit)) { - if (preg_match_all('/"name">(.*?)<\/span>/is', $hit[0], $results, PREG_PATTERN_ORDER)) { - $ret['director'] = $results[1]; - } - } - if ($this->echooutput && isset($ret['title'])) { - ColorCLI::doEcho(ColorCLI::headerOver('IMDb Found ') . ColorCLI::primaryOver($ret['title']), true); - } - return $ret; - } - return false; - } + // Actors. + if (preg_match('/<table class="cast_list">(.+?)<\/table>/s', $buffer, $hit)) { + if (preg_match_all('/<span class="itemprop" itemprop="name">\s*(.+?)\s*<\/span>/i', $hit[0], $results, PREG_PATTERN_ORDER)) { + $ret['actors'] = $results[1]; + } + } - /** - * Fetch TraktTV backdrop / cover / title. - * - * @param $imdbId - * - * @return bool|array - */ - protected function fetchTraktTVProperties($imdbId) - { - if ($this->traktTv === null) { - $this->traktTv = new TraktTv(['Settings' => $this->pdo]); - } - $resp = $this->traktTv->client->movieSummary('tt' . $imdbId, 'full'); - if ($resp !== false) { - $ret = []; - if (isset($resp['ids']['trakt'])) { - $ret['id'] = $resp['ids']['trakt']; - } + // Directors. + if (preg_match('/itemprop="directors?".+?<\/div>/s', $buffer, $hit)) { + if (preg_match_all('/"name">(.*?)<\/span>/is', $hit[0], $results, PREG_PATTERN_ORDER)) { + $ret['director'] = $results[1]; + } + } + if ($this->echooutput && isset($ret['title'])) { + ColorCLI::doEcho(ColorCLI::headerOver('IMDb Found ').ColorCLI::primaryOver($ret['title']), true); + } - if (isset($resp['title'])) { - $ret['title'] = $resp['title']; - } else { - return false; - } - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::alternateOver('Trakt Found ') . ColorCLI::headerOver($ret['title']), true); - } - return $ret; - } - return false; - } + return $ret; + } - /** - * Fetch OMDb backdrop / cover / title. - * - * @param $imdbId - * - * @return bool|array - */ - protected function fetchOmdbAPIProperties($imdbId) - { - if ($this->omdbapikey !== '' && $this->omdbApi === null) { - $this->omdbApi = new OMDbAPI($this->omdbapikey); - $resp = $this->omdbApi->fetch('i', 'tt' . $imdbId); + return false; + } - if (is_object($resp) && $resp->message === 'OK' && $resp->data->Response !== 'False') { - $ret = [ - 'title' => !empty($resp->data->Title) ? $resp->data->Title : '', - 'cover' => !empty($resp->data->Poster) ? $resp->data->Poster : '', - 'genre' => !empty($resp->data->Genre) ? $resp->data->Genre : '', - 'year' => !empty($resp->data->Year) ? $resp->data->Year : '', - 'plot' => !empty($resp->data->Plot) ? $resp->data->Plot : '', - 'rating' => !empty($resp->data->imdbRating) ? $resp->data->imdbRating : '', - 'tagline' => !empty($resp->data->Tagline) ? $resp->data->Tagline : '', - 'director' => !empty($resp->data->Director) ? $resp->data->Director : '', - 'actors' => !empty($resp->data->Actors) ? $resp->data->Actors : '', - 'language' => !empty($resp->data->Language) ? $resp->data->Language : '' + /** + * Fetch TraktTV backdrop / cover / title. + * + * @param $imdbId + * + * @return bool|array + */ + protected function fetchTraktTVProperties($imdbId) + { + if ($this->traktTv === null) { + $this->traktTv = new TraktTv(['Settings' => $this->pdo]); + } + $resp = $this->traktTv->client->movieSummary('tt'.$imdbId, 'full'); + if ($resp !== false) { + $ret = []; + if (isset($resp['ids']['trakt'])) { + $ret['id'] = $resp['ids']['trakt']; + } + + if (isset($resp['title'])) { + $ret['title'] = $resp['title']; + } else { + return false; + } + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::alternateOver('Trakt Found ').ColorCLI::headerOver($ret['title']), true); + } + + return $ret; + } + + return false; + } + + /** + * Fetch OMDb backdrop / cover / title. + * + * @param $imdbId + * + * @return bool|array + */ + protected function fetchOmdbAPIProperties($imdbId) + { + if ($this->omdbapikey !== '' && $this->omdbApi === null) { + $this->omdbApi = new OMDbAPI($this->omdbapikey); + $resp = $this->omdbApi->fetch('i', 'tt'.$imdbId); + + if (is_object($resp) && $resp->message === 'OK' && $resp->data->Response !== 'False') { + $ret = [ + 'title' => ! empty($resp->data->Title) ? $resp->data->Title : '', + 'cover' => ! empty($resp->data->Poster) ? $resp->data->Poster : '', + 'genre' => ! empty($resp->data->Genre) ? $resp->data->Genre : '', + 'year' => ! empty($resp->data->Year) ? $resp->data->Year : '', + 'plot' => ! empty($resp->data->Plot) ? $resp->data->Plot : '', + 'rating' => ! empty($resp->data->imdbRating) ? $resp->data->imdbRating : '', + 'tagline' => ! empty($resp->data->Tagline) ? $resp->data->Tagline : '', + 'director' => ! empty($resp->data->Director) ? $resp->data->Director : '', + 'actors' => ! empty($resp->data->Actors) ? $resp->data->Actors : '', + 'language' => ! empty($resp->data->Language) ? $resp->data->Language : '', ]; - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::alternateOver('OMDbAPI Found ') . ColorCLI::headerOver($ret['title']), true); - } - return $ret; - } - return false; - } - return false; - } + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::alternateOver('OMDbAPI Found ').ColorCLI::headerOver($ret['title']), true); + } - /** - * Update a release with a IMDB id. - * - * @param string $buffer Data to parse a IMDB id/Trakt Id from. - * @param string $service Method that called this method. - * @param int $id id of the release. - * @param int $processImdb To get IMDB info on this IMDB id or not. - * - * @return string - */ - public function doMovieUpdate($buffer, $service, $id, $processImdb = 1): string - { - $imdbID = false; - if (is_string($buffer) && preg_match('/(?:imdb.*?)?(?:tt|Title\?)(?P<imdbid>\d{5,7})/i', $buffer, $matches)) { - $imdbID = $matches['imdbid']; - } + return $ret; + } - if ($imdbID !== false) { - $this->service = $service; - if ($this->echooutput && $this->service !== '') { - ColorCLI::doEcho(ColorCLI::headerOver($service . ' found IMDBid: ') . ColorCLI::primary('tt' . $imdbID)); - } + return false; + } - $this->pdo->queryExec(sprintf('UPDATE releases SET imdbid = %s WHERE id = %d', $this->pdo->escapeString($imdbID), $id)); + return false; + } - // If set, scan for imdb info. - if ($processImdb === 1) { - $movCheck = $this->getMovieInfo($imdbID); - if ($movCheck === false || (isset($movCheck['updateddate']) && (time() - strtotime($movCheck['updateddate'])) > 2592000)) { - if ($this->updateMovieInfo($imdbID) === false) { - $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $id)); - } - } - } - } - return $imdbID; - } + /** + * Update a release with a IMDB id. + * + * @param string $buffer Data to parse a IMDB id/Trakt Id from. + * @param string $service Method that called this method. + * @param int $id id of the release. + * @param int $processImdb To get IMDB info on this IMDB id or not. + * + * @return string + */ + public function doMovieUpdate($buffer, $service, $id, $processImdb = 1): string + { + $imdbID = false; + if (is_string($buffer) && preg_match('/(?:imdb.*?)?(?:tt|Title\?)(?P<imdbid>\d{5,7})/i', $buffer, $matches)) { + $imdbID = $matches['imdbid']; + } - /** - * Process releases with no IMDB id's. - * - * @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. - * @param int $lookupIMDB (Optional) 0 Don't lookup IMDB, 1 lookup IMDB, 2 lookup IMDB on releases that were renamed. - */ - public function processMovieReleases($groupID = '', $guidChar = '', $lookupIMDB = 1): void - { - if ($lookupIMDB === 0) { - return; - } + if ($imdbID !== false) { + $this->service = $service; + if ($this->echooutput && $this->service !== '') { + ColorCLI::doEcho(ColorCLI::headerOver($service.' found IMDBid: ').ColorCLI::primary('tt'.$imdbID)); + } - // Get all releases without an IMDB id. - $res = $this->pdo->query( + $this->pdo->queryExec(sprintf('UPDATE releases SET imdbid = %s WHERE id = %d', $this->pdo->escapeString($imdbID), $id)); + + // If set, scan for imdb info. + if ($processImdb === 1) { + $movCheck = $this->getMovieInfo($imdbID); + if ($movCheck === false || (isset($movCheck['updateddate']) && (time() - strtotime($movCheck['updateddate'])) > 2592000)) { + if ($this->updateMovieInfo($imdbID) === false) { + $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $id)); + } + } + } + } + + return $imdbID; + } + + /** + * Process releases with no IMDB id's. + * + * @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. + * @param int $lookupIMDB (Optional) 0 Don't lookup IMDB, 1 lookup IMDB, 2 lookup IMDB on releases that were renamed. + */ + public function processMovieReleases($groupID = '', $guidChar = '', $lookupIMDB = 1): void + { + if ($lookupIMDB === 0) { + return; + } + + // Get all releases without an IMDB id. + $res = $this->pdo->query( sprintf(' SELECT searchname, id FROM releases @@ -1154,308 +1176,309 @@ class Movie %s %s %s LIMIT %d', $this->catWhere, - ($groupID === '' ? '' : ('AND groups_id = ' . $groupID)), - ($guidChar === '' ? '' : 'AND leftguid = ' . $this->pdo->escapeString($guidChar)), + ($groupID === '' ? '' : ('AND groups_id = '.$groupID)), + ($guidChar === '' ? '' : 'AND leftguid = '.$this->pdo->escapeString($guidChar)), ($lookupIMDB === 2 ? 'AND isrenamed = 1' : ''), $this->movieqty ) ); - $movieCount = count($res); + $movieCount = count($res); - if ($movieCount > 0) { - if ($this->traktTv === null) { - $this->traktTv = new TraktTv(['Settings' => $this->pdo]); - } - if ($this->echooutput && $movieCount > 1) { - ColorCLI::doEcho(ColorCLI::header('Processing ' . $movieCount . ' movie releases.')); - } + if ($movieCount > 0) { + if ($this->traktTv === null) { + $this->traktTv = new TraktTv(['Settings' => $this->pdo]); + } + if ($this->echooutput && $movieCount > 1) { + ColorCLI::doEcho(ColorCLI::header('Processing '.$movieCount.' movie releases.')); + } - // Loop over releases. - foreach ($res as $arr) { - // Try to get a name/year. - if ($this->parseMovieSearchName($arr['searchname']) === false) { - //We didn't find a name, so set to all 0's so we don't parse again. - $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $arr['id'])); - continue; - } - $this->currentRelID = $arr['id']; + // Loop over releases. + foreach ($res as $arr) { + // Try to get a name/year. + if ($this->parseMovieSearchName($arr['searchname']) === false) { + //We didn't find a name, so set to all 0's so we don't parse again. + $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $arr['id'])); + continue; + } + $this->currentRelID = $arr['id']; - $movieName = $this->currentTitle; - if ($this->currentYear !== false) { - $movieName .= ' (' . $this->currentYear . ')'; - } + $movieName = $this->currentTitle; + if ($this->currentYear !== false) { + $movieName .= ' ('.$this->currentYear.')'; + } - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::primaryOver('Looking up: ') . ColorCLI::headerOver($movieName), true); - } + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::primaryOver('Looking up: ').ColorCLI::headerOver($movieName), true); + } - $movieUpdated = false; + $movieUpdated = false; - // Check local DB. - $getIMDBid = $this->localIMDBsearch(); + // Check local DB. + $getIMDBid = $this->localIMDBsearch(); - if ($getIMDBid !== false) { - $imdbID = $this->doMovieUpdate('tt' . $getIMDBid, 'Local DB', $arr['id']); - if ($imdbID !== false) { - $movieUpdated = true; - } - } + if ($getIMDBid !== false) { + $imdbID = $this->doMovieUpdate('tt'.$getIMDBid, 'Local DB', $arr['id']); + if ($imdbID !== false) { + $movieUpdated = true; + } + } - // Check OMDbAPI - if ($movieUpdated === false) { - $omdbTitle = strtolower(str_replace(' ', '_', $this->currentTitle)); - if ($this->omdbapikey !== '' && $this->omdbApi === null) { - $this->omdbApi = new OMDbAPI($this->omdbapikey); - $buffer = $this->omdbApi->search($omdbTitle, 'movie'); + // Check OMDbAPI + if ($movieUpdated === false) { + $omdbTitle = strtolower(str_replace(' ', '_', $this->currentTitle)); + if ($this->omdbapikey !== '' && $this->omdbApi === null) { + $this->omdbApi = new OMDbAPI($this->omdbapikey); + $buffer = $this->omdbApi->search($omdbTitle, 'movie'); - if (is_object($buffer) && $buffer->message === 'OK' && $buffer->data->Response !== 'False') { - $getIMDBid = $buffer->data->Search[0]->imdbID; + if (is_object($buffer) && $buffer->message === 'OK' && $buffer->data->Response !== 'False') { + $getIMDBid = $buffer->data->Search[0]->imdbID; - if (!empty($getIMDBid)) { - $imdbID = $this->doMovieUpdate($getIMDBid, 'OMDbAPI', $arr['id']); - if ($imdbID !== false) { - $movieUpdated = true; - } - } - } - } - } + if (! empty($getIMDBid)) { + $imdbID = $this->doMovieUpdate($getIMDBid, 'OMDbAPI', $arr['id']); + if ($imdbID !== false) { + $movieUpdated = true; + } + } + } + } + } - // Check on Trakt. - if ($movieUpdated === false) { - $data = $this->traktTv->client->movieSummary($movieName, 'full'); - if ($data !== false) { - $this->parseTraktTv($data); - if (!empty($data['ids']['imdb'])) { - $imdbID = $this->doMovieUpdate($data['ids']['imdb'], 'Trakt', $arr['id']); - if ($imdbID !== false) { - $movieUpdated = true; - } - } - } - } + // Check on Trakt. + if ($movieUpdated === false) { + $data = $this->traktTv->client->movieSummary($movieName, 'full'); + if ($data !== false) { + $this->parseTraktTv($data); + if (! empty($data['ids']['imdb'])) { + $imdbID = $this->doMovieUpdate($data['ids']['imdb'], 'Trakt', $arr['id']); + if ($imdbID !== false) { + $movieUpdated = true; + } + } + } + } - // Try on search engines. - if ($movieUpdated === false) { - if ($this->searchEngines && $this->currentYear !== false) { - if ($this->imdbIDFromEngines() === true) { - $movieUpdated = true; - } - } - } + // Try on search engines. + if ($movieUpdated === false) { + if ($this->searchEngines && $this->currentYear !== false) { + if ($this->imdbIDFromEngines() === true) { + $movieUpdated = true; + } + } + } - // We failed to get an IMDB id from all sources. - if ($movieUpdated === false) { - $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $arr['id'])); - } - } - } - } + // We failed to get an IMDB id from all sources. + if ($movieUpdated === false) { + $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $arr['id'])); + } + } + } + } - /** - * Try to fetch an IMDB id locally. - * - * @return int|bool Int, the imdbid when true, Bool when false. - */ - protected function localIMDBsearch() - { - $query = 'SELECT imdbid FROM movieinfo'; - $andYearIn = ''; + /** + * Try to fetch an IMDB id locally. + * + * @return int|bool Int, the imdbid when true, Bool when false. + */ + protected function localIMDBsearch() + { + $query = 'SELECT imdbid FROM movieinfo'; + $andYearIn = ''; - //If we found a year, try looking in a 4 year range. - if ($this->currentYear !== false) { - $start = (int) $this->currentYear - 2; - $end = (int) $this->currentYear + 2; - $andYearIn = 'AND year IN ('; - while ($start < $end) { - $andYearIn .= $start . ','; - $start++; - } - $andYearIn .= $end . ')'; - } - $IMDBCheck = $this->pdo->queryOneRow( + //If we found a year, try looking in a 4 year range. + if ($this->currentYear !== false) { + $start = (int) $this->currentYear - 2; + $end = (int) $this->currentYear + 2; + $andYearIn = 'AND year IN ('; + while ($start < $end) { + $andYearIn .= $start.','; + $start++; + } + $andYearIn .= $end.')'; + } + $IMDBCheck = $this->pdo->queryOneRow( sprintf('%s WHERE title %s %s', $query, $this->pdo->likeString($this->currentTitle), $andYearIn)); - // Look by %word%word%word% etc.. - if ($IMDBCheck === false) { - $pieces = explode(' ', $this->currentTitle); - $tempTitle = '%'; - foreach ($pieces as $piece) { - $tempTitle .= str_replace(["'", '!', '"'], '', $piece) . '%'; - } - $IMDBCheck = $this->pdo->queryOneRow( + // Look by %word%word%word% etc.. + if ($IMDBCheck === false) { + $pieces = explode(' ', $this->currentTitle); + $tempTitle = '%'; + foreach ($pieces as $piece) { + $tempTitle .= str_replace(["'", '!', '"'], '', $piece).'%'; + } + $IMDBCheck = $this->pdo->queryOneRow( sprintf("%s WHERE replace(replace(title, \"'\", ''), '!', '') %s %s", $query, $this->pdo->likeString($tempTitle), $andYearIn ) ); - } + } - // Try replacing er with re ? - if ($IMDBCheck === false) { - $tempTitle = str_replace('er', 're', $this->currentTitle); - if ($tempTitle !== $this->currentTitle) { - $IMDBCheck = $this->pdo->queryOneRow( + // Try replacing er with re ? + if ($IMDBCheck === false) { + $tempTitle = str_replace('er', 're', $this->currentTitle); + if ($tempTitle !== $this->currentTitle) { + $IMDBCheck = $this->pdo->queryOneRow( sprintf('%s WHERE title %s %s', $query, $this->pdo->likeString($tempTitle), $andYearIn ) ); - // Final check if everything else failed. - if ($IMDBCheck === false) { - $pieces = explode(' ', $tempTitle); - $tempTitle = '%'; - foreach ($pieces as $piece) { - $tempTitle .= str_replace(["'", '!', '"'], '', $piece) . '%'; - } - $IMDBCheck = $this->pdo->queryOneRow( + // Final check if everything else failed. + if ($IMDBCheck === false) { + $pieces = explode(' ', $tempTitle); + $tempTitle = '%'; + foreach ($pieces as $piece) { + $tempTitle .= str_replace(["'", '!', '"'], '', $piece).'%'; + } + $IMDBCheck = $this->pdo->queryOneRow( sprintf("%s WHERE replace(replace(replace(title, \"'\", ''), '!', ''), '\"', '') %s %s", $query, $this->pdo->likeString($tempTitle), $andYearIn ) ); - } - } - } + } + } + } - return ( + return $IMDBCheck === false ? false : (is_numeric($IMDBCheck['imdbid']) - ? (int)$IMDBCheck['imdbid'] + ? (int) $IMDBCheck['imdbid'] : false - ) - ); - } + ); + } - /** - * Try to get an IMDB id from search engines. - * - * @return bool - */ - protected function imdbIDFromEngines(): bool - { - if ($this->googleLimit < 41 && (time() - $this->googleBan) > 600) { - if ($this->googleSearch() === true) { - return true; - } - } + /** + * Try to get an IMDB id from search engines. + * + * @return bool + */ + protected function imdbIDFromEngines(): bool + { + if ($this->googleLimit < 41 && (time() - $this->googleBan) > 600) { + if ($this->googleSearch() === true) { + return true; + } + } - if ($this->yahooLimit < 41 && $this->yahooSearch() === true) { - return true; - } + if ($this->yahooLimit < 41 && $this->yahooSearch() === true) { + return true; + } - // Not using this right now because bing's advanced search is not good enough. - /*if ($this->bingLimit < 41) { - if ($this->bingSearch() === true) { - return true; - } - }*/ + // Not using this right now because bing's advanced search is not good enough. + /*if ($this->bingLimit < 41) { + if ($this->bingSearch() === true) { + return true; + } + }*/ - return false; - } + return false; + } - /** - * Try to find a IMDB id on google.com - * - * @return bool - */ - protected function googleSearch(): bool - { - try { - $buffer = $this->client->get( - 'https://www.google.com/search?hl=en&as_q=&as_epq=' . + /** + * Try to find a IMDB id on google.com. + * + * @return bool + */ + protected function googleSearch(): bool + { + try { + $buffer = $this->client->get( + 'https://www.google.com/search?hl=en&as_q=&as_epq='. urlencode( - $this->currentTitle . - ' ' . + $this->currentTitle. + ' '. $this->currentYear - ) . - '&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch=' . - urlencode('www.imdb.com/title/') . + ). + '&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch='. + urlencode('www.imdb.com/title/'). '&as_occt=title&safe=images&tbs=&as_filetype=&as_rights=' )->getBody()->getContents(); - } catch (RequestException $e) { - if ($e->hasResponse()) { - if($e->getCode() === 404) { - ColorCLI::doEcho(ColorCLI::notice('Data not available on Google search')); - } else if ($e->getCode() === 503) { - ColorCLI::doEcho(ColorCLI::notice('Google service unavailable')); - } else { - ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Google, http error reported: ' . $e->getCode())); - } - } - } catch (\RuntimeException $e) { - ColorCLI::doEcho(ColorCLI::notice('Runtime error: ' . $e->getCode())); - } + } catch (RequestException $e) { + if ($e->hasResponse()) { + if ($e->getCode() === 404) { + ColorCLI::doEcho(ColorCLI::notice('Data not available on Google search')); + } elseif ($e->getCode() === 503) { + ColorCLI::doEcho(ColorCLI::notice('Google service unavailable')); + } else { + ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Google, http error reported: '.$e->getCode())); + } + } + } catch (\RuntimeException $e) { + ColorCLI::doEcho(ColorCLI::notice('Runtime error: '.$e->getCode())); + } - // Make sure we got some data. - if (!empty($buffer)) { - $this->googleLimit++; + // Make sure we got some data. + if (! empty($buffer)) { + $this->googleLimit++; - if (preg_match('/(To continue, please type the characters below)|(- did not match any documents\.)/i', $buffer, $matches)) { - if (!empty($matches[1])) { - $this->googleBan = time(); - } - } else if ($this->doMovieUpdate($buffer, 'Google.com', $this->currentRelID) !== false) { - return true; - } - } - return false; - } + if (preg_match('/(To continue, please type the characters below)|(- did not match any documents\.)/i', $buffer, $matches)) { + if (! empty($matches[1])) { + $this->googleBan = time(); + } + } elseif ($this->doMovieUpdate($buffer, 'Google.com', $this->currentRelID) !== false) { + return true; + } + } - /** - * Try to find a IMDB id on bing.com - * - * @return bool - */ - protected function bingSearch(): bool - { - try { - $buffer = $this->client->get( - 'http://www.bing.com/search?q=' . + return false; + } + + /** + * Try to find a IMDB id on bing.com. + * + * @return bool + */ + protected function bingSearch(): bool + { + try { + $buffer = $this->client->get( + 'http://www.bing.com/search?q='. urlencode( - '("' . - $this->currentTitle . - '" and "' . - $this->currentYear . + '("'. + $this->currentTitle. + '" and "'. + $this->currentYear. '") site:www.imdb.com/title/' - ) . + ). '&qs=n&form=QBLH&filt=all' )->getBody()->getContents(); - } catch (RequestException $e) { - if ($e->hasResponse()) { - if($e->getCode() === 404) { - ColorCLI::doEcho(ColorCLI::notice('Data not available on Bing search')); - } else if ($e->getCode() === 503) { - ColorCLI::doEcho(ColorCLI::notice('Bing search service unavailable')); - } else { - ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Bing search , http error reported: ' . $e->getCode())); - } - } - } catch (\RuntimeException $e) { - ColorCLI::doEcho(ColorCLI::notice('Runtime error: ' . $e->getCode())); - } + } catch (RequestException $e) { + if ($e->hasResponse()) { + if ($e->getCode() === 404) { + ColorCLI::doEcho(ColorCLI::notice('Data not available on Bing search')); + } elseif ($e->getCode() === 503) { + ColorCLI::doEcho(ColorCLI::notice('Bing search service unavailable')); + } else { + ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Bing search , http error reported: '.$e->getCode())); + } + } + } catch (\RuntimeException $e) { + ColorCLI::doEcho(ColorCLI::notice('Runtime error: '.$e->getCode())); + } - if (!empty($buffer)) { - $this->bingLimit++; + if (! empty($buffer)) { + $this->bingLimit++; - if ($this->doMovieUpdate($buffer, 'Bing.com', $this->currentRelID) !== false) { - return true; - } - } - return false; - } + if ($this->doMovieUpdate($buffer, 'Bing.com', $this->currentRelID) !== false) { + return true; + } + } - /** - * Try to find a IMDB id on yahoo.com - * - * @return bool - */ - protected function yahooSearch(): bool - { - try { - $buffer = $this->client->get( - 'http://search.yahoo.com/search?n=10&ei=UTF-8&va_vt=title&vo_vt=any&ve_vt=any&vp_vt=any&vf=all&vm=p&fl=0&fr=fp-top&p=' . + return false; + } + + /** + * Try to find a IMDB id on yahoo.com. + * + * @return bool + */ + protected function yahooSearch(): bool + { + try { + $buffer = $this->client->get( + 'http://search.yahoo.com/search?n=10&ei=UTF-8&va_vt=title&vo_vt=any&ve_vt=any&vp_vt=any&vf=all&vm=p&fl=0&fr=fp-top&p='. urlencode( - '' . + ''. implode('+', explode( ' ', @@ -1469,95 +1492,98 @@ class Movie ) ) ) - ) . - '+' . + ). + '+'. $this->currentYear - ) . - '&vs=' . + ). + '&vs='. urlencode('www.imdb.com/title/') )->getBody()->getContents(); - } catch (RequestException $e) { - if ($e->hasResponse()) { - if($e->getCode() === 404) { - ColorCLI::doEcho(ColorCLI::notice('Data not available on Yahoo search')); - } else if ($e->getCode() === 503) { - ColorCLI::doEcho(ColorCLI::notice('Yahoo search service unavailable')); - } else { - ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Yahoo search, http error reported: ' . $e->getCode())); - } - } - } catch (\RuntimeException $e) { - ColorCLI::doEcho(ColorCLI::notice('Runtime error: ' . $e->getCode())); - } + } catch (RequestException $e) { + if ($e->hasResponse()) { + if ($e->getCode() === 404) { + ColorCLI::doEcho(ColorCLI::notice('Data not available on Yahoo search')); + } elseif ($e->getCode() === 503) { + ColorCLI::doEcho(ColorCLI::notice('Yahoo search service unavailable')); + } else { + ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Yahoo search, http error reported: '.$e->getCode())); + } + } + } catch (\RuntimeException $e) { + ColorCLI::doEcho(ColorCLI::notice('Runtime error: '.$e->getCode())); + } - if (!empty($buffer)) { - $this->yahooLimit++; + if (! empty($buffer)) { + $this->yahooLimit++; - if ($this->doMovieUpdate($buffer, 'Yahoo.com', $this->currentRelID) !== false) { - return true; - } - } - return false; - } + if ($this->doMovieUpdate($buffer, 'Yahoo.com', $this->currentRelID) !== false) { + return true; + } + } - /** - * Parse a movie name from a release search name. - * - * @param string $releaseName - * - * @return bool - */ - protected function parseMovieSearchName($releaseName): bool - { - $name = $year = ''; - $followingList = '[^\w]((1080|480|720)p|AC3D|Directors([^\w]CUT)?|DD5\.1|(DVD|BD|BR)(Rip)?|BluRay|divx|HDTV|iNTERNAL|LiMiTED|(Real\.)?Proper|RE(pack|Rip)|Sub\.?(fix|pack)|Unrated|WEB-DL|(x|H)[-._ ]?264|xvid)[^\w]'; + return false; + } - /* Initial scan of getting a year/name. - * [\w. -]+ Gets 0-9a-z. - characters, most scene movie titles contain these chars. - * ie: [61420]-[FULL]-[a.b.foreignEFNet]-[ Coraline.2009.DUTCH.INTERNAL.1080p.BluRay.x264-VeDeTT ]-[21/85] - "vedett-coralien-1080p.r04" yEnc - * Then we look up the year, (19|20)\d\d, so $matches[1] would be Coraline $matches[2] 2009 - */ - if (preg_match('/(?P<name>[\w. -]+)[^\w](?P<year>(19|20)\d\d)/i', $releaseName, $matches)) { - $name = $matches['name']; - $year = $matches['year']; + /** + * Parse a movie name from a release search name. + * + * @param string $releaseName + * + * @return bool + */ + protected function parseMovieSearchName($releaseName): bool + { + $name = $year = ''; + $followingList = '[^\w]((1080|480|720)p|AC3D|Directors([^\w]CUT)?|DD5\.1|(DVD|BD|BR)(Rip)?|BluRay|divx|HDTV|iNTERNAL|LiMiTED|(Real\.)?Proper|RE(pack|Rip)|Sub\.?(fix|pack)|Unrated|WEB-DL|(x|H)[-._ ]?264|xvid)[^\w]'; - /* If we didn't find a year, try to get a name anyways. - * Try to look for a title before the $followingList and after anything but a-z0-9 two times or more (-[ for example) - */ - } else if (preg_match('/([^\w]{2,})?(?P<name>[\w .-]+?)' . $followingList . '/i', $releaseName, $matches)) { - $name = $matches['name']; - } + /* Initial scan of getting a year/name. + * [\w. -]+ Gets 0-9a-z. - characters, most scene movie titles contain these chars. + * ie: [61420]-[FULL]-[a.b.foreignEFNet]-[ Coraline.2009.DUTCH.INTERNAL.1080p.BluRay.x264-VeDeTT ]-[21/85] - "vedett-coralien-1080p.r04" yEnc + * Then we look up the year, (19|20)\d\d, so $matches[1] would be Coraline $matches[2] 2009 + */ + if (preg_match('/(?P<name>[\w. -]+)[^\w](?P<year>(19|20)\d\d)/i', $releaseName, $matches)) { + $name = $matches['name']; + $year = $matches['year']; - // Check if we got something. - if ($name !== '') { + /* If we didn't find a year, try to get a name anyways. + * Try to look for a title before the $followingList and after anything but a-z0-9 two times or more (-[ for example) + */ + } elseif (preg_match('/([^\w]{2,})?(?P<name>[\w .-]+?)'.$followingList.'/i', $releaseName, $matches)) { + $name = $matches['name']; + } + + // Check if we got something. + if ($name !== '') { // If we still have any of the words in $followingList, remove them. - $name = preg_replace('/' . $followingList . '/i', ' ', $name); - // Remove periods, underscored, anything between parenthesis. - $name = preg_replace('/\(.*?\)|[._]/i', ' ', $name); - // Finally remove multiple spaces and trim leading spaces. - $name = trim(preg_replace('/\s{2,}/', ' ', $name)); - // Check if the name is long enough and not just numbers. - if (strlen($name) > 4 && !preg_match('/^\d+$/', $name)) { - if ($this->debug && $this->echooutput) { - ColorCLI::doEcho("DB name: {$releaseName}", true); - } - $this->currentTitle = $name; - $this->currentYear = ($year === '' ? false : $year); - return true; - } - } - return false; - } + $name = preg_replace('/'.$followingList.'/i', ' ', $name); + // Remove periods, underscored, anything between parenthesis. + $name = preg_replace('/\(.*?\)|[._]/i', ' ', $name); + // Finally remove multiple spaces and trim leading spaces. + $name = trim(preg_replace('/\s{2,}/', ' ', $name)); + // Check if the name is long enough and not just numbers. + if (strlen($name) > 4 && ! preg_match('/^\d+$/', $name)) { + if ($this->debug && $this->echooutput) { + ColorCLI::doEcho("DB name: {$releaseName}", true); + } + $this->currentTitle = $name; + $this->currentYear = ($year === '' ? false : $year); - /** - * Get IMDB genres. - * - * @return array - */ - public function getGenres(): array - { - return [ + return true; + } + } + + return false; + } + + /** + * Get IMDB genres. + * + * @return array + */ + public function getGenres(): array + { + return [ 'Action', 'Adventure', 'Animation', @@ -1583,8 +1609,7 @@ class Movie 'Talk-Show', 'Thriller', 'War', - 'Western' + 'Western', ]; - } - + } } diff --git a/nntmux/Music.php b/nntmux/Music.php index f883efc4e..68e08ba07 100755 --- a/nntmux/Music.php +++ b/nntmux/Music.php @@ -1,175 +1,177 @@ <?php + namespace nntmux; -use ApaiIO\Request\GuzzleRequest; -use ApaiIO\ResponseTransformer\XmlToSimpleXmlObject; -use App\Models\Settings; -use GuzzleHttp\Client; use nntmux\db\DB; -use ApaiIO\Configuration\GenericConfiguration; -use ApaiIO\Operations\Search; use ApaiIO\ApaiIO; +use GuzzleHttp\Client; +use App\Models\Settings; +use ApaiIO\Operations\Search; +use ApaiIO\Request\GuzzleRequest; +use ApaiIO\Configuration\GenericConfiguration; +use ApaiIO\ResponseTransformer\XmlToSimpleXmlObject; /** - * Class Music + * Class Music. */ class Music { - /** - * @var \nntmux\db\Settings - */ - public $pdo; + /** + * @var \nntmux\db\Settings + */ + public $pdo; - /** - * @var bool - */ - public $echooutput; + /** + * @var bool + */ + public $echooutput; - /** - * @var array|bool|string - */ - public $pubkey; + /** + * @var array|bool|string + */ + public $pubkey; - /** - * @var array|bool|string - */ - public $privkey; + /** + * @var array|bool|string + */ + public $privkey; - /** - * @var array|bool|string - */ - public $asstag; + /** + * @var array|bool|string + */ + public $asstag; - /** - * @var array|bool|int|string - */ - public $musicqty; + /** + * @var array|bool|int|string + */ + public $musicqty; - /** - * @var array|bool|int|string - */ - public $sleeptime; + /** + * @var array|bool|int|string + */ + public $sleeptime; - /** - * @var string - */ - public $imgSavePath; + /** + * @var string + */ + public $imgSavePath; - /** - * @var string - */ - public $renamed; + /** + * @var string + */ + public $renamed; - /** - * Store names of failed Amazon lookup items - * @var array - */ - public $failCache; + /** + * Store names of failed Amazon lookup items. + * @var array + */ + public $failCache; - /** - * @param array $options Class instances/ echo to CLI. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances/ echo to CLI. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->pubkey = Settings::value('APIs..amazonpubkey'); - $this->privkey = Settings::value('APIs..amazonprivkey'); - $this->asstag = Settings::value('APIs..amazonassociatetag'); - $this->musicqty = Settings::value('..maxmusicprocessed') != '' ? Settings::value('..maxmusicprocessed') : 150; - $this->sleeptime = Settings::value('..amazonsleep') != '' ? Settings::value('..amazonsleep') : 1000; - $this->imgSavePath = NN_COVERS . 'music' . DS; - $this->renamed = ''; - if (Settings::value('..lookupmusic') == 2) { - $this->renamed = 'AND isrenamed = 1'; - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->pubkey = Settings::value('APIs..amazonpubkey'); + $this->privkey = Settings::value('APIs..amazonprivkey'); + $this->asstag = Settings::value('APIs..amazonassociatetag'); + $this->musicqty = Settings::value('..maxmusicprocessed') != '' ? Settings::value('..maxmusicprocessed') : 150; + $this->sleeptime = Settings::value('..amazonsleep') != '' ? Settings::value('..amazonsleep') : 1000; + $this->imgSavePath = NN_COVERS.'music'.DS; + $this->renamed = ''; + if (Settings::value('..lookupmusic') == 2) { + $this->renamed = 'AND isrenamed = 1'; + } - $this->failCache = []; - } + $this->failCache = []; + } - /** - * @param $id - * - * @return array|bool - */ - public function getMusicInfo($id) - { - return $this->pdo->queryOneRow(sprintf('SELECT musicinfo.*, genres.title AS genres FROM musicinfo LEFT OUTER JOIN genres ON genres.id = musicinfo.genres_id WHERE musicinfo.id = %d ', $id)); - } + /** + * @param $id + * + * @return array|bool + */ + public function getMusicInfo($id) + { + return $this->pdo->queryOneRow(sprintf('SELECT musicinfo.*, genres.title AS genres FROM musicinfo LEFT OUTER JOIN genres ON genres.id = musicinfo.genres_id WHERE musicinfo.id = %d ', $id)); + } - /** - * @param $artist - * @param $album - * - * @return array|bool - */ - public function getMusicInfoByName($artist, $album) - { - $pdo = $this->pdo; - $like = 'ILIKE'; - if ($pdo->DbSystem() === 'mysql') { - $like = 'LIKE'; - } + /** + * @param $artist + * @param $album + * + * @return array|bool + */ + public function getMusicInfoByName($artist, $album) + { + $pdo = $this->pdo; + $like = 'ILIKE'; + if ($pdo->DbSystem() === 'mysql') { + $like = 'LIKE'; + } - //only used to get a count of words - $searchwords = $searchsql = ''; - $ft = $pdo->queryDirect("SHOW INDEX FROM musicinfo WHERE key_name = 'ix_musicinfo_artist_title_ft'"); - if ($ft->rowCount() !== 2) { - $searchsql .= sprintf(" artist LIKE %s AND title %s %s'", $pdo->escapeString('%' . $artist . '%'), $like, $pdo->escapeString('%' . $album . '%')); - } else { - $album = preg_replace('/( - | -|\(.+\)|\(|\))/', ' ', $album); - $album = preg_replace('/[^\w ]+/', '', $album); - $album = preg_replace('/(WEB|FLAC|CD)/', '', $album); - $album = trim(preg_replace('/\s\s+/i', ' ', $album)); - $album = trim($album); - $words = explode(' ', $album); + //only used to get a count of words + $searchwords = $searchsql = ''; + $ft = $pdo->queryDirect("SHOW INDEX FROM musicinfo WHERE key_name = 'ix_musicinfo_artist_title_ft'"); + if ($ft->rowCount() !== 2) { + $searchsql .= sprintf(" artist LIKE %s AND title %s %s'", $pdo->escapeString('%'.$artist.'%'), $like, $pdo->escapeString('%'.$album.'%')); + } else { + $album = preg_replace('/( - | -|\(.+\)|\(|\))/', ' ', $album); + $album = preg_replace('/[^\w ]+/', '', $album); + $album = preg_replace('/(WEB|FLAC|CD)/', '', $album); + $album = trim(preg_replace('/\s\s+/i', ' ', $album)); + $album = trim($album); + $words = explode(' ', $album); - foreach ($words as $word) { - $word = trim(rtrim(trim($word), '-')); - if ($word !== '' && $word !== '-') { - $word = '+' . $word; - $searchwords .= sprintf('%s ', $word); - } - } - $searchwords = trim($searchwords); - $searchsql .= sprintf(' MATCH(artist, title) AGAINST(%s IN BOOLEAN MODE)', $pdo->escapeString($searchwords)); - } - return $pdo->queryOneRow(sprintf('SELECT * FROM musicinfo WHERE %s', $searchsql)); - } + foreach ($words as $word) { + $word = trim(rtrim(trim($word), '-')); + if ($word !== '' && $word !== '-') { + $word = '+'.$word; + $searchwords .= sprintf('%s ', $word); + } + } + $searchwords = trim($searchwords); + $searchsql .= sprintf(' MATCH(artist, title) AGAINST(%s IN BOOLEAN MODE)', $pdo->escapeString($searchwords)); + } - /** - * @param $cat - * @param $start - * @param $num - * @param $orderby - * @param array $excludedcats - * - * @return array - */ - public function getMusicRange($cat, $start, $num, $orderby, array $excludedcats = []) - { - $browseby = $this->getBrowseBy(); + return $pdo->queryOneRow(sprintf('SELECT * FROM musicinfo WHERE %s', $searchsql)); + } - $catsrch = ''; - if (count($cat) > 0 && $cat[0] != -1) { - $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); - } + /** + * @param $cat + * @param $start + * @param $num + * @param $orderby + * @param array $excludedcats + * + * @return array + */ + public function getMusicRange($cat, $start, $num, $orderby, array $excludedcats = []) + { + $browseby = $this->getBrowseBy(); - $exccatlist = ''; - if (count($excludedcats) > 0) { - $exccatlist = ' AND r.categories_id NOT IN (' . implode(',', $excludedcats) . ')'; - } + $catsrch = ''; + if (count($cat) > 0 && $cat[0] != -1) { + $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); + } - $order = $this->getMusicOrder($orderby); + $exccatlist = ''; + if (count($excludedcats) > 0) { + $exccatlist = ' AND r.categories_id NOT IN ('.implode(',', $excludedcats).')'; + } - $music = $this->pdo->queryCalc( + $order = $this->getMusicOrder($orderby); + + $music = $this->pdo->queryCalc( sprintf(" SELECT SQL_CALC_FOUND_ROWS m.id, @@ -189,20 +191,20 @@ class Music $exccatlist, $order[0], $order[1], - ($start === false ? '' : ' LIMIT ' . $num . ' OFFSET ' . $start) + ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start) ), true, NN_CACHE_EXPIRY_MEDIUM ); - $musicIDs = $releaseIDs = false; + $musicIDs = $releaseIDs = false; - if (is_array($music['result'])) { - foreach ($music['result'] AS $mus => $id) { - $musicIDs[] = $id['id']; - $releaseIDs[] = $id['grp_release_id']; - } - } + if (is_array($music['result'])) { + foreach ($music['result'] as $mus => $id) { + $musicIDs[] = $id['id']; + $releaseIDs[] = $id['grp_release_id']; + } + } - $sql = sprintf(" + $sql = sprintf(" SELECT GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id, GROUP_CONCAT(r.rarinnerfilecount ORDER BY r.postdate DESC SEPARATOR ',') as grp_rarinnerfilecount, @@ -238,24 +240,24 @@ class Music $order[0], $order[1] ); - $return = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - if (!empty($return)) { - $return[0]['_totalcount'] = $music['total'] ?? 0; - } + $return = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); + if (! empty($return)) { + $return[0]['_totalcount'] = $music['total'] ?? 0; + } - return $return; - } + return $return; + } - /** - * @param $orderby - * - * @return array - */ - public function getMusicOrder($orderby) - { - $order = ($orderby == '') ? 'r.postdate' : $orderby; - $orderArr = explode("_", $order); - switch ($orderArr[0]) { + /** + * @param $orderby + * + * @return array + */ + public function getMusicOrder($orderby) + { + $order = ($orderby == '') ? 'r.postdate' : $orderby; + $orderArr = explode('_', $order); + switch ($orderArr[0]) { case 'artist': $orderfield = 'm.artist'; break; @@ -279,87 +281,90 @@ class Music $orderfield = 'r.postdate'; break; } - $ordersort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc'; - return array($orderfield, $ordersort); - } + $ordersort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc'; - /** - * @return array - */ - public function getMusicOrdering() - { - return array('artist_asc', 'artist_desc', 'posted_asc', 'posted_desc', 'size_asc', 'size_desc', 'files_asc', 'files_desc', 'stats_asc', 'stats_desc', 'year_asc', 'year_desc', 'genre_asc', 'genre_desc'); - } + return [$orderfield, $ordersort]; + } - /** - * @return array - */ - public function getBrowseByOptions() - { - return array('artist' => 'artist', 'title' => 'title', 'genre' => 'genres_id', 'year' => 'year'); - } + /** + * @return array + */ + public function getMusicOrdering() + { + return ['artist_asc', 'artist_desc', 'posted_asc', 'posted_desc', 'size_asc', 'size_desc', 'files_asc', 'files_desc', 'stats_asc', 'stats_desc', 'year_asc', 'year_desc', 'genre_asc', 'genre_desc']; + } - /** - * @return string - */ - public function getBrowseBy() - { - $browseby = ' '; - $browsebyArr = $this->getBrowseByOptions(); - foreach ($browsebyArr as $bbk => $bbv) { - if (isset($_REQUEST[$bbk]) && !empty($_REQUEST[$bbk])) { - $bbs = stripslashes($_REQUEST[$bbk]); - if (stripos($bbv, 'id') !== false) { - $browseby .= 'AND m.' . $bbv . ' = ' . $bbs; - } else { - $browseby .= 'AND m.' . $bbv . ' ' . $this->pdo->likeString($bbs, true, true); - } - } - } - return $browseby; - } + /** + * @return array + */ + public function getBrowseByOptions() + { + return ['artist' => 'artist', 'title' => 'title', 'genre' => 'genres_id', 'year' => 'year']; + } - /** - * @param $data - * @param $field - * - * @return string - */ - public function makeFieldLinks($data, $field) - { - $tmpArr = explode(', ', $data[$field]); - $newArr = []; - $i = 0; - foreach ($tmpArr as $ta) { - if (trim($ta) == '') { - continue; - } - if ($i > 5) { - break; - } //only use first 6 - $newArr[] = '<a href="' . WWW_TOP . '/music?' . $field . '=' . urlencode($ta) . '" title="' . $ta . '">' . $ta . '</a>'; - $i++; - } - return implode(', ', $newArr); - } + /** + * @return string + */ + public function getBrowseBy() + { + $browseby = ' '; + $browsebyArr = $this->getBrowseByOptions(); + foreach ($browsebyArr as $bbk => $bbv) { + if (isset($_REQUEST[$bbk]) && ! empty($_REQUEST[$bbk])) { + $bbs = stripslashes($_REQUEST[$bbk]); + if (stripos($bbv, 'id') !== false) { + $browseby .= 'AND m.'.$bbv.' = '.$bbs; + } else { + $browseby .= 'AND m.'.$bbv.' '.$this->pdo->likeString($bbs, true, true); + } + } + } - /** - * @param $id - * @param $title - * @param $asin - * @param $url - * @param $salesrank - * @param $artist - * @param $publisher - * @param $releasedate - * @param $year - * @param $tracks - * @param $cover - * @param $genres_id - */ - public function update($id, $title, $asin, $url, $salesrank, $artist, $publisher, $releasedate, $year, $tracks, $cover, $genres_id) - { - $this->pdo->queryExec( + return $browseby; + } + + /** + * @param $data + * @param $field + * + * @return string + */ + public function makeFieldLinks($data, $field) + { + $tmpArr = explode(', ', $data[$field]); + $newArr = []; + $i = 0; + foreach ($tmpArr as $ta) { + if (trim($ta) == '') { + continue; + } + if ($i > 5) { + break; + } //only use first 6 + $newArr[] = '<a href="'.WWW_TOP.'/music?'.$field.'='.urlencode($ta).'" title="'.$ta.'">'.$ta.'</a>'; + $i++; + } + + return implode(', ', $newArr); + } + + /** + * @param $id + * @param $title + * @param $asin + * @param $url + * @param $salesrank + * @param $artist + * @param $publisher + * @param $releasedate + * @param $year + * @param $tracks + * @param $cover + * @param $genres_id + */ + public function update($id, $title, $asin, $url, $salesrank, $artist, $publisher, $releasedate, $year, $tracks, $cover, $genres_id) + { + $this->pdo->queryExec( sprintf(' UPDATE musicinfo SET title = %s, asin = %s, url = %s, salesrank = %s, artist = %s, publisher = %s, releasedate = %s, @@ -371,129 +376,129 @@ class Music $this->pdo->escapeString($year), $this->pdo->escapeString($tracks), $cover, $genres_id, $id ) ); - } + } - /** - * @param $title - * @param $year - * @param null $amazdata - * - * @return bool - */ - public function updateMusicInfo($title, $year, $amazdata = null) - { - $gen = new Genres(['Settings' => $this->pdo]); - $ri = new ReleaseImage($this->pdo); - $titlepercent = 0; + /** + * @param $title + * @param $year + * @param null $amazdata + * + * @return bool + */ + public function updateMusicInfo($title, $year, $amazdata = null) + { + $gen = new Genres(['Settings' => $this->pdo]); + $ri = new ReleaseImage($this->pdo); + $titlepercent = 0; - $mus = []; - if ($title != '') { - $amaz = $this->fetchAmazonProperties($title); - } else if ($amazdata != null) { - $amaz = $amazdata; - } else { - $amaz = false; - } + $mus = []; + if ($title != '') { + $amaz = $this->fetchAmazonProperties($title); + } elseif ($amazdata != null) { + $amaz = $amazdata; + } else { + $amaz = false; + } - if (!$amaz) { - return false; - } + if (! $amaz) { + return false; + } - if (isset($amaz->Items->Item->ItemAttributes->Title)) { - $mus['title'] = (string)$amaz->Items->Item->ItemAttributes->Title; - if (empty($mus['title'])) { - return false; - } - } else { - return false; - } + if (isset($amaz->Items->Item->ItemAttributes->Title)) { + $mus['title'] = (string) $amaz->Items->Item->ItemAttributes->Title; + if (empty($mus['title'])) { + return false; + } + } else { + return false; + } - // Load genres. - $defaultGenres = $gen->getGenres(Genres::MUSIC_TYPE); - $genreassoc = []; - foreach ($defaultGenres as $dg) { - $genreassoc[$dg['id']] = strtolower($dg['title']); - } + // Load genres. + $defaultGenres = $gen->getGenres(Genres::MUSIC_TYPE); + $genreassoc = []; + foreach ($defaultGenres as $dg) { + $genreassoc[$dg['id']] = strtolower($dg['title']); + } - // Get album properties. - $mus['coverurl'] = (string)$amaz->Items->Item->LargeImage->URL; - if ($mus['coverurl'] != '') { - $mus['cover'] = 1; - } else { - $mus['cover'] = 0; - } + // Get album properties. + $mus['coverurl'] = (string) $amaz->Items->Item->LargeImage->URL; + if ($mus['coverurl'] != '') { + $mus['cover'] = 1; + } else { + $mus['cover'] = 0; + } - $mus['asin'] = (string)$amaz->Items->Item->ASIN; + $mus['asin'] = (string) $amaz->Items->Item->ASIN; - $mus['url'] = (string)$amaz->Items->Item->DetailPageURL; - $mus['url'] = str_replace('%26tag%3Dws', '%26tag%3Dopensourceins%2D21', $mus['url']); + $mus['url'] = (string) $amaz->Items->Item->DetailPageURL; + $mus['url'] = str_replace('%26tag%3Dws', '%26tag%3Dopensourceins%2D21', $mus['url']); - $mus['salesrank'] = (string)$amaz->Items->Item->SalesRank; - if ($mus['salesrank'] == '') { - $mus['salesrank'] = 'null'; - } + $mus['salesrank'] = (string) $amaz->Items->Item->SalesRank; + if ($mus['salesrank'] == '') { + $mus['salesrank'] = 'null'; + } - $mus['artist'] = (string)$amaz->Items->Item->ItemAttributes->Artist; - if (empty($mus['artist'])) { - $mus['artist'] = (string)$amaz->Items->Item->ItemAttributes->Creator; - if (empty($mus['artist'])) { - $mus['artist'] = ''; - } - } + $mus['artist'] = (string) $amaz->Items->Item->ItemAttributes->Artist; + if (empty($mus['artist'])) { + $mus['artist'] = (string) $amaz->Items->Item->ItemAttributes->Creator; + if (empty($mus['artist'])) { + $mus['artist'] = ''; + } + } - $mus['publisher'] = (string)$amaz->Items->Item->ItemAttributes->Publisher; + $mus['publisher'] = (string) $amaz->Items->Item->ItemAttributes->Publisher; - $mus['releasedate'] = $this->pdo->escapeString((string)$amaz->Items->Item->ItemAttributes->ReleaseDate); - if ($mus['releasedate'] == "''") { - $mus['releasedate'] = 'null'; - } + $mus['releasedate'] = $this->pdo->escapeString((string) $amaz->Items->Item->ItemAttributes->ReleaseDate); + if ($mus['releasedate'] == "''") { + $mus['releasedate'] = 'null'; + } - $mus['review'] = ""; - if (isset($amaz->Items->Item->EditorialReviews)) { - $mus['review'] = trim(strip_tags((string)$amaz->Items->Item->EditorialReviews->EditorialReview->Content)); - } + $mus['review'] = ''; + if (isset($amaz->Items->Item->EditorialReviews)) { + $mus['review'] = trim(strip_tags((string) $amaz->Items->Item->EditorialReviews->EditorialReview->Content)); + } - $mus['year'] = $year; - if ($mus['year'] == '') { - $mus['year'] = ($mus['releasedate'] != 'null' ? substr($mus['releasedate'], 1, 4) : date('Y')); - } + $mus['year'] = $year; + if ($mus['year'] == '') { + $mus['year'] = ($mus['releasedate'] != 'null' ? substr($mus['releasedate'], 1, 4) : date('Y')); + } - $mus['tracks'] = ''; - if (isset($amaz->Items->Item->Tracks)) { - $tmpTracks = (array)$amaz->Items->Item->Tracks->Disc; - $tracks = $tmpTracks['Track']; - $mus['tracks'] = (is_array($tracks) && !empty($tracks)) ? implode('|', $tracks) : ''; - } + $mus['tracks'] = ''; + if (isset($amaz->Items->Item->Tracks)) { + $tmpTracks = (array) $amaz->Items->Item->Tracks->Disc; + $tracks = $tmpTracks['Track']; + $mus['tracks'] = (is_array($tracks) && ! empty($tracks)) ? implode('|', $tracks) : ''; + } - similar_text($mus['artist'] . " " . $mus['title'], $title, $titlepercent); - if ($titlepercent < 60) { - return false; - } + similar_text($mus['artist'].' '.$mus['title'], $title, $titlepercent); + if ($titlepercent < 60) { + return false; + } - $genreKey = -1; - $genreName = ''; - if (isset($amaz->Items->Item->BrowseNodes)) { - // Had issues getting this out of the browsenodes obj. - // Workaround is to get the xml and load that into its own obj. - $amazGenresXml = $amaz->Items->Item->BrowseNodes->asXml(); - $amazGenresObj = simplexml_load_string($amazGenresXml); - $amazGenres = $amazGenresObj->xpath('//BrowseNodeId'); + $genreKey = -1; + $genreName = ''; + if (isset($amaz->Items->Item->BrowseNodes)) { + // Had issues getting this out of the browsenodes obj. + // Workaround is to get the xml and load that into its own obj. + $amazGenresXml = $amaz->Items->Item->BrowseNodes->asXml(); + $amazGenresObj = simplexml_load_string($amazGenresXml); + $amazGenres = $amazGenresObj->xpath('//BrowseNodeId'); - foreach ($amazGenres as $amazGenre) { - $currNode = trim($amazGenre[0]); - if (empty($genreName)) { - $genreMatch = $this->matchBrowseNode($currNode); - if ($genreMatch !== false) { - $genreName = $genreMatch; - break; - } - } - } + foreach ($amazGenres as $amazGenre) { + $currNode = trim($amazGenre[0]); + if (empty($genreName)) { + $genreMatch = $this->matchBrowseNode($currNode); + if ($genreMatch !== false) { + $genreName = $genreMatch; + break; + } + } + } - if (in_array(strtolower($genreName), $genreassoc, false)) { - $genreKey = array_search(strtolower($genreName), $genreassoc, false); - } else { - $genreKey = $this->pdo->queryInsert( + if (in_array(strtolower($genreName), $genreassoc, false)) { + $genreKey = array_search(strtolower($genreName), $genreassoc, false); + } else { + $genreKey = $this->pdo->queryInsert( sprintf(' INSERT INTO genres (title, type) VALUES (%s, %d)', @@ -501,160 +506,154 @@ class Music Genres::MUSIC_TYPE ) ); - } - } - $mus['musicgenre'] = $genreName; - $mus['musicgenres_id'] = $genreKey; + } + } + $mus['musicgenre'] = $genreName; + $mus['musicgenres_id'] = $genreKey; - $check = $this->pdo->queryOneRow(sprintf('SELECT id FROM musicinfo WHERE asin = %s', $this->pdo->escapeString($mus['asin']))); - if ($check === false) { - $musicId = $this->pdo->queryInsert(sprintf('INSERT INTO musicinfo (title, asin, url, salesrank, artist, publisher, ' - . 'releasedate, review, year, genres_id, tracks, cover, createddate, updateddate) VALUES ' - . '(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, now(), now())', $this->pdo->escapeString($mus['title']), $this->pdo->escapeString($mus['asin']), $this->pdo->escapeString($mus['url']), $mus['salesrank'], $this->pdo->escapeString($mus['artist']), $this->pdo->escapeString($mus['publisher']), $mus['releasedate'], $this->pdo->escapeString($mus['review']), $this->pdo->escapeString($mus['year']), ($mus['musicgenres_id'] == -1 ? "null" : $mus['musicgenres_id']), $this->pdo->escapeString($mus['tracks']), $mus['cover'])); - } else { - $musicId = $check['id']; - $this->pdo->queryExec(sprintf('UPDATE musicinfo SET title = %s, asin = %s, url = %s, salesrank = %s, artist = %s, ' - . 'publisher = %s, releasedate = %s, review = %s, year = %s, genres_id = %s, tracks = %s, cover = %s, ' - . 'updateddate = NOW() WHERE id = %d', $this->pdo->escapeString($mus['title']), $this->pdo->escapeString($mus['asin']), $this->pdo->escapeString($mus['url']), $mus['salesrank'], $this->pdo->escapeString($mus['artist']), $this->pdo->escapeString($mus['publisher']), $mus['releasedate'], $this->pdo->escapeString($mus['review']), $this->pdo->escapeString($mus['year']), ($mus['musicgenres_id'] == -1 ? "null" : $mus['musicgenres_id']), $this->pdo->escapeString($mus['tracks']), $mus['cover'], $musicId)); - } + $check = $this->pdo->queryOneRow(sprintf('SELECT id FROM musicinfo WHERE asin = %s', $this->pdo->escapeString($mus['asin']))); + if ($check === false) { + $musicId = $this->pdo->queryInsert(sprintf('INSERT INTO musicinfo (title, asin, url, salesrank, artist, publisher, ' + .'releasedate, review, year, genres_id, tracks, cover, createddate, updateddate) VALUES ' + .'(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, now(), now())', $this->pdo->escapeString($mus['title']), $this->pdo->escapeString($mus['asin']), $this->pdo->escapeString($mus['url']), $mus['salesrank'], $this->pdo->escapeString($mus['artist']), $this->pdo->escapeString($mus['publisher']), $mus['releasedate'], $this->pdo->escapeString($mus['review']), $this->pdo->escapeString($mus['year']), ($mus['musicgenres_id'] == -1 ? 'null' : $mus['musicgenres_id']), $this->pdo->escapeString($mus['tracks']), $mus['cover'])); + } else { + $musicId = $check['id']; + $this->pdo->queryExec(sprintf('UPDATE musicinfo SET title = %s, asin = %s, url = %s, salesrank = %s, artist = %s, ' + .'publisher = %s, releasedate = %s, review = %s, year = %s, genres_id = %s, tracks = %s, cover = %s, ' + .'updateddate = NOW() WHERE id = %d', $this->pdo->escapeString($mus['title']), $this->pdo->escapeString($mus['asin']), $this->pdo->escapeString($mus['url']), $mus['salesrank'], $this->pdo->escapeString($mus['artist']), $this->pdo->escapeString($mus['publisher']), $mus['releasedate'], $this->pdo->escapeString($mus['review']), $this->pdo->escapeString($mus['year']), ($mus['musicgenres_id'] == -1 ? 'null' : $mus['musicgenres_id']), $this->pdo->escapeString($mus['tracks']), $mus['cover'], $musicId)); + } - if ($musicId) { - if ($this->echooutput) { - ColorCLI::doEcho( - ColorCLI::header(PHP_EOL . 'Added/updated album: ') . - ColorCLI::alternateOver(' Artist: ') . - ColorCLI::primary($mus['artist']) . - ColorCLI::alternateOver(' Title: ') . - ColorCLI::primary($mus['title']) . - ColorCLI::alternateOver(' Year: ') . + if ($musicId) { + if ($this->echooutput) { + ColorCLI::doEcho( + ColorCLI::header(PHP_EOL.'Added/updated album: '). + ColorCLI::alternateOver(' Artist: '). + ColorCLI::primary($mus['artist']). + ColorCLI::alternateOver(' Title: '). + ColorCLI::primary($mus['title']). + ColorCLI::alternateOver(' Year: '). ColorCLI::primary($mus['year']) ); - } - $mus['cover'] = $ri->saveImage($musicId, $mus['coverurl'], $this->imgSavePath, 250, 250); - } else { - if ($this->echooutput) { - if ($mus['artist'] == '') { - $artist = ''; - } else { - $artist = 'Artist: ' . $mus['artist'] . ', Album: '; - } - ColorCLI::doEcho( - ColorCLI::headerOver('Nothing to update: ') . + } + $mus['cover'] = $ri->saveImage($musicId, $mus['coverurl'], $this->imgSavePath, 250, 250); + } else { + if ($this->echooutput) { + if ($mus['artist'] == '') { + $artist = ''; + } else { + $artist = 'Artist: '.$mus['artist'].', Album: '; + } + ColorCLI::doEcho( + ColorCLI::headerOver('Nothing to update: '). ColorCLI::primaryOver( - $artist . - $mus['title'] . - ' (' . - $mus['year'] . + $artist. + $mus['title']. + ' ('. + $mus['year']. ')' ) ); - } - } + } + } - return $musicId; - } + return $musicId; + } - /** - * @param $title - * - * @return bool|mixed - * @throws \Exception - */ - public function fetchAmazonProperties($title) - { - $response = false; - $conf = new GenericConfiguration(); - $client = new Client(); - $request = new GuzzleRequest($client); + /** + * @param $title + * + * @return bool|mixed + * @throws \Exception + */ + public function fetchAmazonProperties($title) + { + $response = false; + $conf = new GenericConfiguration(); + $client = new Client(); + $request = new GuzzleRequest($client); - try { - $conf + try { + $conf ->setCountry('com') ->setAccessKey($this->pubkey) ->setSecretKey($this->privkey) ->setAssociateTag($this->asstag) ->setRequest($request) ->setResponseTransformer(new XmlToSimpleXmlObject()); - } catch (\Exception $e) { - echo $e->getMessage(); - } + } catch (\Exception $e) { + echo $e->getMessage(); + } - $apaiIo = new ApaiIO($conf); - // Try Music category. - try { - $search = new Search(); - $search->setCategory('Music'); - $search->setKeywords($title); - $search->setResponseGroup(['Large']); - $response = $apaiIo->runOperation($search); - } catch (\Exception $e) { - // Empty because we try another method. - } + $apaiIo = new ApaiIO($conf); + // Try Music category. + try { + $search = new Search(); + $search->setCategory('Music'); + $search->setKeywords($title); + $search->setResponseGroup(['Large']); + $response = $apaiIo->runOperation($search); + } catch (\Exception $e) { + // Empty because we try another method. + } - // Try MP3 category. - if ($response === false) { - usleep(700000); - try { - $search = new Search(); - $search->setCategory('MP3Downloads'); - $search->setKeywords($title); - $search->setResponseGroup(['Large']); - $response = $apaiIo->runOperation($search); - } catch (\Exception $e) { - // Empty because we try another method. - } - } + // Try MP3 category. + if ($response === false) { + usleep(700000); + try { + $search = new Search(); + $search->setCategory('MP3Downloads'); + $search->setKeywords($title); + $search->setResponseGroup(['Large']); + $response = $apaiIo->runOperation($search); + } catch (\Exception $e) { + // Empty because we try another method. + } + } - // Try Digital Music category. - if ($response === false) { - usleep(700000); - try { - $search = new Search(); - $search->setCategory('DigitalMusic'); - $search->setKeywords($title); - $search->setResponseGroup(['Large']); - $response = $apaiIo->runOperation($search); - } catch (\Exception $e) { - // Empty because we try another method. - } - } + // Try Digital Music category. + if ($response === false) { + usleep(700000); + try { + $search = new Search(); + $search->setCategory('DigitalMusic'); + $search->setKeywords($title); + $search->setResponseGroup(['Large']); + $response = $apaiIo->runOperation($search); + } catch (\Exception $e) { + // Empty because we try another method. + } + } - // Try Music Tracks category. - if ($response === false) { - usleep(700000); - try { - $search = new Search(); - $search->setCategory('MusicTracks'); - $search->setKeywords($title); - $search->setResponseGroup(['Large']); - $response = $apaiIo->runOperation($search); - } catch (\Exception $e) { - // Empty because we exhausted all possibilities. - } - } - if ($response === false) - { - throw new \Exception('Could not connect to Amazon'); - } - else - { - if (isset($response->Items->Item->ItemAttributes->Title)) - { - return $response; - } - else - { - return false; - } - } - } + // Try Music Tracks category. + if ($response === false) { + usleep(700000); + try { + $search = new Search(); + $search->setCategory('MusicTracks'); + $search->setKeywords($title); + $search->setResponseGroup(['Large']); + $response = $apaiIo->runOperation($search); + } catch (\Exception $e) { + // Empty because we exhausted all possibilities. + } + } + if ($response === false) { + throw new \Exception('Could not connect to Amazon'); + } else { + if (isset($response->Items->Item->ItemAttributes->Title)) { + return $response; + } else { + return false; + } + } + } - /** - * @param bool $local - */ - public function processMusicReleases($local = false) - { - $res = $this->pdo->queryDirect( + /** + * @param bool $local + */ + public function processMusicReleases($local = false) + { + $res = $this->pdo->queryDirect( sprintf(' SELECT searchname, id FROM releases @@ -670,112 +669,112 @@ class Music $this->musicqty ) ); - if ($res instanceof \Traversable && $res->rowCount() > 0) { - if ($this->echooutput) { - ColorCLI::doEcho( - ColorCLI::header('Processing ' . $res->rowCount() .' music release(s).' + if ($res instanceof \Traversable && $res->rowCount() > 0) { + if ($this->echooutput) { + ColorCLI::doEcho( + ColorCLI::header('Processing '.$res->rowCount().' music release(s).' ) ); - } + } - foreach ($res as $arr) { - $startTime = microtime(true); - $usedAmazon = false; - $album = $this->parseArtist($arr['searchname']); - if ($album !== false) { - $newname = $album['name'] . ' (' . $album['year'] . ')'; + foreach ($res as $arr) { + $startTime = microtime(true); + $usedAmazon = false; + $album = $this->parseArtist($arr['searchname']); + if ($album !== false) { + $newname = $album['name'].' ('.$album['year'].')'; - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::headerOver('Looking up: ') . ColorCLI::primary($newname)); - } + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::headerOver('Looking up: ').ColorCLI::primary($newname)); + } - // Do a local lookup first - $musicCheck = $this->getMusicInfoByName('', $album["name"]); + // Do a local lookup first + $musicCheck = $this->getMusicInfoByName('', $album['name']); - if ($musicCheck === false && in_array($album['name'] . $album['year'], $this->failCache, false)) { - // Lookup recently failed, no point trying again - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::headerOver('Cached previous failure. Skipping.') . PHP_EOL); - } - $albumId = -2; - } else if ($musicCheck === false && $local === false) { - $albumId = $this->updateMusicInfo($album['name'], $album['year']); - $usedAmazon = true; - if ($albumId === false) { - $albumId = -2; - $this->failCache[] = $album['name'] . $album['year']; - } - } else { - $albumId = $musicCheck['id']; - } + if ($musicCheck === false && in_array($album['name'].$album['year'], $this->failCache, false)) { + // Lookup recently failed, no point trying again + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::headerOver('Cached previous failure. Skipping.').PHP_EOL); + } + $albumId = -2; + } elseif ($musicCheck === false && $local === false) { + $albumId = $this->updateMusicInfo($album['name'], $album['year']); + $usedAmazon = true; + if ($albumId === false) { + $albumId = -2; + $this->failCache[] = $album['name'].$album['year']; + } + } else { + $albumId = $musicCheck['id']; + } - // Update release. - $this->pdo->queryExec(sprintf('UPDATE releases SET musicinfo_id = %d WHERE id = %d', $albumId, $arr['id'])); - } // No album found. - else { - $this->pdo->queryExec(sprintf('UPDATE releases SET musicinfo_id = %d WHERE id = %d', -2, $arr['id'])); - echo '.'; - } + // Update release. + $this->pdo->queryExec(sprintf('UPDATE releases SET musicinfo_id = %d WHERE id = %d', $albumId, $arr['id'])); + } // No album found. + else { + $this->pdo->queryExec(sprintf('UPDATE releases SET musicinfo_id = %d WHERE id = %d', -2, $arr['id'])); + echo '.'; + } - // Sleep to not flood amazon. - $diff = floor((microtime(true) - $startTime) * 1000000); - if ($this->sleeptime * 1000 - $diff > 0 && $usedAmazon === true) { - usleep($this->sleeptime * 1000 - $diff); - } - } + // Sleep to not flood amazon. + $diff = floor((microtime(true) - $startTime) * 1000000); + if ($this->sleeptime * 1000 - $diff > 0 && $usedAmazon === true) { + usleep($this->sleeptime * 1000 - $diff); + } + } - if ($this->echooutput) { - echo "\n"; - } + if ($this->echooutput) { + echo "\n"; + } + } else { + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::header('No music releases to process.')); + } + } + } - } else { - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::header('No music releases to process.')); - } - } - } + /** + * @param $releasename + * + * @return array|bool + */ + public function parseArtist($releasename) + { + if (preg_match('/(.+?)(\d{1,2} \d{1,2} )?\(?(19\d{2}|20[0-1][\d])\b/', $releasename, $name)) { + $result = []; + $result['year'] = $name[3]; - /** - * @param $releasename - * - * @return array|bool - */ - public function parseArtist($releasename) - { - if (preg_match('/(.+?)(\d{1,2} \d{1,2} )?\(?(19\d{2}|20[0-1][\d])\b/', $releasename, $name)) { - $result = []; - $result["year"] = $name[3]; + $a = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(Bootleg|Boxset|Clean.+Version|Compiled by.+|\dCD|Digipak|DIRFIX|DVBS|FLAC|(Ltd )?(Deluxe|Limited|Special).+Edition|Promo|PROOF|Reissue|Remastered|REPACK|RETAIL(.+UK)?|SACD|Sampler|SAT|Summer.+Mag|UK.+Import|Deluxe.+Version|VINYL|WEB)/i', ' ', $name[1]); + $b = preg_replace('/( |-)([a-z]+[\d]+[a-z]+[\d]+.+|[a-z]{2,}[\d]{2,}?.+|3FM|B00[a-z0-9]+|BRC482012|H056|UXM1DW086|(4WCD|ATL|bigFM|CDP|DST|ERE|FIM|MBZZ|MSOne|MVRD|QEDCD|RNB|SBD|SFT|ZYX)( |-)\d.+)/i', ' ', $a); + $c = preg_replace('/( |-)(\d{1,2} \d{1,2} )?([A-Z])( ?$)|\(?[\d]{8,}\)?|( |-)(CABLE|FREEWEB|LINE|MAG|MCD|YMRSMILES)|\(([a-z]{2,}[\d]{2,}|ost)\)|-web-/i', ' ', $b); + $d = preg_replace('/VA( |-)/', 'Various Artists ', $c); + $e = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(DAB|DE|DVBC|EP|FIX|IT|Jap|NL|PL|(Pure )?FM|SSL|VLS)( |-)/i', ' ', $d); + $f = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(CABLE|CD(A|EP|M|R|S)?|QEDCD|SAT|SBD)( |-)/i', ' ', $e); + $g = str_replace(['_', '-'], ' ', $f); + $h = trim(preg_replace('/\s\s+/', ' ', $g)); + $newname = trim(preg_replace('/ [a-z]{2}$| [a-z]{3} \d{2,}$|\d{5,} \d{5,}$|-WEB$/i', '', $h)); - $a = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(Bootleg|Boxset|Clean.+Version|Compiled by.+|\dCD|Digipak|DIRFIX|DVBS|FLAC|(Ltd )?(Deluxe|Limited|Special).+Edition|Promo|PROOF|Reissue|Remastered|REPACK|RETAIL(.+UK)?|SACD|Sampler|SAT|Summer.+Mag|UK.+Import|Deluxe.+Version|VINYL|WEB)/i', ' ', $name[1]); - $b = preg_replace('/( |-)([a-z]+[\d]+[a-z]+[\d]+.+|[a-z]{2,}[\d]{2,}?.+|3FM|B00[a-z0-9]+|BRC482012|H056|UXM1DW086|(4WCD|ATL|bigFM|CDP|DST|ERE|FIM|MBZZ|MSOne|MVRD|QEDCD|RNB|SBD|SFT|ZYX)( |-)\d.+)/i', ' ', $a); - $c = preg_replace('/( |-)(\d{1,2} \d{1,2} )?([A-Z])( ?$)|\(?[\d]{8,}\)?|( |-)(CABLE|FREEWEB|LINE|MAG|MCD|YMRSMILES)|\(([a-z]{2,}[\d]{2,}|ost)\)|-web-/i', ' ', $b); - $d = preg_replace('/VA( |-)/', 'Various Artists ', $c); - $e = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(DAB|DE|DVBC|EP|FIX|IT|Jap|NL|PL|(Pure )?FM|SSL|VLS)( |-)/i', ' ', $d); - $f = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(CABLE|CD(A|EP|M|R|S)?|QEDCD|SAT|SBD)( |-)/i', ' ', $e); - $g = str_replace(['_', '-'], ' ', $f); - $h = trim(preg_replace('/\s\s+/', ' ', $g)); - $newname = trim(preg_replace('/ [a-z]{2}$| [a-z]{3} \d{2,}$|\d{5,} \d{5,}$|-WEB$/i', '', $h)); + if (! preg_match('/^[a-z0-9]+$/i', $newname) && strlen($newname) > 10) { + $result['name'] = $newname; - if (!preg_match('/^[a-z0-9]+$/i', $newname) && strlen($newname) > 10) { - $result['name'] = $newname; - return $result; - } else { - return false; - } - } else { - return false; - } - } + return $result; + } else { + return false; + } + } else { + return false; + } + } - /** - * @param bool $activeOnly - * - * @return array - */ - public function getGenres($activeOnly = false) - { - if ($activeOnly) { - return $this->pdo->query(' + /** + * @param bool $activeOnly + * + * @return array + */ + public function getGenres($activeOnly = false) + { + if ($activeOnly) { + return $this->pdo->query(' SELECT ge.* FROM genres ge INNER JOIN @@ -786,27 +785,26 @@ class Music WHERE ge.type = " . Category::MUSIC_ROOT . " ORDER BY title' ); - } else { - return $this->pdo->query(' + } else { + return $this->pdo->query(' SELECT * FROM genres WHERE type = " . Category::MUSIC_ROOT . " ORDER BY title' ); - } - } + } + } + /** + * @param $nodeId + * + * @return bool|string + */ + public function matchBrowseNode($nodeId) + { + $str = ''; - /** - * @param $nodeId - * - * @return bool|string - */ - public function matchBrowseNode($nodeId) - { - $str = ''; - - //music nodes above mp3 download nodes - switch ($nodeId) { + //music nodes above mp3 download nodes + switch ($nodeId) { case '163420': $str = 'Music Video & Concerts'; break; @@ -899,7 +897,7 @@ class Music $str = 'Miscellaneous'; break; } - return ($str != '') ? $str : false; - } + return ($str != '') ? $str : false; + } } diff --git a/nntmux/NNTP.php b/nntmux/NNTP.php index 14d2e3953..7742adfa8 100755 --- a/nntmux/NNTP.php +++ b/nntmux/NNTP.php @@ -1,9 +1,10 @@ <?php + namespace nntmux; -use App\Extensions\util\Yenc; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; +use App\Extensions\util\Yenc; /** * Class for connecting to the usenet, retrieving articles and article headers, @@ -12,554 +13,534 @@ use nntmux\db\DB; */ class NNTP extends \Net_NNTP_Client { - public $pdo; + public $pdo; - /** - * @var ColorCLI - * @access protected - */ - protected $_colorCLI; + /** + * @var ColorCLI + */ + protected $_colorCLI; - /** - * @var Logger - * @access protected - */ - protected $_debugging; + /** + * @var Logger + */ + protected $_debugging; - /** - * Log/echo debug? - * @var bool - * @access protected - */ - protected $_debugBool; + /** + * Log/echo debug? + * @var bool + */ + protected $_debugBool; - /** - * Echo to cli? - * @var bool - * @access protected - */ - protected $_echo; + /** + * Echo to cli? + * @var bool + */ + protected $_echo; - /** - * Does the server support XFeature GZip header compression? - * @var boolean - * @access protected - */ - protected $_compressionSupported = true; + /** + * Does the server support XFeature GZip header compression? + * @var bool + */ + protected $_compressionSupported = true; - /** - * Is header compression enabled for the session? - * @var bool - * @access protected - */ - protected $_compressionEnabled = false; + /** + * Is header compression enabled for the session? + * @var bool + */ + protected $_compressionEnabled = false; - /** - * Currently selected group. - * @var string - * @access protected - */ - protected $_currentGroup = ''; + /** + * Currently selected group. + * @var string + */ + protected $_currentGroup = ''; - /** - * Port of the current NNTP server. - * @var int - * @access protected - */ - protected $_currentPort = 'NNTP_PORT'; + /** + * Port of the current NNTP server. + * @var int + */ + protected $_currentPort = 'NNTP_PORT'; - /** - * Address of the current NNTP server. - * @var string - * @access protected - */ - protected $_currentServer = 'NNTP_SERVER'; + /** + * Address of the current NNTP server. + * @var string + */ + protected $_currentServer = 'NNTP_SERVER'; - /** - * Are we allowed to post to usenet? - * @var bool - * @access protected - */ - protected $_postingAllowed = false; + /** + * Are we allowed to post to usenet? + * @var bool + */ + protected $_postingAllowed = false; - /** - * How many times should we try to reconnect to the NNTP server? - * @var int - * @access protected - */ - protected $_nntpRetries; + /** + * How many times should we try to reconnect to the NNTP server? + * @var int + */ + protected $_nntpRetries; - /** - * Default constructor. - * - * @param array $options Class instances and echo to CLI bool. - * - * @access public - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Default constructor. + * + * @param array $options Class instances and echo to CLI bool. + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => true, 'Logger' => null, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - parent::__construct(); + parent::__construct(); - $this->_echo = ($options['Echo'] && NN_ECHOCLI); + $this->_echo = ($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->_debugBool = (NN_LOGGING || NN_DEBUG); - if ($this->_debugBool) { - try { - $this->_debugging = ($options['Logger'] instanceof Logger ? $options['Logger'] : new Logger(['ColorCLI' => $this->pdo->log])); - } catch (LoggerException $error) { - $this->_debugBool = false; - } - } + $this->_debugBool = (NN_LOGGING || NN_DEBUG); + if ($this->_debugBool) { + try { + $this->_debugging = ($options['Logger'] instanceof Logger ? $options['Logger'] : new Logger(['ColorCLI' => $this->pdo->log])); + } catch (LoggerException $error) { + $this->_debugBool = false; + } + } - $this->_nntpRetries = Settings::value('..nntpretries') !== '' ? (int)Settings::value('..nntpretries') : 0 + 1; - } + $this->_nntpRetries = Settings::value('..nntpretries') !== '' ? (int) Settings::value('..nntpretries') : 0 + 1; + } - /** - * Destruct. - * Close the NNTP connection if still connected. - * - * @access public - */ - public function __destruct() - { - $this->doQuit(); - } + /** + * Destruct. + * Close the NNTP connection if still connected. + */ + public function __destruct() + { + $this->doQuit(); + } - /** - * Connect to a usenet server. - * - * @param boolean $compression Should we attempt to enable XFeature Gzip compression on this connection? - * @param boolean $alternate Use the alternate NNTP connection. - * - * @return mixed On success = (bool) Did we successfully connect to the usenet? - * @throws \Exception - * On failure = (object) PEAR_Error. - * - * @access public - */ - public function doConnect($compression = true, $alternate = false) - { - if (// (Alternate is wanted, AND current server is alt, OR Alternate is not wanted AND current is main.) AND - (($alternate && $this->_currentServer === env('NNTP_SERVER_A')) || (!$alternate && $this->_currentServer === env('NNTP_SERVER'))) && + /** + * Connect to a usenet server. + * + * @param bool $compression Should we attempt to enable XFeature Gzip compression on this connection? + * @param bool $alternate Use the alternate NNTP connection. + * + * @return mixed On success = (bool) Did we successfully connect to the usenet? + * @throws \Exception + * On failure = (object) PEAR_Error. + */ + public function doConnect($compression = true, $alternate = false) + { + if (// (Alternate is wanted, AND current server is alt, OR Alternate is not wanted AND current is main.) AND + (($alternate && $this->_currentServer === env('NNTP_SERVER_A')) || (! $alternate && $this->_currentServer === env('NNTP_SERVER'))) && // Don't reconnect to usenet if: // We are already connected to usenet. parent::_isConnected() ) { - return true; - } + return true; + } - $this->doQuit(); + $this->doQuit(); - $ret = $connected = $cError = $aError = false; + $ret = $connected = $cError = $aError = false; - // Set variables to connect based on if we are using the alternate provider or not. - if (!$alternate) { - $sslEnabled = env('NNTP_SSLENABLED') ? true : false; - $this->_currentServer = env('NNTP_SERVER'); - $this->_currentPort = env('NNTP_PORT'); - $userName = env('NNTP_USERNAME'); - $password = env('NNTP_PASSWORD'); - $socketTimeout = !empty(env('NNTP_SOCKET_TIMEOUT')) ? env('NNTP_SOCKET_TIMEOUT') : $this->_socketTimeout; - } else { - $sslEnabled = env('NNTP_SSLENABLED_A') ? true : false; - $this->_currentServer = env('NNTP_SERVER_A'); - $this->_currentPort = env('NNTP_PORT_A'); - $userName = env('NNTP_USERNAME_A'); - $password = env('NNTP_PASSWORD_A'); - $socketTimeout = !empty(env('NNTP_SOCKET_TIMEOUT_A')) ? env('NNTP_SOCKET_TIMEOUT_A') : $this->_socketTimeout; - } + // Set variables to connect based on if we are using the alternate provider or not. + if (! $alternate) { + $sslEnabled = env('NNTP_SSLENABLED') ? true : false; + $this->_currentServer = env('NNTP_SERVER'); + $this->_currentPort = env('NNTP_PORT'); + $userName = env('NNTP_USERNAME'); + $password = env('NNTP_PASSWORD'); + $socketTimeout = ! empty(env('NNTP_SOCKET_TIMEOUT')) ? env('NNTP_SOCKET_TIMEOUT') : $this->_socketTimeout; + } else { + $sslEnabled = env('NNTP_SSLENABLED_A') ? true : false; + $this->_currentServer = env('NNTP_SERVER_A'); + $this->_currentPort = env('NNTP_PORT_A'); + $userName = env('NNTP_USERNAME_A'); + $password = env('NNTP_PASSWORD_A'); + $socketTimeout = ! empty(env('NNTP_SOCKET_TIMEOUT_A')) ? env('NNTP_SOCKET_TIMEOUT_A') : $this->_socketTimeout; + } - $enc = ($sslEnabled ? ' (ssl)' : ' (non-ssl)'); - $sslEnabled = ($sslEnabled ? 'tls' : false); + $enc = ($sslEnabled ? ' (ssl)' : ' (non-ssl)'); + $sslEnabled = ($sslEnabled ? 'tls' : false); - // Try to connect until we run of out tries. - $retries = $this->_nntpRetries; - while (true) { - $retries--; - $authenticated = false; + // Try to connect until we run of out tries. + $retries = $this->_nntpRetries; + while (true) { + $retries--; + $authenticated = false; - // If we are not connected, try to connect. - if (!$connected) { - $ret = $this->connect($this->_currentServer, $sslEnabled, $this->_currentPort, 5, $socketTimeout); - } + // If we are not connected, try to connect. + if (! $connected) { + $ret = $this->connect($this->_currentServer, $sslEnabled, $this->_currentPort, 5, $socketTimeout); + } - // Check if we got an error while connecting. - $cErr = $this->isError($ret); + // Check if we got an error while connecting. + $cErr = $this->isError($ret); - // If no error, we are connected. - if (!$cErr) { - // Say that we are connected so we don't retry. - $connected = true; - // When there is no error it returns bool if we are allowed to post or not. - $this->_postingAllowed = $ret; - } else { - // Only fetch the message once. - if (!$cError) { - $cError = $ret->getMessage(); - } - } + // If no error, we are connected. + if (! $cErr) { + // Say that we are connected so we don't retry. + $connected = true; + // When there is no error it returns bool if we are allowed to post or not. + $this->_postingAllowed = $ret; + } else { + // Only fetch the message once. + if (! $cError) { + $cError = $ret->getMessage(); + } + } - // If error, try to connect again. - if ($cErr && $retries > 0) { - continue; - } + // If error, try to connect again. + if ($cErr && $retries > 0) { + continue; + } - // If we have no more retries and could not connect, return an error. - if ($retries === 0 && !$connected) { - $message = - 'Cannot connect to server ' . - $this->_currentServer . - $enc . - ': ' . + // If we have no more retries and could not connect, return an error. + if ($retries === 0 && ! $connected) { + $message = + 'Cannot connect to server '. + $this->_currentServer. + $enc. + ': '. $cError; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR); - } - return $this->throwError(ColorCLI::error($message)); - } + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR); + } - // If we are connected, try to authenticate. - if ($connected === true && $authenticated === false) { + return $this->throwError(ColorCLI::error($message)); + } + + // If we are connected, try to authenticate. + if ($connected === true && $authenticated === false) { // If the username is empty it probably means the server does not require a username. - if ($userName === '') { - $authenticated = true; + if ($userName === '') { + $authenticated = true; - // Try to authenticate to usenet. - } else { - $ret2 = $this->authenticate($userName, $password); + // Try to authenticate to usenet. + } else { + $ret2 = $this->authenticate($userName, $password); - // Check if there was an error authenticating. - $aErr = $this->isError($ret2); + // Check if there was an error authenticating. + $aErr = $this->isError($ret2); - // If there was no error, then we are authenticated. - if (!$aErr) { - $authenticated = true; - } elseif (!$aError) { - $aError = $ret2->getMessage(); - } + // If there was no error, then we are authenticated. + if (! $aErr) { + $authenticated = true; + } elseif (! $aError) { + $aError = $ret2->getMessage(); + } - // If error, try to authenticate again. - if ($aErr && $retries > 0) { - continue; - } + // If error, try to authenticate again. + if ($aErr && $retries > 0) { + continue; + } - // If we ran out of retries, return an error. - if ($retries === 0 && $authenticated === false) { - $message = - 'Cannot authenticate to server ' . - $this->_currentServer . - $enc . - ' - ' . - $userName . - ' (' . $aError . ')'; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR); - } - return $this->throwError(ColorCLI::error($message)); - } - } - } + // If we ran out of retries, return an error. + if ($retries === 0 && $authenticated === false) { + $message = + 'Cannot authenticate to server '. + $this->_currentServer. + $enc. + ' - '. + $userName. + ' ('.$aError.')'; + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR); + } - // If we are connected and authenticated, try enabling compression if we have it enabled. - if ($connected === true && $authenticated === true) { - // Check if we should use compression on the connection. - if ($compression === false || (int)Settings::value('..compressedheaders') === 0) { - $this->_compressionSupported = false; - } - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, 'Connected to ' . $this->_currentServer . '.', Logger::LOG_INFO); - } - return true; - } - // If we reached this point and have not connected after all retries, break out of the loop. - if ($retries === 0) { - break; - } + return $this->throwError(ColorCLI::error($message)); + } + } + } - // Sleep .4 seconds between retries. - usleep(400000); - } - // If we somehow got out of the loop, return an error. - $message = 'Unable to connect to ' . $this->_currentServer . $enc; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR); - } - return $this->throwError(ColorCLI::error($message)); - } + // If we are connected and authenticated, try enabling compression if we have it enabled. + if ($connected === true && $authenticated === true) { + // Check if we should use compression on the connection. + if ($compression === false || (int) Settings::value('..compressedheaders') === 0) { + $this->_compressionSupported = false; + } + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, 'Connected to '.$this->_currentServer.'.', Logger::LOG_INFO); + } - /** - * Disconnect from the current NNTP server. - * - * @param bool $force Force quit even if not connected? - * - * @return mixed On success : (bool) Did we successfully disconnect from usenet? - * On Failure : (object) PEAR_Error. - * - * @access public - */ - public function doQuit($force = false) - { - $this->_resetProperties(); + return true; + } + // If we reached this point and have not connected after all retries, break out of the loop. + if ($retries === 0) { + break; + } - // Check if we are connected to usenet. - if ($force === true || parent::_isConnected(false)) { - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, 'Disconnecting from ' . $this->_currentServer, Logger::LOG_INFO); - } - // Disconnect from usenet. - return parent::disconnect(); - } - return true; - } + // Sleep .4 seconds between retries. + usleep(400000); + } + // If we somehow got out of the loop, return an error. + $message = 'Unable to connect to '.$this->_currentServer.$enc; + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR); + } - /** - * Reset some properties when disconnecting from usenet. - * - * @void - * - * @access protected - */ - protected function _resetProperties(): void - { - $this->_compressionEnabled = false; - $this->_compressionSupported = true; - $this->_currentGroup = ''; - $this->_postingAllowed = false; - parent::_resetProperties(); - } + return $this->throwError(ColorCLI::error($message)); + } - /** - * Attempt to enable compression if the admin enabled the site setting. - * - * @note This can be used to enable compression if the server was connected without compression. - * - * @access public - * @throws \Exception - */ - public function enableCompression(): void - { - if ((int)Settings::value('..compressedheaders') !== 1) { - return; - } - $this->_enableCompression(); - } + /** + * Disconnect from the current NNTP server. + * + * @param bool $force Force quit even if not connected? + * + * @return mixed On success : (bool) Did we successfully disconnect from usenet? + * On Failure : (object) PEAR_Error. + */ + public function doQuit($force = false) + { + $this->_resetProperties(); - /** - * @param string $group Name of the group to select. - * @param bool $articles (optional) experimental! When true the article numbers is returned in 'articles'. - * @param bool $force Force a refresh to get updated data from the usenet server. - * - * @return mixed On success : (array) Group information. - * @throws \Exception - * On failure : (object) PEAR_Error. - * - * @access public - */ - public function selectGroup($group, $articles = false, $force = false) - { - $connected = $this->_checkConnection(false); - if ($connected !== true) { - return $connected; - } + // Check if we are connected to usenet. + if ($force === true || parent::_isConnected(false)) { + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, 'Disconnecting from '.$this->_currentServer, Logger::LOG_INFO); + } + // Disconnect from usenet. + return parent::disconnect(); + } - // Check if the current selected group is the same, or if we have not selected a group or if a fresh summary is wanted. - if ($force || $this->_currentGroup !== $group || $this->_selectedGroupSummary === null) { - $this->_currentGroup = $group; - return parent::selectGroup($group, $articles); - } - return $this->_selectedGroupSummary; - } + return true; + } - /** - * Fetch an overview of article(s) in the currently selected group. - * - * @param string $range - * @param bool $names - * @param bool $forceNames - * - * @return mixed On success : (array) Multidimensional array with article headers. - * @throws \Exception - * On failure : (object) PEAR_Error. - * - * @access public - */ - public function getOverview($range = null, $names = true, $forceNames = true) - { - $connected = $this->_checkConnection(); - if ($connected !== true) { - return $connected; - } + /** + * Reset some properties when disconnecting from usenet. + * + * @void + */ + protected function _resetProperties(): void + { + $this->_compressionEnabled = false; + $this->_compressionSupported = true; + $this->_currentGroup = ''; + $this->_postingAllowed = false; + parent::_resetProperties(); + } - // Enabled header compression if not enabled. - $this->_enableCompression(); - return parent::getOverview($range, $names, $forceNames); - } + /** + * Attempt to enable compression if the admin enabled the site setting. + * + * @note This can be used to enable compression if the server was connected without compression. + * + * @throws \Exception + */ + public function enableCompression(): void + { + if ((int) Settings::value('..compressedheaders') !== 1) { + return; + } + $this->_enableCompression(); + } - /** - * Pass a XOVER command to the NNTP provider, return array of articles using the overview format as array keys. - * - * @note This is a faster implementation of getOverview. - * - * Example successful return: - * array(9) { - * 'Number' => string(9) "679871775" - * 'Subject' => string(18) "This is an example" - * 'From' => string(19) "Example@example.com" - * 'Date' => string(24) "26 Jun 2014 13:08:22 GMT" - * 'Message-ID' => string(57) "<part1of1.uS*yYxQvtAYt$5t&wmE%UejhjkCKXBJ!@example.local>" - * 'References' => string(0) "" - * 'Bytes' => string(3) "123" - * 'Lines' => string(1) "9" - * 'Xref' => string(66) "e alt.test:679871775" - * } - * - * @param string $range Range of articles to get the overview for. Examples follow: - * Single article number: "679871775" - * Range of article numbers: "679871775-679999999" - * All newer than article number: "679871775-" - * All older than article number: "-679871775" - * Message-ID: "<part1of1.uS*yYxQvtAYt$5t&wmE%UejhjkCKXBJ!@example.local>" - * - * @return array|object Multi-dimensional Array of headers on success, PEAR object on failure. - * @throws \Exception - */ - public function getXOVER($range) - { - // Check if we are still connected. - $connected = $this->_checkConnection(); - if ($connected !== true) { - return $connected; - } + /** + * @param string $group Name of the group to select. + * @param bool $articles (optional) experimental! When true the article numbers is returned in 'articles'. + * @param bool $force Force a refresh to get updated data from the usenet server. + * + * @return mixed On success : (array) Group information. + * @throws \Exception + * On failure : (object) PEAR_Error. + */ + public function selectGroup($group, $articles = false, $force = false) + { + $connected = $this->_checkConnection(false); + if ($connected !== true) { + return $connected; + } - // Enabled header compression if not enabled. - $this->_enableCompression(); + // Check if the current selected group is the same, or if we have not selected a group or if a fresh summary is wanted. + if ($force || $this->_currentGroup !== $group || $this->_selectedGroupSummary === null) { + $this->_currentGroup = $group; - // Send XOVER command to NNTP with wanted articles. - $response = $this->_sendCommand('XOVER ' . $range); - if ($this->isError($response)) { - return $response; - } + return parent::selectGroup($group, $articles); + } - // Verify the NNTP server got the right command, get the headers data. - if ($response === NET_NNTP_PROTOCOL_RESPONSECODE_OVERVIEW_FOLLOWS) { - $data = $this->_getTextResponse(); - if ($this->isError($data)) { - return $data; - } - } else { - return $this->_handleErrorResponse($response); - } + return $this->_selectedGroupSummary; + } - // Fetch the header overview format (for setting the array keys on the return array). - if ($this->_overviewFormatCache !== null && isset($this->_overviewFormatCache['Xref'])) { - $overview = $this->_overviewFormatCache; - } else { - $overview = $this->getOverviewFormat(false, true); - if ($this->isError($overview)) { - return $overview; - } - $this->_overviewFormatCache = $overview; - } - // Add the "Number" key. - $overview = array_merge(['Number' => false], $overview); + /** + * Fetch an overview of article(s) in the currently selected group. + * + * @param string $range + * @param bool $names + * @param bool $forceNames + * + * @return mixed On success : (array) Multidimensional array with article headers. + * @throws \Exception + * On failure : (object) PEAR_Error. + */ + public function getOverview($range = null, $names = true, $forceNames = true) + { + $connected = $this->_checkConnection(); + if ($connected !== true) { + return $connected; + } - // Iterator used for selecting the header elements to insert into the overview format array. - $iterator = 0; + // Enabled header compression if not enabled. + $this->_enableCompression(); - // Loop over strings of headers. - foreach ($data as $key => $header) { + return parent::getOverview($range, $names, $forceNames); + } + + /** + * Pass a XOVER command to the NNTP provider, return array of articles using the overview format as array keys. + * + * @note This is a faster implementation of getOverview. + * + * Example successful return: + * array(9) { + * 'Number' => string(9) "679871775" + * 'Subject' => string(18) "This is an example" + * 'From' => string(19) "Example@example.com" + * 'Date' => string(24) "26 Jun 2014 13:08:22 GMT" + * 'Message-ID' => string(57) "<part1of1.uS*yYxQvtAYt$5t&wmE%UejhjkCKXBJ!@example.local>" + * 'References' => string(0) "" + * 'Bytes' => string(3) "123" + * 'Lines' => string(1) "9" + * 'Xref' => string(66) "e alt.test:679871775" + * } + * + * @param string $range Range of articles to get the overview for. Examples follow: + * Single article number: "679871775" + * Range of article numbers: "679871775-679999999" + * All newer than article number: "679871775-" + * All older than article number: "-679871775" + * Message-ID: "<part1of1.uS*yYxQvtAYt$5t&wmE%UejhjkCKXBJ!@example.local>" + * + * @return array|object Multi-dimensional Array of headers on success, PEAR object on failure. + * @throws \Exception + */ + public function getXOVER($range) + { + // Check if we are still connected. + $connected = $this->_checkConnection(); + if ($connected !== true) { + return $connected; + } + + // Enabled header compression if not enabled. + $this->_enableCompression(); + + // Send XOVER command to NNTP with wanted articles. + $response = $this->_sendCommand('XOVER '.$range); + if ($this->isError($response)) { + return $response; + } + + // Verify the NNTP server got the right command, get the headers data. + if ($response === NET_NNTP_PROTOCOL_RESPONSECODE_OVERVIEW_FOLLOWS) { + $data = $this->_getTextResponse(); + if ($this->isError($data)) { + return $data; + } + } else { + return $this->_handleErrorResponse($response); + } + + // Fetch the header overview format (for setting the array keys on the return array). + if ($this->_overviewFormatCache !== null && isset($this->_overviewFormatCache['Xref'])) { + $overview = $this->_overviewFormatCache; + } else { + $overview = $this->getOverviewFormat(false, true); + if ($this->isError($overview)) { + return $overview; + } + $this->_overviewFormatCache = $overview; + } + // Add the "Number" key. + $overview = array_merge(['Number' => false], $overview); + + // Iterator used for selecting the header elements to insert into the overview format array. + $iterator = 0; + + // Loop over strings of headers. + foreach ($data as $key => $header) { // Split the individual headers by tab. - $header = explode("\t", $header); + $header = explode("\t", $header); - // Make sure it's not empty. - if ($header === false) { - continue; - } + // Make sure it's not empty. + if ($header === false) { + continue; + } - // Temp array to store the header. - $headerArray = $overview; + // Temp array to store the header. + $headerArray = $overview; - // Loop over the overview format and insert the individual header elements. - foreach ($overview as $name => $element) { - // Strip Xref: - if ($element === true) { - $header[$iterator] = substr($header[$iterator], 6); - } - $headerArray[$name] = $header[$iterator++]; - } - // Add the individual header array back to the return array. - $data[$key] = $headerArray; - $iterator = 0; - } - // Return the array of headers. - return $data; - } + // Loop over the overview format and insert the individual header elements. + foreach ($overview as $name => $element) { + // Strip Xref: + if ($element === true) { + $header[$iterator] = substr($header[$iterator], 6); + } + $headerArray[$name] = $header[$iterator++]; + } + // Add the individual header array back to the return array. + $data[$key] = $headerArray; + $iterator = 0; + } + // Return the array of headers. + return $data; + } - /** - * Fetch valid groups. - * - * Returns a list of valid groups (that the client is permitted to select) and associated information. - * - * @param string $wildMat (optional) http://tools.ietf.org/html/rfc3977#section-4 - * - * @return array|object Pear error on failure, array with groups on success. - * @access public - */ - public function getGroups($wildMat = null) - { - // Enabled header compression if not enabled. - $this->_enableCompression(); - return parent::getGroups($wildMat); - } + /** + * Fetch valid groups. + * + * Returns a list of valid groups (that the client is permitted to select) and associated information. + * + * @param string $wildMat (optional) http://tools.ietf.org/html/rfc3977#section-4 + * + * @return array|object Pear error on failure, array with groups on success. + */ + public function getGroups($wildMat = null) + { + // Enabled header compression if not enabled. + $this->_enableCompression(); - /** - * Download multiple article bodies and string them together. - * - * @param string $groupName The name of the group the articles are in. - * @param mixed $identifiers (string) Message-ID. - * (int) Article number. - * (array) Article numbers or Message-ID's (can contain both in the same array) - * @param bool $alternate Use the alternate NNTP provider? - * - * @return mixed On success : (string) The article bodies. - * @throws \Exception - * On failure : (object) PEAR_Error. - * - * @access public - */ - public function getMessages($groupName, $identifiers, $alternate = false) - { - $connected = $this->_checkConnection(); - if ($connected !== true) { - return $connected; - } + return parent::getGroups($wildMat); + } - // String to hold all the bodies. - $body = ''; + /** + * Download multiple article bodies and string them together. + * + * @param string $groupName The name of the group the articles are in. + * @param mixed $identifiers (string) Message-ID. + * (int) Article number. + * (array) Article numbers or Message-ID's (can contain both in the same array) + * @param bool $alternate Use the alternate NNTP provider? + * + * @return mixed On success : (string) The article bodies. + * @throws \Exception + * On failure : (object) PEAR_Error. + */ + public function getMessages($groupName, $identifiers, $alternate = false) + { + $connected = $this->_checkConnection(); + if ($connected !== true) { + return $connected; + } - $aConnected = false; - $nntp = ($alternate === true ? new NNTP(['Echo' => $this->_echo, 'Settings' => $this->pdo]) : null); + // String to hold all the bodies. + $body = ''; - // Check if the msgIds are in an array. - if (is_array($identifiers)) { + $aConnected = false; + $nntp = ($alternate === true ? new self(['Echo' => $this->_echo, 'Settings' => $this->pdo]) : null); - $loops = $messageSize = 0; + // Check if the msgIds are in an array. + if (is_array($identifiers)) { + $loops = $messageSize = 0; - // Loop over the message-ID's or article numbers. - foreach ($identifiers as $wanted) { + // Loop over the message-ID's or article numbers. + foreach ($identifiers as $wanted) { /* This is to attempt to prevent string size overflow. * We get the size of 1 body in bytes, we increment the loop on every loop, @@ -568,741 +549,732 @@ class NNTP extends \Net_NNTP_Client * If we exceed, return the data. * If we don't do this, these errors are fatal. */ - if ((++$loops * $messageSize) >= 1700000000) { - return $body; - } + if ((++$loops * $messageSize) >= 1700000000) { + return $body; + } - // Download the body. - $message = $this->_getMessage($groupName, $wanted); + // Download the body. + $message = $this->_getMessage($groupName, $wanted); - // Append the body to $body. - if (!$this->isError($message)) { - $body .= $message; + // Append the body to $body. + if (! $this->isError($message)) { + $body .= $message; - if ($messageSize === 0) { - $messageSize = strlen($message); - } + if ($messageSize === 0) { + $messageSize = strlen($message); + } - // If there is an error try the alternate provider or return the PEAR error. - } else { - // Check if admin has enabled alternate in site->edit. - if ($alternate === true) { - if ($aConnected === false) { - // Check if the current connected server is the alternate or not. - if ($this->_currentServer === env('NNTP_SERVER')) { - // It's the main so connect to the alternate. - $aConnected = $nntp->doConnect(true, true); - } else { - // It's the alternate so connect to the main. - $aConnected = $nntp->doConnect(); - } - } - // If we connected successfully to usenet try to download the article body. - if ($aConnected === true) { - $newBody = $nntp->_getMessage($groupName, $wanted); - // Check if we got an error. - if ($nntp->isError($newBody)) { - if ($aConnected) { - $nntp->doQuit(); - } - // If we got some data, return it. - if ($body !== '') { - return $body; - } - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $newBody->getMessage(), Logger::LOG_NOTICE); - } - // Return the error. - return $newBody; - } - // Append the alternate body to the main body. - $body .= $newBody; - } - } else { - // If we got some data, return it. - if ($body !== '') { - return $body; - } - return $message; - } - } - } + // If there is an error try the alternate provider or return the PEAR error. + } else { + // Check if admin has enabled alternate in site->edit. + if ($alternate === true) { + if ($aConnected === false) { + // Check if the current connected server is the alternate or not. + if ($this->_currentServer === env('NNTP_SERVER')) { + // It's the main so connect to the alternate. + $aConnected = $nntp->doConnect(true, true); + } else { + // It's the alternate so connect to the main. + $aConnected = $nntp->doConnect(); + } + } + // If we connected successfully to usenet try to download the article body. + if ($aConnected === true) { + $newBody = $nntp->_getMessage($groupName, $wanted); + // Check if we got an error. + if ($nntp->isError($newBody)) { + if ($aConnected) { + $nntp->doQuit(); + } + // If we got some data, return it. + if ($body !== '') { + return $body; + } + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $newBody->getMessage(), Logger::LOG_NOTICE); + } + // Return the error. + return $newBody; + } + // Append the alternate body to the main body. + $body .= $newBody; + } + } else { + // If we got some data, return it. + if ($body !== '') { + return $body; + } - // If it's a string check if it's a valid message-ID. - } else if (is_string($identifiers) || is_numeric($identifiers)) { - $body = $this->_getMessage($groupName, $identifiers); - if ($alternate === true && $this->isError($body)) { - $nntp->doConnect(true, true); - $body = $nntp->_getMessage($groupName, $identifiers); - $aConnected = true; - } + return $message; + } + } + } - // Else return an error. - } else { - $message = 'Wrong Identifier type, array, int or string accepted. This type of var was passed: ' . gettype($identifiers); - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING); - } - return $this->throwError(ColorCLI::error($message)); - } + // If it's a string check if it's a valid message-ID. + } elseif (is_string($identifiers) || is_numeric($identifiers)) { + $body = $this->_getMessage($groupName, $identifiers); + if ($alternate === true && $this->isError($body)) { + $nntp->doConnect(true, true); + $body = $nntp->_getMessage($groupName, $identifiers); + $aConnected = true; + } - if ($aConnected === true) { - $nntp->doQuit(); - } + // Else return an error. + } else { + $message = 'Wrong Identifier type, array, int or string accepted. This type of var was passed: '.gettype($identifiers); + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING); + } - return $body; - } + return $this->throwError(ColorCLI::error($message)); + } - /** - * Download a full article, the body and the header, return an array with named keys and their - * associated values, optionally decode the body using yEnc. - * - * @param string $groupName The name of the group the article is in. - * @param mixed $identifier (string)The message-ID of the article to download. - * (int) The article number. - * @param bool $yEnc Attempt to yEnc decode the body. - * - * @return mixed On success : (array) The article. - * On failure : (object) PEAR_Error. - * - * @access public - */ - public function get_Article($groupName, $identifier, $yEnc = false) - { - $connected = $this->_checkConnection(); - if ($connected !== true) { - return $connected; - } + if ($aConnected === true) { + $nntp->doQuit(); + } - // Make sure the requested group is already selected, if not select it. - if (parent::group() !== $groupName) { - // Select the group. - $summary = $this->selectGroup($groupName); - // If there was an error selecting the group, return PEAR error object. - if ($this->isError($summary)) { - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_NOTICE); - } - return $summary; - } - } + return $body; + } - // Check if it's an article number or message-ID. - if (!is_numeric($identifier)) { - // If it's a message-ID, check if it has the required triangular brackets. - $identifier = $this->_formatMessageID($identifier); - } + /** + * Download a full article, the body and the header, return an array with named keys and their + * associated values, optionally decode the body using yEnc. + * + * @param string $groupName The name of the group the article is in. + * @param mixed $identifier (string)The message-ID of the article to download. + * (int) The article number. + * @param bool $yEnc Attempt to yEnc decode the body. + * + * @return mixed On success : (array) The article. + * On failure : (object) PEAR_Error. + */ + public function get_Article($groupName, $identifier, $yEnc = false) + { + $connected = $this->_checkConnection(); + if ($connected !== true) { + return $connected; + } - // Download the article. - $article = parent::getArticle($identifier); - // If there was an error downloading the article, return a PEAR error object. - if ($this->isError($article)) { - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $article->getMessage(), Logger::LOG_NOTICE); - } - return $article; - } + // Make sure the requested group is already selected, if not select it. + if (parent::group() !== $groupName) { + // Select the group. + $summary = $this->selectGroup($groupName); + // If there was an error selecting the group, return PEAR error object. + if ($this->isError($summary)) { + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_NOTICE); + } - $ret = $article; - // Make sure the article is an array and has more than 1 element. - if (count($article) > 0) { - $ret = []; - $body = ''; - $emptyLine = false; - foreach ($article as $line) { - // If we found the empty line it means we are done reading the header and we will start reading the body. - if (!$emptyLine) { - if ($line === '') { - $emptyLine = True; - continue; - } + return $summary; + } + } - // Use the line type of the article as the array key (From, Subject, etc..). - if (preg_match('/([A-Z-]+?): (.*)/i', $line, $matches)) { - // If the line type takes more than 1 line, append the rest of the content to the same key. - if (array_key_exists($matches[1], $ret)) { - $ret[$matches[1]] .= $matches[2]; - } else { - $ret[$matches[1]] = $matches[2]; - } - } + // Check if it's an article number or message-ID. + if (! is_numeric($identifier)) { + // If it's a message-ID, check if it has the required triangular brackets. + $identifier = $this->_formatMessageID($identifier); + } - // Now we have the header, so get the body from the rest of the lines. - } else { - $body .= $line; - } - } - // Finally we decode the message using yEnc. - $ret['Message'] = ($yEnc ? Yenc::decodeIgnore($body) : $body); - } - return $ret; - } + // Download the article. + $article = parent::getArticle($identifier); + // If there was an error downloading the article, return a PEAR error object. + if ($this->isError($article)) { + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $article->getMessage(), Logger::LOG_NOTICE); + } - /** - * Download a full article header. - * - * @param string $groupName The name of the group the article is in. - * @param mixed $identifier (string) The message-ID of the article to download. - * (int) The article number. - * - * @return mixed On success : (array) The header. - * @throws \Exception - * On failure : (object) PEAR_Error. - * - * @access public - */ - public function get_Header($groupName, $identifier) - { - $connected = $this->_checkConnection(); - if ($connected !== true) { - return $connected; - } + return $article; + } - // Make sure the requested group is already selected, if not select it. - if (parent::group() !== $groupName) { - // Select the group. - $summary = $this->selectGroup($groupName); - // Return PEAR error object on failure. - if ($this->isError($summary)) { - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_NOTICE); - } - return $summary; - } - } + $ret = $article; + // Make sure the article is an array and has more than 1 element. + if (count($article) > 0) { + $ret = []; + $body = ''; + $emptyLine = false; + foreach ($article as $line) { + // If we found the empty line it means we are done reading the header and we will start reading the body. + if (! $emptyLine) { + if ($line === '') { + $emptyLine = true; + continue; + } - // Check if it's an article number or message-id. - if (!is_numeric($identifier)) { - // Verify we have the required triangular brackets if it is a message-id. - $identifier = $this->_formatMessageID($identifier); - } + // Use the line type of the article as the array key (From, Subject, etc..). + if (preg_match('/([A-Z-]+?): (.*)/i', $line, $matches)) { + // If the line type takes more than 1 line, append the rest of the content to the same key. + if (array_key_exists($matches[1], $ret)) { + $ret[$matches[1]] .= $matches[2]; + } else { + $ret[$matches[1]] = $matches[2]; + } + } - // Download the header. - $header = parent::getHeader($identifier); - // If we failed, return PEAR error object. - if ($this->isError($header)) { - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $header->getMessage(), Logger::LOG_NOTICE); - } - return $header; - } + // Now we have the header, so get the body from the rest of the lines. + } else { + $body .= $line; + } + } + // Finally we decode the message using yEnc. + $ret['Message'] = ($yEnc ? Yenc::decodeIgnore($body) : $body); + } - $ret = $header; - if (count($header) > 0) { - $ret = []; - // Use the line types of the header as array keys (From, Subject, etc). - foreach ($header as $line) { - if (preg_match('/([A-Z-]+?): (.*)/i', $line, $matches)) { - // If the line type takes more than 1 line, re-use the same array key. - if (array_key_exists($matches[1], $ret)) { - $ret[$matches[1]] .= $matches[2]; - } else { - $ret[$matches[1]] = $matches[2]; - } - } - } - } - return $ret; - } + return $ret; + } - /** - * Post an article to usenet. - * - * @param string|array $groups mixed (array) Groups. ie.: $groups = array('alt.test', 'alt.testing', 'free.pt'); - * (string) Group. ie.: $groups = 'alt.test'; - * @param string $subject string The subject. ie.: $subject = 'Test article'; - * @param string|\Exception $body string The message. ie.: $message = 'This is only a test, please disregard.'; - * @param string $from string The poster. ie.: $from = '<anon@anon.com>'; - * @param $extra string Extra, separated by \r\n - * ie.: $extra = 'Organization: <NNTmux>\r\nNNTP-Posting-Host: <127.0.0.1>'; - * @param $yEnc bool Encode the message with yEnc? - * @param $compress bool Compress the message with GZip? - * - * @throws \Exception - * - * @return mixed On success : (bool) True. - * On failure : (object) PEAR_Error. - * - * @access public - */ - public function postArticle($groups, $subject, $body, $from, $yEnc = true, $compress = true, $extra = '') - { - if (!$this->_postingAllowed) { - $message = 'You do not have the right to post articles on server ' . $this->_currentServer; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); - } - return $this->throwError(ColorCLI::error($message)); - } + /** + * Download a full article header. + * + * @param string $groupName The name of the group the article is in. + * @param mixed $identifier (string) The message-ID of the article to download. + * (int) The article number. + * + * @return mixed On success : (array) The header. + * @throws \Exception + * On failure : (object) PEAR_Error. + */ + public function get_Header($groupName, $identifier) + { + $connected = $this->_checkConnection(); + if ($connected !== true) { + return $connected; + } - $connected = $this->_checkConnection(); - if ($connected !== true) { - return $connected; - } + // Make sure the requested group is already selected, if not select it. + if (parent::group() !== $groupName) { + // Select the group. + $summary = $this->selectGroup($groupName); + // Return PEAR error object on failure. + if ($this->isError($summary)) { + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_NOTICE); + } - // Throw errors if subject or from are more than 510 chars. - if (strlen($subject) > 510) { - $message = 'Max length of subject is 510 chars.'; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING); - } - return $this->throwError(ColorCLI::error($message)); - } + return $summary; + } + } - if (strlen($from) > 510) { - $message = 'Max length of from is 510 chars.'; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING); - } - return $this->throwError(ColorCLI::error($message)); - } + // Check if it's an article number or message-id. + if (! is_numeric($identifier)) { + // Verify we have the required triangular brackets if it is a message-id. + $identifier = $this->_formatMessageID($identifier); + } - // Check if the group is string or array. - if (is_array($groups)) { - $groups = implode(', ', $groups); - } + // Download the header. + $header = parent::getHeader($identifier); + // If we failed, return PEAR error object. + if ($this->isError($header)) { + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $header->getMessage(), Logger::LOG_NOTICE); + } - // Check if we should encode to yEnc. - if ($yEnc) { - $bin = $compress ? gzdeflate($body, 4) : $body; - $body = Yenc::encode($bin, $subject); - // If not yEnc, then check if the body is 510+ chars, split it at 510 chars and separate with \r\n - } else { - $body = $this->_splitLines($body, $compress); - } + return $header; + } - // From is required by NNTP servers, but parent function mail does not require it, so format it. - $from = 'From: ' . $from; - // If we had extra stuff to post, format it with from. - if ($extra !== '') { - $from = $from . "\r\n" . $extra; - } + $ret = $header; + if (count($header) > 0) { + $ret = []; + // Use the line types of the header as array keys (From, Subject, etc). + foreach ($header as $line) { + if (preg_match('/([A-Z-]+?): (.*)/i', $line, $matches)) { + // If the line type takes more than 1 line, re-use the same array key. + if (array_key_exists($matches[1], $ret)) { + $ret[$matches[1]] .= $matches[2]; + } else { + $ret[$matches[1]] = $matches[2]; + } + } + } + } - return parent::mail($groups, $subject, $body, $from); - } + return $ret; + } - /** - * Restart the NNTP connection if an error occurs in the selectGroup - * function, if it does not restart display the error. - * - * @param NNTP $nntp Instance of class NNTP. - * @param string $group Name of the group. - * @param bool $comp Use compression or not? - * - * @return mixed On success : (array) The group summary. - * @throws \Exception - * On Failure : (object) PEAR_Error. - * - * @access public - */ - public function dataError($nntp, $group, $comp = true) - { - // Disconnect. - $nntp->doQuit(); - // Try reconnecting. This uses another round of max retries. - if ($nntp->doConnect($comp) !== true) { - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, 'Unable to reconnect to usenet!', Logger::LOG_NOTICE); - } - return $this->throwError('Unable to reconnect to usenet!'); - } + /** + * Post an article to usenet. + * + * @param string|array $groups mixed (array) Groups. ie.: $groups = array('alt.test', 'alt.testing', 'free.pt'); + * (string) Group. ie.: $groups = 'alt.test'; + * @param string $subject string The subject. ie.: $subject = 'Test article'; + * @param string|\Exception $body string The message. ie.: $message = 'This is only a test, please disregard.'; + * @param string $from string The poster. ie.: $from = '<anon@anon.com>'; + * @param $extra string Extra, separated by \r\n + * ie.: $extra = 'Organization: <NNTmux>\r\nNNTP-Posting-Host: <127.0.0.1>'; + * @param $yEnc bool Encode the message with yEnc? + * @param $compress bool Compress the message with GZip? + * + * @throws \Exception + * + * @return mixed On success : (bool) True. + * On failure : (object) PEAR_Error. + */ + public function postArticle($groups, $subject, $body, $from, $yEnc = true, $compress = true, $extra = '') + { + if (! $this->_postingAllowed) { + $message = 'You do not have the right to post articles on server '.$this->_currentServer; + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); + } - // Try re-selecting the group. - $data = $nntp->selectGroup($group); - if ($this->isError($data)) { - $message = "Code {$data->code}: {$data->message}\nSkipping group: {$group}"; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); - } + return $this->throwError(ColorCLI::error($message)); + } - if ($this->_echo) { - ColorCLI::doEcho(ColorCLI::error($message), true); - } - $nntp->doQuit(); - } - return $data; - } + $connected = $this->_checkConnection(); + if ($connected !== true) { + return $connected; + } - /** - * Path to yyDecoder binary. - * @var bool|string - * @access protected - */ - protected $_yyDecoderPath; + // Throw errors if subject or from are more than 510 chars. + if (strlen($subject) > 510) { + $message = 'Max length of subject is 510 chars.'; + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING); + } - /** - * If on unix, hide yydecode CLI output. - * @var string - * @access protected - */ - protected $_yEncSilence; + return $this->throwError(ColorCLI::error($message)); + } - /** - * Path to temp yEnc input storage file. - * @var string - * @access protected - */ - protected $_yEncTempInput; + if (strlen($from) > 510) { + $message = 'Max length of from is 510 chars.'; + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING); + } - /** - * Path to temp yEnc output storage file. - * @var string - * @access protected - */ - protected $_yEncTempOutput; + return $this->throwError(ColorCLI::error($message)); + } - /** - * Split a string into lines of 510 chars ending with \r\n. - * Usenet limits lines to 512 chars, with \r\n that leaves us 510. - * - * @param string $string The string to split. - * @param bool $compress Compress the string with gzip? - * - * @return string The split string. - * - * @access protected - */ - protected function _splitLines($string, $compress = false): string - { - // Check if the length is longer than 510 chars. - if (strlen($string) > 510) { - // If it is, split it @ 510 and terminate with \r\n. - $string = chunk_split($string, 510, "\r\n"); - } + // Check if the group is string or array. + if (is_array($groups)) { + $groups = implode(', ', $groups); + } - // Compress the string if requested. - return ($compress ? gzdeflate($string, 4) : $string); - } + // Check if we should encode to yEnc. + if ($yEnc) { + $bin = $compress ? gzdeflate($body, 4) : $body; + $body = Yenc::encode($bin, $subject); + // If not yEnc, then check if the body is 510+ chars, split it at 510 chars and separate with \r\n + } else { + $body = $this->_splitLines($body, $compress); + } - /** - * Try to see if the NNTP server implements XFeature GZip Compression, - * change the compression bool object if so. - * - * @param bool $secondTry This is only used if enabling compression fails, the function will call itself to retry. - * @return mixed On success : (bool) True: The server understood and compression is enabled. - * (bool) False: The server did not understand, compression is not enabled. - * On failure : (object) PEAR_Error. - * - * @access protected - */ - protected function _enableCompression($secondTry = false) - { - if ($this->_compressionEnabled === true) { - return true; - } - if ($this->_compressionSupported === false) { - return false; - } + // From is required by NNTP servers, but parent function mail does not require it, so format it. + $from = 'From: '.$from; + // If we had extra stuff to post, format it with from. + if ($extra !== '') { + $from = $from."\r\n".$extra; + } - // Send this command to the usenet server. - $response = $this->_sendCommand('XFEATURE COMPRESS GZIP'); + return parent::mail($groups, $subject, $body, $from); + } - // Check if it's good. - if ($this->isError($response)) { - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $response->getMessage(), Logger::LOG_NOTICE); - } - $this->_compressionSupported = false; - return $response; - } - if ($response !== 290) { - if ($secondTry === false) { - // Retry. - $this->cmdQuit(); - if ($this->_checkConnection()) { - return $this->_enableCompression(true); - } - } - $msg = "Sent 'XFEATURE COMPRESS GZIP' to server, got '$response: " . $this->_currentStatusResponse() . "'"; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $msg, Logger::LOG_NOTICE); - } - $this->_compressionSupported = false; + /** + * Restart the NNTP connection if an error occurs in the selectGroup + * function, if it does not restart display the error. + * + * @param NNTP $nntp Instance of class NNTP. + * @param string $group Name of the group. + * @param bool $comp Use compression or not? + * + * @return mixed On success : (array) The group summary. + * @throws \Exception + * On Failure : (object) PEAR_Error. + */ + public function dataError($nntp, $group, $comp = true) + { + // Disconnect. + $nntp->doQuit(); + // Try reconnecting. This uses another round of max retries. + if ($nntp->doConnect($comp) !== true) { + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, 'Unable to reconnect to usenet!', Logger::LOG_NOTICE); + } - return false; + return $this->throwError('Unable to reconnect to usenet!'); + } - } + // Try re-selecting the group. + $data = $nntp->selectGroup($group); + if ($this->isError($data)) { + $message = "Code {$data->code}: {$data->message}\nSkipping group: {$group}"; + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); + } - $this->_compressionEnabled = true; - $this->_compressionSupported = true; - return true; - } + if ($this->_echo) { + ColorCLI::doEcho(ColorCLI::error($message), true); + } + $nntp->doQuit(); + } - /** - * Override PEAR NNTP's function to use our _getXFeatureTextResponse instead - * of their _getTextResponse function since it is incompatible at decoding - * headers when XFeature GZip compression is enabled server side. - * - * @return self|string Our overridden function when compression is enabled. - * parent Parent function when no compression. - * - * @access protected - */ - protected function _getTextResponse() - { - if ($this->_compressionEnabled === true && + return $data; + } + + /** + * Path to yyDecoder binary. + * @var bool|string + */ + protected $_yyDecoderPath; + + /** + * If on unix, hide yydecode CLI output. + * @var string + */ + protected $_yEncSilence; + + /** + * Path to temp yEnc input storage file. + * @var string + */ + protected $_yEncTempInput; + + /** + * Path to temp yEnc output storage file. + * @var string + */ + protected $_yEncTempOutput; + + /** + * Split a string into lines of 510 chars ending with \r\n. + * Usenet limits lines to 512 chars, with \r\n that leaves us 510. + * + * @param string $string The string to split. + * @param bool $compress Compress the string with gzip? + * + * @return string The split string. + */ + protected function _splitLines($string, $compress = false): string + { + // Check if the length is longer than 510 chars. + if (strlen($string) > 510) { + // If it is, split it @ 510 and terminate with \r\n. + $string = chunk_split($string, 510, "\r\n"); + } + + // Compress the string if requested. + return $compress ? gzdeflate($string, 4) : $string; + } + + /** + * Try to see if the NNTP server implements XFeature GZip Compression, + * change the compression bool object if so. + * + * @param bool $secondTry This is only used if enabling compression fails, the function will call itself to retry. + * @return mixed On success : (bool) True: The server understood and compression is enabled. + * (bool) False: The server did not understand, compression is not enabled. + * On failure : (object) PEAR_Error. + */ + protected function _enableCompression($secondTry = false) + { + if ($this->_compressionEnabled === true) { + return true; + } + if ($this->_compressionSupported === false) { + return false; + } + + // Send this command to the usenet server. + $response = $this->_sendCommand('XFEATURE COMPRESS GZIP'); + + // Check if it's good. + if ($this->isError($response)) { + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $response->getMessage(), Logger::LOG_NOTICE); + } + $this->_compressionSupported = false; + + return $response; + } + if ($response !== 290) { + if ($secondTry === false) { + // Retry. + $this->cmdQuit(); + if ($this->_checkConnection()) { + return $this->_enableCompression(true); + } + } + $msg = "Sent 'XFEATURE COMPRESS GZIP' to server, got '$response: ".$this->_currentStatusResponse()."'"; + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $msg, Logger::LOG_NOTICE); + } + $this->_compressionSupported = false; + + return false; + } + + $this->_compressionEnabled = true; + $this->_compressionSupported = true; + + return true; + } + + /** + * Override PEAR NNTP's function to use our _getXFeatureTextResponse instead + * of their _getTextResponse function since it is incompatible at decoding + * headers when XFeature GZip compression is enabled server side. + * + * @return self|string Our overridden function when compression is enabled. + * parent Parent function when no compression. + */ + protected function _getTextResponse() + { + if ($this->_compressionEnabled === true && isset($this->_currentStatusResponse[1]) && stripos($this->_currentStatusResponse[1], 'COMPRESS=GZIP') !== false) { + return $this->_getXFeatureTextResponse(); + } - return $this->_getXFeatureTextResponse(); - } - return parent::_getTextResponse(); - } + return parent::_getTextResponse(); + } - /** - * Loop over the compressed data when XFeature GZip Compress is turned on, - * string the data until we find a indicator - * (period, carriage feed, line return ;; .\r\n), decompress the data, - * split the data (bunch of headers in a string) into an array, finally - * return the array. - * - * Have we failed to decompress the data, was there a - * problem downloading the data, etc.. - * @return array|string On success : (array) The headers. - * On failure : (object) PEAR_Error. - * On decompress failure: (string) error message - * - * @access protected - */ - protected function &_getXFeatureTextResponse() - { - $possibleTerm = false; - $data = null; + /** + * Loop over the compressed data when XFeature GZip Compress is turned on, + * string the data until we find a indicator + * (period, carriage feed, line return ;; .\r\n), decompress the data, + * split the data (bunch of headers in a string) into an array, finally + * return the array. + * + * Have we failed to decompress the data, was there a + * problem downloading the data, etc.. + * @return array|string On success : (array) The headers. + * On failure : (object) PEAR_Error. + * On decompress failure: (string) error message + */ + protected function &_getXFeatureTextResponse() + { + $possibleTerm = false; + $data = null; - while (!feof($this->_socket)) { + while (! feof($this->_socket)) { // Did we find a possible ending ? (.\r\n) - if ($possibleTerm !== false) { + if ($possibleTerm !== false) { // Loop, sleeping shortly, to allow the server time to upload data, if it has any. - for ($i = 0; $i < 3; $i++) { - // If the socket is really empty, fGets will get stuck here, so set the socket to non blocking in case. - stream_set_blocking($this->_socket, 0); + for ($i = 0; $i < 3; $i++) { + // If the socket is really empty, fGets will get stuck here, so set the socket to non blocking in case. + stream_set_blocking($this->_socket, 0); - // Now try to download from the socket. - $buffer = fgets($this->_socket); + // Now try to download from the socket. + $buffer = fgets($this->_socket); - // And set back the socket to blocking. - stream_set_blocking($this->_socket, 1); + // And set back the socket to blocking. + stream_set_blocking($this->_socket, 1); - // Don't sleep on last iteration. - if (!empty($buffer)) { - break; - } - if ($i < 2) { - usleep(10000); - } - } + // Don't sleep on last iteration. + if (! empty($buffer)) { + break; + } + if ($i < 2) { + usleep(10000); + } + } - // If the buffer was really empty, then we know $possibleTerm was the real ending. - if (empty($buffer)) { - // Remove .\r\n from end, decompress data. - $deComp = @gzuncompress(mb_substr($data, 0, -3, '8bit')); + // If the buffer was really empty, then we know $possibleTerm was the real ending. + if (empty($buffer)) { + // Remove .\r\n from end, decompress data. + $deComp = @gzuncompress(mb_substr($data, 0, -3, '8bit')); - if (!empty($deComp)) { - - $bytesReceived = strlen($data); - if ($this->_echo && $bytesReceived > 10240) { - ColorCLI::doEcho( + if (! empty($deComp)) { + $bytesReceived = strlen($data); + if ($this->_echo && $bytesReceived > 10240) { + ColorCLI::doEcho( ColorCLI::primaryOver( - 'Received ' . round($bytesReceived / 1024) . - 'KB from group (' . $this->group() . ').' + 'Received '.round($bytesReceived / 1024). + 'KB from group ('.$this->group().').' ), true ); - } + } - // Split the string of headers into an array of individual headers, then return it. - $deComp = explode("\r\n", trim($deComp)); - return $deComp; - } - $message = 'Decompression of OVER headers failed.'; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); - } - $message = $this->throwError(ColorCLI::error($message), 1000); - return $message; + // Split the string of headers into an array of individual headers, then return it. + $deComp = explode("\r\n", trim($deComp)); - } - // The buffer was not empty, so we know this was not the real ending, so reset $possibleTerm. - $possibleTerm = false; - } else { - // Get data from the stream. - $buffer = fgets($this->_socket); - } + return $deComp; + } + $message = 'Decompression of OVER headers failed.'; + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); + } + $message = $this->throwError(ColorCLI::error($message), 1000); - // If we got no data at all try one more time to pull data. - if (empty($buffer)) { - usleep(10000); - $buffer = fgets($this->_socket); + return $message; + } + // The buffer was not empty, so we know this was not the real ending, so reset $possibleTerm. + $possibleTerm = false; + } else { + // Get data from the stream. + $buffer = fgets($this->_socket); + } - // If wet got nothing again, return error. - if (empty($buffer)) { - $message = 'Error fetching data from usenet server while downloading OVER headers.'; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); - } - $message = $this->throwError(ColorCLI::error($message), 1000); - return $message; - } - } + // If we got no data at all try one more time to pull data. + if (empty($buffer)) { + usleep(10000); + $buffer = fgets($this->_socket); - // Append current buffer to rest of buffer. - $data .= $buffer; + // If wet got nothing again, return error. + if (empty($buffer)) { + $message = 'Error fetching data from usenet server while downloading OVER headers.'; + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); + } + $message = $this->throwError(ColorCLI::error($message), 1000); - // Check if we have the ending (.\r\n) - if (substr($buffer, -3) === ".\r\n") { - // We have a possible ending, next loop check if it is. - $possibleTerm = true; - } - } + return $message; + } + } - $message = 'Unspecified error while downloading OVER headers.'; - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); - } - $message = $this->throwError(ColorCLI::error($message), 1000); - return $message; - } + // Append current buffer to rest of buffer. + $data .= $buffer; - /** - * Check if the Message-ID has the required opening and closing brackets. - * - * @param string $messageID The Message-ID with or without brackets. - * - * @return string Message-ID with brackets. - * - * @access protected - */ - protected function _formatMessageID($messageID): string - { - $messageID = (string)$messageID; - if ($messageID === '') { - return false; - } + // Check if we have the ending (.\r\n) + if (substr($buffer, -3) === ".\r\n") { + // We have a possible ending, next loop check if it is. + $possibleTerm = true; + } + } - // Check if the first char is <, if not add it. - if ($messageID[0] !== '<') { - $messageID = ('<' . $messageID); - } + $message = 'Unspecified error while downloading OVER headers.'; + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE); + } + $message = $this->throwError(ColorCLI::error($message), 1000); - // Check if the last char is >, if not add it. - if (substr($messageID, -1) !== '>') { - $messageID .= '>'; - } - return $messageID; - } + return $message; + } - /** - * Download an article body (an article without the header). - * - * @param string $groupName The name of the group the article is in. - * @param mixed $identifier (string) The message-ID of the article to download. - * (int) The article number. - * - * @return string On success : (string) The article's body. - * @throws \Exception - * On failure : (object) PEAR_Error. - * - * @access protected - */ - protected function _getMessage($groupName, $identifier): ?string - { - // Make sure the requested group is already selected, if not select it. - if (parent::group() !== $groupName) { - // Select the group. - $summary = $this->selectGroup($groupName); - // If there was an error selecting the group, return PEAR error object. - if ($this->isError($summary)) { - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_WARNING); - } - return $summary; - } - } + /** + * Check if the Message-ID has the required opening and closing brackets. + * + * @param string $messageID The Message-ID with or without brackets. + * + * @return string Message-ID with brackets. + */ + protected function _formatMessageID($messageID): string + { + $messageID = (string) $messageID; + if ($messageID === '') { + return false; + } - // Check if this is an article number or message-id. - if (!is_numeric($identifier)) { - // It's a message-id so check if it has the triangular brackets. - $identifier = $this->_formatMessageID($identifier); - } + // Check if the first char is <, if not add it. + if ($messageID[0] !== '<') { + $messageID = ('<'.$messageID); + } - // Tell the news server we want the body of an article. - $response = $this->_sendCommand('BODY ' . $identifier); - if ($this->isError($response)) { - return $response; - } + // Check if the last char is >, if not add it. + if (substr($messageID, -1) !== '>') { + $messageID .= '>'; + } - $body = ''; - if ($response === NET_NNTP_PROTOCOL_RESPONSECODE_BODY_FOLLOWS) { + return $messageID; + } + + /** + * Download an article body (an article without the header). + * + * @param string $groupName The name of the group the article is in. + * @param mixed $identifier (string) The message-ID of the article to download. + * (int) The article number. + * + * @return string On success : (string) The article's body. + * @throws \Exception + * On failure : (object) PEAR_Error. + */ + protected function _getMessage($groupName, $identifier): ?string + { + // Make sure the requested group is already selected, if not select it. + if (parent::group() !== $groupName) { + // Select the group. + $summary = $this->selectGroup($groupName); + // If there was an error selecting the group, return PEAR error object. + if ($this->isError($summary)) { + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_WARNING); + } + + return $summary; + } + } + + // Check if this is an article number or message-id. + if (! is_numeric($identifier)) { + // It's a message-id so check if it has the triangular brackets. + $identifier = $this->_formatMessageID($identifier); + } + + // Tell the news server we want the body of an article. + $response = $this->_sendCommand('BODY '.$identifier); + if ($this->isError($response)) { + return $response; + } + + $body = ''; + if ($response === NET_NNTP_PROTOCOL_RESPONSECODE_BODY_FOLLOWS) { // Continue until connection is lost - while (!feof($this->_socket)) { + while (! feof($this->_socket)) { // Retrieve and append up to 1024 characters from the server. - $line = fgets($this->_socket, 1024); + $line = fgets($this->_socket, 1024); - // If the socket is empty/ an error occurs, false is returned. - // Since the socket is blocking, the socket should not be empty, so it's definitely an error. - if ($line === false) { - return $this->throwError('Failed to read line from socket.', null); - } + // If the socket is empty/ an error occurs, false is returned. + // Since the socket is blocking, the socket should not be empty, so it's definitely an error. + if ($line === false) { + return $this->throwError('Failed to read line from socket.', null); + } - // Check if the line terminates the text response. - if ($line === ".\r\n") { - if ($this->_debugBool) { - $this->_debugging->log(__CLASS__, - __FUNCTION__, 'Fetched body for article ' . $identifier, Logger::LOG_INFO + // Check if the line terminates the text response. + if ($line === ".\r\n") { + if ($this->_debugBool) { + $this->_debugging->log(__CLASS__, + __FUNCTION__, 'Fetched body for article '.$identifier, Logger::LOG_INFO ); - } + } - // Attempt to yEnc decode and return the body. - return Yenc::decodeIgnore($body); - } + // Attempt to yEnc decode and return the body. + return Yenc::decodeIgnore($body); + } - // Check for line that starts with double period, remove one. - if ($line[0] === '.' && $line[1] === '.') { - $line = substr($line, 1); - } + // Check for line that starts with double period, remove one. + if ($line[0] === '.' && $line[1] === '.') { + $line = substr($line, 1); + } - // Add the line to the rest of the lines. - $body .= $line; + // Add the line to the rest of the lines. + $body .= $line; + } - } + return $this->throwError('End of stream! Connection lost?', null); + } - return $this->throwError('End of stream! Connection lost?', null); - } + return $this->_handleErrorResponse($response); + } - return $this->_handleErrorResponse($response); - } - - /** - * Check if we are still connected. Reconnect if not. - * - * @param bool $reSelectGroup Select back the group after connecting? - * - * @return mixed On success: (bool) True; - * @throws \Exception - * On failure: (object) PEAR_Error - * - * @access protected - */ - protected function _checkConnection($reSelectGroup = true) - { - $currentGroup = $this->_currentGroup; - // Check if we are connected. - if (parent::_isConnected()) { - $retVal = true; - } else { - switch ($this->_currentServer) { + /** + * Check if we are still connected. Reconnect if not. + * + * @param bool $reSelectGroup Select back the group after connecting? + * + * @return mixed On success: (bool) True; + * @throws \Exception + * On failure: (object) PEAR_Error + */ + protected function _checkConnection($reSelectGroup = true) + { + $currentGroup = $this->_currentGroup; + // Check if we are connected. + if (parent::_isConnected()) { + $retVal = true; + } else { + switch ($this->_currentServer) { case env('NNTP_SERVER'): if (is_resource($this->_socket)) { - $this->doQuit(true); + $this->doQuit(true); } $retVal = $this->doConnect(); break; case env('NNTP_SERVER_A'): if (is_resource($this->_socket)) { - $this->doQuit(true); + $this->doQuit(true); } $retVal = $this->doConnect(true, true); break; @@ -1310,13 +1282,14 @@ class NNTP extends \Net_NNTP_Client $retVal = $this->throwError('Wrong server constant used in NNTP checkConnection()!'); } - if ($retVal === true && $reSelectGroup) { - $group = $this->selectGroup($currentGroup); - if ($this->isError($group)) { - $retVal = $group; - } - } - } - return $retVal; - } + if ($retVal === true && $reSelectGroup) { + $group = $this->selectGroup($currentGroup); + if ($this->isError($group)) { + $retVal = $group; + } + } + } + + return $retVal; + } } diff --git a/nntmux/NZB.php b/nntmux/NZB.php index 11f5b5e10..cf71c538d 100755 --- a/nntmux/NZB.php +++ b/nntmux/NZB.php @@ -1,10 +1,11 @@ <?php + namespace nntmux; -use App\Extensions\util\Versions; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; use nntmux\utility\Utility; +use App\Extensions\util\Versions; /** * Class for reading and writing NZB files on the hard disk, @@ -12,475 +13,455 @@ use nntmux\utility\Utility; */ class NZB { - const NZB_NONE = 0; // Release has no NZB file yet. + const NZB_NONE = 0; // Release has no NZB file yet. const NZB_ADDED = 1; // Release had an NZB file created. const NZB_DTD_NAME = 'nzb'; - const NZB_DTD_PUBLIC = '-//newzBin//DTD NZB 1.1//EN'; - const NZB_DTD_EXTERNAL = 'http://www.newzbin.com/DTD/nzb/nzb-1.1.dtd'; - const NZB_XML_NS = 'http://www.newzbin.com/DTD/2003/nzb'; + const NZB_DTD_PUBLIC = '-//newzBin//DTD NZB 1.1//EN'; + const NZB_DTD_EXTERNAL = 'http://www.newzbin.com/DTD/nzb/nzb-1.1.dtd'; + const NZB_XML_NS = 'http://www.newzbin.com/DTD/2003/nzb'; - /** - * Levels deep to store NZB files. - * - * @var int - */ - protected $nzbSplitLevel; + /** + * Levels deep to store NZB files. + * + * @var int + */ + protected $nzbSplitLevel; - /** - * Path to store NZB files. - * - * @var string - */ - protected $siteNzbPath; + /** + * Path to store NZB files. + * + * @var string + */ + protected $siteNzbPath; - /** - * Group id when writing NZBs. - * - * @var int - * @access protected - */ - protected $groupID; + /** + * Group id when writing NZBs. + * + * @var int + */ + protected $groupID; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var Logger - */ - protected $debugging; + /** + * @var Logger + */ + protected $debugging; - /** - * @var bool - */ - protected $_debug = false; + /** + * @var bool + */ + protected $_debug = false; - /** - * Base query for selecting collection data for writing NZB files. - * - * @var string - * @access protected - */ - protected $_collectionsQuery; + /** + * Base query for selecting collection data for writing NZB files. + * + * @var string + */ + protected $_collectionsQuery; - /** - * Base query for selecting binary data for writing NZB files. - * - * @var string - * @access protected - */ - protected $_binariesQuery; + /** + * Base query for selecting binary data for writing NZB files. + * + * @var string + */ + protected $_binariesQuery; - /** - * Base query for selecting parts data for writing NZB files. - * - * @var string - * @access protected - */ - protected $_partsQuery; + /** + * Base query for selecting parts data for writing NZB files. + * + * @var string + */ + protected $_partsQuery; - /** - * String used for head in NZB XML file. - * - * @var string - * @access protected - */ - protected $_nzbCommentString; + /** + * String used for head in NZB XML file. + * + * @var string + */ + protected $_nzbCommentString; - /** - * Names of CBP tables. - * - * @var array [string => string] - * @access protected - */ - protected $_tableNames; + /** + * Names of CBP tables. + * + * @var array [string => string] + */ + protected $_tableNames; - /** - * Default constructor. - * - * @param \nntmux\db\DB $pdo - * - * @access public - * @throws \Exception - */ - public function __construct(&$pdo) - { - $this->pdo = ($pdo instanceof DB ? $pdo : new DB()); + /** + * Default constructor. + * + * @param \nntmux\db\DB $pdo + * + * @throws \Exception + */ + public function __construct(&$pdo) + { + $this->pdo = ($pdo instanceof DB ? $pdo : new DB()); - $nzbSplitLevel = Settings::value('..nzbsplitlevel'); - $this->nzbSplitLevel = (empty($nzbSplitLevel) ? 1 : $nzbSplitLevel); - $this->siteNzbPath = (string)Settings::value('..nzbpath'); - if (substr($this->siteNzbPath, -1) !== DS) { - $this->siteNzbPath .= DS; - } - $this->_nzbCommentString = sprintf( + $nzbSplitLevel = Settings::value('..nzbsplitlevel'); + $this->nzbSplitLevel = (empty($nzbSplitLevel) ? 1 : $nzbSplitLevel); + $this->siteNzbPath = (string) Settings::value('..nzbpath'); + if (substr($this->siteNzbPath, -1) !== DS) { + $this->siteNzbPath .= DS; + } + $this->_nzbCommentString = sprintf( 'NZB Generated by: NNTmux %s %s', (new Versions())->getGitTagInFile(), Utility::htmlfmt(date('F j, Y, g:i a O')) ); - $this->_debug = (NN_DEBUG || NN_LOGGING); + $this->_debug = (NN_DEBUG || NN_LOGGING); - if (NN_DEBUG || NN_LOGGING) { - $this->_debug = true; - try { - $this->debugging = new Logger(['ColorCLI' => $this->pdo->log]); - } catch (LoggerException $error) { - $this->_debug = false; - } - } - } + if (NN_DEBUG || NN_LOGGING) { + $this->_debug = true; + try { + $this->debugging = new Logger(['ColorCLI' => $this->pdo->log]); + } catch (LoggerException $error) { + $this->_debug = false; + } + } + } - /** - * Initiate class vars when writing NZB's. - * - * @param int $groupID - * - * @access public - */ - public function initiateForWrite($groupID) - { - $this->groupID = $groupID; - // Set table names + /** + * Initiate class vars when writing NZB's. + * + * @param int $groupID + */ + public function initiateForWrite($groupID) + { + $this->groupID = $groupID; + // Set table names - if ($this->groupID === '') { - exit("{$this->groupID} is missing\n"); - } - $this->_tableNames = [ - 'cName' => 'collections_' . $this->groupID, - 'bName' => 'binaries_' . $this->groupID, - 'pName' => 'parts_' . $this->groupID + if ($this->groupID === '') { + exit("{$this->groupID} is missing\n"); + } + $this->_tableNames = [ + 'cName' => 'collections_'.$this->groupID, + 'bName' => 'binaries_'.$this->groupID, + 'pName' => 'parts_'.$this->groupID, ]; - $this->setQueries(); - } + $this->setQueries(); + } - protected function setQueries(): void - { - $this->_collectionsQuery = " + protected function setQueries(): void + { + $this->_collectionsQuery = " SELECT c.*, UNIX_TIMESTAMP(c.date) AS udate, g.name AS groupname FROM {$this->_tableNames['cName']} c INNER JOIN groups g ON c.groups_id = g.id WHERE c.releases_id = "; - $this->_binariesQuery = " + $this->_binariesQuery = " SELECT b.id, b.name, b.totalparts FROM {$this->_tableNames['bName']} b WHERE b.collections_id = %d ORDER BY b.name ASC"; - $this->_partsQuery = " + $this->_partsQuery = " SELECT DISTINCT(p.messageid), p.size, p.partnumber FROM {$this->_tableNames['pName']} p WHERE p.binaries_id = %d ORDER BY p.partnumber ASC"; - } + } - /** - * Write an NZB to the hard drive for a single release. - * - * @param int $relID The ID of the release in the DB. - * @param string $relGuid The guid of the release. - * @param string $name The name of the release. - * @param string $cTitle The name of the category this release is in. - * - * @return bool Have we successfully written the NZB to the hard drive? - * - * @access public - */ - public function writeNZBforReleaseId($relID, $relGuid, $name, $cTitle): bool - { - $collections = $this->pdo->queryDirect($this->_collectionsQuery . $relID); + /** + * Write an NZB to the hard drive for a single release. + * + * @param int $relID The ID of the release in the DB. + * @param string $relGuid The guid of the release. + * @param string $name The name of the release. + * @param string $cTitle The name of the category this release is in. + * + * @return bool Have we successfully written the NZB to the hard drive? + */ + public function writeNZBforReleaseId($relID, $relGuid, $name, $cTitle): bool + { + $collections = $this->pdo->queryDirect($this->_collectionsQuery.$relID); - if (!$collections instanceof \Traversable) { - return false; - } + if (! $collections instanceof \Traversable) { + return false; + } - $XMLWriter = new \XMLWriter(); - $XMLWriter->openMemory(); - $XMLWriter->setIndent(true); - $XMLWriter->setIndentString(' '); + $XMLWriter = new \XMLWriter(); + $XMLWriter->openMemory(); + $XMLWriter->setIndent(true); + $XMLWriter->setIndentString(' '); - $nzb_guid = ''; + $nzb_guid = ''; - $XMLWriter->startDocument('1.0', 'UTF-8'); - $XMLWriter->startDTD(self::NZB_DTD_NAME, self::NZB_DTD_PUBLIC, self::NZB_DTD_EXTERNAL); - $XMLWriter->endDTD(); - $XMLWriter->writeComment($this->_nzbCommentString); + $XMLWriter->startDocument('1.0', 'UTF-8'); + $XMLWriter->startDTD(self::NZB_DTD_NAME, self::NZB_DTD_PUBLIC, self::NZB_DTD_EXTERNAL); + $XMLWriter->endDTD(); + $XMLWriter->writeComment($this->_nzbCommentString); - $XMLWriter->startElement('nzb'); - $XMLWriter->writeAttribute('xmlns', self::NZB_XML_NS); - $XMLWriter->startElement('head'); - $XMLWriter->startElement('meta'); - $XMLWriter->writeAttribute('type', 'category'); - $XMLWriter->text($cTitle); - $XMLWriter->endElement(); - $XMLWriter->startElement('meta'); - $XMLWriter->writeAttribute('type', 'name'); - $XMLWriter->text($name); - $XMLWriter->endElement(); - $XMLWriter->endElement(); //head + $XMLWriter->startElement('nzb'); + $XMLWriter->writeAttribute('xmlns', self::NZB_XML_NS); + $XMLWriter->startElement('head'); + $XMLWriter->startElement('meta'); + $XMLWriter->writeAttribute('type', 'category'); + $XMLWriter->text($cTitle); + $XMLWriter->endElement(); + $XMLWriter->startElement('meta'); + $XMLWriter->writeAttribute('type', 'name'); + $XMLWriter->text($name); + $XMLWriter->endElement(); + $XMLWriter->endElement(); //head - foreach ($collections as $collection) { - $binaries = $this->pdo->queryDirect(sprintf($this->_binariesQuery, $collection['id'])); - if ($binaries === false) { - return false; - } + foreach ($collections as $collection) { + $binaries = $this->pdo->queryDirect(sprintf($this->_binariesQuery, $collection['id'])); + if ($binaries === false) { + return false; + } - $poster = $collection['fromname']; + $poster = $collection['fromname']; - foreach ($binaries as $binary) { - $parts = $this->pdo->queryDirect(sprintf($this->_partsQuery, $binary['id'])); - if ($parts === false) { - return false; - } + foreach ($binaries as $binary) { + $parts = $this->pdo->queryDirect(sprintf($this->_partsQuery, $binary['id'])); + if ($parts === false) { + return false; + } - $subject = $binary['name'] . '(1/' . $binary['totalparts'] . ')'; - $XMLWriter->startElement('file'); - $XMLWriter->writeAttribute('poster', $poster); - $XMLWriter->writeAttribute('date', $collection['udate']); - $XMLWriter->writeAttribute('subject', $subject); - $XMLWriter->startElement('groups'); - if (preg_match_all('#(\S+):\S+#', $collection['xref'], $matches)) { - $matches = array_unique($matches[1]); - foreach ($matches as $group) { - $XMLWriter->writeElement('group', $group); - } - } else { - return false; - } - $XMLWriter->endElement(); //groups - $XMLWriter->startElement('segments'); - foreach ($parts as $part) { - if ($nzb_guid === '') { - $nzb_guid = $part['messageid']; - } - $XMLWriter->startElement('segment'); - $XMLWriter->writeAttribute('bytes', $part['size']); - $XMLWriter->writeAttribute('number', $part['partnumber']); - $XMLWriter->text($part['messageid']); - $XMLWriter->endElement(); - } - $XMLWriter->endElement(); //segments + $subject = $binary['name'].'(1/'.$binary['totalparts'].')'; + $XMLWriter->startElement('file'); + $XMLWriter->writeAttribute('poster', $poster); + $XMLWriter->writeAttribute('date', $collection['udate']); + $XMLWriter->writeAttribute('subject', $subject); + $XMLWriter->startElement('groups'); + if (preg_match_all('#(\S+):\S+#', $collection['xref'], $matches)) { + $matches = array_unique($matches[1]); + foreach ($matches as $group) { + $XMLWriter->writeElement('group', $group); + } + } else { + return false; + } + $XMLWriter->endElement(); //groups + $XMLWriter->startElement('segments'); + foreach ($parts as $part) { + if ($nzb_guid === '') { + $nzb_guid = $part['messageid']; + } + $XMLWriter->startElement('segment'); + $XMLWriter->writeAttribute('bytes', $part['size']); + $XMLWriter->writeAttribute('number', $part['partnumber']); + $XMLWriter->text($part['messageid']); + $XMLWriter->endElement(); + } + $XMLWriter->endElement(); //segments $XMLWriter->endElement(); //file - } - } - $XMLWriter->endElement(); //nzb - $XMLWriter->endDocument(); - $path = ($this->buildNZBPath($relGuid, $this->nzbSplitLevel, true) . $relGuid . '.nzb.gz'); - $fp = gzopen($path, 'wb7'); - if (!$fp) { - return false; - } - gzwrite($fp, $XMLWriter->outputMemory()); - gzclose($fp); - unset($XMLWriter); - if (!is_file($path)) { - echo "ERROR: $path does not exist.\n"; + } + } + $XMLWriter->endElement(); //nzb + $XMLWriter->endDocument(); + $path = ($this->buildNZBPath($relGuid, $this->nzbSplitLevel, true).$relGuid.'.nzb.gz'); + $fp = gzopen($path, 'wb7'); + if (! $fp) { + return false; + } + gzwrite($fp, $XMLWriter->outputMemory()); + gzclose($fp); + unset($XMLWriter); + if (! is_file($path)) { + echo "ERROR: $path does not exist.\n"; - return false; - } - // Mark release as having NZB. - $this->pdo->queryExec( + return false; + } + // Mark release as having NZB. + $this->pdo->queryExec( sprintf(' UPDATE releases SET nzbstatus = %d %s WHERE id = %d', - NZB::NZB_ADDED, ($nzb_guid === '' ? '' : ', nzb_guid = UNHEX( ' . $this->pdo->escapeString(md5($nzb_guid)) . ' )'), + self::NZB_ADDED, ($nzb_guid === '' ? '' : ', nzb_guid = UNHEX( '.$this->pdo->escapeString(md5($nzb_guid)).' )'), $relID ) ); - // Delete CBP for release that has its NZB created. - $this->pdo->queryExec( + // Delete CBP for release that has its NZB created. + $this->pdo->queryExec( sprintf(' DELETE c, b, p FROM %s c JOIN %s b ON(c.id=b.collections_id) STRAIGHT_JOIN %s p ON(b.id=p.binaries_id) WHERE c.releases_id = %d', $this->_tableNames['cName'], $this->_tableNames['bName'], $this->_tableNames['pName'], $relID ) ); - // Chmod to fix issues some users have with file permissions. - chmod($path, 0777); + // Chmod to fix issues some users have with file permissions. + chmod($path, 0777); - return true; - } + return true; + } - /** - * Build a folder path on the hard drive where the NZB file will be stored. - * - * @param string $releaseGuid The guid of the release. - * @param int $levelsToSplit How many sub-paths the folder will be in. - * @param bool $createIfNotExist Create the folder if it doesn't exist. - * - * @return string $nzbpath The path to store the NZB file. - * - * @access public - */ - public function buildNZBPath($releaseGuid, $levelsToSplit, $createIfNotExist) - { - $nzbPath = ''; + /** + * Build a folder path on the hard drive where the NZB file will be stored. + * + * @param string $releaseGuid The guid of the release. + * @param int $levelsToSplit How many sub-paths the folder will be in. + * @param bool $createIfNotExist Create the folder if it doesn't exist. + * + * @return string $nzbpath The path to store the NZB file. + */ + public function buildNZBPath($releaseGuid, $levelsToSplit, $createIfNotExist) + { + $nzbPath = ''; - for ($i = 0; $i < $levelsToSplit && $i < 32; $i++) { - $nzbPath .= substr($releaseGuid, $i, 1) . DS; - } + for ($i = 0; $i < $levelsToSplit && $i < 32; $i++) { + $nzbPath .= substr($releaseGuid, $i, 1).DS; + } - $nzbPath = $this->siteNzbPath . $nzbPath; + $nzbPath = $this->siteNzbPath.$nzbPath; - if ($createIfNotExist === true && !is_dir($nzbPath)) { - mkdir($nzbPath, 0777, true); - } + if ($createIfNotExist === true && ! is_dir($nzbPath)) { + mkdir($nzbPath, 0777, true); + } - return $nzbPath; - } + return $nzbPath; + } - /** - * Retrieve path + filename of the NZB to be stored. - * - * @param string $releaseGuid The guid of the release. - * @param int $levelsToSplit How many sub-paths the folder will be in. (optional) - * @param bool $createIfNotExist Create the folder if it doesn't exist. (optional) - * - * @return string Path+filename. - * - * @access public - */ - public function getNZBPath($releaseGuid, $levelsToSplit = 0, $createIfNotExist = false): string - { - if ($levelsToSplit === 0) { - $levelsToSplit = $this->nzbSplitLevel; - } + /** + * Retrieve path + filename of the NZB to be stored. + * + * @param string $releaseGuid The guid of the release. + * @param int $levelsToSplit How many sub-paths the folder will be in. (optional) + * @param bool $createIfNotExist Create the folder if it doesn't exist. (optional) + * + * @return string Path+filename. + */ + public function getNZBPath($releaseGuid, $levelsToSplit = 0, $createIfNotExist = false): string + { + if ($levelsToSplit === 0) { + $levelsToSplit = $this->nzbSplitLevel; + } - return ($this->buildNZBPath($releaseGuid, $levelsToSplit, $createIfNotExist) . $releaseGuid . '.nzb.gz'); - } + return $this->buildNZBPath($releaseGuid, $levelsToSplit, $createIfNotExist).$releaseGuid.'.nzb.gz'; + } - /** - * Determine is an NZB exists, returning the path+filename, if not return false. - * - * @param string $releaseGuid The guid of the release. - * - * @return bool|string On success: (string) Path+file name of the nzb. - * On failure: (bool) False. - * - * @access public - */ - public function NZBPath($releaseGuid) - { - $nzbFile = $this->getNZBPath($releaseGuid); + /** + * Determine is an NZB exists, returning the path+filename, if not return false. + * + * @param string $releaseGuid The guid of the release. + * + * @return bool|string On success: (string) Path+file name of the nzb. + * On failure: (bool) False. + */ + public function NZBPath($releaseGuid) + { + $nzbFile = $this->getNZBPath($releaseGuid); - return (is_file($nzbFile) ? $nzbFile : false); - } + return is_file($nzbFile) ? $nzbFile : false; + } - /** - * Retrieve various information on a NZB file (the subject, # of pars, - * file extensions, file sizes, file completion, group names, # of parts). - * - * @param string $nzb The NZB contents in a string. - * @param array $options - * 'no-file-key' => True - use numeric array key; False - Use filename as array key. - * 'strip-count' => True - Strip file/part count from file name to make the array key; False - Leave file name as is. - * - * @return array $result Empty if not an NZB or the contents of the NZB. - * - * @access public - */ - public function nzbFileList($nzb, array $options = []): array - { - $defaults = [ + /** + * Retrieve various information on a NZB file (the subject, # of pars, + * file extensions, file sizes, file completion, group names, # of parts). + * + * @param string $nzb The NZB contents in a string. + * @param array $options + * 'no-file-key' => True - use numeric array key; False - Use filename as array key. + * 'strip-count' => True - Strip file/part count from file name to make the array key; False - Leave file name as is. + * + * @return array $result Empty if not an NZB or the contents of the NZB. + */ + public function nzbFileList($nzb, array $options = []): array + { + $defaults = [ 'no-file-key' => true, 'strip-count' => false, ]; - $options += $defaults; + $options += $defaults; - $num_pars = $i = 0; - $result = []; + $num_pars = $i = 0; + $result = []; - if (!$nzb) { - return $result; - } + if (! $nzb) { + return $result; + } - $xml = @simplexml_load_string(str_replace("\x0F", '', $nzb)); - if (!$xml || strtolower($xml->getName()) !== 'nzb') { - return $result; - } + $xml = @simplexml_load_string(str_replace("\x0F", '', $nzb)); + if (! $xml || strtolower($xml->getName()) !== 'nzb') { + return $result; + } - foreach ($xml->file as $file) { - // Subject. - $title = (string)$file->attributes()->subject; + foreach ($xml->file as $file) { + // Subject. + $title = (string) $file->attributes()->subject; - // Amount of pars. - if (stripos($title, '.par2')) { - $num_pars++; - } + // Amount of pars. + if (stripos($title, '.par2')) { + $num_pars++; + } - if ($options['no-file-key'] === false) { - $i = $title; - if ($options['strip-count']) { - // Strip file / part count to get proper sorting. - $i = preg_replace('#\d+[- ._]?(/|\||[o0]f)[- ._]?\d+?(?![- ._]\d)#i', '', $i); - // Change .rar and .par2 to be sorted before .part0x.rar and .volxxx+xxx.par2 - if (strpos($i, '.par2') !== false && !preg_match('#\.vol\d+\+\d+\.par2#i', $i)) { - $i = str_replace('.par2', '.vol0.par2', $i); - } else if (preg_match('#\.rar[^a-z0-9]#i', $i) && !preg_match('#\.part\d+\.rar#i', $i)) { - $i = preg_replace('#\.rar(?:[^a-z0-9])#i', '.part0.rar', $i); - } - } - } + if ($options['no-file-key'] === false) { + $i = $title; + if ($options['strip-count']) { + // Strip file / part count to get proper sorting. + $i = preg_replace('#\d+[- ._]?(/|\||[o0]f)[- ._]?\d+?(?![- ._]\d)#i', '', $i); + // Change .rar and .par2 to be sorted before .part0x.rar and .volxxx+xxx.par2 + if (strpos($i, '.par2') !== false && ! preg_match('#\.vol\d+\+\d+\.par2#i', $i)) { + $i = str_replace('.par2', '.vol0.par2', $i); + } elseif (preg_match('#\.rar[^a-z0-9]#i', $i) && ! preg_match('#\.part\d+\.rar#i', $i)) { + $i = preg_replace('#\.rar(?:[^a-z0-9])#i', '.part0.rar', $i); + } + } + } - $result[$i]['title'] = $title; + $result[$i]['title'] = $title; - // Extensions. - if (preg_match( + // Extensions. + if (preg_match( '/\.(\d{2,3}|7z|ace|ai7|srr|srt|sub|aiff|asc|avi|audio|bin|bz2|' - . 'c|cfc|cfm|chm|class|conf|cpp|cs|css|csv|cue|deb|divx|doc|dot|' - . 'eml|enc|exe|file|gif|gz|hlp|htm|html|image|iso|jar|java|jpeg|' - . 'jpg|js|lua|m|m3u|mkv|mm|mov|mp3|mp4|mpg|nfo|nzb|odc|odf|odg|odi|odp|' - . 'ods|odt|ogg|par2|parity|pdf|pgp|php|pl|png|ppt|ps|py|r\d{2,3}|' - . 'ram|rar|rb|rm|rpm|rtf|sfv|sig|sql|srs|swf|sxc|sxd|sxi|sxw|tar|' - . 'tex|tgz|txt|vcf|video|vsd|wav|wma|wmv|xls|xml|xpi|xvid|zip7|zip)' - . '[" ](?!(\)|\-))/i', + .'c|cfc|cfm|chm|class|conf|cpp|cs|css|csv|cue|deb|divx|doc|dot|' + .'eml|enc|exe|file|gif|gz|hlp|htm|html|image|iso|jar|java|jpeg|' + .'jpg|js|lua|m|m3u|mkv|mm|mov|mp3|mp4|mpg|nfo|nzb|odc|odf|odg|odi|odp|' + .'ods|odt|ogg|par2|parity|pdf|pgp|php|pl|png|ppt|ps|py|r\d{2,3}|' + .'ram|rar|rb|rm|rpm|rtf|sfv|sig|sql|srs|swf|sxc|sxd|sxi|sxw|tar|' + .'tex|tgz|txt|vcf|video|vsd|wav|wma|wmv|xls|xml|xpi|xvid|zip7|zip)' + .'[" ](?!(\)|\-))/i', $title, $ext ) ) { + if (preg_match('/\.r\d{2,3}/i', $ext[0])) { + $ext[1] = 'rar'; + } + $result[$i]['ext'] = strtolower($ext[1]); + } else { + $result[$i]['ext'] = ''; + } - if (preg_match('/\.r\d{2,3}/i', $ext[0])) { - $ext[1] = 'rar'; - } - $result[$i]['ext'] = strtolower($ext[1]); - } else { - $result[$i]['ext'] = ''; - } + $fileSize = $numSegments = 0; - $fileSize = $numSegments = 0; + // Parts. + if (! isset($result[$i]['segments'])) { + $result[$i]['segments'] = []; + } - // Parts. - if (!isset($result[$i]['segments'])) { - $result[$i]['segments'] = []; - } + // File size. + foreach ($file->segments->segment as $segment) { + $result[$i]['segments'][] = (string) $segment; + $fileSize += $segment->attributes()->bytes; + $numSegments++; + } + $result[$i]['size'] = $fileSize; - // File size. - foreach ($file->segments->segment as $segment) { - $result[$i]['segments'][] = (string)$segment; - $fileSize += $segment->attributes()->bytes; - $numSegments++; - } - $result[$i]['size'] = $fileSize; + // File completion. + if (preg_match('/(\d+)\)$/', $title, $parts)) { + $result[$i]['partstotal'] = $parts[1]; + } + $result[$i]['partsactual'] = $numSegments; - // File completion. - if (preg_match('/(\d+)\)$/', $title, $parts)) { - $result[$i]['partstotal'] = $parts[1]; - } - $result[$i]['partsactual'] = $numSegments; + // Groups. + if (! isset($result[$i]['groups'])) { + $result[$i]['groups'] = []; + } + foreach ($file->groups->group as $g) { + $result[$i]['groups'][] = (string) $g; + } - // Groups. - if (!isset($result[$i]['groups'])) { - $result[$i]['groups'] = []; - } - foreach ($file->groups->group as $g) { - $result[$i]['groups'][] = (string)$g; - } + unset($result[$i]['segments']['@attributes']); + if ($options['no-file-key']) { + $i++; + } + } - unset($result[$i]['segments']['@attributes']); - if ($options['no-file-key']) { - $i++; - } - } - - return $result; - } + return $result; + } } diff --git a/nntmux/NZBContents.php b/nntmux/NZBContents.php index 9c4d1eafb..c2c735548 100755 --- a/nntmux/NZBContents.php +++ b/nntmux/NZBContents.php @@ -1,86 +1,78 @@ <?php + namespace nntmux; -use App\Models\Settings; use nntmux\db\DB; -use nntmux\processing\PostProcess; +use App\Models\Settings; use nntmux\utility\Utility; +use nntmux\processing\PostProcess; /** * Gets information contained within the NZB. * * Class NZBContents */ -Class NZBContents +class NZBContents { - /** - * @var DB - * @access protected - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var NNTP - * @access protected - */ - protected $nntp; + /** + * @var NNTP + */ + protected $nntp; - /** - * @var Nfo - * @access protected - */ - protected $nfo; + /** + * @var Nfo + */ + protected $nfo; - /** - * @var PostProcess - * @access protected - */ - protected $pp; + /** + * @var PostProcess + */ + protected $pp; - /** - * @var NZB - * @access protected - */ - protected $nzb; + /** + * @var NZB + */ + protected $nzb; - /** - * @var bool stdClass - * @access protected - */ - protected $site; + /** + * @var bool stdClass + */ + protected $site; - /** - * @var bool - * @access protected - */ - protected $lookuppar2; + /** + * @var bool + */ + protected $lookuppar2; - /** - * @var bool - * @access protected - */ - protected $echooutput; - protected $alternateNNTP; + /** + * @var bool + */ + protected $echooutput; + protected $alternateNNTP; - /** - * Construct. - * - * @param array $options - * array( - * 'Echo' => bool ; To echo to CLI or not. - * 'NNTP' => NNTP ; Class NNTP. - * 'Nfo' => Nfo ; Class Nfo. - * 'NZB' => NZB ; Class NZB. - * 'Settings' => DB ; Class nntmux\db\Settings. - * 'PostProcess' => PostProcess ; Class PostProcess. - * ) - * - * @access public - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Construct. + * + * @param array $options + * array( + * 'Echo' => bool ; To echo to CLI or not. + * 'NNTP' => NNTP ; Class NNTP. + * 'Nfo' => Nfo ; Class Nfo. + * 'NZB' => NZB ; Class NZB. + * 'Settings' => DB ; Class nntmux\db\Settings. + * 'PostProcess' => PostProcess ; Class PostProcess. + * ) + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'NNTP' => null, 'Nfo' => null, @@ -88,229 +80,225 @@ Class NZBContents 'Settings' => null, 'PostProcess' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $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 Nfo ? $options['Nfo'] : new Nfo(['Echo' => $this->echooutput, 'Settings' => $this->pdo])); - $this->pp = ( + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + $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 Nfo ? $options['Nfo'] : new Nfo(['Echo' => $this->echooutput, 'Settings' => $this->pdo])); + $this->pp = ( $options['PostProcess'] instanceof PostProcess ? $options['PostProcess'] : new PostProcess(['Echo' => $this->echooutput, 'Nfo' => $this->nfo, 'Settings' => $this->pdo]) ); - $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo)); - $this->lookuppar2 = (int)Settings::value('..lookuppar2') === 1 ? true : false; - $this->alternateNNTP = (int)Settings::value('..alternate_nntp') === 1 ? true : false; - } + $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo)); + $this->lookuppar2 = (int) Settings::value('..lookuppar2') === 1 ? true : false; + $this->alternateNNTP = (int) Settings::value('..alternate_nntp') === 1 ? true : false; + } - /** - * Look for an .nfo file in the NZB, return the NFO message id. - * Gets the NZB completion. - * Looks for PAR2 files in the NZB. - * - * @param string $guid - * @param string $relID - * @param int $groupID - * @param string $groupName - * - * @return bool - * - * @access public - */ - public function getNfoFromNZB($guid, $relID, $groupID, $groupName) - { - $fetchedBinary = false; + /** + * Look for an .nfo file in the NZB, return the NFO message id. + * Gets the NZB completion. + * Looks for PAR2 files in the NZB. + * + * @param string $guid + * @param string $relID + * @param int $groupID + * @param string $groupName + * + * @return bool + */ + public function getNfoFromNZB($guid, $relID, $groupID, $groupName) + { + $fetchedBinary = false; - $messageID = $this->parseNZB($guid, $relID, $groupID, true); - if ($messageID !== false) { - $fetchedBinary = $this->nntp->getMessages($groupName, $messageID['id'], $this->alternateNNTP); - if ($this->nntp->isError($fetchedBinary)) { - // NFO download failed, increment attempts. - $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = nfostatus - 1 WHERE id = %d', $relID)); - if ($this->echooutput) { - echo 'f'; - } - return false; - } - if ($this->nfo->isNFO($fetchedBinary, $guid) === true) { - if ($this->echooutput) { - echo ($messageID['hidden'] === false ? '+' : '*'); - } - } else { - if ($this->echooutput) { - echo '-'; - } - $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', Nfo::NFO_NONFO, $relID)); - $fetchedBinary = false; - } - } else { - if ($this->echooutput) { - echo '-'; - } - $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', Nfo::NFO_NONFO, $relID)); - } + $messageID = $this->parseNZB($guid, $relID, $groupID, true); + if ($messageID !== false) { + $fetchedBinary = $this->nntp->getMessages($groupName, $messageID['id'], $this->alternateNNTP); + if ($this->nntp->isError($fetchedBinary)) { + // NFO download failed, increment attempts. + $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = nfostatus - 1 WHERE id = %d', $relID)); + if ($this->echooutput) { + echo 'f'; + } - return $fetchedBinary; - } + return false; + } + if ($this->nfo->isNFO($fetchedBinary, $guid) === true) { + if ($this->echooutput) { + echo $messageID['hidden'] === false ? '+' : '*'; + } + } else { + if ($this->echooutput) { + echo '-'; + } + $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', Nfo::NFO_NONFO, $relID)); + $fetchedBinary = false; + } + } else { + if ($this->echooutput) { + echo '-'; + } + $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', Nfo::NFO_NONFO, $relID)); + } - /** - * Gets the completion from the NZB, optionally looks if there is an NFO/PAR2 file. - * - * @param string $guid - * @param int $relID - * @param int $groupID - * @param bool $nfoCheck - * - * @return array|bool - * - * @access public - */ - public function parseNZB($guid, $relID, $groupID, $nfoCheck = false) - { - $nzbFile = $this->LoadNZB($guid); - if ($nzbFile !== false) { - $messageID = $hiddenID = ''; - $actualParts = $artificialParts = 0; - $foundPAR2 = $this->lookuppar2 === false ? true : false; - $foundNFO = $hiddenNFO = $nfoCheck === false ? true : false; - $foundSRR = false; + return $fetchedBinary; + } - foreach ($nzbFile->file as $nzbcontents) { - foreach ($nzbcontents->segments->segment as $segment) { - $actualParts++; - } + /** + * Gets the completion from the NZB, optionally looks if there is an NFO/PAR2 file. + * + * @param string $guid + * @param int $relID + * @param int $groupID + * @param bool $nfoCheck + * + * @return array|bool + */ + public function parseNZB($guid, $relID, $groupID, $nfoCheck = false) + { + $nzbFile = $this->LoadNZB($guid); + if ($nzbFile !== false) { + $messageID = $hiddenID = ''; + $actualParts = $artificialParts = 0; + $foundPAR2 = $this->lookuppar2 === false ? true : false; + $foundNFO = $hiddenNFO = $nfoCheck === false ? true : false; + $foundSRR = false; - $subject = (string)$nzbcontents->attributes()->subject; - if (preg_match('/(\d+)\)$/', $subject, $parts)) { - $artificialParts += $parts[1]; - } + foreach ($nzbFile->file as $nzbcontents) { + foreach ($nzbcontents->segments->segment as $segment) { + $actualParts++; + } - if ($foundNFO === false) { - if (preg_match('/\.\b(nfo|inf|ofn)\b(?![ .-])/i', $subject)) { - $messageID = (string)$nzbcontents->segments->segment; - $foundNFO = true; - } - } + $subject = (string) $nzbcontents->attributes()->subject; + if (preg_match('/(\d+)\)$/', $subject, $parts)) { + $artificialParts += $parts[1]; + } - if ($foundNFO === false && $hiddenNFO === false) { - if (preg_match('/\(1\/1\)$/i', $subject) && - !preg_match('/\.(apk|bat|bmp|cbr|cbz|cfg|css|csv|cue|db|dll|doc|epub|exe|gif|htm|ico|idx|ini' . - '|jpg|lit|log|m3u|mid|mobi|mp3|nib|nzb|odt|opf|otf|par|par2|pdf|psd|pps|png|ppt|r\d{2,4}' . + if ($foundNFO === false) { + if (preg_match('/\.\b(nfo|inf|ofn)\b(?![ .-])/i', $subject)) { + $messageID = (string) $nzbcontents->segments->segment; + $foundNFO = true; + } + } + + if ($foundNFO === false && $hiddenNFO === false) { + if (preg_match('/\(1\/1\)$/i', $subject) && + ! preg_match('/\.(apk|bat|bmp|cbr|cbz|cfg|css|csv|cue|db|dll|doc|epub|exe|gif|htm|ico|idx|ini'. + '|jpg|lit|log|m3u|mid|mobi|mp3|nib|nzb|odt|opf|otf|par|par2|pdf|psd|pps|png|ppt|r\d{2,4}'. '|rar|sfv|srr|sub|srt|sql|rom|rtf|tif|torrent|ttf|txt|vb|vol\d+\+\d+|wps|xml|zip)/i', - $subject)) - { - $hiddenID = (string)$nzbcontents->segments->segment; - $hiddenNFO = true; - } - } + $subject)) { + $hiddenID = (string) $nzbcontents->segments->segment; + $hiddenNFO = true; + } + } - if ($foundPAR2 === false) { - if (preg_match('/\.(par[&2" ]|\d{2,3}").+\(1\/1\)$/i', $subject)) { - if ($this->pp->parsePAR2((string)$nzbcontents->segments->segment, $relID, $groupID, $this->nntp, 1) === true) { - $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID)); - $foundPAR2 = true; - } - } - } - } + if ($foundPAR2 === false) { + if (preg_match('/\.(par[&2" ]|\d{2,3}").+\(1\/1\)$/i', $subject)) { + if ($this->pp->parsePAR2((string) $nzbcontents->segments->segment, $relID, $groupID, $this->nntp, 1) === true) { + $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID)); + $foundPAR2 = true; + } + } + } + } - if ($artificialParts <= 0 || $actualParts <= 0) { - $completion = 0; - } else { - $completion = ($actualParts / $artificialParts) * 100; - } - if ($completion > 100) { - $completion = 100; - } + if ($artificialParts <= 0 || $actualParts <= 0) { + $completion = 0; + } else { + $completion = ($actualParts / $artificialParts) * 100; + } + if ($completion > 100) { + $completion = 100; + } - $this->pdo->queryExec(sprintf('UPDATE releases SET completion = %d WHERE id = %d', $completion, $relID)); + $this->pdo->queryExec(sprintf('UPDATE releases SET completion = %d WHERE id = %d', $completion, $relID)); - if ($foundNFO === true && strlen($messageID) > 1) { - return array('hidden' => false, 'id' => $messageID); - } + if ($foundNFO === true && strlen($messageID) > 1) { + return ['hidden' => false, 'id' => $messageID]; + } - if ($hiddenNFO === true && strlen($hiddenID) > 1) { - return array('hidden' => true, 'id' => $hiddenID); - } - } - return false; - } + if ($hiddenNFO === true && strlen($hiddenID) > 1) { + return ['hidden' => true, 'id' => $hiddenID]; + } + } - /** - * Decompress a NZB, load it into simplexml and return. - * - * @param string $guid Release guid. - * - * @return bool SimpleXMLElement - * - * @access public - */ - public function LoadNZB($guid) - { - // Fetch the NZB location using the GUID. - $nzbPath = $this->nzb->NZBPath($guid); - if ($nzbPath === false) { - if ($this->echooutput) { - echo PHP_EOL . $guid . ' appears to be missing the nzb file, skipping.' . PHP_EOL; - } - return false; - } - $nzbContents = Utility::unzipGzipFile($nzbPath); - if (!$nzbContents) { - if ($this->echooutput) { - echo - PHP_EOL . - 'Unable to decompress: ' . - $nzbPath . - ' - ' . - fileperms($nzbPath) . - ' - may have bad file permissions, skipping.' . + return false; + } + + /** + * Decompress a NZB, load it into simplexml and return. + * + * @param string $guid Release guid. + * + * @return bool SimpleXMLElement + */ + public function LoadNZB($guid) + { + // Fetch the NZB location using the GUID. + $nzbPath = $this->nzb->NZBPath($guid); + if ($nzbPath === false) { + if ($this->echooutput) { + echo PHP_EOL.$guid.' appears to be missing the nzb file, skipping.'.PHP_EOL; + } + + return false; + } + $nzbContents = Utility::unzipGzipFile($nzbPath); + if (! $nzbContents) { + if ($this->echooutput) { + echo + PHP_EOL. + 'Unable to decompress: '. + $nzbPath. + ' - '. + fileperms($nzbPath). + ' - may have bad file permissions, skipping.'. PHP_EOL; - } - return false; - } + } - $nzbFile = @simplexml_load_string($nzbContents); - if (!$nzbFile) { - if ($this->echooutput) { - echo PHP_EOL . "Unable to load NZB: $guid appears to be an invalid NZB, skipping." . PHP_EOL; - } - return false; - } + return false; + } - return $nzbFile; - } + $nzbFile = @simplexml_load_string($nzbContents); + if (! $nzbFile) { + if ($this->echooutput) { + echo PHP_EOL."Unable to load NZB: $guid appears to be an invalid NZB, skipping.".PHP_EOL; + } - /** - * Attempts to get the releasename from a par2 file - * - * @param string $guid - * @param int $relID - * @param int $groupID - * @param int $nameStatus - * @param int $show - * - * @return bool - * - * @access public - */ - public function checkPAR2($guid, $relID, $groupID, $nameStatus, $show) - { - $nzbFile = $this->LoadNZB($guid); - if ($nzbFile !== false) { - foreach ($nzbFile->file as $nzbContents) { - if ($nameStatus === 1 && $this->pp->parsePAR2((string)$nzbContents->segments->segment, $relID, $groupID, $this->nntp, $show) === true && preg_match('/\.(par[2" ]|\d{2,3}").+\(1\/1\)/i', (string)$nzbContents->attributes()->subject)) { - $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID)); + return false; + } - return true; - } - } - } - if ($nameStatus === 1) { - $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID)); - } + return $nzbFile; + } - return false; - } + /** + * Attempts to get the releasename from a par2 file. + * + * @param string $guid + * @param int $relID + * @param int $groupID + * @param int $nameStatus + * @param int $show + * + * @return bool + */ + public function checkPAR2($guid, $relID, $groupID, $nameStatus, $show) + { + $nzbFile = $this->LoadNZB($guid); + if ($nzbFile !== false) { + foreach ($nzbFile->file as $nzbContents) { + if ($nameStatus === 1 && $this->pp->parsePAR2((string) $nzbContents->segments->segment, $relID, $groupID, $this->nntp, $show) === true && preg_match('/\.(par[2" ]|\d{2,3}").+\(1\/1\)/i', (string) $nzbContents->attributes()->subject)) { + $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID)); + + return true; + } + } + } + if ($nameStatus === 1) { + $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID)); + } + + return false; + } } diff --git a/nntmux/NZBExport.php b/nntmux/NZBExport.php index 6ec89a48c..4b0827c28 100755 --- a/nntmux/NZBExport.php +++ b/nntmux/NZBExport.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; use nntmux\db\DB; @@ -6,270 +7,258 @@ use nntmux\utility\Utility; /** * Export NZB's to a folder. - * Class NZBExport + * Class NZBExport. */ class NZBExport { - /** - * Started from browser? - * @var bool - * @access protected - */ - protected $browser; + /** + * Started from browser? + * @var bool + */ + protected $browser; - /** - * @var string Return value on browser. - * @access protected - */ - protected $retVal; + /** + * @var string Return value on browser. + */ + protected $retVal; - /** - * @var \nntmux\db\Settings - * @access protected - */ - protected $pdo; + /** + * @var \nntmux\db\Settings + */ + protected $pdo; - /** - * @var NZB - * @access protected - */ - protected $nzb; + /** + * @var NZB + */ + protected $nzb; - /** - * @var Releases - * @access protected - */ - protected $releases; + /** + * @var Releases + */ + protected $releases; - /** - * @var bool - * @access protected - */ - protected $echoCLI; + /** + * @var bool + */ + protected $echoCLI; - /** - * @param array $options Class instances / various options. - * - * @access public - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances / various options. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Browser' => false, // Started from browser? 'Echo' => true, // Echo to CLI? 'NZB' => null, 'Releases' => null, 'Settings' => null, ]; - $options += $defaults; + $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)); - } + $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; - } + /** + * Export to user specified folder. + * + * @param array $params + * + * @return bool + */ + public function beginExport($params) + { + $gzip = false; + if ($params[4] === true) { + $gzip = true; + } - $fromDate = $toDate = ''; - $path = $params[0]; + $fromDate = $toDate = ''; + $path = $params[0]; - // Check if the path ends with dir separator. - if (substr($path, -1) !== DS) { - $path .= DS; - } + // 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 it's a directory. + if (! is_dir($path)) { + $this->echoOut('Folder does not exist: '.$path); - // Check if we can write to it. - if (!is_writable($path)) { - $this->echoOut('Folder is not writable: ' . $path); - return $this->returnValue(); - } + 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 we can write to it. + if (! is_writable($path)) { + $this->echoOut('Folder is not writable: '.$path); - // 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]; - } + return $this->returnValue(); + } - // 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'); - } + // 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]; + } - $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; - } + // 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]; + } - // 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) { + // 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; - } + $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']); + // 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); - } + // 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++; + $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); - } + 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 $this->returnValue(); + } - /** - * Return bool on CLI, string on browser. - * @return bool|string - * - * @access protected - */ - protected function returnValue() - { - return ($this->browser ? $this->retVal : true); - } + /** + * Return bool on CLI, string on browser. + * @return bool|string + */ + 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; - } + /** + * Check if date is in good format. + * + * @param string $date + * + * @return bool + */ + protected function checkDate($date) + { + if (! preg_match('/^(\d{2}\/){2}\d{4}$/', $date)) { + $this->echoOut('Wrong date format: '.$date); - /** - * 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; - } - } + return false; + } - /** - * 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)); - } + return true; + } + + /** + * Echo message to browser or CLI. + * + * @param string $message + */ + 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 + */ + protected function safeFilename($filename) + { + return trim(preg_replace('/[^\w\s.-]*/i', '', $filename)); + } } diff --git a/nntmux/NZBGet.php b/nntmux/NZBGet.php index 917a78013..e154eec8d 100755 --- a/nntmux/NZBGet.php +++ b/nntmux/NZBGet.php @@ -1,139 +1,125 @@ <?php + namespace nntmux; -use GuzzleHttp\Client; -use GuzzleHttp\Psr7\Request; -use nntmux\utility\Utility; use nntmux\db\DB; +use GuzzleHttp\Client; +use nntmux\utility\Utility; +use GuzzleHttp\Psr7\Request; /** - * Class NZBGet + * Class NZBGet. * * Transfers data between an NZBGet server and a nntmux website. - * - * @package nntmux */ class NZBGet { - /** - * NZBGet username. - * @var string - * @access public - */ - public $userName = ''; + /** + * NZBGet username. + * @var string + */ + public $userName = ''; - /** - * NZBGet password. - * @var string - * @access public - */ - public $password = ''; + /** + * NZBGet password. + * @var string + */ + public $password = ''; - /** - * NZBGet URL. - * @var string - * @access public - */ - public $url = ''; + /** + * NZBGet URL. + * @var string + */ + public $url = ''; - /** - * Full URL (containing password/username/etc). - * @var string|bool - * @access protected - */ - protected $fullURL = ''; + /** + * Full URL (containing password/username/etc). + * @var string|bool + */ + protected $fullURL = ''; - /** - * User id. - * @var int - * @access protected - */ - protected $uid = 0; + /** + * User id. + * @var int + */ + protected $uid = 0; - /** - * The users RSS token. - * @var string - * @access protected - */ - protected $rsstoken = ''; + /** + * The users RSS token. + * @var string + */ + protected $rsstoken = ''; - /** - * URL to your NNTmux site. - * @var string - * @access protected - */ - protected $serverurl = ''; + /** + * URL to your NNTmux site. + * @var string + */ + protected $serverurl = ''; - /** - * @var Releases - * @access protected - */ - protected $Releases; + /** + * @var Releases + */ + protected $Releases; - /** - * @var NZB - * @access protected - */ - protected $NZB; + /** + * @var NZB + */ + protected $NZB; - /** - * @var Client - */ - protected $client; + /** + * @var Client + */ + protected $client; - /** - * Construct. - * Set up full URL. - * - * @var \BasePage $page - * - * @access public - */ - public function __construct(&$page) - { - $this->serverurl = $page->serverurl; - $this->uid = $page->userdata['id']; - $this->rsstoken = $page->userdata['rsstoken']; + /** + * Construct. + * Set up full URL. + * + * @var \BasePage + */ + public function __construct(&$page) + { + $this->serverurl = $page->serverurl; + $this->uid = $page->userdata['id']; + $this->rsstoken = $page->userdata['rsstoken']; - if (!empty($page->userdata['nzbgeturl'])) { - $this->url = $page->userdata['nzbgeturl']; - $this->userName = (empty($page->userdata['nzbgetusername']) ? '' : $page->userdata['nzbgetusername']); - $this->password = (empty($page->userdata['nzbgetpassword']) ? '' : $page->userdata['nzbgetpassword']); - } + if (! empty($page->userdata['nzbgeturl'])) { + $this->url = $page->userdata['nzbgeturl']; + $this->userName = (empty($page->userdata['nzbgetusername']) ? '' : $page->userdata['nzbgetusername']); + $this->password = (empty($page->userdata['nzbgetpassword']) ? '' : $page->userdata['nzbgetpassword']); + } - $this->fullURL = $this->verifyURL($this->url); - $this->Releases = new Releases(); - $this->pdo = new DB(); - $this->NZB = new NZB($this->pdo); - $this->client = new Client(); - } + $this->fullURL = $this->verifyURL($this->url); + $this->Releases = new Releases(); + $this->pdo = new DB(); + $this->NZB = new NZB($this->pdo); + $this->client = new Client(); + } - /** - * Send a NZB to NZBGet. - * - * @param string $guid Release identifier. - * - * @return bool|mixed - * - * @access public - */ - public function sendNZBToNZBGet($guid) - { - $relData = $this->Releases->getByGuid($guid); + /** + * Send a NZB to NZBGet. + * + * @param string $guid Release identifier. + * + * @return bool|mixed + */ + public function sendNZBToNZBGet($guid) + { + $relData = $this->Releases->getByGuid($guid); - $string = Utility::unzipGzipFile($this->NZB->NZBPath($guid)); - $string = ($string === false ? '' : $string); + $string = Utility::unzipGzipFile($this->NZB->NZBPath($guid)); + $string = ($string === false ? '' : $string); - $header = + $header = '<?xml version="1.0"?> <methodCall> <methodName>append</methodName> <params> <param> - <value><string>' . $relData['searchname'] . '</string></value> + <value><string>'.$relData['searchname'].'</string></value> </param> <param> - <value><string>' . $relData['category_name'] . '</string></value> + <value><string>'.$relData['category_name'].'</string></value> </param> <param> <value><i4>0</i4></value> @@ -143,39 +129,37 @@ class NZBGet </param> <param> <value> - <string>' . - base64_encode($string) . + <string>'. + base64_encode($string). '</string> </value> </param> </params> </methodCall>'; - new Request('POST', $this->fullURL . 'append', ['Content-Type' => 'text/xml; charset=UTF8'], $header); - } + new Request('POST', $this->fullURL.'append', ['Content-Type' => 'text/xml; charset=UTF8'], $header); + } - /** - * Send a NZB URL to NZBGet. - * - * @param string $guid Release identifier. - * - * @return bool|mixed - * - * @access public - */ - public function sendURLToNZBGet($guid) - { - $reldata = $this->Releases->getByGuid($guid); + /** + * Send a NZB URL to NZBGet. + * + * @param string $guid Release identifier. + * + * @return bool|mixed + */ + public function sendURLToNZBGet($guid) + { + $reldata = $this->Releases->getByGuid($guid); - $header = + $header = '<?xml version="1.0"?> <methodCall> <methodName>appendurl</methodName> <params> <param> - <value><string>' . $reldata['searchname'] . '.nzb' . '</string></value> + <value><string>'.$reldata['searchname'].'.nzb'.'</string></value> </param> <param> - <value><string>' . $reldata['category_name'] . '</string></value> + <value><string>'.$reldata['category_name'].'</string></value> </param> <param> <value><i4>0</i4></value> @@ -185,13 +169,13 @@ class NZBGet </param> <param> <value> - <string>' . - $this->serverurl . - 'getnzb/' . - $guid . - '%26i%3D' . - $this->uid . - '%26r%3D' . + <string>'. + $this->serverurl. + 'getnzb/'. + $guid. + '%26i%3D'. + $this->uid. + '%26r%3D'. $this->rsstoken . '</string> @@ -199,19 +183,17 @@ class NZBGet </param> </params> </methodCall>'; - new Request('POST', $this->fullURL . 'append', ['Content-Type' => 'text/xml; charset=UTF8'], $header); - } + new Request('POST', $this->fullURL.'append', ['Content-Type' => 'text/xml; charset=UTF8'], $header); + } - /** - * Pause download queue on server. This method is equivalent for command "nzbget -P". - * - * @return void - * - * @access public - */ - public function pauseAll() - { - $header = + /** + * Pause download queue on server. This method is equivalent for command "nzbget -P". + * + * @return void + */ + public function pauseAll() + { + $header = '<?xml version="1.0"?> <methodCall> <methodName>pausedownload2</methodName> @@ -221,19 +203,17 @@ class NZBGet </param> </params> </methodCall>'; - new Request('POST', $this->fullURL . 'pausedownload2', ['Content-Type' => 'text/xml; charset=UTF8'], $header); - } + new Request('POST', $this->fullURL.'pausedownload2', ['Content-Type' => 'text/xml; charset=UTF8'], $header); + } - /** - * Resume (previously paused) download queue on server. This method is equivalent for command "nzbget -U". - * - * @return void - * - * @access public - */ - public function resumeAll() - { - $header = + /** + * Resume (previously paused) download queue on server. This method is equivalent for command "nzbget -U". + * + * @return void + */ + public function resumeAll() + { + $header = '<?xml version="1.0"?> <methodCall> <methodName>resumedownload2</methodName> @@ -243,19 +223,17 @@ class NZBGet </param> </params> </methodCall>'; - new Request('POST', $this->fullURL . 'resumedownload2', ['Content-Type' => 'text/xml; charset=UTF8'], $header); - } + new Request('POST', $this->fullURL.'resumedownload2', ['Content-Type' => 'text/xml; charset=UTF8'], $header); + } - /** - * Pause a single NZB from the queue. - * - * @param string $id - * - * @access public - */ - public function pauseFromQueue($id) - { - $header = + /** + * Pause a single NZB from the queue. + * + * @param string $id + */ + public function pauseFromQueue($id) + { + $header = '<?xml version="1.0"?> <methodCall> <methodName>editqueue</methodName> @@ -272,25 +250,23 @@ class NZBGet <param> <value> <array> - <value><i4>' . $id . '</i4></value> + <value><i4>'.$id.'</i4></value> </array> </value> </param> </params> </methodCall>'; - new Request('POST', $this->fullURL . 'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header); - } + new Request('POST', $this->fullURL.'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header); + } - /** - * Resume a single NZB from the queue. - * - * @param string $id - * - * @access public - */ - public function resumeFromQueue($id) - { - $header = + /** + * Resume a single NZB from the queue. + * + * @param string $id + */ + public function resumeFromQueue($id) + { + $header = '<?xml version="1.0"?> <methodCall> <methodName>editqueue</methodName> @@ -307,25 +283,23 @@ class NZBGet <param> <value> <array> - <value><i4>' . $id . '</i4></value> + <value><i4>'.$id.'</i4></value> </array> </value> </param> </params> </methodCall>'; - new Request('POST', $this->fullURL . 'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header); - } + new Request('POST', $this->fullURL.'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header); + } - /** - * Delete a single NZB from the queue. - * - * @param string $id - * - * @access public - */ - public function delFromQueue($id) - { - $header = + /** + * Delete a single NZB from the queue. + * + * @param string $id + */ + public function delFromQueue($id) + { + $header = '<?xml version="1.0"?> <methodCall> <methodName>editqueue</methodName> @@ -342,121 +316,114 @@ class NZBGet <param> <value> <array> - <value><i4>' . $id . '</i4></value> + <value><i4>'.$id.'</i4></value> </array> </value> </param> </params> </methodCall>'; - new Request('POST', $this->fullURL . 'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header); - } + new Request('POST', $this->fullURL.'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header); + } - /** - * Set download speed limit. This method is equivalent for command "nzbget -R <Limit>". - * - * @param int $limit The speed to limit it to. - * - * @return bool - * - * @access public - */ - public function rate($limit) - { - $header = + /** + * Set download speed limit. This method is equivalent for command "nzbget -R <Limit>". + * + * @param int $limit The speed to limit it to. + * + * @return bool + */ + public function rate($limit) + { + $header = '<?xml version="1.0"?> <methodCall> <methodName>rate</methodName> <params> <param> - <value><i4>' . $limit . '</i4></value> + <value><i4>'.$limit.'</i4></value> </param> </params> </methodCall>'; - new Request('POST', $this->fullURL . 'rate', ['Content-Type' => 'text/xml; charset=UTF8'], $header); - } + new Request('POST', $this->fullURL.'rate', ['Content-Type' => 'text/xml; charset=UTF8'], $header); + } - /** - * Get all items in download queue. - * - * @return array|bool - * - * @access public - */ - public function getQueue() - { - $data = $this->client->get($this->fullURL . 'listgroups')->getBody()->getContents(); - $retVal = false; - if ($data) { - $xml = simplexml_load_string($data); - if ($xml) { - $retVal = []; - $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; - } + /** + * Get all items in download queue. + * + * @return array|bool + */ + public function getQueue() + { + $data = $this->client->get($this->fullURL.'listgroups')->getBody()->getContents(); + $retVal = false; + if ($data) { + $xml = simplexml_load_string($data); + if ($xml) { + $retVal = []; + $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++; + } + } + } - /** - * Request for current status (summary) information. Parts of informations returned by this method can be printed by command "nzbget -L". - * - * @return array|bool The status. - * - * @access public - */ - public function status() - { - $data = $this->client->get($this->fullURL . 'status')->getBody()->getContents(); - $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; + } - } - } - } - return $retVal; - } + /** + * Request for current status (summary) information. Parts of informations returned by this method can be printed by command "nzbget -L". + * + * @return array|bool The status. + */ + public function status() + { + $data = $this->client->get($this->fullURL.'status')->getBody()->getContents(); + $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; + } + } + } + } - /** - * Verify if the NZBGet URL is correct. - * - * @param string $url NZBGet URL to verify. - * - * @return bool|string - * - * @access public - */ - public function verifyURL ($url) - { - if (preg_match('/(?P<protocol>https?):\/\/(?P<url>.+?)(:(?P<port>\d+\/)|\/)$/i', $url, $matches)) { - return - $matches['protocol'] . - '://' . - $this->userName . - ':' . - $this->password . - '@' . - $matches['url'] . - (isset($matches['port']) ? ':' . $matches['port'] : (substr($matches['url'], -1) === '/' ? '' : '/')) . + return $retVal; + } + + /** + * Verify if the NZBGet URL is correct. + * + * @param string $url NZBGet URL to verify. + * + * @return bool|string + */ + public function verifyURL($url) + { + if (preg_match('/(?P<protocol>https?):\/\/(?P<url>.+?)(:(?P<port>\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; - } - } + } else { + return false; + } + } } diff --git a/nntmux/NZBImport.php b/nntmux/NZBImport.php index 6c3d00c2e..aafd451c0 100755 --- a/nntmux/NZBImport.php +++ b/nntmux/NZBImport.php @@ -1,112 +1,101 @@ <?php + namespace nntmux; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; use nntmux\utility\Utility; /** * Import NZB files into the database. - * Class NZBImport + * Class NZBImport. */ class NZBImport { - /** - * @var \nntmux\db\Settings - * @access protected - */ - protected $pdo; + /** + * @var \nntmux\db\Settings + */ + protected $pdo; - /** - * @var Binaries - * @access protected - */ - protected $binaries; + /** + * @var Binaries + */ + protected $binaries; - /** - * @var ReleaseCleaning - * @access protected - */ - protected $releaseCleaner; + /** + * @var ReleaseCleaning + */ + protected $releaseCleaner; - /** - * @var bool|\stdClass - * @access protected - */ - protected $site; + /** + * @var bool|\stdClass + */ + protected $site; - /** - * @var int - * @access protected - */ - protected $crossPostt; + /** + * @var int + */ + protected $crossPostt; - /** - * @var Categorize - * @access protected - */ - protected $category; + /** + * @var Categorize + */ + protected $category; - /** - * List of all the group names/ids in the DB. - * @var array - * @access protected - */ - protected $allGroups; + /** + * List of all the group names/ids in the DB. + * @var array + */ + protected $allGroups; - /** - * Was this run from the browser? - * @var bool - * @access protected - */ - protected $browser; + /** + * Was this run from the browser? + * @var bool + */ + protected $browser; - /** - * Return value for browser. - * @var string - * @access protected - */ - protected $retVal; + /** + * Return value for browser. + * @var string + */ + protected $retVal; - /** - * Guid of the current releases. - * @var string - * @access protected - */ - protected $relGuid; + /** + * Guid of the current releases. + * @var string + */ + protected $relGuid; - /** - * @var bool - */ - public $echoCLI; + /** + * @var bool + */ + public $echoCLI; - /** - * @var NZB - */ - public $nzb; + /** + * @var NZB + */ + public $nzb; - /** - * @var string the MD5 hash of the first segment Message-ID of the NZB - */ - protected $nzbGuid; + /** + * @var string the MD5 hash of the first segment Message-ID of the NZB + */ + protected $nzbGuid; - /** - * Access point to add new groups. - * - * @var Groups $groups - */ - private $groups; + /** + * Access point to add new groups. + * + * @var Groups + */ + private $groups; - /** - * Construct. - * - * @param array $options Class instances / various options. - * - * @access public - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Construct. + * + * @param array $options Class instances / various options. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Browser' => false, // Was this started from the browser? 'Echo' => true, // Echo to CLI? 'Binaries' => null, @@ -116,271 +105,259 @@ class NZBImport 'Releases' => null, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echoCLI = (!$this->browser && NN_ECHOCLI && $options['Echo']); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->binaries = ($options['Binaries'] instanceof Binaries ? $options['Binaries'] : new Binaries(['Settings' => $this->pdo, 'Echo' => $this->echoCLI])); - $this->category = ($options['Categorize'] instanceof Categorize ? $options['Categorize'] : new Categorize(['Settings' => $this->pdo])); - $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo)); - $this->releaseCleaner = ($options['ReleaseCleaning'] instanceof ReleaseCleaning ? $options['ReleaseCleaning'] : new ReleaseCleaning($this->pdo)); - $this->releases = ($options['Releases'] instanceof Releases ? $options['Releases'] : new Releases(['settings' => $this->pdo])); - $this->groups = new Groups(['Settings' => $this->pdo]); + $this->echoCLI = (! $this->browser && NN_ECHOCLI && $options['Echo']); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->binaries = ($options['Binaries'] instanceof Binaries ? $options['Binaries'] : new Binaries(['Settings' => $this->pdo, 'Echo' => $this->echoCLI])); + $this->category = ($options['Categorize'] instanceof Categorize ? $options['Categorize'] : new Categorize(['Settings' => $this->pdo])); + $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo)); + $this->releaseCleaner = ($options['ReleaseCleaning'] instanceof ReleaseCleaning ? $options['ReleaseCleaning'] : new ReleaseCleaning($this->pdo)); + $this->releases = ($options['Releases'] instanceof Releases ? $options['Releases'] : new Releases(['settings' => $this->pdo])); + $this->groups = new Groups(['Settings' => $this->pdo]); - $this->crossPostt = Settings::value('..crossposttime') !== '' ? Settings::value('..crossposttime') : 2; - $this->browser = $options['Browser']; - $this->retVal = ''; - } + $this->crossPostt = Settings::value('..crossposttime') !== '' ? Settings::value('..crossposttime') : 2; + $this->browser = $options['Browser']; + $this->retVal = ''; + } - /** - * @param array $filesToProcess List of NZB files to import. - * @param bool|string $useNzbName Use the NZB file name as release name? - * @param bool $delete Delete the NZB when done? - * @param bool $deleteFailed Delete the NZB if failed importing? - * - * @return string|bool - * - * @access public - */ - public function beginImport($filesToProcess, $useNzbName = false, $delete = true, $deleteFailed = true) - { - // Get all the groups in the DB. - if (!$this->getAllGroups()) { - if ($this->browser) { - return $this->retVal; - } else { - return false; - } - } + /** + * @param array $filesToProcess List of NZB files to import. + * @param bool|string $useNzbName Use the NZB file name as release name? + * @param bool $delete Delete the NZB when done? + * @param bool $deleteFailed Delete the NZB if failed importing? + * + * @return string|bool + */ + public function beginImport($filesToProcess, $useNzbName = false, $delete = true, $deleteFailed = true) + { + // Get all the groups in the DB. + if (! $this->getAllGroups()) { + if ($this->browser) { + return $this->retVal; + } else { + return false; + } + } - $start = date('Y-m-d H:i:s'); - $nzbsImported = $nzbsSkipped = 0; + $start = date('Y-m-d H:i:s'); + $nzbsImported = $nzbsSkipped = 0; - // Loop over the file names. - foreach ($filesToProcess as $nzbFile) { + // Loop over the file names. + foreach ($filesToProcess as $nzbFile) { + $this->nzbGuid = ''; - $this->nzbGuid = ''; - - // Check if the file is really there. - if (is_file($nzbFile)) { + // Check if the file is really there. + if (is_file($nzbFile)) { // Get the contents of the NZB file as a string. - if (strtolower(substr($nzbFile, -7)) === '.nzb.gz') { - $nzbString = Utility::unzipGzipFile($nzbFile); - } else { - $nzbString = file_get_contents($nzbFile); - } + if (strtolower(substr($nzbFile, -7)) === '.nzb.gz') { + $nzbString = Utility::unzipGzipFile($nzbFile); + } else { + $nzbString = file_get_contents($nzbFile); + } - if ($nzbString === false) { - $this->echoOut('ERROR: Unable to read: ' . $nzbFile); + if ($nzbString === false) { + $this->echoOut('ERROR: Unable to read: '.$nzbFile); - if ($deleteFailed) { - @unlink($nzbFile); - } - $nzbsSkipped++; - continue; - } + if ($deleteFailed) { + @unlink($nzbFile); + } + $nzbsSkipped++; + continue; + } - // Load it as a XML object. - $nzbXML = @simplexml_load_string($nzbString); - if ($nzbXML === false || strtolower($nzbXML->getName()) != 'nzb') { - $this->echoOut('ERROR: Unable to load NZB XML data: ' . $nzbFile); + // Load it as a XML object. + $nzbXML = @simplexml_load_string($nzbString); + if ($nzbXML === false || strtolower($nzbXML->getName()) != 'nzb') { + $this->echoOut('ERROR: Unable to load NZB XML data: '.$nzbFile); - if ($deleteFailed) { - @unlink($nzbFile); - } - $nzbsSkipped++; - continue; - } + if ($deleteFailed) { + @unlink($nzbFile); + } + $nzbsSkipped++; + continue; + } - // Try to insert the NZB details into the DB. - $inserted = $this->scanNZBFile($nzbXML, ($useNzbName ? str_ireplace('.nzb', '', basename($nzbFile)) : false)); + // Try to insert the NZB details into the DB. + $inserted = $this->scanNZBFile($nzbXML, ($useNzbName ? str_ireplace('.nzb', '', basename($nzbFile)) : false)); - if ($inserted) { + if ($inserted) { // Try to copy the NZB to the NZB folder. - $path = $this->nzb->getNZBPath($this->relGuid, 0, true); + $path = $this->nzb->getNZBPath($this->relGuid, 0, true); - // Try to compress the NZB file in the NZB folder. - $fp = gzopen($path, 'w5'); - gzwrite($fp, $nzbString); - gzclose($fp); + // Try to compress the NZB file in the NZB folder. + $fp = gzopen($path, 'w5'); + gzwrite($fp, $nzbString); + gzclose($fp); - if (!is_file($path)) { - $this->echoOut('ERROR: Problem compressing NZB file to: ' . $path); + if (! is_file($path)) { + $this->echoOut('ERROR: Problem compressing NZB file to: '.$path); - // Remove the release. - $this->pdo->queryExec(" + // Remove the release. + $this->pdo->queryExec(" DELETE FROM releases WHERE guid = {$this->pdo->escapeString($this->relGuid)}" ); - if ($deleteFailed) { - @unlink($nzbFile); - } - $nzbsSkipped++; - continue; + if ($deleteFailed) { + @unlink($nzbFile); + } + $nzbsSkipped++; + continue; + } else { + $this->updateNzbGuid(); - } else { + if ($delete) { + // Remove the nzb file. + @unlink($nzbFile); + } - $this->updateNzbGuid(); - - if ($delete) { - // Remove the nzb file. - @unlink($nzbFile); - } - - $nzbsImported++; - continue; - } - - } else { - - $this->echoOut('ERROR: Failed to insert NZB!'); - if ($deleteFailed) { - @unlink($nzbFile); - } - $nzbsSkipped++; - continue; - } - - } else { - $this->echoOut('ERROR: Unable to fetch: ' . $nzbFile); - $nzbsSkipped++; - continue; - } - } - $this->echoOut( - 'Proccessed ' . - $nzbsImported . - ' NZBs in ' . - (strtotime(date('Y-m-d H:i:s')) - strtotime($start)) . - ' seconds, ' . - $nzbsSkipped . + $nzbsImported++; + continue; + } + } else { + $this->echoOut('ERROR: Failed to insert NZB!'); + if ($deleteFailed) { + @unlink($nzbFile); + } + $nzbsSkipped++; + continue; + } + } else { + $this->echoOut('ERROR: Unable to fetch: '.$nzbFile); + $nzbsSkipped++; + continue; + } + } + $this->echoOut( + 'Proccessed '. + $nzbsImported. + ' NZBs in '. + (strtotime(date('Y-m-d H:i:s')) - strtotime($start)). + ' seconds, '. + $nzbsSkipped. ' NZBs were skipped.' ); - if ($this->browser) { - return $this->retVal; - } else { - return true; - } - } + if ($this->browser) { + return $this->retVal; + } else { + return true; + } + } - /** - * @param object $nzbXML Reference of simpleXmlObject with NZB contents. - * @param bool|string $useNzbName Use the NZB file name as release name? - * @return bool - * - * @access protected - */ - protected function scanNZBFile(&$nzbXML, $useNzbName = false) - { - $binary_names = []; - $totalFiles = $totalSize = $groupID = 0; - $isBlackListed = $groupName = $firstName = $posterName = $postDate = false; + /** + * @param object $nzbXML Reference of simpleXmlObject with NZB contents. + * @param bool|string $useNzbName Use the NZB file name as release name? + * @return bool + */ + protected function scanNZBFile(&$nzbXML, $useNzbName = false) + { + $binary_names = []; + $totalFiles = $totalSize = $groupID = 0; + $isBlackListed = $groupName = $firstName = $posterName = $postDate = false; - // Go through the NZB, get the details, look if it's blacklisted, look if we have the groups. - foreach ($nzbXML->file as $file) { + // Go through the NZB, get the details, look if it's blacklisted, look if we have the groups. + foreach ($nzbXML->file as $file) { + $binary_names[] = $file['subject']; + $totalFiles++; + $groupID = -1; - $binary_names[] = $file['subject']; - $totalFiles++; - $groupID = -1; + // Get the nzb info. + if ($firstName === false) { + $firstName = (string) $file->attributes()->subject; + } + if ($posterName === false) { + $posterName = (string) $file->attributes()->poster; + } + if ($postDate === false) { + $postDate = date('Y-m-d H:i:s', (string) $file->attributes()->date); + } - // Get the nzb info. - if ($firstName === false) { - $firstName = (string)$file->attributes()->subject; - } - if ($posterName === false) { - $posterName = (string)$file->attributes()->poster; - } - if ($postDate === false) { - $postDate = date("Y-m-d H:i:s", (string)$file->attributes()->date); - } + // Make a fake message array to use to check the blacklist. + $msg = ['Subject' => (string) $file->attributes()->subject, 'From' => (string) $file->attributes()->poster, 'Message-ID' => '']; - // Make a fake message array to use to check the blacklist. - $msg = ['Subject' => (string)$file->attributes()->subject, 'From' => (string)$file->attributes()->poster, 'Message-ID' => '']; + // Get the group names, group_id, check if it's blacklisted. + $groupArr = []; + foreach ($file->groups->group as $group) { + $group = (string) $group; - // Get the group names, group_id, check if it's blacklisted. - $groupArr = []; - foreach ($file->groups->group as $group) { - $group = (string)$group; - - // If group_id is -1 try to get a group_id. - if ($groupID === -1) { - if (array_key_exists($group, $this->allGroups)) { - $groupID = $this->allGroups[$group]; - if (!$groupName) { - $groupName = $group; - } - } else { - $group = $this->groups->isValidGroup($group); - if ($group !== false) { - $groupID = $this->groups->add([ + // If group_id is -1 try to get a group_id. + if ($groupID === -1) { + if (array_key_exists($group, $this->allGroups)) { + $groupID = $this->allGroups[$group]; + if (! $groupName) { + $groupName = $group; + } + } else { + $group = $this->groups->isValidGroup($group); + if ($group !== false) { + $groupID = $this->groups->add([ 'name' => $group, 'description' => 'Added by NZBimport script.', 'backfill_target' => 1, 'first_record' => 0, 'last_record' => 0, 'active' => 0, - 'backfill' => 0 + 'backfill' => 0, ]); - $this->allGroups[$group] = $groupID; + $this->allGroups[$group] = $groupID; - $this->echoOut("Adding missing group: ($group)"); - } - } - } - // Add all the found groups to an array. - $groupArr[] = $group; + $this->echoOut("Adding missing group: ($group)"); + } + } + } + // Add all the found groups to an array. + $groupArr[] = $group; - // Check if this NZB is blacklisted. - if ($this->binaries->isBlackListed($msg, $group)) { - $isBlackListed = true; - break; - } - } + // Check if this NZB is blacklisted. + if ($this->binaries->isBlackListed($msg, $group)) { + $isBlackListed = true; + break; + } + } - // If we found a group and it's not blacklisted. - if ($groupID !== -1 && !$isBlackListed) { + // If we found a group and it's not blacklisted. + if ($groupID !== -1 && ! $isBlackListed) { // Get the size of the release. - if (count($file->segments->segment) > 0) { - foreach ($file->segments->segment as $segment) { - $totalSize += (int)$segment->attributes()->bytes; - } - } + if (count($file->segments->segment) > 0) { + foreach ($file->segments->segment as $segment) { + $totalSize += (int) $segment->attributes()->bytes; + } + } + } else { + if ($isBlackListed) { + $errorMessage = 'Subject is blacklisted: '.utf8_encode(trim($firstName)); + } else { + $errorMessage = 'No group found for '.$firstName.' (one of '.implode(', ', $groupArr).' are missing'; + } + $this->echoOut($errorMessage); - } else { - if ($isBlackListed) { - $errorMessage = 'Subject is blacklisted: ' . utf8_encode(trim($firstName)); - } else { - $errorMessage = 'No group found for ' . $firstName . ' (one of ' . implode(', ', $groupArr) . ' are missing'; - } - $this->echoOut($errorMessage); + return false; + } + } - return false; - } - } + // Sort values alphabetically but keep the keys intact + if (count($binary_names) > 0) { + asort($binary_names); + foreach ($nzbXML->file as $file) { + if ($file['subject'] == $binary_names[0]) { + $this->nzbGuid = md5($file->segments->segment); + break; + } + } + } - // Sort values alphabetically but keep the keys intact - if (count($binary_names) > 0) { - asort($binary_names); - foreach ($nzbXML->file as $file) { - if ($file["subject"] == $binary_names[0]) { - $this->nzbGuid = md5($file->segments->segment); - break; - } - } - } - - // Try to insert the NZB details into the DB. - return $this->insertNZB( + // Try to insert the NZB details into the DB. + return $this->insertNZB( [ 'subject' => $firstName, 'useFName' => $useNzbName, - 'postDate' => empty($postDate) ? date("Y-m-d H:i:s") : $postDate, + 'postDate' => empty($postDate) ? date('Y-m-d H:i:s') : $postDate, 'from' => empty($posterName) ? '' : $posterName, 'groups_id' => $groupID, 'groupName' => $groupName, @@ -388,46 +365,44 @@ class NZBImport 'totalSize' => $totalSize, ] ); - } + } - /** - * Insert the NZB details into the database. - * - * @param $nzbDetails - * - * @return bool - * - * @access protected - */ - protected function insertNZB($nzbDetails) - { - // Make up a GUID for the release. - $this->relGuid = $this->releases->createGUID(); + /** + * Insert the NZB details into the database. + * + * @param $nzbDetails + * + * @return bool + */ + protected function insertNZB($nzbDetails) + { + // Make up a GUID for the release. + $this->relGuid = $this->releases->createGUID(); - // Remove part count from subject. - $partLess = preg_replace('/(\(\d+\/\d+\))*$/', 'yEnc', $nzbDetails['subject']); - // Remove added yEnc from above and anything after. - $subject = utf8_encode(trim(preg_replace('/yEnc.*$/i', 'yEnc', $partLess))); + // Remove part count from subject. + $partLess = preg_replace('/(\(\d+\/\d+\))*$/', 'yEnc', $nzbDetails['subject']); + // Remove added yEnc from above and anything after. + $subject = utf8_encode(trim(preg_replace('/yEnc.*$/i', 'yEnc', $partLess))); - $renamed = 0; - if ($nzbDetails['useFName']) { - // If the user wants to use the file name.. use it. - $cleanName = $nzbDetails['useFName']; - $renamed = 1; - } else { - // Pass the subject through release cleaner to get a nicer name. - $cleanName = $this->releaseCleaner->releaseCleaner($subject, $nzbDetails['from'], $nzbDetails['totalSize'], $nzbDetails['groupName']); - if (isset($cleanName['properlynamed'])) { - $cleanName = $cleanName['cleansubject']; - $renamed = (isset($cleanName['properlynamed']) && $cleanName['properlynamed'] === true ? 1 : 0); - } - } + $renamed = 0; + if ($nzbDetails['useFName']) { + // If the user wants to use the file name.. use it. + $cleanName = $nzbDetails['useFName']; + $renamed = 1; + } else { + // Pass the subject through release cleaner to get a nicer name. + $cleanName = $this->releaseCleaner->releaseCleaner($subject, $nzbDetails['from'], $nzbDetails['totalSize'], $nzbDetails['groupName']); + if (isset($cleanName['properlynamed'])) { + $cleanName = $cleanName['cleansubject']; + $renamed = (isset($cleanName['properlynamed']) && $cleanName['properlynamed'] === true ? 1 : 0); + } + } - $escapedSubject = $this->pdo->escapeString($subject); - $escapedFromName = $this->pdo->escapeString($nzbDetails['from']); + $escapedSubject = $this->pdo->escapeString($subject); + $escapedFromName = $this->pdo->escapeString($nzbDetails['from']); - // Look for a duplicate on name, poster and size. - $dupeCheck = $this->pdo->queryOneRow( + // Look for a duplicate on name, poster and size. + $dupeCheck = $this->pdo->queryOneRow( sprintf(' SELECT id FROM releases @@ -441,10 +416,10 @@ class NZBImport ) ); - if ($dupeCheck === false) { - $escapedSearchName = $this->pdo->escapeString($cleanName); - // Insert the release into the DB. - $relID = $this->releases->insertRelease( + if ($dupeCheck === false) { + $escapedSearchName = $this->pdo->escapeString($cleanName); + // Insert the release into the DB. + $relID = $this->releases->insertRelease( [ 'name' => $escapedSubject, 'searchname' => $escapedSearchName, @@ -458,75 +433,74 @@ class NZBImport 'isrenamed' => $renamed, 'reqidstatus' => 0, 'predb_id' => 0, - 'nzbstatus' => NZB::NZB_ADDED + 'nzbstatus' => NZB::NZB_ADDED, ] ); - } else { - //$this->echoOut('This release is already in our DB so skipping: ' . $subject); - return false; - } + } else { + //$this->echoOut('This release is already in our DB so skipping: ' . $subject); + return false; + } - if (isset($relID) && $relID === false) { - $this->echoOut('ERROR: Problem inserting: ' . $subject); - return false; - } - return true; - } + if (isset($relID) && $relID === false) { + $this->echoOut('ERROR: Problem inserting: '.$subject); - /** - * Get all groups in the DB. - * - * @return bool - * @access protected - */ - protected function getAllGroups() - { - $this->allGroups = []; - $groups = $this->pdo->queryDirect(' + return false; + } + + return true; + } + + /** + * Get all groups in the DB. + * + * @return bool + */ + protected function getAllGroups() + { + $this->allGroups = []; + $groups = $this->pdo->queryDirect(' SELECT id, name FROM groups' ); - if ($groups instanceof \Traversable) { - foreach ($groups as $group) { - $this->allGroups[$group['name']] = $group['id']; - } - } + if ($groups instanceof \Traversable) { + foreach ($groups as $group) { + $this->allGroups[$group['name']] = $group['id']; + } + } - if (count($this->allGroups) === 0) { - $this->echoOut('You have no groups in your database!'); - return false; - } - return true; - } + if (count($this->allGroups) === 0) { + $this->echoOut('You have no groups in your database!'); - /** - * 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; - } - } + return false; + } - /** - * The function updates the NZB guid after there is no chance of deletion - * - * @access protected - */ - protected function updateNzbGuid() - { - $this->pdo->queryExec(" + return true; + } + + /** + * Echo message to browser or CLI. + * + * @param string $message + */ + protected function echoOut($message) + { + if ($this->browser) { + $this->retVal .= $message.'<br />'; + } elseif ($this->echoCLI) { + echo $message.PHP_EOL; + } + } + + /** + * The function updates the NZB guid after there is no chance of deletion. + */ + protected function updateNzbGuid() + { + $this->pdo->queryExec(" UPDATE releases SET nzb_guid = UNHEX({$this->pdo->escapeString($this->nzbGuid)}) WHERE guid = {$this->pdo->escapeString($this->relGuid)}" ); - } + } } diff --git a/nntmux/NZBInfo.php b/nntmux/NZBInfo.php index fb07a983c..fa3e7a47d 100755 --- a/nntmux/NZBInfo.php +++ b/nntmux/NZBInfo.php @@ -1,49 +1,51 @@ <?php + namespace nntmux; + use nntmux\utility\Utility; class NZBInfo { - public $source = ''; - public $metadata = []; - public $groups = []; - public $filecount = 0; - public $parcount = 0; - public $rarcount = 0; - public $zipcount = 0; - public $videocount = 0; - public $audiocount = 0; + public $source = ''; + public $metadata = []; + public $groups = []; + public $filecount = 0; + public $parcount = 0; + public $rarcount = 0; + public $zipcount = 0; + public $videocount = 0; + public $audiocount = 0; public $imgcount = 0; public $srrcount = 0; public $txtcount = 0; public $sfvcount = 0; - public $filesize = 0; - public $poster = ''; - public $postedfirst = 0; - public $postedlast = 0; - public $completion = 0; - public $segmenttotal = 0; - public $segmentactual = 0; - public $gid = ''; + public $filesize = 0; + public $poster = ''; + public $postedfirst = 0; + public $postedlast = 0; + public $completion = 0; + public $segmenttotal = 0; + public $segmentactual = 0; + public $gid = ''; - public $nzb = []; - public $nfofiles = []; - public $samplefiles = []; - public $mediafiles = []; - public $audiofiles = []; - public $rarfiles = []; + public $nzb = []; + public $nfofiles = []; + public $samplefiles = []; + public $mediafiles = []; + public $audiofiles = []; + public $rarfiles = []; public $imgfiles = []; public $srrfiles = []; public $txtfiles = []; public $sfvfiles = []; - public $segmentfiles = []; + public $segmentfiles = []; public $parfiles = []; private $isLoaded = false; - private $loadAllVars = false; + private $loadAllVars = false; - public function __construct() - { + public function __construct() + { $this->nfofileregex = '/[ "\(\[].*?\.(nfo|ofn)[ "\)\]]/iS'; $this->mediafileregex = '/.*\.(AVI|VOB|MKV|MP4|TS|WMV|MOV|M4V|F4V|MPG|MPEG)(\.001)?[ "\)\]]/iS'; $this->audiofileregex = '/\.(MP3|FLAC|AAC|OGG|AIFF)[ "\)\]]/iS'; @@ -54,305 +56,307 @@ class NZBInfo $this->sfvfileregex = '/\.(sfv)[ "\)\]]/iS'; } - public function loadFromString($str, $loadAllVars=false) - { - if (empty($this->source)) - $this->source = 'string'; - $this->loadAllVars = $loadAllVars; + public function loadFromString($str, $loadAllVars = false) + { + if (empty($this->source)) { + $this->source = 'string'; + } + $this->loadAllVars = $loadAllVars; - $xmlObj = @simplexml_load_string($str); - if ($this->isValidNzb($xmlObj)) - $this->parseNzb($xmlObj); + $xmlObj = @simplexml_load_string($str); + if ($this->isValidNzb($xmlObj)) { + $this->parseNzb($xmlObj); + } - unset($xmlObj); + unset($xmlObj); - return $this->isLoaded; - } + return $this->isLoaded; + } - public function loadFromFile($loc, $loadAllVars=false) + public function loadFromFile($loc, $loadAllVars = false) { $this->source = $loc; $this->loadAllVars = $loadAllVars; - if (file_exists($loc)) - { - if (preg_match('/\.(gz|zip)$/i', $loc, $ext)) - { - switch(strtolower($ext[1])) - { + if (file_exists($loc)) { + if (preg_match('/\.(gz|zip)$/i', $loc, $ext)) { + switch (strtolower($ext[1])) { case 'gz': $loc = 'compress.zlib://'.$loc; break; case 'zip': $zip = new ZipArchive; - if ($zip->open($loc) === true && $zip->numFiles == 1) + if ($zip->open($loc) === true && $zip->numFiles == 1) { return $this->loadFromString($zip->getFromIndex(0), $loadAllVars); - else + } else { $loc = 'zip://'.$loc; + } break; } } libxml_use_internal_errors(true); $xmlObj = @simplexml_load_file($loc); - if ($this->isValidNzb($xmlObj)) + if ($this->isValidNzb($xmlObj)) { $this->parseNzb($xmlObj); + } unset($xmlObj); } + return $this->isLoaded; } - public function summarize() - { - $out = []; - $out[] = 'Reading from '.basename($this->source).'...'; - if (!empty($this->nfofiles)) - $out[] = ' -nfo detected'; - if (!empty($this->samplefiles)) - $out[] = ' -sample detected'; - if (!empty($this->mediafiles)) - $out[] = ' -media detected'; - if (!empty($this->audio)) - $out[] = ' -audio detected'; + public function summarize() + { + $out = []; + $out[] = 'Reading from '.basename($this->source).'...'; + if (! empty($this->nfofiles)) { + $out[] = ' -nfo detected'; + } + if (! empty($this->samplefiles)) { + $out[] = ' -sample detected'; + } + if (! empty($this->mediafiles)) { + $out[] = ' -media detected'; + } + if (! empty($this->audio)) { + $out[] = ' -audio detected'; + } - if (!empty($this->metadata)) - { - $out[] = ' -metadata:'; - foreach($this->metadata as $mk=>$mv) - $out[] = ' -'.$mk.': '.$mv; - } + if (! empty($this->metadata)) { + $out[] = ' -metadata:'; + foreach ($this->metadata as $mk=>$mv) { + $out[] = ' -'.$mk.': '.$mv; + } + } - $out[] = ' -sngl: '.sizeof($this->segmentfiles); + $out[] = ' -sngl: '.sizeof($this->segmentfiles); - $out[] = ' -pstr: '.$this->poster; - $out[] = ' -grps: '.implode(', ', $this->groups); - $out[] = ' -size: '.round(($this->filesize / 1048576), 2).' MB in '.$this->filecount.' Files'; - $out[] = ' -'.$this->rarcount.' rars'; - $out[] = ' -'.$this->parcount.' pars'; + $out[] = ' -pstr: '.$this->poster; + $out[] = ' -grps: '.implode(', ', $this->groups); + $out[] = ' -size: '.round(($this->filesize / 1048576), 2).' MB in '.$this->filecount.' Files'; + $out[] = ' -'.$this->rarcount.' rars'; + $out[] = ' -'.$this->parcount.' pars'; $out[] = ' -'.$this->sfvcount.' sfvs'; - $out[] = ' -'.$this->zipcount.' zips'; - $out[] = ' -'.$this->videocount.' videos'; - $out[] = ' -'.$this->audiocount.' audios'; - $out[] = ' -cmpltn: '.$this->completion.'% ('.$this->segmentactual.'/'.$this->segmenttotal.')'; - $out[] = ' -pstd: '.date("Y-m-d H:i:s", $this->postedlast); - $out[] = ''; - $out[] = ''; + $out[] = ' -'.$this->zipcount.' zips'; + $out[] = ' -'.$this->videocount.' videos'; + $out[] = ' -'.$this->audiocount.' audios'; + $out[] = ' -cmpltn: '.$this->completion.'% ('.$this->segmentactual.'/'.$this->segmenttotal.')'; + $out[] = ' -pstd: '.date('Y-m-d H:i:s', $this->postedlast); + $out[] = ''; + $out[] = ''; - return implode(PHP_EOL, $out); - } + return implode(PHP_EOL, $out); + } - private function isValidNzb($xmlObj) - { - if (!$xmlObj || strtolower($xmlObj->getName()) != 'nzb' || !isset($xmlObj->file)) - return false; + private function isValidNzb($xmlObj) + { + if (! $xmlObj || strtolower($xmlObj->getName()) != 'nzb' || ! isset($xmlObj->file)) { + return false; + } return true; - } + } - private function parseNzb($xmlObj) - { - //Metadata - if (isset($xmlObj->head->meta)) - { - foreach($xmlObj->head->meta as $meta) - { - if (isset($meta->attributes()->type)) - { - $metaKey = (string) $meta->attributes()->type; - $this->metadata[$metaKey] = (string) $meta; - } - } - } + private function parseNzb($xmlObj) + { + //Metadata + if (isset($xmlObj->head->meta)) { + foreach ($xmlObj->head->meta as $meta) { + if (isset($meta->attributes()->type)) { + $metaKey = (string) $meta->attributes()->type; + $this->metadata[$metaKey] = (string) $meta; + } + } + } - //NZB GID = first segment of first file - $gid = (string) $xmlObj->file->segments->segment; - if (!empty($gid)) - $this->gid = md5($gid); + //NZB GID = first segment of first file + $gid = (string) $xmlObj->file->segments->segment; + if (! empty($gid)) { + $this->gid = md5($gid); + } - foreach($xmlObj->file as $file) - { - $fileArr = []; - $fileArr['subject'] = (string) $file->attributes()->subject; - $fileArr['poster'] = (string) $file->attributes()->poster; - $fileArr['posted'] = (int) $file->attributes()->date; - $fileArr['groups'] = []; - $fileArr['filesize'] = 0; - $fileArr['segmenttotal'] = 0; - $fileArr['segmentactual'] = 0; - $fileArr['completion'] = 0; - $fileArr['segments'] = []; + foreach ($xmlObj->file as $file) { + $fileArr = []; + $fileArr['subject'] = (string) $file->attributes()->subject; + $fileArr['poster'] = (string) $file->attributes()->poster; + $fileArr['posted'] = (int) $file->attributes()->date; + $fileArr['groups'] = []; + $fileArr['filesize'] = 0; + $fileArr['segmenttotal'] = 0; + $fileArr['segmentactual'] = 0; + $fileArr['completion'] = 0; + $fileArr['segments'] = []; - //subject - $subject = $fileArr['subject']; + //subject + $subject = $fileArr['subject']; - //poster - $this->poster = $fileArr['poster']; + //poster + $this->poster = $fileArr['poster']; - //dates - $date = $fileArr['posted']; - if ($date > $this->postedlast || $this->postedlast == 0) - $this->postedlast = $date; + //dates + $date = $fileArr['posted']; + if ($date > $this->postedlast || $this->postedlast == 0) { + $this->postedlast = $date; + } - if ($date < $this->postedfirst || $this->postedfirst == 0) - $this->postedfirst = $date; + if ($date < $this->postedfirst || $this->postedfirst == 0) { + $this->postedfirst = $date; + } + //groups + foreach ($file->groups->group as $group) { + $this->groups[] = (string) $group; + $fileArr['groups'][] = (string) $group; + } - //groups - foreach ($file->groups->group as $group) - { - $this->groups[] = (string) $group; - $fileArr['groups'][] = (string) $group; - } + //file segments + foreach ($file->segments->segment as $segment) { + $bytes = (int) $segment->attributes()->bytes; + $number = (int) $segment->attributes()->number; - //file segments - foreach($file->segments->segment as $segment) - { - $bytes = (int) $segment->attributes()->bytes; - $number = (int) $segment->attributes()->number; + $this->filesize += $bytes; + $this->segmentactual++; - $this->filesize += $bytes; - $this->segmentactual++; - - $fileArr['filesize'] += $bytes; - $fileArr['segmentactual']++; - $fileArr['segments'][$number] = (string) $segment; + $fileArr['filesize'] += $bytes; + $fileArr['segmentactual']++; + $fileArr['segments'][$number] = (string) $segment; $fileArr['segmentbytes'][$number] = $bytes; - } + } $pattern = '|\((\d+)[\/](\d+)\)|i'; preg_match_all($pattern, $subject, $matches, PREG_PATTERN_ORDER); $matchcnt = sizeof($matches[0]); $msgPart = $msgTotalParts = 0; - for ($i=0; $i<$matchcnt; $i++) - { + for ($i = 0; $i < $matchcnt; $i++) { //not (int)'d here because of the preg_replace later on $msgPart = $matches[1][$i]; $msgTotalParts = $matches[2][$i]; } - if((int)$msgPart > 0 && (int)$msgTotalParts > 0) - { + if ((int) $msgPart > 0 && (int) $msgTotalParts > 0) { $this->segmenttotal += (int) $msgTotalParts; $fileArr['segmenttotal'] = (int) $msgTotalParts; - $fileArr['completion'] = number_format(($fileArr['segmentactual']/$fileArr['segmenttotal'])*100, 0); + $fileArr['completion'] = number_format(($fileArr['segmentactual'] / $fileArr['segmenttotal']) * 100, 0); $fileArr['subject'] = utf8_encode(trim(preg_replace('|\('.$msgPart.'[\/]'.$msgTotalParts.'\)|i', '', $subject))); } - //file counts - $this->filecount++; + //file counts + $this->filecount++; - if ($fileArr['segmenttotal'] == 1) - $this->segmentfiles[] = $fileArr; + if ($fileArr['segmenttotal'] == 1) { + $this->segmentfiles[] = $fileArr; + } - if (preg_match($this->nfofileregex, $subject)) - $this->nfofiles[] = $fileArr; + if (preg_match($this->nfofileregex, $subject)) { + $this->nfofiles[] = $fileArr; + } - if (preg_match($this->mediafileregex, $subject) && preg_match('/sample[\.\-]/i', $subject) && !preg_match('/\.par2|\.srs/i', $subject)) - $this->samplefiles[] = $fileArr; + if (preg_match($this->mediafileregex, $subject) && preg_match('/sample[\.\-]/i', $subject) && ! preg_match('/\.par2|\.srs/i', $subject)) { + $this->samplefiles[] = $fileArr; + } - if (preg_match($this->mediafileregex, $subject) && !preg_match('/sample[\.\-]/i', $subject) && !preg_match('/\.par2|\.srs/i', $subject)) - { - $this->mediafiles[] = $fileArr; - $this->videocount++; - } + if (preg_match($this->mediafileregex, $subject) && ! preg_match('/sample[\.\-]/i', $subject) && ! preg_match('/\.par2|\.srs/i', $subject)) { + $this->mediafiles[] = $fileArr; + $this->videocount++; + } - if (preg_match('/\.(rar|r\d{2,3})(?!\.)/i', $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) - $this->rarcount++; + if (preg_match('/\.(rar|r\d{2,3})(?!\.)/i', $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) { + $this->rarcount++; + } - if (preg_match($this->rarfileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) - $this->rarfiles[] = $fileArr; + if (preg_match($this->rarfileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) { + $this->rarfiles[] = $fileArr; + } - if (preg_match($this->audiofileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) - { - $this->audiofiles[] = $fileArr; - $this->audiocount++; - } + if (preg_match($this->audiofileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) { + $this->audiofiles[] = $fileArr; + $this->audiocount++; + } - if (preg_match($this->imgfileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject)) - { + if (preg_match($this->imgfileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject)) { $this->imgfiles[] = $fileArr; $this->imgcount++; } - if (preg_match($this->srrfileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject)) - { + if (preg_match($this->srrfileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject)) { $this->srrfiles[] = $fileArr; $this->srrcount++; } - if (preg_match($this->txtfileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject)) - { + if (preg_match($this->txtfileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject)) { $this->txtfiles[] = $fileArr; $this->txtcount++; } - if (preg_match($this->sfvfileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|nzb)/iS', $subject)) - { + if (preg_match($this->sfvfileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|nzb)/iS', $subject)) { $this->sfvfiles[] = $fileArr; $this->sfvcount++; } - if (preg_match('/\.par2(?!\.)/iS', $subject)) - { + if (preg_match('/\.par2(?!\.)/iS', $subject)) { $this->parcount++; - if (!preg_match('/(vol\d+\+|vol[_\.\s]\d)/iS', $subject) && $fileArr['segmenttotal'] < 3) + if (! preg_match('/(vol\d+\+|vol[_\.\s]\d)/iS', $subject) && $fileArr['segmenttotal'] < 3) { $this->parfiles[] = $fileArr; + } } - if (preg_match('/\.zip(?!\.)/i', $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) - $this->zipcount++; + if (preg_match('/\.zip(?!\.)/i', $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) { + $this->zipcount++; + } - if ($this->loadAllVars === true) - $this->nzb[] = $fileArr; - else - $this->nzb[]['subject'] = $fileArr['subject']; - } + if ($this->loadAllVars === true) { + $this->nzb[] = $fileArr; + } else { + $this->nzb[]['subject'] = $fileArr['subject']; + } + } - $this->groups = array_unique($this->groups); + $this->groups = array_unique($this->groups); - if ($this->segmenttotal > 0) - $this->completion = number_format(($this->segmentactual/$this->segmenttotal)*100, 0); + if ($this->segmenttotal > 0) { + $this->completion = number_format(($this->segmentactual / $this->segmenttotal) * 100, 0); + } - if (is_array($this->nzb) && !empty($this->nzb)) - $this->isLoaded = true; + if (is_array($this->nzb) && ! empty($this->nzb)) { + $this->isLoaded = true; + } - return $this->isLoaded; - } + return $this->isLoaded; + } public function toNzb() { - if ($this->loadAllVars === false) + if ($this->loadAllVars === false) { return false; + } $nzb = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; $nzb .= "<!DOCTYPE nzb PUBLIC \"-//newzBin//DTD NZB 1.1//EN\" \"http://www.newzbin.com/DTD/nzb/nzb-1.1.dtd\">\n"; $nzb .= "<nzb xmlns=\"http://www.newzbin.com/DTD/2003/nzb\">\n\n"; - if (!empty($this->metadata)) - { + if (! empty($this->metadata)) { $nzb .= "<head>\n"; - $out = []; - foreach($this->metadata as $mk=>$mv) + $out = []; + foreach ($this->metadata as $mk=>$mv) { $out[] = ' <meta type="'.$mk.'">'.$mv."</meta>\n"; + } $nzb .= "</head>\n"; } - foreach($this->nzb as $postFile) - { - $nzb .= "<file poster=\"".htmlspecialchars($postFile["poster"], ENT_QUOTES, 'utf-8')."\" date=\"".$postFile["posted"]."\" subject=\"".htmlspecialchars($postFile["subject"], ENT_QUOTES, 'utf-8')." (1/".$postFile["segmenttotal"].")\">\n"; + foreach ($this->nzb as $postFile) { + $nzb .= '<file poster="'.htmlspecialchars($postFile['poster'], ENT_QUOTES, 'utf-8').'" date="'.$postFile['posted'].'" subject="'.htmlspecialchars($postFile['subject'], ENT_QUOTES, 'utf-8').' (1/'.$postFile['segmenttotal'].")\">\n"; $nzb .= " <groups>\n"; - foreach($postFile['groups'] as $fileGroup) - { - $nzb .= " <group>".$fileGroup."</group>\n"; + foreach ($postFile['groups'] as $fileGroup) { + $nzb .= ' <group>'.$fileGroup."</group>\n"; } $nzb .= " </groups>\n"; $nzb .= " <segments>\n"; - foreach($postFile['segments'] as $fileSegmentNum=>$fileSegment) - { - $nzb .= " <segment bytes=\"".$postFile['segmentbytes'][$fileSegmentNum]."\" number=\"".$fileSegmentNum."\">".Utility::htmlfmt($fileSegment)."</segment>\n"; + foreach ($postFile['segments'] as $fileSegmentNum=>$fileSegment) { + $nzb .= ' <segment bytes="'.$postFile['segmentbytes'][$fileSegmentNum].'" number="'.$fileSegmentNum.'">'.Utility::htmlfmt($fileSegment)."</segment>\n"; } $nzb .= " </segments>\n</file>\n"; } - $nzb .= "<!-- nntmux ".date("Y-m-d H:i:s")." -->\n</nzb>"; + $nzb .= '<!-- nntmux '.date('Y-m-d H:i:s')." -->\n</nzb>"; return $nzb; } diff --git a/nntmux/NZBMultiGroup.php b/nntmux/NZBMultiGroup.php index 7c638a6dd..44a6c3b39 100644 --- a/nntmux/NZBMultiGroup.php +++ b/nntmux/NZBMultiGroup.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; /** @@ -7,35 +8,33 @@ namespace nntmux; */ class NZBMultiGroup extends NZB { - /** - * Default constructor. - * - * @access public - * - * @param $pdo - * - * @throws \Exception - */ - public function __construct(&$pdo) - { - parent::__construct($pdo); - } + /** + * Default constructor. + * + * + * @param $pdo + * + * @throws \Exception + */ + public function __construct(&$pdo) + { + parent::__construct($pdo); + } - /** - * Initiate class vars when writing NZB's. - * - * @access public - * - * @param int $groupID - */ - public function initiateForWrite($groupID) - { - $this->_tableNames = [ + /** + * Initiate class vars when writing NZB's. + * + * + * @param int $groupID + */ + public function initiateForWrite($groupID) + { + $this->_tableNames = [ 'cName' => 'multigroup_collections', 'bName' => 'multigroup_binaries', 'pName' => 'multigroup_parts', ]; - $this->setQueries(); - } + $this->setQueries(); + } } diff --git a/nntmux/NZBVortex.php b/nntmux/NZBVortex.php index 78cc0a8b9..7b648c930 100755 --- a/nntmux/NZBVortex.php +++ b/nntmux/NZBVortex.php @@ -1,29 +1,28 @@ <?php + namespace nntmux; final class NZBVortex { - protected $nonce = null; + protected $nonce = null; protected $session = null; public function __construct() { - if (is_null($this->session)) - { + if (is_null($this->session)) { $this->getNonce(); $this->login(); } } /** - * get text for state + * get text for state. * @param int $code * @return string */ public function getState($code = 0) { - $states = array - ( + $states = [ 0 => 'Waiting', 1 => 'Downloading', 2 => 'Waiting for save', @@ -48,23 +47,22 @@ final class NZBVortex 21 => 'Uncompress failed', 22 => 'Check failed, data corrupt', 23 => 'Move failed', - 24 => 'Badly encoded download (uuencoded)' - ); + 24 => 'Badly encoded download (uuencoded)', + ]; return (isset($states[$code])) ? $states[$code] : -1; } /** - * get overview of NZB's in queue + * get overview of NZB's in queue. * @return array */ public function getOverview() { - $params = array('sessionid' => $this->session); + $params = ['sessionid' => $this->session]; $response = $this->sendRequest(sprintf('app/webUpdate'), $params); - foreach ($response['nzbs'] as &$nzb) - { + foreach ($response['nzbs'] as &$nzb) { $nzb['original_state'] = $nzb['state']; $nzb['state'] = (1 == $nzb['isPaused']) ? 'Paused' : $this->getState($nzb['state']); } @@ -72,167 +70,148 @@ final class NZBVortex return $response; } - /** - * add NZB to queue + * add NZB to queue. * @param string $nzb * @return void */ public function addQueue($nzb = '') { - if (!empty($nzb)) - { + if (! empty($nzb)) { $page = new Page; $user = new Users; - $host = $page->serverurl; - $data = $user->getById($user->currentUserId()); - $url = sprintf("%sgetnzb/%s.nzb&i=%s&r=%s", $host, $nzb, $data['id'], $data['rsstoken']); + $host = $page->serverurl; + $data = $user->getById($user->currentUserId()); + $url = sprintf('%sgetnzb/%s.nzb&i=%s&r=%s', $host, $nzb, $data['id'], $data['rsstoken']); - $params = array - ( + $params = [ 'sessionid' => $this->session, - 'url' => $url - ); + 'url' => $url, + ]; $response = $this->sendRequest('nzb/add', $params); } } - /** - * resume NZB + * resume NZB. * @param int $id * @return void */ public function resume($id = 0) { - if ($id > 0) - { - # /nzb/(id)/resume - $params = array('sessionid' => $this->session); + if ($id > 0) { + // /nzb/(id)/resume + $params = ['sessionid' => $this->session]; $response = $this->sendRequest(sprintf('nzb/%s/resume', $id), $params); } } - /** - * pause NZB + * pause NZB. * @param int $id * @return void */ public function pause($id = 0) { - if ($id > 0) - { - # /nzb/(id)/pause - $params = array('sessionid' => $this->session); + if ($id > 0) { + // /nzb/(id)/pause + $params = ['sessionid' => $this->session]; $response = $this->sendRequest(sprintf('nzb/%s/pause', $id), $params); } } - /** - * move NZB up in queue + * move NZB up in queue. * @param int $id * @return void */ public function moveUp($id = 0) { - if ($id > 0) - { - # nzb/(nzbid)/moveup - $params = array('sessionid' => $this->session); + if ($id > 0) { + // nzb/(nzbid)/moveup + $params = ['sessionid' => $this->session]; $response = $this->sendRequest(sprintf('nzb/%s/moveup', $id), $params); } } - /** - * move NZB down in queue + * move NZB down in queue. * @param int $id * @return void */ public function moveDown($id = 0) { - if ($id > 0) - { - # nzb/(nzbid)/movedown - $params = array('sessionid' => $this->session); + if ($id > 0) { + // nzb/(nzbid)/movedown + $params = ['sessionid' => $this->session]; $response = $this->sendRequest(sprintf('nzb/%s/movedown', $id), $params); } } - /** - * move NZB to bottom of queue + * move NZB to bottom of queue. * @param int $id * @return void */ public function moveBottom($id = 0) { - if ($id > 0) - { - # nzb/(nzbid)/movebottom - $params = array('sessionid' => $this->session); + if ($id > 0) { + // nzb/(nzbid)/movebottom + $params = ['sessionid' => $this->session]; $response = $this->sendRequest(sprintf('nzb/%s/movebottom', $id), $params); } } - /** - * Remove a (finished/unfinished) NZB from queue and delete files + * Remove a (finished/unfinished) NZB from queue and delete files. * @param int $id * @return void */ public function delete($id = 0) { - if ($id > 0) - { - # nzb/(nzbid)/movebottom - $params = array('sessionid' => $this->session); + if ($id > 0) { + // nzb/(nzbid)/movebottom + $params = ['sessionid' => $this->session]; $response = $this->sendRequest(sprintf('nzb/%s/cancelDelete', $id), $params); } } - /** - * move NZB to top of queue + * move NZB to top of queue. * @param int $id * @return void */ public function moveTop($id = 0) { - if ($id > 0) - { - # nzb/(nzbid)/movebottom - $params = array('sessionid' => $this->session); + if ($id > 0) { + // nzb/(nzbid)/movebottom + $params = ['sessionid' => $this->session]; $response = $this->sendRequest(sprintf('nzb/%s/movetop', $id), $params); } } - /** - * get filelist for nzb + * get filelist for nzb. * @param int $id * @return array|bool */ public function getFilelist($id = 0) { - if ($id > 0) - { - # file/(nzbid) - $params = array('sessionid' => $this->session); + if ($id > 0) { + // file/(nzbid) + $params = ['sessionid' => $this->session]; $response = $this->sendRequest(sprintf('file/%s', $id), $params); + return $response; } return false; } - /** - * get /auth/nonce + * get /auth/nonce. * @return void */ protected function getNonce() @@ -246,29 +225,30 @@ final class NZBVortex */ protected function login() { - $user = new Users(); - $data = $user->getById($user->currentUserId()); - $cnonce = generateUuid(); - $hash = hash('sha256', sprintf("%s:%s:%s", $this->nonce, $cnonce, $data['nzbvortex_api_key']), true); - $hash = base64_encode($hash); + $user = new Users(); + $data = $user->getById($user->currentUserId()); + $cnonce = generateUuid(); + $hash = hash('sha256', sprintf('%s:%s:%s', $this->nonce, $cnonce, $data['nzbvortex_api_key']), true); + $hash = base64_encode($hash); - $params = array - ( + $params = [ 'nonce' => $this->nonce, 'cnonce' => $cnonce, - 'hash' => $hash - ); + 'hash' => $hash, + ]; $response = $this->sendRequest('auth/login', $params); - if ('successful' == $response['loginResult']) + if ('successful' == $response['loginResult']) { $this->session = $response['sessionID']; + } - if ('failed' == $response['loginResult']) { } + if ('failed' == $response['loginResult']) { + } } /** - * sendRequest() + * sendRequest(). * * @param $path * @param array $params @@ -281,9 +261,9 @@ final class NZBVortex $user = new Users; $data = $user->getById($user->currentUserId()); - $url = sprintf('%s/api', $data['nzbvortex_server_url']); + $url = sprintf('%s/api', $data['nzbvortex_server_url']); $params = http_build_query($params); - $ch = curl_init(sprintf("%s/%s?%s", $url, $path, $params)); + $ch = curl_init(sprintf('%s/%s?%s', $url, $path, $params)); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); @@ -291,18 +271,17 @@ final class NZBVortex curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); - #curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); - #curl_setopt($ch, CURLOPT_PROXY, 'localhost:8888'); + //curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); + //curl_setopt($ch, CURLOPT_PROXY, 'localhost:8888'); $response = curl_exec($ch); $response = json_decode($response, true); - $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); - $error = curl_error($ch); + $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $error = curl_error($ch); curl_close($ch); - switch ($status) - { + switch ($status) { case 0: throw new \Exception(sprintf('Unable to connect. Is NZBVortex running? Is your API key correct? Is something blocking ports? (Err: %s)', $error)); break; @@ -316,7 +295,7 @@ final class NZBVortex break; default: - throw new \Exception(sprintf("%s (%s): %s", $path, $status, $response['result'])); + throw new \Exception(sprintf('%s (%s): %s', $path, $status, $response['result'])); break; } } diff --git a/nntmux/NameFixer.php b/nntmux/NameFixer.php index e91c58fa3..6626149d4 100755 --- a/nntmux/NameFixer.php +++ b/nntmux/NameFixer.php @@ -1,152 +1,153 @@ <?php + namespace nntmux; use nntmux\db\DB; -use nntmux\processing\PostProcess; use nntmux\utility\Utility; +use nntmux\processing\PostProcess; /** - * Class NameFixer + * Class NameFixer. */ class NameFixer { - const PREDB_REGEX = '/([\w\(\)]+[\s\._-]([\w\(\)]+[\s\._-])+[\w\(\)]+-\w+)/'; + const PREDB_REGEX = '/([\w\(\)]+[\s\._-]([\w\(\)]+[\s\._-])+[\w\(\)]+-\w+)/'; - // Constants for name fixing status - const PROC_NFO_NONE = 0; - const PROC_NFO_DONE = 1; - const PROC_FILES_NONE = 0; - const PROC_FILES_DONE = 1; - const PROC_PAR2_NONE = 0; - const PROC_PAR2_DONE = 1; - const PROC_UID_NONE = 0; - const PROC_UID_DONE = 1; - const PROC_HASH16K_NONE = 0; - const PROC_HASH16K_DONE = 1; - const PROC_SRR_NONE = 0; - const PROC_SRR_DONE = 1; + // Constants for name fixing status + const PROC_NFO_NONE = 0; + const PROC_NFO_DONE = 1; + const PROC_FILES_NONE = 0; + const PROC_FILES_DONE = 1; + const PROC_PAR2_NONE = 0; + const PROC_PAR2_DONE = 1; + const PROC_UID_NONE = 0; + const PROC_UID_DONE = 1; + const PROC_HASH16K_NONE = 0; + const PROC_HASH16K_DONE = 1; + const PROC_SRR_NONE = 0; + const PROC_SRR_DONE = 1; - // Constants for overall rename status - const IS_RENAMED_NONE = 0; - const IS_RENAMED_DONE = 1; + // Constants for overall rename status + const IS_RENAMED_NONE = 0; + const IS_RENAMED_DONE = 1; - /** - * Has the current release found a new name? - * - * @var bool - */ - public $matched; + /** + * Has the current release found a new name? + * + * @var bool + */ + public $matched; - /** - * How many releases have got a new name? - * - * @var int - */ - public $fixed; + /** + * How many releases have got a new name? + * + * @var int + */ + public $fixed; - /** - * How many releases were checked. - * - * @var int - */ - public $checked; + /** + * How many releases were checked. + * + * @var int + */ + public $checked; - /** - * Whether or not the check has completed - * - * @var bool - */ - public $done; + /** + * Whether or not the check has completed. + * + * @var bool + */ + public $done; - /** - * Whether or not to echo info to CLI - * - * @var bool - */ - public $echooutput; + /** + * Whether or not to echo info to CLI. + * + * @var bool + */ + public $echooutput; - /** - * Total releases we are working on. - * - * @var int - */ - protected $_totalReleases; + /** + * Total releases we are working on. + * + * @var int + */ + protected $_totalReleases; - /** - * The cleaned filename we want to match - * - * @var string - */ - protected $_fileName; + /** + * The cleaned filename we want to match. + * + * @var string + */ + protected $_fileName; - /** - * The release ID we are trying to rename - * - * @var int - */ - protected $relid; + /** + * The release ID we are trying to rename. + * + * @var int + */ + protected $relid; - /** - * @var string - */ - protected $othercats; + /** + * @var string + */ + protected $othercats; - /** - * @var string - */ - protected $timeother; + /** + * @var string + */ + protected $timeother; - /** - * @var string - */ - protected $timeall; + /** + * @var string + */ + protected $timeall; - /** - * @var string - */ - protected $fullother; + /** + * @var string + */ + protected $fullother; - /** - * @var string - */ - protected $fullall; + /** + * @var string + */ + protected $fullall; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var ConsoleTools - */ - public $consoletools; + /** + * @var ConsoleTools + */ + public $consoletools; - /** - * @var Category - */ - public $category; + /** + * @var Category + */ + public $category; - /** - * @var Utility - */ - public $text; + /** + * @var Utility + */ + public $text; - /** - * @var Groups - */ - public $_groups; + /** + * @var Groups + */ + public $_groups; - /** - * @var SphinxSearch - */ - public $sphinx; + /** + * @var SphinxSearch + */ + public $sphinx; - /** - * @param array $options Class instances / Echo to cli. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances / Echo to cli. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => true, 'Categorize' => null, 'ConsoleTools' => null, @@ -155,43 +156,43 @@ class NameFixer 'Settings' => null, 'SphinxSearch' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->relid = $this->fixed = $this->checked = 0; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->othercats = implode(',', Category::OTHERS_GROUP); - $this->timeother = sprintf(' AND rel.adddate > (NOW() - INTERVAL 6 HOUR) AND rel.categories_id IN (%s) GROUP BY rel.id ORDER BY postdate DESC', $this->othercats); - $this->timeall = ' AND rel.adddate > (NOW() - INTERVAL 6 HOUR) GROUP BY rel.id ORDER BY postdate DESC'; - $this->fullother = sprintf(' AND rel.categories_id IN (%s) GROUP BY rel.id', $this->othercats); - $this->fullall = ''; - $this->_fileName = ''; - $this->done = $this->matched = false; - $this->consoletools = ($options['ConsoleTools'] instanceof ConsoleTools ? $options['ConsoleTools'] : new ConsoleTools(['ColorCLI' => $this->pdo->log])); - $this->category = ($options['Categorize'] instanceof Categorize ? $options['Categorize'] : new Categorize(['Settings' => $this->pdo])); - $this->text = ($options['Misc'] instanceof Utility ? $options['Misc'] : new Utility()); - $this->_groups = ($options['Groups'] instanceof Groups ? $options['Groups'] : new Groups(['Settings' => $this->pdo])); - $this->sphinx = ($options['SphinxSearch'] instanceof SphinxSearch ? $options['SphinxSearch'] : new SphinxSearch()); - } + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + $this->relid = $this->fixed = $this->checked = 0; + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->othercats = implode(',', Category::OTHERS_GROUP); + $this->timeother = sprintf(' AND rel.adddate > (NOW() - INTERVAL 6 HOUR) AND rel.categories_id IN (%s) GROUP BY rel.id ORDER BY postdate DESC', $this->othercats); + $this->timeall = ' AND rel.adddate > (NOW() - INTERVAL 6 HOUR) GROUP BY rel.id ORDER BY postdate DESC'; + $this->fullother = sprintf(' AND rel.categories_id IN (%s) GROUP BY rel.id', $this->othercats); + $this->fullall = ''; + $this->_fileName = ''; + $this->done = $this->matched = false; + $this->consoletools = ($options['ConsoleTools'] instanceof ConsoleTools ? $options['ConsoleTools'] : new ConsoleTools(['ColorCLI' => $this->pdo->log])); + $this->category = ($options['Categorize'] instanceof Categorize ? $options['Categorize'] : new Categorize(['Settings' => $this->pdo])); + $this->text = ($options['Misc'] instanceof Utility ? $options['Misc'] : new Utility()); + $this->_groups = ($options['Groups'] instanceof Groups ? $options['Groups'] : new Groups(['Settings' => $this->pdo])); + $this->sphinx = ($options['SphinxSearch'] instanceof SphinxSearch ? $options['SphinxSearch'] : new SphinxSearch()); + } - /** - * Attempts to fix release names using the NFO. - * - * @param int $time 1: 24 hours, 2: no time limit - * @param boolean $echo 1: change the name, anything else: preview of what could have been changed. - * @param int $cats 1: other categories, 2: all categories - * @param $nameStatus - * @param $show - */ - public function fixNamesWithNfo($time, $echo, $cats, $nameStatus, $show): void - { - $this->_echoStartMessage($time, '.nfo files'); - $type = 'NFO, '; + /** + * Attempts to fix release names using the NFO. + * + * @param int $time 1: 24 hours, 2: no time limit + * @param bool $echo 1: change the name, anything else: preview of what could have been changed. + * @param int $cats 1: other categories, 2: all categories + * @param $nameStatus + * @param $show + */ + public function fixNamesWithNfo($time, $echo, $cats, $nameStatus, $show): void + { + $this->_echoStartMessage($time, '.nfo files'); + $type = 'NFO, '; - // Only select releases we haven't checked here before - $preId = false; - if ($cats === 3) { - $query = sprintf(' + // Only select releases we haven't checked here before + $preId = false; + if ($cats === 3) { + $query = sprintf(' SELECT rel.id AS releases_id, rel.fromname FROM releases rel INNER JOIN release_nfos nfo ON (nfo.releases_id = rel.id) @@ -199,10 +200,10 @@ class NameFixer AND rel.predb_id = 0', NZB::NZB_ADDED ); - $cats = 2; - $preId = true; - } else { - $query = sprintf(' + $cats = 2; + $preId = true; + } else { + $query = sprintf(' SELECT rel.id AS releases_id, rel.fromname FROM releases rel INNER JOIN release_nfos nfo ON (nfo.releases_id = rel.id) @@ -213,19 +214,19 @@ class NameFixer Category::OTHER_MISC, self::PROC_NFO_NONE ); - } + } - $releases = $this->_getReleases($time, $cats, $query); + $releases = $this->_getReleases($time, $cats, $query); - if ($releases instanceof \Traversable) { - $total = $releases->rowCount(); + if ($releases instanceof \Traversable) { + $total = $releases->rowCount(); - if ($total > 0) { - $this->_totalReleases = $total; - echo ColorCLI::primary(number_format($total) . ' releases to process.'); + if ($total > 0) { + $this->_totalReleases = $total; + echo ColorCLI::primary(number_format($total).' releases to process.'); - foreach ($releases as $rel) { - $releaseRow = $this->pdo->queryOneRow( + foreach ($releases as $rel) { + $releaseRow = $this->pdo->queryOneRow( sprintf(' SELECT nfo.releases_id AS nfoid, rel.groups_id, rel.fromname, rel.categories_id, rel.name, rel.searchname, UNCOMPRESS(nfo) AS textstring, rel.id AS releases_id @@ -236,42 +237,42 @@ class NameFixer ) ); - $this->checked++; + $this->checked++; - // Ignore encrypted NFOs. - if (preg_match('/^=newz\[NZB\]=\w+/', $releaseRow['textstring'])) { - $this->_updateSingleColumn('proc_nfo', self::PROC_NFO_DONE, $rel['releases_id']); - continue; - } + // Ignore encrypted NFOs. + if (preg_match('/^=newz\[NZB\]=\w+/', $releaseRow['textstring'])) { + $this->_updateSingleColumn('proc_nfo', self::PROC_NFO_DONE, $rel['releases_id']); + continue; + } - $this->reset(); - $this->checkName($releaseRow, $echo, $type, $nameStatus, $show, $preId); - $this->_echoRenamed($show); - } - $this->_echoFoundCount($echo, ' NFO\'s'); - } else { - echo ColorCLI::info('Nothing to fix.'); - } - } - } + $this->reset(); + $this->checkName($releaseRow, $echo, $type, $nameStatus, $show, $preId); + $this->_echoRenamed($show); + } + $this->_echoFoundCount($echo, ' NFO\'s'); + } else { + echo ColorCLI::info('Nothing to fix.'); + } + } + } - /** - * Attempts to fix release names using the File name. - * - * @param int $time 1: 24 hours, 2: no time limit - * @param boolean $echo 1: change the name, anything else: preview of what could have been changed. - * @param int $cats 1: other categories, 2: all categories - * @param $nameStatus - * @param $show - */ - public function fixNamesWithFiles($time, $echo, $cats, $nameStatus, $show): void - { - $this->_echoStartMessage($time, 'file names'); - $type = 'Filenames, '; + /** + * Attempts to fix release names using the File name. + * + * @param int $time 1: 24 hours, 2: no time limit + * @param bool $echo 1: change the name, anything else: preview of what could have been changed. + * @param int $cats 1: other categories, 2: all categories + * @param $nameStatus + * @param $show + */ + public function fixNamesWithFiles($time, $echo, $cats, $nameStatus, $show): void + { + $this->_echoStartMessage($time, 'file names'); + $type = 'Filenames, '; - $preId = false; - if ($cats === 3) { - $query = sprintf(' + $preId = false; + if ($cats === 3) { + $query = sprintf(' SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id, rf.releases_id AS fileid, rel.id AS releases_id FROM releases rel @@ -280,10 +281,10 @@ class NameFixer AND predb_id = 0', NZB::NZB_ADDED ); - $cats = 2; - $preId = true; - } else { - $query = sprintf(' + $cats = 2; + $preId = true; + } else { + $query = sprintf(' SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id, rf.releases_id AS fileid, rel.id AS releases_id FROM releases rel @@ -296,46 +297,45 @@ class NameFixer Category::OTHER_HASHED, self::PROC_FILES_NONE ); - } + } - $releases = $this->_getReleases($time, $cats, $query); - if ($releases instanceof \Traversable) { + $releases = $this->_getReleases($time, $cats, $query); + if ($releases instanceof \Traversable) { + $total = $releases->rowCount(); + if ($total > 0) { + $this->_totalReleases = $total; + echo ColorCLI::primary(number_format($total).' file names to process.'); - $total = $releases->rowCount(); - if ($total > 0) { - $this->_totalReleases = $total; - echo ColorCLI::primary(number_format($total) . ' file names to process.'); + foreach ($releases as $release) { + $this->reset(); + $this->checkName($release, $echo, $type, $nameStatus, $show, $preId); + $this->checked++; + $this->_echoRenamed($show); + } - foreach ($releases as $release) { - $this->reset(); - $this->checkName($release, $echo, $type, $nameStatus, $show, $preId); - $this->checked++; - $this->_echoRenamed($show); - } + $this->_echoFoundCount($echo, ' files'); + } else { + echo ColorCLI::info('Nothing to fix.'); + } + } + } - $this->_echoFoundCount($echo, ' files'); - } else { - echo ColorCLI::info('Nothing to fix.'); - } - } - } + /** + * Attempts to fix release names using the File name. + * + * @param int $time 1: 24 hours, 2: no time limit + * @param bool $echo 1: change the name, anything else: preview of what could have been changed. + * @param int $cats 1: other categories, 2: all categories + * @param $nameStatus + * @param $show + */ + public function fixXXXNamesWithFiles($time, $echo, $cats, $nameStatus, $show): void + { + $this->_echoStartMessage($time, 'file names'); + $type = 'Filenames, '; - /** - * Attempts to fix release names using the File name. - * - * @param int $time 1: 24 hours, 2: no time limit - * @param boolean $echo 1: change the name, anything else: preview of what could have been changed. - * @param int $cats 1: other categories, 2: all categories - * @param $nameStatus - * @param $show - */ - public function fixXXXNamesWithFiles($time, $echo, $cats, $nameStatus, $show): void - { - $this->_echoStartMessage($time, 'file names'); - $type = 'Filenames, '; - - if ($cats === 3) { - $query = sprintf(' + if ($cats === 3) { + $query = sprintf(' SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id, rf.releases_id AS fileid, rel.id AS releases_id FROM releases rel @@ -344,9 +344,9 @@ class NameFixer AND predb_id = 0', NZB::NZB_ADDED ); - $cats = 2; - } else { - $query = sprintf(' + $cats = 2; + } else { + $query = sprintf(' SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id, rf.releases_id AS fileid, rel.id AS releases_id FROM releases rel @@ -359,45 +359,44 @@ class NameFixer Category::OTHER_HASHED, $this->pdo->likeString('SDPORN', true, true) ); - } + } - $releases = $this->_getReleases($time, $cats, $query); - if ($releases instanceof \Traversable) { + $releases = $this->_getReleases($time, $cats, $query); + if ($releases instanceof \Traversable) { + $total = $releases->rowCount(); + if ($total > 0) { + $this->_totalReleases = $total; + echo ColorCLI::primary(number_format($total).' xxx file names to process.'); - $total = $releases->rowCount(); - if ($total > 0) { - $this->_totalReleases = $total; - echo ColorCLI::primary(number_format($total) . ' xxx file names to process.'); + foreach ($releases as $release) { + $this->reset(); + $this->xxxNameCheck($release, $echo, $type, $nameStatus, $show); + $this->checked++; + $this->_echoRenamed($show); + } + $this->_echoFoundCount($echo, ' files'); + } else { + echo ColorCLI::info('Nothing to fix.'); + } + } + } - foreach ($releases as $release) { - $this->reset(); - $this->xxxNameCheck($release, $echo, $type, $nameStatus, $show); - $this->checked++; - $this->_echoRenamed($show); - } - $this->_echoFoundCount($echo, ' files'); - } else { - echo ColorCLI::info('Nothing to fix.'); - } - } - } + /** + * Attempts to fix release names using the File name. + * + * @param int $time 1: 24 hours, 2: no time limit + * @param bool $echo 1: change the name, anything else: preview of what could have been changed. + * @param int $cats 1: other categories, 2: all categories + * @param $nameStatus + * @param $show + */ + public function fixNamesWithSrr($time, $echo, $cats, $nameStatus, $show): void + { + $this->_echoStartMessage($time, 'SRR file names'); + $type = 'SRR, '; - /** - * Attempts to fix release names using the File name. - * - * @param int $time 1: 24 hours, 2: no time limit - * @param boolean $echo 1: change the name, anything else: preview of what could have been changed. - * @param int $cats 1: other categories, 2: all categories - * @param $nameStatus - * @param $show - */ - public function fixNamesWithSrr($time, $echo, $cats, $nameStatus, $show): void - { - $this->_echoStartMessage($time, 'SRR file names'); - $type = 'SRR, '; - - if ($cats === 3) { - $query = sprintf(' + if ($cats === 3) { + $query = sprintf(' SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id, rf.releases_id AS fileid, rel.id AS releases_id FROM releases rel @@ -406,9 +405,9 @@ class NameFixer AND predb_id = 0', NZB::NZB_ADDED ); - $cats = 2; - } else { - $query = sprintf(' + $cats = 2; + } else { + $query = sprintf(' SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id, rf.releases_id AS fileid, rel.id AS releases_id FROM releases rel @@ -423,54 +422,53 @@ class NameFixer $this->pdo->likeString('.srr', true, false), self::PROC_SRR_NONE ); - } + } - $releases = $this->_getReleases($time, $cats, $query); - if ($releases instanceof \Traversable) { + $releases = $this->_getReleases($time, $cats, $query); + if ($releases instanceof \Traversable) { + $total = $releases->rowCount(); + if ($total > 0) { + $this->_totalReleases = $total; + echo ColorCLI::primary(number_format($total).' srr file extensions to process.'); - $total = $releases->rowCount(); - if ($total > 0) { - $this->_totalReleases = $total; - echo ColorCLI::primary(number_format($total) . ' srr file extensions to process.'); + foreach ($releases as $release) { + $this->reset(); + $this->srrNameCheck($release, $echo, $type, $nameStatus, $show); + $this->checked++; + $this->_echoRenamed($show); + } + $this->_echoFoundCount($echo, ' files'); + } else { + echo ColorCLI::info('Nothing to fix.'); + } + } + } - foreach ($releases as $release) { - $this->reset(); - $this->srrNameCheck($release, $echo, $type, $nameStatus, $show); - $this->checked++; - $this->_echoRenamed($show); - } - $this->_echoFoundCount($echo, ' files'); - } else { - echo ColorCLI::info('Nothing to fix.'); - } - } - } + /** + * Attempts to fix release names using the Par2 File. + * + * @param int $time 1: 24 hours, 2: no time limit + * @param int $echo 1: change the name, anything else: preview of what could have been changed. + * @param int $cats 1: other categories, 2: all categories + * @param $nameStatus + * @param $show + * @param NNTP $nntp + */ + public function fixNamesWithPar2($time, $echo, $cats, $nameStatus, $show, $nntp): void + { + $this->_echoStartMessage($time, 'par2 files'); - /** - * Attempts to fix release names using the Par2 File. - * - * @param int $time 1: 24 hours, 2: no time limit - * @param int $echo 1: change the name, anything else: preview of what could have been changed. - * @param int $cats 1: other categories, 2: all categories - * @param $nameStatus - * @param $show - * @param NNTP $nntp - */ - public function fixNamesWithPar2($time, $echo, $cats, $nameStatus, $show, $nntp): void - { - $this->_echoStartMessage($time, 'par2 files'); - - if ($cats === 3) { - $query = sprintf(' + if ($cats === 3) { + $query = sprintf(' SELECT rel.id AS releases_id, rel.guid, rel.groups_id, rel.fromname FROM releases rel WHERE rel.nzbstatus = %d AND rel.predb_id = 0', NZB::NZB_ADDED ); - $cats = 2; - } else { - $query = sprintf(' + $cats = 2; + } else { + $query = sprintf(' SELECT rel.id AS releases_id, rel.guid, rel.groups_id, rel.fromname FROM releases rel WHERE rel.isrenamed = %d @@ -479,61 +477,60 @@ class NameFixer self::IS_RENAMED_NONE, self::PROC_PAR2_NONE ); - } + } - $releases = $this->_getReleases($time, $cats, $query); + $releases = $this->_getReleases($time, $cats, $query); - if ($releases instanceof \Traversable) { + if ($releases instanceof \Traversable) { + $total = $releases->rowCount(); + if ($total > 0) { + $this->_totalReleases = $total; - $total = $releases->rowCount(); - if ($total > 0) { - $this->_totalReleases = $total; - - echo ColorCLI::primary(number_format($total) . ' releases to process.'); - $Nfo = new Nfo(['Echo' => $this->echooutput, 'Settings' => $this->pdo]); - $nzbContents = new NZBContents( + echo ColorCLI::primary(number_format($total).' releases to process.'); + $Nfo = new Nfo(['Echo' => $this->echooutput, 'Settings' => $this->pdo]); + $nzbContents = new NZBContents( [ 'Echo' => $this->echooutput, 'NNTP' => $nntp, 'Nfo' => $Nfo, 'Settings' => $this->pdo, - 'PostProcess' => new PostProcess(['Settings' => $this->pdo, 'Nfo' => $Nfo]) + 'PostProcess' => new PostProcess(['Settings' => $this->pdo, 'Nfo' => $Nfo]), ] ); - foreach ($releases as $release) { - if ($nzbContents->checkPAR2($release['guid'], $release['releases_id'], $release['groups_id'], $nameStatus, $show) === true) { - $this->fixed++; - } + foreach ($releases as $release) { + if ($nzbContents->checkPAR2($release['guid'], $release['releases_id'], $release['groups_id'], $nameStatus, $show) === true) { + $this->fixed++; + } - $this->checked++; - $this->_echoRenamed($show); - } - $this->_echoFoundCount($echo, ' files'); - } else { - echo ColorCLI::alternate('Nothing to fix.'); - } - } - } + $this->checked++; + $this->_echoRenamed($show); + } + $this->_echoFoundCount($echo, ' files'); + } else { + echo ColorCLI::alternate('Nothing to fix.'); + } + } + } - /** - * Attempts to fix release names using the mediainfo xml Unique_ID. - * - * @param int $time 1: 24 hours, 2: no time limit - * @param boolean $echo 1: change the name, anything else: preview of what could have been changed. - * @param int $cats 1: other categories, 2: all categories - * @param $nameStatus - * @param $show - */ - public function fixNamesWithMedia($time, $echo, $cats, $nameStatus, $show): void - { - $type = 'UID, '; + /** + * Attempts to fix release names using the mediainfo xml Unique_ID. + * + * @param int $time 1: 24 hours, 2: no time limit + * @param bool $echo 1: change the name, anything else: preview of what could have been changed. + * @param int $cats 1: other categories, 2: all categories + * @param $nameStatus + * @param $show + */ + public function fixNamesWithMedia($time, $echo, $cats, $nameStatus, $show): void + { + $type = 'UID, '; - $this->_echoStartMessage($time, 'mediainfo Unique_IDs'); + $this->_echoStartMessage($time, 'mediainfo Unique_IDs'); - // Re-check all releases we haven't matched to a PreDB - if ($cats === 3) { - $query = sprintf(' + // Re-check all releases we haven't matched to a PreDB + if ($cats === 3) { + $query = sprintf(' SELECT rel.id AS releases_id, rel.size AS relsize, rel.groups_id, rel.fromname, rel.categories_id, rel.name, rel.name AS textstring, rel.predb_id, rel.searchname, @@ -545,10 +542,10 @@ class NameFixer AND rel.predb_id = 0', NZB::NZB_ADDED ); - $cats = 2; - // Otherwise check only releases we haven't renamed and checked uid before in Misc categories - } else { - $query = sprintf(' + $cats = 2; + // Otherwise check only releases we haven't renamed and checked uid before in Misc categories + } else { + $query = sprintf(' SELECT rel.id AS releases_id, rel.size AS relsize, rel.groups_id, rel.fromname, rel.categories_id, rel.name, rel.name AS textstring, rel.predb_id, rel.searchname, @@ -567,45 +564,45 @@ class NameFixer Category::OTHER_HASHED, self::PROC_UID_NONE ); - } + } - $releases = $this->_getReleases($time, $cats, $query); - if ($releases instanceof \Traversable) { - $total = $releases->rowCount(); - if ($total > 0) { - $this->_totalReleases = $total; - echo ColorCLI::primary(number_format($total) . ' unique ids to process.'); - foreach ($releases as $rel) { - $this->checked++; - $this->reset(); - $this->uidCheck($rel, $echo, $type, $nameStatus, $show); - $this->_echoRenamed($show); - } - $this->_echoFoundCount($echo, ' UID\'s'); - } else { - echo ColorCLI::info('Nothing to fix.'); - } - } - } + $releases = $this->_getReleases($time, $cats, $query); + if ($releases instanceof \Traversable) { + $total = $releases->rowCount(); + if ($total > 0) { + $this->_totalReleases = $total; + echo ColorCLI::primary(number_format($total).' unique ids to process.'); + foreach ($releases as $rel) { + $this->checked++; + $this->reset(); + $this->uidCheck($rel, $echo, $type, $nameStatus, $show); + $this->_echoRenamed($show); + } + $this->_echoFoundCount($echo, ' UID\'s'); + } else { + echo ColorCLI::info('Nothing to fix.'); + } + } + } - /** - * Attempts to fix release names using the par2 hash_16K block. - * - * @param int $time 1: 24 hours, 2: no time limit - * @param boolean $echo 1: change the name, anything else: preview of what could have been changed. - * @param int $cats 1: other categories, 2: all categories - * @param $nameStatus - * @param $show - */ - public function fixNamesWithParHash($time, $echo, $cats, $nameStatus, $show): void - { - $type = 'PAR2 hash, '; + /** + * Attempts to fix release names using the par2 hash_16K block. + * + * @param int $time 1: 24 hours, 2: no time limit + * @param bool $echo 1: change the name, anything else: preview of what could have been changed. + * @param int $cats 1: other categories, 2: all categories + * @param $nameStatus + * @param $show + */ + public function fixNamesWithParHash($time, $echo, $cats, $nameStatus, $show): void + { + $type = 'PAR2 hash, '; - $this->_echoStartMessage($time, 'PAR2 hash_16K'); + $this->_echoStartMessage($time, 'PAR2 hash_16K'); - // Re-check all releases we haven't matched to a PreDB - if ($cats === 3) { - $query = sprintf(' + // Re-check all releases we haven't matched to a PreDB + if ($cats === 3) { + $query = sprintf(' SELECT rel.id AS releases_id, rel.size AS relsize, rel.groups_id, rel.fromname, rel.categories_id, rel.name, rel.name AS textstring, rel.predb_id, rel.searchname, @@ -616,10 +613,10 @@ class NameFixer AND rel.predb_id = 0', NZB::NZB_ADDED ); - $cats = 2; - // Otherwise check only releases we haven't renamed and checked their par2 hash_16K before in Misc categories - } else { - $query = sprintf(' + $cats = 2; + // Otherwise check only releases we haven't renamed and checked their par2 hash_16K before in Misc categories + } else { + $query = sprintf(' SELECT rel.id AS releases_id, rel.size AS relsize, rel.groups_id, rel.fromname, rel.categories_id, rel.name, rel.name AS textstring, rel.predb_id, rel.searchname, @@ -637,206 +634,205 @@ class NameFixer Category::OTHER_HASHED, self::PROC_HASH16K_NONE ); - } + } - $releases = $this->_getReleases($time, $cats, $query); + $releases = $this->_getReleases($time, $cats, $query); - if ($releases instanceof \Traversable) { - $total = $releases->rowCount(); - if ($total > 0) { - $this->_totalReleases = $total; - echo ColorCLI::primary(number_format($total) . ' hash_16K to process.'); - foreach ($releases as $rel) { - $this->checked++; - $this->reset(); - $this->hashCheck($rel, $echo, $type, $nameStatus, $show); - $this->_echoRenamed($show); - } - $this->_echoFoundCount($echo, ' hashes'); - } else { - echo ColorCLI::info('Nothing to fix.'); - } - } - } + if ($releases instanceof \Traversable) { + $total = $releases->rowCount(); + if ($total > 0) { + $this->_totalReleases = $total; + echo ColorCLI::primary(number_format($total).' hash_16K to process.'); + foreach ($releases as $rel) { + $this->checked++; + $this->reset(); + $this->hashCheck($rel, $echo, $type, $nameStatus, $show); + $this->_echoRenamed($show); + } + $this->_echoFoundCount($echo, ' hashes'); + } else { + echo ColorCLI::info('Nothing to fix.'); + } + } + } - /** - * @param int $time 1: 24 hours, 2: no time limit - * @param int $cats 1: other categories, 2: all categories - * @param string $query Query to execute. - * - * @param string $limit limit defined by maxperrun - * - * @return bool|\PDOStatement False on failure, PDOStatement with query results on success. - */ - protected function _getReleases($time, $cats, $query, $limit = '') - { - $releases = false; - $queryLimit = ($limit === '') ? '' : ' LIMIT ' . $limit; - // 24 hours, other cats - if ($time === 1 && $cats === 1) { - echo ColorCLI::header($query . $this->timeother . $queryLimit . ";\n"); - $releases = $this->pdo->queryDirect($query . $this->timeother . $queryLimit); - } // 24 hours, all cats - if ($time === 1 && $cats === 2) { - echo ColorCLI::header($query . $this->timeall . $queryLimit . ";\n"); - $releases = $this->pdo->queryDirect($query . $this->timeall . $queryLimit); - } //other cats - if ($time === 2 && $cats === 1) { - echo ColorCLI::header($query . $this->fullother . $queryLimit . ";\n"); - $releases = $this->pdo->queryDirect($query . $this->fullother . $queryLimit); - } // all cats - if ($time === 2 && $cats === 2) { - echo ColorCLI::header($query . $this->fullall . $queryLimit . ";\n"); - $releases = $this->pdo->queryDirect($query . $this->fullall . $queryLimit); - } + /** + * @param int $time 1: 24 hours, 2: no time limit + * @param int $cats 1: other categories, 2: all categories + * @param string $query Query to execute. + * + * @param string $limit limit defined by maxperrun + * + * @return bool|\PDOStatement False on failure, PDOStatement with query results on success. + */ + protected function _getReleases($time, $cats, $query, $limit = '') + { + $releases = false; + $queryLimit = ($limit === '') ? '' : ' LIMIT '.$limit; + // 24 hours, other cats + if ($time === 1 && $cats === 1) { + echo ColorCLI::header($query.$this->timeother.$queryLimit.";\n"); + $releases = $this->pdo->queryDirect($query.$this->timeother.$queryLimit); + } // 24 hours, all cats + if ($time === 1 && $cats === 2) { + echo ColorCLI::header($query.$this->timeall.$queryLimit.";\n"); + $releases = $this->pdo->queryDirect($query.$this->timeall.$queryLimit); + } //other cats + if ($time === 2 && $cats === 1) { + echo ColorCLI::header($query.$this->fullother.$queryLimit.";\n"); + $releases = $this->pdo->queryDirect($query.$this->fullother.$queryLimit); + } // all cats + if ($time === 2 && $cats === 2) { + echo ColorCLI::header($query.$this->fullall.$queryLimit.";\n"); + $releases = $this->pdo->queryDirect($query.$this->fullall.$queryLimit); + } - return $releases; - } + return $releases; + } - /** - * Echo the amount of releases that found a new name. - * - * @param int $echo 1: change the name, anything else: preview of what could have been changed. - * @param string $type The function type that found the name. - */ - protected function _echoFoundCount($echo, $type): void - { - if ($echo === true) { - echo ColorCLI::header( - PHP_EOL . - number_format($this->fixed) . - ' releases have had their names changed out of: ' . - number_format($this->checked) . - $type . '.' + /** + * Echo the amount of releases that found a new name. + * + * @param int $echo 1: change the name, anything else: preview of what could have been changed. + * @param string $type The function type that found the name. + */ + protected function _echoFoundCount($echo, $type): void + { + if ($echo === true) { + echo ColorCLI::header( + PHP_EOL. + number_format($this->fixed). + ' releases have had their names changed out of: '. + number_format($this->checked). + $type.'.' ); - } else { - echo ColorCLI::header( - PHP_EOL . - number_format($this->fixed) . - ' releases could have their names changed. ' . - number_format($this->checked) . - $type . ' were checked.' + } else { + echo ColorCLI::header( + PHP_EOL. + number_format($this->fixed). + ' releases could have their names changed. '. + number_format($this->checked). + $type.' were checked.' ); - } - } + } + } - /** - * @param int $time 1: 24 hours, 2: no time limit - * @param string $type The function type. - */ - protected function _echoStartMessage($time, $type): void - { - echo ColorCLI::header( + /** + * @param int $time 1: 24 hours, 2: no time limit + * @param string $type The function type. + */ + protected function _echoStartMessage($time, $type): void + { + echo ColorCLI::header( sprintf( 'Fixing search names %s using %s.', ($time === 1 ? 'in the past 6 hours' : 'since the beginning'), $type ) ); + } - } + /** + * @param int $show + */ + protected function _echoRenamed($show): void + { + if ($this->checked % 500 === 0 && $show === 1) { + echo ColorCLI::alternate(PHP_EOL.number_format($this->checked).' files processed.'.PHP_EOL); + } - /** - * @param int $show - */ - protected function _echoRenamed($show): void - { - if ($this->checked % 500 === 0 && $show === 1) { - echo ColorCLI::alternate(PHP_EOL . number_format($this->checked) . ' files processed.' . PHP_EOL); - } - - if ($show === 2) { - $this->consoletools->overWritePrimary( - 'Renamed Releases: [' . - number_format($this->fixed) . - '] ' . + if ($show === 2) { + $this->consoletools->overWritePrimary( + 'Renamed Releases: ['. + number_format($this->fixed). + '] '. $this->consoletools->percentString($this->checked, $this->_totalReleases) ); - } - } + } + } - /** - * Update the release with the new information. - * - * @param array $release - * @param string $name - * @param string $method - * @param boolean $echo - * @param string $type - * @param int $nameStatus - * @param int $show - * @param int $preId - */ - public function updateRelease($release, $name, $method, $echo, $type, int $nameStatus, int $show, int $preId = 0): void - { - $release['releases_id'] = $release['releases_id'] ?? $release['releaseid']; - if ($this->relid !== (int)$release['releases_id']) { - $releaseCleaning = new ReleaseCleaning($this->pdo); - $newName = $releaseCleaning->fixerCleaner($name); - if (strtolower($newName) !== strtolower($release['searchname'])) { - $this->matched = true; - $this->relid = (int)$release['releases_id']; + /** + * Update the release with the new information. + * + * @param array $release + * @param string $name + * @param string $method + * @param bool $echo + * @param string $type + * @param int $nameStatus + * @param int $show + * @param int $preId + */ + public function updateRelease($release, $name, $method, $echo, $type, int $nameStatus, int $show, int $preId = 0): void + { + $release['releases_id'] = $release['releases_id'] ?? $release['releaseid']; + if ($this->relid !== (int) $release['releases_id']) { + $releaseCleaning = new ReleaseCleaning($this->pdo); + $newName = $releaseCleaning->fixerCleaner($name); + if (strtolower($newName) !== strtolower($release['searchname'])) { + $this->matched = true; + $this->relid = (int) $release['releases_id']; - $determinedCategory = $this->category->determineCategory($release['groups_id'], $newName, !empty($release['fromname']) ? $release['fromname'] : ''); + $determinedCategory = $this->category->determineCategory($release['groups_id'], $newName, ! empty($release['fromname']) ? $release['fromname'] : ''); - if ($type === 'PAR2, ') { - $newName = ucwords($newName); - if (preg_match('/(.+?)\.[a-z0-9]{2,3}(PAR2)?$/i', $name, $match)) { - $newName = $match[1]; - } - } + if ($type === 'PAR2, ') { + $newName = ucwords($newName); + if (preg_match('/(.+?)\.[a-z0-9]{2,3}(PAR2)?$/i', $name, $match)) { + $newName = $match[1]; + } + } - $this->fixed++; + $this->fixed++; - if(!empty($release['fromname']) && (preg_match('/oz@lot[.]com/i', $release['fromname']) || preg_match('/anon@y[.]com/i', $release['fromname']))) { - $newName = preg_replace('/(KTR|GUSH|BIUK|WEIRD)$/', 'SDCLiP', $newName); - } - $newName = explode("\\", $newName); - $newName = preg_replace(['/^[-=_\.:\s]+/', '/[-=_\.:\s]+$/'], '', $newName[0]); + if (! empty($release['fromname']) && (preg_match('/oz@lot[.]com/i', $release['fromname']) || preg_match('/anon@y[.]com/i', $release['fromname']))) { + $newName = preg_replace('/(KTR|GUSH|BIUK|WEIRD)$/', 'SDCLiP', $newName); + } + $newName = explode('\\', $newName); + $newName = preg_replace(['/^[-=_\.:\s]+/', '/[-=_\.:\s]+$/'], '', $newName[0]); - if ($this->echooutput === true && $show === 1) { - $groupName = $this->_groups->getNameByID($release['groups_id']); - $oldCatName = $this->category->getNameByID($release['categories_id']); - $newCatName = $this->category->getNameByID($determinedCategory); + if ($this->echooutput === true && $show === 1) { + $groupName = $this->_groups->getNameByID($release['groups_id']); + $oldCatName = $this->category->getNameByID($release['categories_id']); + $newCatName = $this->category->getNameByID($determinedCategory); - if ($type === 'PAR2, ') { - echo PHP_EOL; - } + if ($type === 'PAR2, ') { + echo PHP_EOL; + } - echo - ColorCLI::headerOver(PHP_EOL . 'New name: ') . - ColorCLI::primary(substr($newName, 0, 299)) . - ColorCLI::headerOver('Old name: ') . - ColorCLI::primary($release['searchname']) . - ColorCLI::headerOver('Use name: ') . - ColorCLI::primary($release['name']) . - ColorCLI::headerOver('New cat: ') . - ColorCLI::primary($newCatName) . - ColorCLI::headerOver('Old cat: ') . - ColorCLI::primary($oldCatName) . - ColorCLI::headerOver('Group: ') . - ColorCLI::primary($groupName) . - ColorCLI::headerOver('Method: ') . - ColorCLI::primary($type . $method) . - ColorCLI::headerOver('Releases ID: ') . + echo + ColorCLI::headerOver(PHP_EOL.'New name: '). + ColorCLI::primary(substr($newName, 0, 299)). + ColorCLI::headerOver('Old name: '). + ColorCLI::primary($release['searchname']). + ColorCLI::headerOver('Use name: '). + ColorCLI::primary($release['name']). + ColorCLI::headerOver('New cat: '). + ColorCLI::primary($newCatName). + ColorCLI::headerOver('Old cat: '). + ColorCLI::primary($oldCatName). + ColorCLI::headerOver('Group: '). + ColorCLI::primary($groupName). + ColorCLI::headerOver('Method: '). + ColorCLI::primary($type.$method). + ColorCLI::headerOver('Releases ID: '). ColorCLI::primary($release['releases_id']); - if (!empty($release['filename'])) { - echo - ColorCLI::headerOver('Filename: ') . + if (! empty($release['filename'])) { + echo + ColorCLI::headerOver('Filename: '). ColorCLI::primary($release['filename']); - } + } - if ($type !== 'PAR2, ') { - echo PHP_EOL; - } - } + if ($type !== 'PAR2, ') { + echo PHP_EOL; + } + } - $newTitle = $this->pdo->escapeString(substr($newName, 0, 299)); + $newTitle = $this->pdo->escapeString(substr($newName, 0, 299)); - if ($echo === true) { - if ($nameStatus === 1) { - $status = ''; - switch ($type) { + if ($echo === true) { + if ($nameStatus === 1) { + $status = ''; + switch ($type) { case 'NFO, ': $status = 'isrenamed = 1, iscategorized = 1, proc_nfo = 1,'; break; @@ -867,7 +863,7 @@ class NameFixer $status = 'isrenamed = 1, iscategorized = 1, proc_srr = 1,'; break; } - $this->pdo->queryExec( + $this->pdo->queryExec( sprintf(' UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, @@ -881,10 +877,10 @@ class NameFixer $release['releases_id'] ) ); - $this->sphinx->updateRelease($release['releases_id'], $this->pdo); - } else { - $newTitle = $this->pdo->escapeString(substr($newName, 0, 299)); - $this->pdo->queryExec( + $this->sphinx->updateRelease($release['releases_id'], $this->pdo); + } else { + $newTitle = $this->pdo->escapeString(substr($newName, 0, 299)); + $this->pdo->queryExec( sprintf(' UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, @@ -897,33 +893,32 @@ class NameFixer $release['releases_id'] ) ); - $this->sphinx->updateRelease($release['releases_id'], $this->pdo); - } - } - } - } - $this->done = true; - } + $this->sphinx->updateRelease($release['releases_id'], $this->pdo); + } + } + } + } + $this->done = true; + } - /** - * Echo a updated release name to CLI. - * - * @param array $data - * array( - * 'new_name' => (string) The new release search name. - * 'old_name' => (string) The old release search name. - * 'new_category' => (string) The new category name or ID for the release. - * 'old_category' => (string) The old category name or ID for the release. - * 'group' => (string) The group name or ID of the release. - * 'release_id' => (int) The ID of the release. - * 'method' => (string) The method used to rename the release. - * ) - * - * @access public - * @static - * @void - */ - public static function echoChangedReleaseName(array $data = + /** + * Echo a updated release name to CLI. + * + * @param array $data + * array( + * 'new_name' => (string) The new release search name. + * 'old_name' => (string) The old release search name. + * 'new_category' => (string) The new category name or ID for the release. + * 'old_category' => (string) The old category name or ID for the release. + * 'group' => (string) The group name or ID of the release. + * 'release_id' => (int) The ID of the release. + * 'method' => (string) The method used to rename the release. + * ) + * + * @static + * @void + */ + public static function echoChangedReleaseName(array $data = [ 'new_name' => '', 'old_name' => '', @@ -931,89 +926,87 @@ class NameFixer 'old_category' => '', 'group' => '', 'releases_id' => 0, - 'method' => '' + 'method' => '', ] - ): void - { - echo - PHP_EOL . - ColorCLI::headerOver('New name: ') . ColorCLI::primaryOver($data['new_name']) . PHP_EOL . - ColorCLI::headerOver('Old name: ') . ColorCLI::primaryOver($data['old_name']) . PHP_EOL . - ColorCLI::headerOver('New category: ') . ColorCLI::primaryOver($data['new_category']) . PHP_EOL . - ColorCLI::headerOver('Old category: ') . ColorCLI::primaryOver($data['old_category']) . PHP_EOL . - ColorCLI::headerOver('Group: ') . ColorCLI::primaryOver($data['group']) . PHP_EOL . - ColorCLI::headerOver('Releases ID: ') . ColorCLI::primaryOver($data['releases_id']) . PHP_EOL . - ColorCLI::headerOver('Method: ') . ColorCLI::primaryOver($data['method']) . PHP_EOL; - } + ): void { + echo + PHP_EOL. + ColorCLI::headerOver('New name: ').ColorCLI::primaryOver($data['new_name']).PHP_EOL. + ColorCLI::headerOver('Old name: ').ColorCLI::primaryOver($data['old_name']).PHP_EOL. + ColorCLI::headerOver('New category: ').ColorCLI::primaryOver($data['new_category']).PHP_EOL. + ColorCLI::headerOver('Old category: ').ColorCLI::primaryOver($data['old_category']).PHP_EOL. + ColorCLI::headerOver('Group: ').ColorCLI::primaryOver($data['group']).PHP_EOL. + ColorCLI::headerOver('Releases ID: ').ColorCLI::primaryOver($data['releases_id']).PHP_EOL. + ColorCLI::headerOver('Method: ').ColorCLI::primaryOver($data['method']).PHP_EOL; + } - /** - * Match a PreDB title to a release name or searchname using an exact full-text match - * @param $pre - * @param $echo - * @param $namestatus - * @param $echooutput - * @param $show - * - * @return int - */ - public function matchPredbFT($pre, $echo, $namestatus, $echooutput, $show): int - { - $matching = $total = 0; + /** + * Match a PreDB title to a release name or searchname using an exact full-text match. + * @param $pre + * @param $echo + * @param $namestatus + * @param $echooutput + * @param $show + * + * @return int + */ + public function matchPredbFT($pre, $echo, $namestatus, $echooutput, $show): int + { + $matching = $total = 0; - $join = $this->_preFTsearchQuery($pre['title']); + $join = $this->_preFTsearchQuery($pre['title']); - if ($join === '') { + if ($join === '') { + return $matching; + } - return $matching; - } - - //Find release matches with fulltext and then identify exact matches with cleaned LIKE string - $res = $this->pdo->queryDirect( - sprintf(" + //Find release matches with fulltext and then identify exact matches with cleaned LIKE string + $res = $this->pdo->queryDirect( + sprintf(' SELECT r.id AS releases_id, r.name, r.searchname, r.fromname, r.groups_id, r.categories_id FROM releases r - %1\$s - AND (r.name %2\$s OR r.searchname %2\$s) + %1$s + AND (r.name %2$s OR r.searchname %2$s) AND r.predb_id = 0 - LIMIT 21", + LIMIT 21', $join, $this->pdo->likeString($pre['title'], true, true) ) ); - if ($res !== false) { - $total = $res->rowCount(); - } + if ($res !== false) { + $total = $res->rowCount(); + } - // Run if row count is positive, but do not run if row count exceeds 10 (as this is likely a failed title match) - if ($total > 0 && $total <= 15 && $res instanceof \Traversable) { - foreach ($res as $row) { - if ($pre['title'] !== $row['searchname']) { - $this->updateRelease($row, $pre['title'], $method = 'Title Match source: ' . $pre['source'], $echo, 'PreDB FT Exact, ', $namestatus, $show, $pre['predb_id']); - $matching++; - } else { - $this->_updateSingleColumn('predb_id', $pre['predb_id'], $row['releases_id']); - } - } - } elseif ($total >= 16) { - $matching = -1; - } + // Run if row count is positive, but do not run if row count exceeds 10 (as this is likely a failed title match) + if ($total > 0 && $total <= 15 && $res instanceof \Traversable) { + foreach ($res as $row) { + if ($pre['title'] !== $row['searchname']) { + $this->updateRelease($row, $pre['title'], $method = 'Title Match source: '.$pre['source'], $echo, 'PreDB FT Exact, ', $namestatus, $show, $pre['predb_id']); + $matching++; + } else { + $this->_updateSingleColumn('predb_id', $pre['predb_id'], $row['releases_id']); + } + } + } elseif ($total >= 16) { + $matching = -1; + } - return $matching; - } + return $matching; + } - /** - * @param $preTitle - * - * @return string - */ - protected function _preFTsearchQuery($preTitle): string - { - $join = ''; + /** + * @param $preTitle + * + * @return string + */ + protected function _preFTsearchQuery($preTitle): string + { + $join = ''; - if (strlen($preTitle) >= 15 && preg_match(self::PREDB_REGEX, $preTitle)) { - switch (NN_RELEASE_SEARCH_TYPE) { + if (strlen($preTitle) >= 15 && preg_match(self::PREDB_REGEX, $preTitle)) { + switch (NN_RELEASE_SEARCH_TYPE) { case ReleaseSearch::SPHINX: $titlematch = SphinxSearch::escapeString($preTitle); $join .= sprintf( @@ -1025,7 +1018,7 @@ class NameFixer case ReleaseSearch::FULLTEXT: //Remove all non-printable chars from PreDB title preg_match_all('#[a-zA-Z0-9]{3,}#', $preTitle, $matches, PREG_PATTERN_ORDER); - $titlematch = '+' . implode(' +', $matches[0]); + $titlematch = '+'.implode(' +', $matches[0]); $join .= sprintf( "INNER JOIN release_search_data rs ON rs.releases_id = r.id WHERE @@ -1039,39 +1032,40 @@ class NameFixer $join .= 'WHERE 1=1 '; break; } - } - return $join; - } + } - /** - * Retrieves releases and their file names to attempt PreDB matches - * Runs in a limited mode based on arguments passed or a full mode broken into chunks of entire DB - * - * @param array $args The CLI script arguments - */ - public function getPreFileNames(array $args = []): void - { - $n = PHP_EOL; + return $join; + } - $show = (isset($args[2]) && $args[2] === 'show') ? 1 : 0; + /** + * Retrieves releases and their file names to attempt PreDB matches + * Runs in a limited mode based on arguments passed or a full mode broken into chunks of entire DB. + * + * @param array $args The CLI script arguments + */ + public function getPreFileNames(array $args = []): void + { + $n = PHP_EOL; - if (isset($args[1]) && is_numeric($args[1])) { - $limit = 'LIMIT ' . $args[1]; - $orderby = 'ORDER BY r.id DESC'; - } else { - $maxrelid = 0; - $orderby = 'ORDER BY r.id ASC'; - $limit = 'LIMIT 1000000'; - } + $show = (isset($args[2]) && $args[2] === 'show') ? 1 : 0; - echo ColorCLI::header(PHP_EOL . 'Match PreFiles ' . $args[1] . ' Started at ' . date('g:i:s')); - echo ColorCLI::primary('Matching predb filename to cleaned release_files.name.' . PHP_EOL); + if (isset($args[1]) && is_numeric($args[1])) { + $limit = 'LIMIT '.$args[1]; + $orderby = 'ORDER BY r.id DESC'; + } else { + $maxrelid = 0; + $orderby = 'ORDER BY r.id ASC'; + $limit = 'LIMIT 1000000'; + } - do { - $counter = $counted = 0; - $timestart = time(); + echo ColorCLI::header(PHP_EOL.'Match PreFiles '.$args[1].' Started at '.date('g:i:s')); + echo ColorCLI::primary('Matching predb filename to cleaned release_files.name.'.PHP_EOL); - $query = $this->pdo->queryDirect( + do { + $counter = $counted = 0; + $timestart = time(); + + $query = $this->pdo->queryDirect( sprintf(" SELECT r.id AS releases_id, r.name, r.searchname, r.fromname, r.groups_id, r.categories_id, @@ -1089,67 +1083,67 @@ class NameFixer ) ); - if ($query !== false) { - $total = $query->rowCount(); + if ($query !== false) { + $total = $query->rowCount(); - if ($total > 0 && $query instanceof \Traversable) { - echo ColorCLI::header($n . number_format($total) . ' releases to process.'); + if ($total > 0 && $query instanceof \Traversable) { + echo ColorCLI::header($n.number_format($total).' releases to process.'); - foreach ($query as $row) { - $success = $this->matchPredbFiles($row, true, 1, true, $show); - if ($success === 1) { - $counted++; - } - if ($show === 0) { - $this->consoletools->overWritePrimary('Renamed Releases: [' . number_format($counted) . '] ' . $this->consoletools->percentString(++$counter, $total)); - } - if (isset($maxrelid) && $row['releases_id'] > $maxrelid) { - $maxrelid = $row['releases_id']; - } - } - echo ColorCLI::header($n . 'Renamed ' . number_format($counted) . ' releases in ' . $this->consoletools->convertTime(time() - $timestart) . '.'); - } else { - echo ColorCLI::info($n . 'Nothing to do.'); - break; - } - } else { - break; - } - } while (isset($maxrelid)); - } + foreach ($query as $row) { + $success = $this->matchPredbFiles($row, true, 1, true, $show); + if ($success === 1) { + $counted++; + } + if ($show === 0) { + $this->consoletools->overWritePrimary('Renamed Releases: ['.number_format($counted).'] '.$this->consoletools->percentString(++$counter, $total)); + } + if (isset($maxrelid) && $row['releases_id'] > $maxrelid) { + $maxrelid = $row['releases_id']; + } + } + echo ColorCLI::header($n.'Renamed '.number_format($counted).' releases in '.$this->consoletools->convertTime(time() - $timestart).'.'); + } else { + echo ColorCLI::info($n.'Nothing to do.'); + break; + } + } else { + break; + } + } while (isset($maxrelid)); + } - /** - * Match a release filename to a PreDB filename or title. - * - * @param $release - * @param boolean $echo - * @param integer $namestatus - * @param boolean $echooutput - * @param integer $show - * - * @return int - */ - public function matchPredbFiles($release, $echo, $namestatus, $echooutput, $show): int - { - $matching = 0; - $pre = false; + /** + * Match a release filename to a PreDB filename or title. + * + * @param $release + * @param bool $echo + * @param int $namestatus + * @param bool $echooutput + * @param int $show + * + * @return int + */ + public function matchPredbFiles($release, $echo, $namestatus, $echooutput, $show): int + { + $matching = 0; + $pre = false; - foreach(explode('||', $release['filename']) AS $key => $fileName) { - $this->_fileName = $fileName; - $this->_cleanMatchFiles(); - $preMatch = preg_match('/(\d{2}\.\d{2}\.\d{2})+[\w-.]+[\w]$/i', $this->_fileName, $match); - if ($preMatch) { - $result = $this->pdo->queryOneRow(sprintf("SELECT filename AS filename FROM predb WHERE MATCH(filename) AGAINST ('$match[0]' IN BOOLEAN MODE)")); - $preFTmatch = preg_match('/(\d{2}\.\d{2}\.\d{2})+[\w-.]+[\w]$/i', $result['filename'], $match1); - if ($preFTmatch) { - if ($match[0] === $match1[0]) { - $this->_fileName = $result['filename']; - } - } - } + foreach (explode('||', $release['filename']) as $key => $fileName) { + $this->_fileName = $fileName; + $this->_cleanMatchFiles(); + $preMatch = preg_match('/(\d{2}\.\d{2}\.\d{2})+[\w-.]+[\w]$/i', $this->_fileName, $match); + if ($preMatch) { + $result = $this->pdo->queryOneRow(sprintf("SELECT filename AS filename FROM predb WHERE MATCH(filename) AGAINST ('$match[0]' IN BOOLEAN MODE)")); + $preFTmatch = preg_match('/(\d{2}\.\d{2}\.\d{2})+[\w-.]+[\w]$/i', $result['filename'], $match1); + if ($preFTmatch) { + if ($match[0] === $match1[0]) { + $this->_fileName = $result['filename']; + } + } + } - if ($this->_fileName !== '') { - $pre = $this->pdo->queryOneRow( + if ($this->_fileName !== '') { + $pre = $this->pdo->queryOneRow( sprintf(' SELECT id AS predb_id, title, source FROM predb @@ -1158,36 +1152,37 @@ class NameFixer $this->pdo->escapeString($this->_fileName) ) ); - } + } - if (!empty($pre)) { - $release['filename'] = $this->_fileName; - if ($pre['title'] !== $release['searchname']) { - $this->updateRelease($release, $pre['title'], $method = 'file matched source: ' . $pre['source'], $echo, 'PreDB file match, ', $namestatus, $show, $pre['predb_id']); - } else { - $this->_updateSingleColumn('predb_id', $pre['predb_id'], $release['releases_id']); - } - $matching++; - break; - } - } - return $matching; - } + if (! empty($pre)) { + $release['filename'] = $this->_fileName; + if ($pre['title'] !== $release['searchname']) { + $this->updateRelease($release, $pre['title'], $method = 'file matched source: '.$pre['source'], $echo, 'PreDB file match, ', $namestatus, $show, $pre['predb_id']); + } else { + $this->_updateSingleColumn('predb_id', $pre['predb_id'], $release['releases_id']); + } + $matching++; + break; + } + } - /** - * Cleans file names for PreDB Match - * - * - * @return string - */ - protected function _cleanMatchFiles(): string - { + return $matching; + } + + /** + * Cleans file names for PreDB Match. + * + * + * @return string + */ + protected function _cleanMatchFiles(): string + { // first strip all non-printing chars from filename - $this->_fileName = Utility::stripNonPrintingChars($this->_fileName); + $this->_fileName = Utility::stripNonPrintingChars($this->_fileName); - if (strlen($this->_fileName) > 0 && strpos($this->_fileName, '.') !== 0) { - switch (true) { + if (strlen($this->_fileName) > 0 && strpos($this->_fileName, '.') !== 0) { + switch (true) { case strpos($this->_fileName, '.') !== false: //some filenames start with a period that ends up creating bad matches so we don't process them @@ -1215,37 +1210,38 @@ class NameFixer $this->_fileName = preg_replace('/^\d{2}-/', '', $this->_fileName); } - return trim($this->_fileName); - } - return false; - } + return trim($this->_fileName); + } - /** - * Match a Hash from the predb to a release. - * - * @param string $hash - * @param $release - * @param $echo - * @param $namestatus - * @param boolean $echooutput - * @param $show - * - * @return int - */ - public function matchPredbHash($hash, $release, $echo, $namestatus, $echooutput, $show): int - { - $pdo = $this->pdo; - $matching = 0; - $this->matched = false; + return false; + } - // Determine MD5 or SHA1 - if (strlen($hash) === 40) { - $hashtype = 'SHA1, '; - } else { - $hashtype = 'MD5, '; - } + /** + * Match a Hash from the predb to a release. + * + * @param string $hash + * @param $release + * @param $echo + * @param $namestatus + * @param bool $echooutput + * @param $show + * + * @return int + */ + public function matchPredbHash($hash, $release, $echo, $namestatus, $echooutput, $show): int + { + $pdo = $this->pdo; + $matching = 0; + $this->matched = false; - $row = $pdo->queryOneRow( + // Determine MD5 or SHA1 + if (strlen($hash) === 40) { + $hashtype = 'SHA1, '; + } else { + $hashtype = 'MD5, '; + } + + $row = $pdo->queryOneRow( sprintf(' SELECT p.id AS predb_id, p.title, p.source FROM predb p INNER JOIN predb_hashes h ON h.predb_id = p.id @@ -1255,49 +1251,48 @@ class NameFixer ) ); - if ($row !== false) { - if ($row['title'] !== $release['searchname']) { - $this->updateRelease($release, $row['title'], $method = 'predb hash release name: ' . $row['source'], $echo, $hashtype, $namestatus, $show, $row['predb_id']); - $matching++; - } - } else { - $this->_updateSingleColumn('dehashstatus', $release['dehashstatus'] - 1, $release['releases_id']); - } + if ($row !== false) { + if ($row['title'] !== $release['searchname']) { + $this->updateRelease($release, $row['title'], $method = 'predb hash release name: '.$row['source'], $echo, $hashtype, $namestatus, $show, $row['predb_id']); + $matching++; + } + } else { + $this->_updateSingleColumn('dehashstatus', $release['dehashstatus'] - 1, $release['releases_id']); + } - return $matching; - } + return $matching; + } - /** - * Check the array using regex for a clean name. - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - * @param boolean $preid - * - * @return boolean - */ - public function checkName($release, $echo, $type, $namestatus, $show, $preid = false): bool - { - // Get pre style name from releases.name - if (preg_match_all(self::PREDB_REGEX, $release['textstring'], $matches) && !preg_match('/Source\s\:/i', $release['textstring'])) { - foreach ($matches as $match) { - foreach ($match as $val) { - $title = $this->pdo->queryOneRow('SELECT title, id from predb WHERE title = ' . $this->pdo->escapeString(trim($val))); - if ($title !== false) { - $this->updateRelease($release, $title['title'], $method = 'preDB: Match', $echo, $type, $namestatus, $show, $title['id']); - $preid = true; - } - } - } - } + /** + * Check the array using regex for a clean name. + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + * @param bool $preid + * + * @return bool + */ + public function checkName($release, $echo, $type, $namestatus, $show, $preid = false): bool + { + // Get pre style name from releases.name + if (preg_match_all(self::PREDB_REGEX, $release['textstring'], $matches) && ! preg_match('/Source\s\:/i', $release['textstring'])) { + foreach ($matches as $match) { + foreach ($match as $val) { + $title = $this->pdo->queryOneRow('SELECT title, id from predb WHERE title = '.$this->pdo->escapeString(trim($val))); + if ($title !== false) { + $this->updateRelease($release, $title['title'], $method = 'preDB: Match', $echo, $type, $namestatus, $show, $title['id']); + $preid = true; + } + } + } + } - // if only processing for PreDB match skip to return - if ($preid !== true) { - - switch ($type) { + // if only processing for PreDB match skip to return + if ($preid !== true) { + switch ($type) { case 'PAR2, ': $this->fileCheck($release, $echo, $type, $namestatus, $show); break; @@ -1327,9 +1322,9 @@ class NameFixer $this->appCheck($release, $echo, $type, $namestatus, $show); } - // set NameFixer process flags after run - if ($namestatus === 1 && $this->matched === false) { - switch ($type) { + // set NameFixer process flags after run + if ($namestatus === 1 && $this->matched === false) { + switch ($type) { case 'NFO, ': $this->_updateSingleColumn('proc_nfo', self::PROC_NFO_DONE, $release['releases_id']); break; @@ -1349,24 +1344,24 @@ class NameFixer $this->_updateSingleColumn('proc_uid', self::PROC_UID_DONE, $release['releases_id']); break; } - } - } + } + } - return $this->matched; - } + return $this->matched; + } - /** This function updates a single variable column in releases - * The first parameter is the column to update, the second is the value - * The final parameter is the ID of the release to update - * - * @param string $column - * @param integer $status - * @param integer $id - */ - public function _updateSingleColumn($column = '', $status = 0, $id = 0): void - { - if ($column !== '' && $id !== 0) { - $this->pdo->queryExec( + /** This function updates a single variable column in releases + * The first parameter is the column to update, the second is the value + * The final parameter is the ID of the release to update. + * + * @param string $column + * @param int $status + * @param int $id + */ + public function _updateSingleColumn($column = '', $status = 0, $id = 0): void + { + if ($column !== '' && $id !== 0) { + $this->pdo->queryExec( sprintf(' UPDATE releases SET %s = %s @@ -1376,226 +1371,220 @@ class NameFixer $id ) ); - } - } + } + } - /** - * Look for a TV name. - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - */ - public function tvCheck($release, $echo, $type, $namestatus, $show): void - { - $result = []; + /** + * Look for a TV name. + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + */ + public function tvCheck($release, $echo, $type, $namestatus, $show): void + { + $result = []; - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|(?<!\d)[S|]\d{1,2}[E|x]\d{1,}(?!\d)|ep[._ -]?\d{2})[-\w.\',;.()]+(BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -][-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.source.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[-\w.\',;& ]+((19|20)\d\d)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.year.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[-\w.\',;& ]+(480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.resolution.source.vcodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.source.vcodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.acodec.source.res.vcodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -]((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.year.###(season/episode).source.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w(19|20)\d\d[._ -]\d{2}[._ -]\d{2}[._ -](IndyCar|NBA|NCW(T|Y)S|NNS|NSCS?)([._ -](19|20)\d\d)?[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'tvCheck: Sports', $echo, $type, $namestatus, $show); + } + } + } - if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|(?<!\d)[S|]\d{1,2}[E|x]\d{1,}(?!\d)|ep[._ -]?\d{2})[-\w.\',;.()]+(BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -][-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.source.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[-\w.\',;& ]+((19|20)\d\d)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.year.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[-\w.\',;& ]+(480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.resolution.source.vcodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.source.vcodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.acodec.source.res.vcodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -]((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.year.###(season/episode).source.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w(19|20)\d\d[._ -]\d{2}[._ -]\d{2}[._ -](IndyCar|NBA|NCW(T|Y)S|NNS|NSCS?)([._ -](19|20)\d\d)?[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'tvCheck: Sports', $echo, $type, $namestatus, $show); - } - } - } + /** + * Look for a movie name. + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + */ + public function movieCheck($release, $echo, $type, $namestatus, $show): void + { + $result = []; - /** - * Look for a movie name. - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - */ - public function movieCheck($release, $echo, $type, $namestatus, $show): void - { - $result = []; + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[-\w.\',;& ]+(480|720|1080)[ip][._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.Text.res.vcod.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[._ -](480|720|1080)[ip][-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.vcodec.res.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.vcodec.acodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+(Brazilian|Chinese|Croatian|Danish|Deutsch|Dutch|Estonian|English|Finnish|Flemish|Francais|French|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.language.acodec.source.vcodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.source.acodec.vcodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.source.vcodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.resolution.acodec.vcodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.acodec.vcodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BR(RIP)?|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -][-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.res.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -][-\w.\',;& ]+[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BR(RIP)?|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.eptitle.source.vcodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+(480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.resolution.source.acodec.vcodec.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+(480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[-\w.\',;& ]+(BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -]((19|20)\d\d)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.resolution.acodec.eptitle.source.year.group', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+(Brazilian|Chinese|Croatian|Danish|Deutsch|Dutch|Estonian|English|Finnish|Flemish|Francais|French|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)[._ -]((19|20)\d\d)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.language.year.acodec.src', $echo, $type, $namestatus, $show); + } + } + } - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { + /** + * Look for a game name. + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + */ + public function gameCheck($release, $echo, $type, $namestatus, $show): void + { + $result = []; - if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[-\w.\',;& ]+(480|720|1080)[ip][._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.Text.res.vcod.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[._ -](480|720|1080)[ip][-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.vcodec.res.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.vcodec.acodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+(Brazilian|Chinese|Croatian|Danish|Deutsch|Dutch|Estonian|English|Finnish|Flemish|Francais|French|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.language.acodec.source.vcodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.source.acodec.vcodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.source.vcodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.resolution.acodec.vcodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.acodec.vcodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BR(RIP)?|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -][-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.res.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -][-\w.\',;& ]+[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BR(RIP)?|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.eptitle.source.vcodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+(480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.resolution.source.acodec.vcodec.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+(480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[-\w.\',;& ]+(BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -]((19|20)\d\d)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.resolution.acodec.eptitle.source.year.group', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+(Brazilian|Chinese|Croatian|Danish|Deutsch|Dutch|Estonian|English|Finnish|Flemish|Francais|French|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)[._ -]((19|20)\d\d)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.language.year.acodec.src', $echo, $type, $namestatus, $show); - } - } - } + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + if (preg_match('/\w[-\w.\',;& ]+(ASIA|DLC|EUR|GOTY|JPN|KOR|MULTI\d{1}|NTSCU?|PAL|RF|Region[._ -]?Free|USA|XBLA)[._ -](DLC[._ -]Complete|FRENCH|GERMAN|MULTI\d{1}|PROPER|PSN|READ[._ -]?NFO|UMD)?[._ -]?(GC|NDS|NGC|PS3|PSP|WII|XBOX(360)?)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'gameCheck: Videogames 1', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+(GC|NDS|NGC|PS3|WII|XBOX(360)?)[._ -](DUPLEX|iNSOMNi|OneUp|STRANGE|SWAG|SKY)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'gameCheck: Videogames 2', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[\w.\',;-].+-OUTLAWS/i', $release['textstring'], $result)) { + $result = str_replace('OUTLAWS', 'PC GAME OUTLAWS', $result['0']); + $this->updateRelease($release, $result['0'], $method = 'gameCheck: PC Games -OUTLAWS', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[\w.\',;-].+\-ALiAS/i', $release['textstring'], $result)) { + $newresult = str_replace('-ALiAS', ' PC GAME ALiAS', $result['0']); + $this->updateRelease($release, $newresult, $method = 'gameCheck: PC Games -ALiAS', $echo, $type, $namestatus, $show); + } + } + } - /** - * Look for a game name. - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - */ - public function gameCheck($release, $echo, $type, $namestatus, $show): void - { - $result = []; + /** + * Look for a app name. + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + */ + public function appCheck($release, $echo, $type, $namestatus, $show): void + { + $result = []; - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + if (preg_match('/\w[-\w.\',;& ]+(\d{1,10}|Linux|UNIX)[._ -](RPM)?[._ -]?(X64)?[._ -]?(Incl)[._ -](Keygen)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'appCheck: Apps 1', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[-\w.\',;& ]+\d{1,8}[._ -](winall-freeware)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['0'], $method = 'appCheck: Apps 2', $echo, $type, $namestatus, $show); + } + } + } - if (preg_match('/\w[-\w.\',;& ]+(ASIA|DLC|EUR|GOTY|JPN|KOR|MULTI\d{1}|NTSCU?|PAL|RF|Region[._ -]?Free|USA|XBLA)[._ -](DLC[._ -]Complete|FRENCH|GERMAN|MULTI\d{1}|PROPER|PSN|READ[._ -]?NFO|UMD)?[._ -]?(GC|NDS|NGC|PS3|PSP|WII|XBOX(360)?)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'gameCheck: Videogames 1', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+(GC|NDS|NGC|PS3|WII|XBOX(360)?)[._ -](DUPLEX|iNSOMNi|OneUp|STRANGE|SWAG|SKY)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'gameCheck: Videogames 2', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[\w.\',;-].+-OUTLAWS/i', $release['textstring'], $result)) { - $result = str_replace('OUTLAWS', 'PC GAME OUTLAWS', $result['0']); - $this->updateRelease($release, $result['0'], $method = 'gameCheck: PC Games -OUTLAWS', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[\w.\',;-].+\-ALiAS/i', $release['textstring'], $result)) { - $newresult = str_replace('-ALiAS', ' PC GAME ALiAS', $result['0']); - $this->updateRelease($release, $newresult, $method = 'gameCheck: PC Games -ALiAS', $echo, $type, $namestatus, $show); - } - } - } + /* + * Just for NFOS. + */ - /** - * Look for a app name. - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - */ - public function appCheck($release, $echo, $type, $namestatus, $show): void - { - $result = []; + /** + * TV. + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + */ + public function nfoCheckTV($release, $echo, $type, $namestatus, $show): void + { + $result = []; - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + if (preg_match('/:\s*.*[\\\\\/]([A-Z0-9].+?S\d+[.-_ ]?[ED]\d+.+?)\.\w{2,}\s+/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['1'], $method = 'nfoCheck: Generic TV 1', $echo, $type, $namestatus, $show); + } elseif (preg_match('/(?:(\:\s{1,}))(.+?S\d{1,3}[.-_ ]?[ED]\d{1,3}.+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic TV 2', $echo, $type, $namestatus, $show); + } + } + } - if (preg_match('/\w[-\w.\',;& ]+(\d{1,10}|Linux|UNIX)[._ -](RPM)?[._ -]?(X64)?[._ -]?(Incl)[._ -](Keygen)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'appCheck: Apps 1', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[-\w.\',;& ]+\d{1,8}[._ -](winall-freeware)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['0'], $method = 'appCheck: Apps 2', $echo, $type, $namestatus, $show); - } - } - } + /** + * Movies. + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + */ + public function nfoCheckMov($release, $echo, $type, $namestatus, $show): void + { + $result = []; - /* - * Just for NFOS. - */ + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + if (preg_match('/(?:((?!Source\s)\:\s{1,}))(.+?(19|20)\d\d.+?(BDRip|bluray|DVD(R|Rip)?|XVID).+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 1', $echo, $type, $namestatus, $show); + } elseif (preg_match('/(?:(\s{2,}))((?!Source).+?[\.\-_ ](19|20)\d\d.+?(BDRip|bluray|DVD(R|Rip)?|XVID).+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 2', $echo, $type, $namestatus, $show); + } elseif (preg_match('/(?:(\s{2,}))(.+?[\.\-_ ](NTSC|MULTi).+?(MULTi|DVDR)[\.\-_ ].+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) { + $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 3', $echo, $type, $namestatus, $show); + } + } + } - /** - * TV. - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - */ - public function nfoCheckTV($release, $echo, $type, $namestatus, $show): void - { - $result = []; + /** + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + */ + public function nfoCheckMus($release, $echo, $type, $namestatus, $show): void + { + $result = []; - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { + if ($this->done === false && $this->relid !== (int) $release['releases_id'] && preg_match('/(?:\s{2,})(.+?-FM-\d{2}-\d{2})/i', $release['textstring'], $result)) { + $newname = str_replace('-FM-', '-FM-Radio-MP3-', $result['1']); + $this->updateRelease($release, $newname, $method = 'nfoCheck: Music FM RADIO', $echo, $type, $namestatus, $show); + } + } - if (preg_match('/:\s*.*[\\\\\/]([A-Z0-9].+?S\d+[.-_ ]?[ED]\d+.+?)\.\w{2,}\s+/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['1'], $method = 'nfoCheck: Generic TV 1', $echo, $type, $namestatus, $show); - } else if (preg_match('/(?:(\:\s{1,}))(.+?S\d{1,3}[.-_ ]?[ED]\d{1,3}.+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic TV 2', $echo, $type, $namestatus, $show); - } - } - } + /** + * Title (year). + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + */ + public function nfoCheckTY($release, $echo, $type, $namestatus, $show): void + { + $result = []; - /** - * Movies. - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - */ - public function nfoCheckMov($release, $echo, $type, $namestatus, $show): void - { - $result = []; - - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { - - if (preg_match('/(?:((?!Source\s)\:\s{1,}))(.+?(19|20)\d\d.+?(BDRip|bluray|DVD(R|Rip)?|XVID).+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 1', $echo, $type, $namestatus, $show); - } else if (preg_match('/(?:(\s{2,}))((?!Source).+?[\.\-_ ](19|20)\d\d.+?(BDRip|bluray|DVD(R|Rip)?|XVID).+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 2', $echo, $type, $namestatus, $show); - } else if (preg_match('/(?:(\s{2,}))(.+?[\.\-_ ](NTSC|MULTi).+?(MULTi|DVDR)[\.\-_ ].+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) { - $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 3', $echo, $type, $namestatus, $show); - } - } - } - - /** - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - */ - public function nfoCheckMus($release, $echo, $type, $namestatus, $show): void - { - $result = []; - - if ($this->done === false && $this->relid !== (int)$release['releases_id'] && preg_match('/(?:\s{2,})(.+?-FM-\d{2}-\d{2})/i', $release['textstring'], $result)) { - $newname = str_replace('-FM-', '-FM-Radio-MP3-', $result['1']); - $this->updateRelease($release, $newname, $method = 'nfoCheck: Music FM RADIO', $echo, $type, $namestatus, $show); - } - } - - /** - * Title (year) - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - */ - public function nfoCheckTY($release, $echo, $type, $namestatus, $show): void - { - $result = []; - - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { - if (preg_match('/(\w[-\w`~!@#$%^&*()_+={}|"<>?\[\]\\;\',.\/ ]+\s?\((19|20)\d\d\))/i', $release['textstring'], $result) && !preg_match('/\.pdf|Audio ?Book/i', $release['textstring'])) { - $releasename = $result[0]; - if (preg_match('/(idiomas|lang|language|langue|sprache).*?\b(?P<lang>Brazilian|Chinese|Croatian|Danish|DE|Deutsch|Dutch|Estonian|ES|English|Englisch|Finnish|Flemish|Francais|French|FR|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)\b/i', $release['textstring'], $result)) { - switch ($result['lang']) { + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + if (preg_match('/(\w[-\w`~!@#$%^&*()_+={}|"<>?\[\]\\;\',.\/ ]+\s?\((19|20)\d\d\))/i', $release['textstring'], $result) && ! preg_match('/\.pdf|Audio ?Book/i', $release['textstring'])) { + $releasename = $result[0]; + if (preg_match('/(idiomas|lang|language|langue|sprache).*?\b(?P<lang>Brazilian|Chinese|Croatian|Danish|DE|Deutsch|Dutch|Estonian|ES|English|Englisch|Finnish|Flemish|Francais|French|FR|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)\b/i', $release['textstring'], $result)) { + switch ($result['lang']) { case 'DE': $result['lang'] = 'DUTCH'; break; @@ -1611,11 +1600,11 @@ class NameFixer default: break; } - $releasename = $releasename . '.' . $result['lang']; - } + $releasename = $releasename.'.'.$result['lang']; + } - if (preg_match('/(frame size|(video )?res(olution)?|video).*?(?P<res>(272|336|480|494|528|608|\(?640|688|704|720x480|810|816|820|1 ?080|1280( \@)?|1 ?920(x1080)?))/i', $release['textstring'], $result)) { - switch ($result['res']) { + if (preg_match('/(frame size|(video )?res(olution)?|video).*?(?P<res>(272|336|480|494|528|608|\(?640|688|704|720x480|810|816|820|1 ?080|1280( \@)?|1 ?920(x1080)?))/i', $release['textstring'], $result)) { + switch ($result['res']) { case '272': case '336': case '480': @@ -1645,9 +1634,9 @@ class NameFixer break; } - $releasename = $releasename . '.' . $result['res']; - } else if (preg_match('/(largeur|width).*?(?P<res>(\(?640|688|704|720|1280( \@)?|1 ?920))/i', $release['textstring'], $result)) { - switch ($result['res']) { + $releasename = $releasename.'.'.$result['res']; + } elseif (preg_match('/(largeur|width).*?(?P<res>(\(?640|688|704|720|1280( \@)?|1 ?920))/i', $release['textstring'], $result)) { + switch ($result['res']) { case '640': case '(640': case '688': @@ -1665,12 +1654,11 @@ class NameFixer break; } - $releasename = $releasename . '.' . $result['res']; - } + $releasename = $releasename.'.'.$result['res']; + } - if (preg_match('/source.*?\b(?P<source>BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)\b/i', $release['textstring'], $result)) { - - switch ($result['source']) { + if (preg_match('/source.*?\b(?P<source>BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)\b/i', $release['textstring'], $result)) { + switch ($result['source']) { case 'BD': $result['source'] = 'Bluray.x264'; break; @@ -1693,9 +1681,9 @@ class NameFixer $result['source'] = 'DVDRIP'; } - $releasename = $releasename . '.' . $result['source']; - } else if (preg_match('/(codec( (name|code))?|(original )?format|res(olution)|video( (codec|format|res))?|tv system|type|writing library).*?\b(?P<video>AVC|AVI|DBrip|DIVX|\(Divx|DVD|[HX][._ -]?264|MPEG-4 Visual|NTSC|PAL|WMV|XVID)\b/i', $release['textstring'], $result)) { - switch ($result['video']) { + $releasename = $releasename.'.'.$result['source']; + } elseif (preg_match('/(codec( (name|code))?|(original )?format|res(olution)|video( (codec|format|res))?|tv system|type|writing library).*?\b(?P<video>AVC|AVI|DBrip|DIVX|\(Divx|DVD|[HX][._ -]?264|MPEG-4 Visual|NTSC|PAL|WMV|XVID)\b/i', $release['textstring'], $result)) { + switch ($result['video']) { case 'AVI': $result['video'] = 'DVDRIP'; break; @@ -1722,12 +1710,11 @@ class NameFixer break; } - $releasename = $releasename . '.' . $result['video']; - } + $releasename = $releasename.'.'.$result['video']; + } - if (preg_match('/(audio( format)?|codec( name)?|format).*?\b(?P<audio>0x0055 MPEG-1 Layer 3|AAC( LC)?|AC-?3|\(AC3|DD5(.1)?|(A_)?DTS-?(HD)?|Dolby(\s?TrueHD)?|TrueHD|FLAC|MP3)\b/i', $release['textstring'], $result)) { - - switch ($result['audio']) { + if (preg_match('/(audio( format)?|codec( name)?|format).*?\b(?P<audio>0x0055 MPEG-1 Layer 3|AAC( LC)?|AC-?3|\(AC3|DD5(.1)?|(A_)?DTS-?(HD)?|Dolby(\s?TrueHD)?|TrueHD|FLAC|MP3)\b/i', $release['textstring'], $result)) { + switch ($result['audio']) { case '0x0055 MPEG-1 Layer 3': $result['audio'] = 'MP3'; break; @@ -1743,98 +1730,98 @@ class NameFixer case 'DTSHD': $result['audio'] = 'DTS'; } - $releasename = $releasename . '.' . $result['audio']; - } - $releasename .= '-NoGroup'; - $this->updateRelease($release, $releasename, $method = 'nfoCheck: Title (Year)', $echo, $type, $namestatus, $show); - } - } - } + $releasename = $releasename.'.'.$result['audio']; + } + $releasename .= '-NoGroup'; + $this->updateRelease($release, $releasename, $method = 'nfoCheck: Title (Year)', $echo, $type, $namestatus, $show); + } + } + } - /** - * Games. - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - */ - public function nfoCheckG($release, $echo, $type, $namestatus, $show): void - { - $result = []; + /** + * Games. + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + */ + public function nfoCheckG($release, $echo, $type, $namestatus, $show): void + { + $result = []; - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { - if (preg_match('/ALiAS|BAT-TEAM|FAiRLiGHT|Game Type|Glamoury|HI2U|iTWINS|JAGUAR|(LARGE|MEDIUM)ISO|MAZE|nERv|PROPHET|PROFiT|PROCYON|RELOADED|REVOLVER|ROGUE|ViTALiTY/i', $release['textstring'])) { - if (preg_match('/\w[\w.+&*\/\()\',;: -]+\(c\)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { - $releasename = str_replace(['(c)', '(C)'], '(GAMES) (c)', $result['0']); - $this->updateRelease($release, $releasename, $method = 'nfoCheck: PC Games (c)', $echo, $type, $namestatus, $show); - } else if (preg_match('/\w[\w.+&*\/()\',;: -]+\*ISO\*/i', $release['textstring'], $result)) { - $releasename = str_replace('*ISO*', '*ISO* (PC GAMES)', $result['0']); - $this->updateRelease($release, $releasename, $method = 'nfoCheck: PC Games *ISO*', $echo, $type, $namestatus, $show); - } - } - } - } + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + if (preg_match('/ALiAS|BAT-TEAM|FAiRLiGHT|Game Type|Glamoury|HI2U|iTWINS|JAGUAR|(LARGE|MEDIUM)ISO|MAZE|nERv|PROPHET|PROFiT|PROCYON|RELOADED|REVOLVER|ROGUE|ViTALiTY/i', $release['textstring'])) { + if (preg_match('/\w[\w.+&*\/\()\',;: -]+\(c\)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) { + $releasename = str_replace(['(c)', '(C)'], '(GAMES) (c)', $result['0']); + $this->updateRelease($release, $releasename, $method = 'nfoCheck: PC Games (c)', $echo, $type, $namestatus, $show); + } elseif (preg_match('/\w[\w.+&*\/()\',;: -]+\*ISO\*/i', $release['textstring'], $result)) { + $releasename = str_replace('*ISO*', '*ISO* (PC GAMES)', $result['0']); + $this->updateRelease($release, $releasename, $method = 'nfoCheck: PC Games *ISO*', $echo, $type, $namestatus, $show); + } + } + } + } - // - /** - * Misc. - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - */ - public function nfoCheckMisc($release, $echo, $type, $namestatus, $show): void - { - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { + // - if (preg_match('/Supplier.+?IGUANA/i', $release['textstring'])) { - $releasename = ''; - $result = []; - if (preg_match('/\w[-\w`~!@#$%^&*()+={}|:"<>?\[\]\\;\',.\/ ]+\s\((19|20)\d\d\)/i', $release['textstring'], $result)) { - $releasename = $result[0]; - } else if (preg_match('/\s\[\*\] (English|Dutch|French|German|Spanish)\b/i', $release['textstring'], $result)) { - $releasename = $releasename . "." . $result[1]; - } else if (preg_match('/\s\[\*\] (DT?S [2567][._ -][0-2]( MONO)?)\b/i', $release['textstring'], $result)) { - $releasename = $releasename . "." . $result[2]; - } else if (preg_match('/Format.+(DVD(5|9|R)?|[HX][._ -]?264)\b/i', $release['textstring'], $result)) { - $releasename = $releasename . "." . $result[1]; - } else if (preg_match('/\[(640x.+|1280x.+|1920x.+)\] Resolution\b/i', $release['textstring'], $result)) { - if ($result[1] === '640x.+') { - $result[1] = '480p'; - } else if ($result[1] === '1280x.+') { - $result[1] = '720p'; - } else if ($result[1] === '1920x.+') { - $result[1] = '1080p'; - } - $releasename = $releasename . '.' . $result[1]; - } - $result = $releasename . '.IGUANA'; - $this->updateRelease($release, $result, $method = 'nfoCheck: IGUANA', $echo, $type, $namestatus, $show); - } - } - } + /** + * Misc. + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + */ + public function nfoCheckMisc($release, $echo, $type, $namestatus, $show): void + { + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + if (preg_match('/Supplier.+?IGUANA/i', $release['textstring'])) { + $releasename = ''; + $result = []; + if (preg_match('/\w[-\w`~!@#$%^&*()+={}|:"<>?\[\]\\;\',.\/ ]+\s\((19|20)\d\d\)/i', $release['textstring'], $result)) { + $releasename = $result[0]; + } elseif (preg_match('/\s\[\*\] (English|Dutch|French|German|Spanish)\b/i', $release['textstring'], $result)) { + $releasename = $releasename.'.'.$result[1]; + } elseif (preg_match('/\s\[\*\] (DT?S [2567][._ -][0-2]( MONO)?)\b/i', $release['textstring'], $result)) { + $releasename = $releasename.'.'.$result[2]; + } elseif (preg_match('/Format.+(DVD(5|9|R)?|[HX][._ -]?264)\b/i', $release['textstring'], $result)) { + $releasename = $releasename.'.'.$result[1]; + } elseif (preg_match('/\[(640x.+|1280x.+|1920x.+)\] Resolution\b/i', $release['textstring'], $result)) { + if ($result[1] === '640x.+') { + $result[1] = '480p'; + } elseif ($result[1] === '1280x.+') { + $result[1] = '720p'; + } elseif ($result[1] === '1920x.+') { + $result[1] = '1080p'; + } + $releasename = $releasename.'.'.$result[1]; + } + $result = $releasename.'.IGUANA'; + $this->updateRelease($release, $result, $method = 'nfoCheck: IGUANA', $echo, $type, $namestatus, $show); + } + } + } - /** - * Just for filenames. - * - * @param $release - * @param boolean $echo - * @param string $type - * @param $namestatus - * @param $show - * - * @return bool - */ - public function fileCheck($release, $echo, $type, $namestatus, $show): bool - { - $result = []; + /** + * Just for filenames. + * + * @param $release + * @param bool $echo + * @param string $type + * @param $namestatus + * @param $show + * + * @return bool + */ + public function fileCheck($release, $echo, $type, $namestatus, $show): bool + { + $result = []; - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { - switch (true) { + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + switch (true) { case preg_match('/^(.+?(x264|XviD)\-TVP)\\\\/i', $release['textstring'], $result): $this->updateRelease($release, $result['1'], $method = 'fileCheck: TVP', $echo, $type, $namestatus, $show); break; @@ -1865,7 +1852,7 @@ class NameFixer $this->updateRelease($release, $result['1'], $method = 'fileCheck: XXX Imagesets', $echo, $type, $namestatus, $show); break; case preg_match('/^VIDEOOT-[A-Z0-9]+\\\\([\w!.,& ()\[\]\'\`-]{8,}?\b.?)([-_](proof|sample|thumbs?))*(\.part\d*(\.rar)?|\.rar|\.7z)?(\d{1,3}\.rev|\.vol.+?|\.mp4)/', $release['textstring'], $result): - $this->updateRelease($release, $result['1'] . ' XXX DVDRIP XviD-VIDEOOT', $method = 'fileCheck: XXX XviD VIDEOOT', $echo, $type, $namestatus, $show); + $this->updateRelease($release, $result['1'].' XXX DVDRIP XviD-VIDEOOT', $method = 'fileCheck: XXX XviD VIDEOOT', $echo, $type, $namestatus, $show); break; case preg_match('/^.+?SDPORN/i', $release['textstring'], $result): $this->updateRelease($release, $result['0'], $method = 'fileCheck: XXX SDPORN', $echo, $type, $namestatus, $show); @@ -1884,23 +1871,23 @@ class NameFixer $this->updateRelease($release, $result, $method = 'fileCheck: tvp', $echo, $type, $namestatus, $show); break; case preg_match('/\w[-\w.\',;& ]+\d{3,4}\.hdtv-lol\.(avi|mp4|mkv|ts|nfo|nzb)/i', $release['textstring'], $result): - $this->updateRelease($release, $result['0'], $method = "fileCheck: Title.211.hdtv-lol.extension", $echo, $type, $namestatus, $show); + $this->updateRelease($release, $result['0'], $method = 'fileCheck: Title.211.hdtv-lol.extension', $echo, $type, $namestatus, $show); break; case preg_match('/\w[-\w.\',;& ]+-S\d{1,2}[EX]\d{1,2}-XVID-DL.avi/i', $release['textstring'], $result): - $this->updateRelease($release, $result['0'], $method = "fileCheck: Title-SxxExx-XVID-DL.avi", $echo, $type, $namestatus, $show); + $this->updateRelease($release, $result['0'], $method = 'fileCheck: Title-SxxExx-XVID-DL.avi', $echo, $type, $namestatus, $show); break; case preg_match('/\S.*[\w.\-\',;]+\s\-\ss\d{2}[ex]\d{2}\s\-\s[\w.\-\',;].+\./i', $release['textstring'], $result): - $this->updateRelease($release, $result['0'], $method = "fileCheck: Title - SxxExx - Eptitle", $echo, $type, $namestatus, $show); + $this->updateRelease($release, $result['0'], $method = 'fileCheck: Title - SxxExx - Eptitle', $echo, $type, $namestatus, $show); break; case preg_match('/\w.+?\)\.nds/i', $release['textstring'], $result): - $this->updateRelease($release, $result['0'], $method = "fileCheck: ).nds Nintendo DS", $echo, $type, $namestatus, $show); + $this->updateRelease($release, $result['0'], $method = 'fileCheck: ).nds Nintendo DS', $echo, $type, $namestatus, $show); break; case preg_match('/3DS_\d{4}.+\d{4} - (.+?)\.3ds/i', $release['textstring'], $result): - $this->updateRelease($release, "3DS " . $result['1'], $method = "fileCheck: .3ds Nintendo 3DS", $echo, $type, $namestatus, $show); + $this->updateRelease($release, '3DS '.$result['1'], $method = 'fileCheck: .3ds Nintendo 3DS', $echo, $type, $namestatus, $show); break; case preg_match('/\w.+?\.(epub|mobi|azw|opf|fb2|prc|djvu|cb[rz])/i', $release['textstring'], $result): - $result = str_replace("." . $result['1'], " (" . $result['1'] . ")", $result['0']); - $this->updateRelease($release, $result, $method = "fileCheck: EBook", $echo, $type, $namestatus, $show); + $result = str_replace('.'.$result['1'], ' ('.$result['1'].')', $result['0']); + $this->updateRelease($release, $result, $method = 'fileCheck: EBook', $echo, $type, $namestatus, $show); break; case preg_match('/\w[-\w.\',;& ]+/i', $release['textstring'], $result) && preg_match(self::PREDB_REGEX, $release['textstring']): $this->updateRelease($release, $result['0'], $method = 'fileCheck: Folder name', $echo, $type, $namestatus, $show); @@ -1908,26 +1895,28 @@ class NameFixer default: return false; } - return true; - } - return false; - } - /** - * Look for a name based on mediainfo xml Unique_ID. - * - * @param array $release The release to be matched - * @param boolean $echo Should we show CLI output - * @param string $type The rename type - * @param int $namestatus Should we rename the release if match is found - * @param int $show Should we show the rename results - * - * @return bool Whether or not we matched the release - */ - public function uidCheck($release, $echo, $type, $namestatus, $show): bool - { - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { - $result = $this->pdo->queryDirect(" + return true; + } + + return false; + } + + /** + * Look for a name based on mediainfo xml Unique_ID. + * + * @param array $release The release to be matched + * @param bool $echo Should we show CLI output + * @param string $type The rename type + * @param int $namestatus Should we rename the release if match is found + * @param int $show Should we show the rename results + * + * @return bool Whether or not we matched the release + */ + public function uidCheck($release, $echo, $type, $namestatus, $show): bool + { + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + $result = $this->pdo->queryDirect(" SELECT r.id AS releases_id, r.size AS relsize, r.name AS textstring, r.searchname, r.fromname, r.predb_id FROM releases r LEFT JOIN release_unique ru ON ru.releases_id = r.id @@ -1937,11 +1926,11 @@ class NameFixer AND (r.predb_id > 0 OR r.anidbid > 0 OR r.fromname = 'nonscene@Ef.net (EF)')" ); - if ($result instanceof \Traversable) { - foreach ($result AS $res) { - $floor = round(($res['relsize'] - $release['relsize']) / $res['relsize'] * 100, 1); - if ($floor >= -10 && $floor <= 10) { - $this->updateRelease( + if ($result instanceof \Traversable) { + foreach ($result as $res) { + $floor = round(($res['relsize'] - $release['relsize']) / $res['relsize'] * 100, 1); + if ($floor >= -10 && $floor <= 10) { + $this->updateRelease( $release, $res['searchname'], $method = 'uidCheck: Unique_ID', @@ -1951,30 +1940,32 @@ class NameFixer $show, $res['predb_id'] ); - return true; - } - } - } - } - $this->_updateSingleColumn('proc_uid', self::PROC_UID_DONE, $release['releases_id']); - return false; - } - /** - * Look for a name based on xxx release filename. - * - * @param array $release The release to be matched - * @param boolean $echo Should we show CLI output - * @param string $type The rename type - * @param int $namestatus Should we rename the release if match is found - * @param int $show Should we show the rename results - * - * @return bool Whether or not we matched the release - */ - public function xxxNameCheck($release, $echo, $type, $namestatus, $show): bool - { - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { - $result = $this->pdo->queryDirect(sprintf(" + return true; + } + } + } + } + $this->_updateSingleColumn('proc_uid', self::PROC_UID_DONE, $release['releases_id']); + + return false; + } + + /** + * Look for a name based on xxx release filename. + * + * @param array $release The release to be matched + * @param bool $echo Should we show CLI output + * @param string $type The rename type + * @param int $namestatus Should we rename the release if match is found + * @param int $show Should we show the rename results + * + * @return bool Whether or not we matched the release + */ + public function xxxNameCheck($release, $echo, $type, $namestatus, $show): bool + { + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + $result = $this->pdo->queryDirect(sprintf(" SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id, rf.releases_id AS fileid, rel.id AS releases_id FROM releases rel @@ -1988,10 +1979,10 @@ class NameFixer ) ); - if ($result instanceof \Traversable) { - foreach ($result AS $res) { - if (preg_match('/^.+?SDPORN/i', $res['textstring'], $match)) { - $this->updateRelease( + if ($result instanceof \Traversable) { + foreach ($result as $res) { + if (preg_match('/^.+?SDPORN/i', $res['textstring'], $match)) { + $this->updateRelease( $release, $match['0'], $method = 'fileCheck: XXX SDPORN', @@ -2000,30 +1991,32 @@ class NameFixer $namestatus, $show ); - return true; - } - } - } - } - $this->_updateSingleColumn('proc_files', self::PROC_FILES_DONE, $release['releases_id']); - return false; - } - /** - * Look for a name based on .srr release files extension. - * - * @param array $release The release to be matched - * @param boolean $echo Should we show CLI output - * @param string $type The rename type - * @param int $namestatus Should we rename the release if match is found - * @param int $show Should we show the rename results - * - * @return bool Whether or not we matched the release - */ - public function srrNameCheck($release, $echo, $type, $namestatus, $show): bool - { - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { - $result = $this->pdo->queryDirect(sprintf(" + return true; + } + } + } + } + $this->_updateSingleColumn('proc_files', self::PROC_FILES_DONE, $release['releases_id']); + + return false; + } + + /** + * Look for a name based on .srr release files extension. + * + * @param array $release The release to be matched + * @param bool $echo Should we show CLI output + * @param string $type The rename type + * @param int $namestatus Should we rename the release if match is found + * @param int $show Should we show the rename results + * + * @return bool Whether or not we matched the release + */ + public function srrNameCheck($release, $echo, $type, $namestatus, $show): bool + { + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + $result = $this->pdo->queryDirect(sprintf(" SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id, rf.releases_id AS fileid, rel.id AS releases_id FROM releases rel @@ -2037,10 +2030,10 @@ class NameFixer ) ); - if ($result instanceof \Traversable) { - foreach ($result AS $res) { - if (preg_match('/^(.*)\.srr/i', $res['textstring'], $match)) { - $this->updateRelease( + if ($result instanceof \Traversable) { + foreach ($result as $res) { + if (preg_match('/^(.*)\.srr/i', $res['textstring'], $match)) { + $this->updateRelease( $release, $match['1'], $method = 'fileCheck: SRR extension', @@ -2049,30 +2042,32 @@ class NameFixer $namestatus, $show ); - return true; - } - } - } - } - $this->_updateSingleColumn('proc_srr', self::PROC_SRR_DONE, $release['releases_id']); - return false; - } - /** - * Look for a name based on par2 hash_16K block. - * - * @param array $release The release to be matched - * @param boolean $echo Should we show CLI output - * @param string $type The rename type - * @param int $namestatus Should we rename the release if match is found - * @param int $show Should we show the rename results - * - * @return bool Whether or not we matched the release - */ - public function hashCheck($release, $echo, $type, $namestatus, $show): bool - { - if ($this->done === false && $this->relid !== (int)$release['releases_id']) { - $result = $this->pdo->queryDirect(" + return true; + } + } + } + } + $this->_updateSingleColumn('proc_srr', self::PROC_SRR_DONE, $release['releases_id']); + + return false; + } + + /** + * Look for a name based on par2 hash_16K block. + * + * @param array $release The release to be matched + * @param bool $echo Should we show CLI output + * @param string $type The rename type + * @param int $namestatus Should we rename the release if match is found + * @param int $show Should we show the rename results + * + * @return bool Whether or not we matched the release + */ + public function hashCheck($release, $echo, $type, $namestatus, $show): bool + { + if ($this->done === false && $this->relid !== (int) $release['releases_id']) { + $result = $this->pdo->queryDirect(" SELECT r.id AS releases_id, r.size AS relsize, r.name AS textstring, r.searchname, r.fromname, r.predb_id FROM releases r STRAIGHT_JOIN par_hashes ph ON ph.releases_id = r.id @@ -2081,11 +2076,11 @@ class NameFixer AND (r.predb_id > 0 OR r.anidbid > 0)" ); - if ($result instanceof \Traversable) { - foreach ($result AS $res) { - $floor = round(($res['relsize'] - $release['relsize']) / $res['relsize'] * 100, 1); - if ($floor >= -5 && $floor <= 5) { - $this->updateRelease( + if ($result instanceof \Traversable) { + foreach ($result as $res) { + $floor = round(($res['relsize'] - $release['relsize']) / $res['relsize'] * 100, 1); + if ($floor >= -5 && $floor <= 5) { + $this->updateRelease( $release, $res['searchname'], $method = 'hashCheck: PAR2 hash_16K', @@ -2095,20 +2090,22 @@ class NameFixer $show, $res['predb_id'] ); - return true; - } - } - } - } - $this->_updateSingleColumn('proc_hash16k', self::PROC_HASH16K_DONE, $release['releases_id']); - return false; - } - /** - * Resets NameFixer status variables for new processing - */ - public function reset(): void - { - $this->done = $this->matched = false; - } + return true; + } + } + } + } + $this->_updateSingleColumn('proc_hash16k', self::PROC_HASH16K_DONE, $release['releases_id']); + + return false; + } + + /** + * Resets NameFixer status variables for new processing. + */ + public function reset(): void + { + $this->done = $this->matched = false; + } } diff --git a/nntmux/NetworkException.php b/nntmux/NetworkException.php index 471718b03..8d0223748 100755 --- a/nntmux/NetworkException.php +++ b/nntmux/NetworkException.php @@ -18,7 +18,6 @@ * @author niel */ - namespace nntmux; /** @@ -28,7 +27,5 @@ namespace nntmux; */ class NetworkException extends \RuntimeException { - protected $code = 503; + protected $code = 503; } - -?> diff --git a/nntmux/Nfo.php b/nntmux/Nfo.php index 6fa0d8ffc..9cbd4c86f 100755 --- a/nntmux/Nfo.php +++ b/nntmux/Nfo.php @@ -1,12 +1,13 @@ <?php + namespace nntmux; -use App\Models\Settings; -use dariusiii\rarinfo\Par2Info; -use dariusiii\rarinfo\SfvInfo; use nntmux\db\DB; -use nntmux\processing\PostProcess; +use App\Models\Settings; use nntmux\utility\Utility; +use dariusiii\rarinfo\SfvInfo; +use dariusiii\rarinfo\Par2Info; +use nntmux\processing\PostProcess; /** * Class Nfo @@ -14,295 +15,282 @@ use nntmux\utility\Utility; */ class Nfo { - /** - * Instance of class Settings - * @var DB - * @access private - */ - public $pdo; + /** + * Instance of class Settings. + * @var DB + */ + public $pdo; - /** - * How many nfo's to process per run. - * @var int - * @access private - */ - private $nzbs; + /** + * How many nfo's to process per run. + * @var int + */ + private $nzbs; - /** - * Max NFO size to process. - * @var string|int - * @access private - */ - private $maxsize; + /** + * Max NFO size to process. + * @var string|int + */ + private $maxsize; - /** - * Max amount of times to retry to download a Nfo. - * @var string|int - * @access private - */ - private $maxRetries; + /** + * Max amount of times to retry to download a Nfo. + * @var string|int + */ + private $maxRetries; - /** - * Min NFO size to process. - * @var string|int - * @access private - */ - private $minsize; + /** + * Min NFO size to process. + * @var string|int + */ + private $minsize; - /** - * Path to temporarily store files. - * @var string - * @access private - */ - private $tmpPath; + /** + * Path to temporarily store files. + * @var string + */ + private $tmpPath; - /** - * Echo to cli? - * @var bool - * @access protected - */ - protected $echo; + /** + * Echo to cli? + * @var bool + */ + protected $echo; - const NFO_FAILED = -9; // We failed to get a NFO after admin set max retries. + const NFO_FAILED = -9; // We failed to get a NFO after admin set max retries. const NFO_UNPROC = -1; // Release has not been processed yet. - const NFO_NONFO = 0; // Release has no NFO. - const NFO_FOUND = 1; // Release has an NFO. + const NFO_NONFO = 0; // Release has no NFO. + const NFO_FOUND = 1; // Release has an NFO. /** * Default constructor. * * @param array $options Class instance / echo to cli. * - * @access public * @throws \Exception */ - public function __construct(array $options = []) - { - $defaults = [ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Settings' => null, ]; - $options += $defaults; - $this->echo = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->nzbs = Settings::value('..maxnfoprocessed') !== '' ? (int)Settings::value('..maxnfoprocessed') : 100; - $this->maxsize = Settings::value('..maxsizetoprocessnfo') !== '' ? (int)Settings::value('..maxsizetoprocessnfo') : 100; - $this->maxsize = $this->maxsize > 0 ? ('AND size < ' . ($this->maxsize * 1073741824)) : ''; - $this->minsize = Settings::value('..minsizetoprocessnfo') !== '' ? (int)Settings::value('..minsizetoprocessnfo') : 100; - $this->minsize = $this->minsize > 0 ? ('AND size > ' . ($this->minsize * 1048576)) : ''; - $this->maxRetries = (int)Settings::value('..maxnforetries') >= 0 ? -((int)Settings::value('..maxnforetries') + 1) : self::NFO_UNPROC; - $this->maxRetries = $this->maxRetries < -8 ? -8 : $this->maxRetries; - $this->tmpPath = (string)Settings::value('..tmpunrarpath'); - if (!preg_match('/[\/\\\\]$/', $this->tmpPath)) { - $this->tmpPath .= DS; - } - } + $options += $defaults; + $this->echo = ($options['Echo'] && NN_ECHOCLI); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->nzbs = Settings::value('..maxnfoprocessed') !== '' ? (int) Settings::value('..maxnfoprocessed') : 100; + $this->maxsize = Settings::value('..maxsizetoprocessnfo') !== '' ? (int) Settings::value('..maxsizetoprocessnfo') : 100; + $this->maxsize = $this->maxsize > 0 ? ('AND size < '.($this->maxsize * 1073741824)) : ''; + $this->minsize = Settings::value('..minsizetoprocessnfo') !== '' ? (int) Settings::value('..minsizetoprocessnfo') : 100; + $this->minsize = $this->minsize > 0 ? ('AND size > '.($this->minsize * 1048576)) : ''; + $this->maxRetries = (int) Settings::value('..maxnforetries') >= 0 ? -((int) Settings::value('..maxnforetries') + 1) : self::NFO_UNPROC; + $this->maxRetries = $this->maxRetries < -8 ? -8 : $this->maxRetries; + $this->tmpPath = (string) Settings::value('..tmpunrarpath'); + if (! preg_match('/[\/\\\\]$/', $this->tmpPath)) { + $this->tmpPath .= DS; + } + } - /** - * Look for a TV Show ID in a string. - * - * @param string $str The string with a Show ID. - * - * @return array|bool Return array with show ID and site source or false on failure. - * - * @access public - */ - public function parseShowId($str) - { - $return = false; + /** + * Look for a TV Show ID in a string. + * + * @param string $str The string with a Show ID. + * + * @return array|bool Return array with show ID and site source or false on failure. + */ + public function parseShowId($str) + { + $return = false; - if (preg_match('/tvmaze\.com\/shows\/(\d{1,6})/i', $str, $matches)) { - $return = + if (preg_match('/tvmaze\.com\/shows\/(\d{1,6})/i', $str, $matches)) { + $return = [ 'showid' => trim($matches[1]), - 'site' => 'tvmaze' + 'site' => 'tvmaze', ]; - } + } - if (preg_match('/imdb\.com\/title\/(tt\d{1,8})/i', $str, $matches)) { - $return = + if (preg_match('/imdb\.com\/title\/(tt\d{1,8})/i', $str, $matches)) { + $return = [ 'showid' => trim($matches[1]), - 'site' => 'imdb' + 'site' => 'imdb', ]; - } + } - if (preg_match('/thetvdb\.com\/\?tab=series&id=(\d{1,8})/i', $str, $matches)) { - $return = + if (preg_match('/thetvdb\.com\/\?tab=series&id=(\d{1,8})/i', $str, $matches)) { + $return = [ 'showid' => trim($matches[1]), - 'site' => 'thetvdb' + 'site' => 'thetvdb', ]; - } - return $return; - } + } - /** - * Confirm this is an NFO file. - * - * @param string $possibleNFO The nfo. - * @param string $guid The guid of the release. - * - * @return bool True on success, False on failure. - * @throws \Exception - * - * @access public - */ - public function isNFO(&$possibleNFO, $guid): bool - { - if ($possibleNFO === false) { - return false; - } + return $return; + } - // Make sure it's not too big or small, size needs to be at least 12 bytes for header checking. Ignore common file types. - $size = strlen($possibleNFO); - if ($size < 65535 && + /** + * Confirm this is an NFO file. + * + * @param string $possibleNFO The nfo. + * @param string $guid The guid of the release. + * + * @return bool True on success, False on failure. + * @throws \Exception + */ + public function isNFO(&$possibleNFO, $guid): bool + { + if ($possibleNFO === false) { + return false; + } + + // Make sure it's not too big or small, size needs to be at least 12 bytes for header checking. Ignore common file types. + $size = strlen($possibleNFO); + if ($size < 65535 && $size > 11 && - !preg_match( - '/\A(\s*<\?xml|=newz\[NZB\]=|RIFF|\s*[RP]AR|.{0,10}(JFIF|matroska|ftyp|ID3))|;\s*Generated\s*by.*SF\w/i' - , $possibleNFO)) - { - // File/GetId3 work with files, so save to disk. - $tmpPath = $this->tmpPath . $guid . '.nfo'; - file_put_contents($tmpPath, $possibleNFO); + ! preg_match( + '/\A(\s*<\?xml|=newz\[NZB\]=|RIFF|\s*[RP]AR|.{0,10}(JFIF|matroska|ftyp|ID3))|;\s*Generated\s*by.*SF\w/i', $possibleNFO)) { + // File/GetId3 work with files, so save to disk. + $tmpPath = $this->tmpPath.$guid.'.nfo'; + file_put_contents($tmpPath, $possibleNFO); - // Linux boxes have 'file' (so should Macs), Windows *can* have it too: see GNUWIN.txt in docs. - $result = Utility::fileInfo($tmpPath); - if (!empty($result)) { + // Linux boxes have 'file' (so should Macs), Windows *can* have it too: see GNUWIN.txt in docs. + $result = Utility::fileInfo($tmpPath); + if (! empty($result)) { // Check if it's text. - if (preg_match('/(ASCII|ISO-8859|UTF-(8|16|32).*?)\s*text/', $result)) { - @unlink($tmpPath); - return true; + if (preg_match('/(ASCII|ISO-8859|UTF-(8|16|32).*?)\s*text/', $result)) { + @unlink($tmpPath); - // Or binary. - } + return true; - if (preg_match('/^(JPE?G|Parity|PNG|RAR|XML|(7-)?[Zz]ip)/', $result) || preg_match('/[\x00-\x08\x12-\x1F\x0B\x0E\x0F]/', $possibleNFO)) { - @unlink($tmpPath); - return false; - } - } + // Or binary. + } - // If above checks couldn't make a categorical identification, Use GetId3 to check if it's an image/video/rar/zip etc.. - $check = (new \getID3())->analyze($tmpPath); - @unlink($tmpPath); - if (isset($check['error'])) { + if (preg_match('/^(JPE?G|Parity|PNG|RAR|XML|(7-)?[Zz]ip)/', $result) || preg_match('/[\x00-\x08\x12-\x1F\x0B\x0E\x0F]/', $possibleNFO)) { + @unlink($tmpPath); + + return false; + } + } + + // If above checks couldn't make a categorical identification, Use GetId3 to check if it's an image/video/rar/zip etc.. + $check = (new \getID3())->analyze($tmpPath); + @unlink($tmpPath); + if (isset($check['error'])) { // Check if it's a par2. - $par2info = new Par2Info(); - $par2info->setData($possibleNFO); - if ($par2info->error) { - // Check if it's an SFV. - $sfv = new SfvInfo(); - $sfv->setData($possibleNFO); - if ($sfv->error) { - return true; - } - } - } - } - return false; - } + $par2info = new Par2Info(); + $par2info->setData($possibleNFO); + if ($par2info->error) { + // Check if it's an SFV. + $sfv = new SfvInfo(); + $sfv->setData($possibleNFO); + if ($sfv->error) { + return true; + } + } + } + } - /** - * Add an NFO from alternate sources. ex.: PreDB, rar, zip, etc... - * - * @param string $nfo The nfo. - * @param array $release The SQL row for this release. - * @param NNTP $nntp Instance of class NNTP. - * - * @return bool True on success, False on failure. - * @throws \Exception - * - * @access public - */ - public function addAlternateNfo(&$nfo, $release, $nntp): bool - { - if ($release['id'] > 0 && $this->isNFO($nfo, $release['guid'])) { + return false; + } - $check = $this->pdo->queryOneRow(sprintf('SELECT releases_id FROM release_nfos WHERE releases_id = %d', $release['id'])); + /** + * Add an NFO from alternate sources. ex.: PreDB, rar, zip, etc... + * + * @param string $nfo The nfo. + * @param array $release The SQL row for this release. + * @param NNTP $nntp Instance of class NNTP. + * + * @return bool True on success, False on failure. + * @throws \Exception + */ + public function addAlternateNfo(&$nfo, $release, $nntp): bool + { + if ($release['id'] > 0 && $this->isNFO($nfo, $release['guid'])) { + $check = $this->pdo->queryOneRow(sprintf('SELECT releases_id FROM release_nfos WHERE releases_id = %d', $release['id'])); - if ($check === false) { - $this->pdo->queryInsert( + if ($check === false) { + $this->pdo->queryInsert( sprintf('INSERT INTO release_nfos (nfo, releases_id) VALUES (compress(%s), %d)', $this->pdo->escapeString($nfo), $release['id'] ) ); - } + } - $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', self::NFO_FOUND, $release['id'])); + $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', self::NFO_FOUND, $release['id'])); - if (!isset($release['completion'])) { - $release['completion'] = 0; - } + if (! isset($release['completion'])) { + $release['completion'] = 0; + } - if ((int)$release['completion'] === 0) { - $nzbContents = new NZBContents( + if ((int) $release['completion'] === 0) { + $nzbContents = new NZBContents( [ 'Echo' => $this->echo, 'NNTP' => $nntp, 'Nfo' => $this, 'Settings' => $this->pdo, - 'PostProcess' => new PostProcess(['Echo' => $this->echo, 'Settings' => $this->pdo, 'Nfo' => $this]) + 'PostProcess' => new PostProcess(['Echo' => $this->echo, 'Settings' => $this->pdo, 'Nfo' => $this]), ] ); - $nzbContents->parseNZB($release['guid'], $release['id'], $release['groups_id']); - } - return true; - } - return false; - } + $nzbContents->parseNZB($release['guid'], $release['id'], $release['groups_id']); + } - /** - * Get a string like this: - * "AND r.nzbstatus = 1 AND r.nfostatus BETWEEN -8 AND -1 AND r.size < 1073741824 AND r.size > 1048576" - * To use in a query. - * - * @return string - * @throws \Exception - * @access public - * @static - */ - public static function NfoQueryString() - { - $maxSize = (int)Settings::value('..maxsizetoprocessnfo'); - $minSize = (int)Settings::value('..minsizetoprocessnfo'); - $dummy = (int)Settings::value('..maxnforetries'); - $maxRetries = ($dummy >= 0 ? -($dummy + 1) : self::NFO_UNPROC); - return sprintf( + return true; + } + + return false; + } + + /** + * Get a string like this: + * "AND r.nzbstatus = 1 AND r.nfostatus BETWEEN -8 AND -1 AND r.size < 1073741824 AND r.size > 1048576" + * To use in a query. + * + * @return string + * @throws \Exception + * @static + */ + public static function NfoQueryString() + { + $maxSize = (int) Settings::value('..maxsizetoprocessnfo'); + $minSize = (int) Settings::value('..minsizetoprocessnfo'); + $dummy = (int) Settings::value('..maxnforetries'); + $maxRetries = ($dummy >= 0 ? -($dummy + 1) : self::NFO_UNPROC); + + return sprintf( 'AND r.nzbstatus = %d AND r.nfostatus BETWEEN %d AND %d %s %s', NZB::NZB_ADDED, ($maxRetries < -8 ? -8 : $maxRetries), self::NFO_UNPROC, - ($maxSize > 0 ? ('AND r.size < ' . ($maxSize * 1073741824)) : ''), - ($minSize > 0 ? ('AND r.size > ' . ($minSize * 1048576)) : '') + ($maxSize > 0 ? ('AND r.size < '.($maxSize * 1073741824)) : ''), + ($minSize > 0 ? ('AND r.size > '.($minSize * 1048576)) : '') ); - } + } - /** - * Attempt to find NFO files inside the NZB's of releases. - * - * @param $nntp - * @param string $groupID (optional) Group ID. - * @param string $guidChar (optional) First character of the release GUID (used for multi-processing). - * @param int $processImdb (optional) Attempt to find IMDB id's in the NZB? - * @param int $processTv (optional) Attempt to find Tv id's in the NZB? - * - * @return int How many NFO's were processed? - * @throws \Exception - * - * @access public - */ - public function processNfoFiles($nntp, $groupID = '', $guidChar = '', $processImdb = 1, $processTv = 1): int - { - $ret = 0; - $guidCharQuery = ($guidChar === '' ? '' : 'AND r.leftguid = ' . $this->pdo->escapeString($guidChar)); - $groupIDQuery = ($groupID === '' ? '' : 'AND r.groups_id = ' . $groupID); - $optionsQuery = self::NfoQueryString($this->pdo); + /** + * Attempt to find NFO files inside the NZB's of releases. + * + * @param $nntp + * @param string $groupID (optional) Group ID. + * @param string $guidChar (optional) First character of the release GUID (used for multi-processing). + * @param int $processImdb (optional) Attempt to find IMDB id's in the NZB? + * @param int $processTv (optional) Attempt to find Tv id's in the NZB? + * + * @return int How many NFO's were processed? + * @throws \Exception + */ + public function processNfoFiles($nntp, $groupID = '', $guidChar = '', $processImdb = 1, $processTv = 1): int + { + $ret = 0; + $guidCharQuery = ($guidChar === '' ? '' : 'AND r.leftguid = '.$this->pdo->escapeString($guidChar)); + $groupIDQuery = ($groupID === '' ? '' : 'AND r.groups_id = '.$groupID); + $optionsQuery = self::NfoQueryString($this->pdo); - $res = $this->pdo->query( + $res = $this->pdo->query( sprintf(' SELECT r.id, r.guid, r.groups_id, r.name FROM releases r @@ -315,23 +303,23 @@ class Nfo $this->nzbs ) ); - $nfoCount = count($res); + $nfoCount = count($res); - if ($nfoCount > 0) { - ColorCLI::doEcho( + if ($nfoCount > 0) { + ColorCLI::doEcho( ColorCLI::primary( - PHP_EOL . - ($guidChar === '' ? '' : '[' . $guidChar . '] ') . - ($groupID === '' ? '' : '[' . $groupID . '] ') . - 'Processing ' . $nfoCount . - ' NFO(s), starting at ' . $this->nzbs . + PHP_EOL. + ($guidChar === '' ? '' : '['.$guidChar.'] '). + ($groupID === '' ? '' : '['.$groupID.'] '). + 'Processing '.$nfoCount. + ' NFO(s), starting at '.$this->nzbs. ' * = hidden NFO, + = NFO, - = no NFO, f = download failed.' ) ); - if ($this->echo) { - // Get count of releases per nfo status - $nfoStats = $this->pdo->queryDirect( + if ($this->echo) { + // Get count of releases per nfo status + $nfoStats = $this->pdo->queryDirect( sprintf(' SELECT r.nfostatus AS status, COUNT(r.id) AS count FROM releases r @@ -343,52 +331,52 @@ class Nfo $groupIDQuery ) ); - if ($nfoStats instanceof \Traversable) { - $outString = PHP_EOL . 'Available to process'; - foreach ($nfoStats as $row) { - $outString .= ', ' . $row['status'] . ' = ' . number_format($row['count']); - } - ColorCLI::doEcho(ColorCLI::header($outString . '.')); - } - } + if ($nfoStats instanceof \Traversable) { + $outString = PHP_EOL.'Available to process'; + foreach ($nfoStats as $row) { + $outString .= ', '.$row['status'].' = '.number_format($row['count']); + } + ColorCLI::doEcho(ColorCLI::header($outString.'.')); + } + } - $groups = new Groups(['Settings' => $this->pdo]); - $nzbContents = new NZBContents( + $groups = new Groups(['Settings' => $this->pdo]); + $nzbContents = new NZBContents( [ 'Echo' => $this->echo, 'NNTP' => $nntp, 'Nfo' => $this, 'Settings' => $this->pdo, - 'PostProcess' => new PostProcess(['Echo' => $this->echo, 'Nfo' => $this, 'Settings' => $this->pdo]) + 'PostProcess' => new PostProcess(['Echo' => $this->echo, 'Nfo' => $this, 'Settings' => $this->pdo]), ] ); - $movie = new Movie(['Echo' => $this->echo, 'Settings' => $this->pdo]); + $movie = new Movie(['Echo' => $this->echo, 'Settings' => $this->pdo]); - foreach ($res as $arr) { - $fetchedBinary = $nzbContents->getNfoFromNZB($arr['guid'], $arr['id'], $arr['groups_id'], $groups->getNameByID($arr['groups_id'])); - if ($fetchedBinary !== false) { - // Insert nfo into database. - $cp = 'COMPRESS(%s)'; - $nc = $this->pdo->escapeString($fetchedBinary); + foreach ($res as $arr) { + $fetchedBinary = $nzbContents->getNfoFromNZB($arr['guid'], $arr['id'], $arr['groups_id'], $groups->getNameByID($arr['groups_id'])); + if ($fetchedBinary !== false) { + // Insert nfo into database. + $cp = 'COMPRESS(%s)'; + $nc = $this->pdo->escapeString($fetchedBinary); - $ckreleaseid = $this->pdo->queryOneRow(sprintf('SELECT releases_id FROM release_nfos WHERE releases_id = %d', $arr['id'])); - if (!isset($ckreleaseid['id'])) { - $this->pdo->queryInsert(sprintf('INSERT INTO release_nfos (nfo, releases_id) VALUES (' . $cp . ', %d)', $nc, $arr['id'])); - } - $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', self::NFO_FOUND, $arr['id'])); - $ret++; - $movie->doMovieUpdate($fetchedBinary, 'nfo', $arr['id'], $processImdb); + $ckreleaseid = $this->pdo->queryOneRow(sprintf('SELECT releases_id FROM release_nfos WHERE releases_id = %d', $arr['id'])); + if (! isset($ckreleaseid['id'])) { + $this->pdo->queryInsert(sprintf('INSERT INTO release_nfos (nfo, releases_id) VALUES ('.$cp.', %d)', $nc, $arr['id'])); + } + $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', self::NFO_FOUND, $arr['id'])); + $ret++; + $movie->doMovieUpdate($fetchedBinary, 'nfo', $arr['id'], $processImdb); - // If set scan for tv info. - if ($processTv === 1) { - (new PostProcess(['Echo' => $this->echo, 'Settings' => $this->pdo]))->processTv($groupID, $guidChar, $processTv); - } - } - } - } + // If set scan for tv info. + if ($processTv === 1) { + (new PostProcess(['Echo' => $this->echo, 'Settings' => $this->pdo]))->processTv($groupID, $guidChar, $processTv); + } + } + } + } - // Remove nfo that we cant fetch after 5 attempts. - $releases = $this->pdo->queryDirect( + // Remove nfo that we cant fetch after 5 attempts. + $releases = $this->pdo->queryDirect( sprintf( 'SELECT r.id FROM releases r @@ -402,34 +390,34 @@ class Nfo ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - // remove any releasenfo for failed - $this->pdo->queryExec(sprintf(' + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + // remove any releasenfo for failed + $this->pdo->queryExec(sprintf(' DELETE FROM release_nfos WHERE nfo IS NULL AND releases_id = %d', $release['id'] ) ); - // set release.nfostatus to failed - $this->pdo->queryExec(sprintf(' + // set release.nfostatus to failed + $this->pdo->queryExec(sprintf(' UPDATE releases r SET r.nfostatus = %d WHERE r.id = %d', self::NFO_FAILED, $release['id'] ) ); - } - } + } + } - if ($this->echo) { - if ($nfoCount > 0) { - echo PHP_EOL; - } - if ($ret > 0) { - ColorCLI::doEcho($ret . ' NFO file(s) found/processed.', true); - } - } - return $ret; - } + if ($this->echo) { + if ($nfoCount > 0) { + echo PHP_EOL; + } + if ($ret > 0) { + ColorCLI::doEcho($ret.' NFO file(s) found/processed.', true); + } + } + return $ret; + } } diff --git a/nntmux/Object.php b/nntmux/Object.php index 7d8065324..473c6f87e 100755 --- a/nntmux/Object.php +++ b/nntmux/Object.php @@ -17,13 +17,14 @@ * @link <http://www.gnu.org/licenses/>. * @author niel */ + namespace nntmux; use Closure; /** * Base class in hierarchy, from which all concrete classes inherit. This class defines - * several conventions for how classes in Lithium should be structured: + * several conventions for how classes in Lithium should be structured:. * * - **Universal constructor**: Any class which defines a `__construct()` method should take * exactly one parameter (`$config`), and that parameter should always be an array. Any settings @@ -46,130 +47,132 @@ use Closure; */ class Object { - /** - * Holds an array of values that should be processed on initialization. Each value should have - * a matching protected property (prefixed with `_`) defined in the class. If the property is - * an array, the property name should be the key and the value should be `'merge'`. See the - * `_init()` method for more details. - * - * @see lithium\core\Object::_init() - * @var array - */ - protected $_autoConfig = []; + /** + * Holds an array of values that should be processed on initialization. Each value should have + * a matching protected property (prefixed with `_`) defined in the class. If the property is + * an array, the property name should be the key and the value should be `'merge'`. See the + * `_init()` method for more details. + * + * @see lithium\core\Object::_init() + * @var array + */ + protected $_autoConfig = []; - /** - * Stores configuration information for object instances at time of construction. - * **Do not override.** Pass any additional variables to `parent::__construct()`. - * - * @var array - */ - protected $_config = []; + /** + * Stores configuration information for object instances at time of construction. + * **Do not override.** Pass any additional variables to `parent::__construct()`. + * + * @var array + */ + protected $_config = []; - /** - * Contains a 2-dimensional array of filters applied to this object's methods, indexed by method - * name. See the associated methods for more details. - * - * @see lithium\core\Object::_filter() - * @see lithium\core\Object::applyFilter() - * @var array - */ - protected $_methodFilters = []; + /** + * Contains a 2-dimensional array of filters applied to this object's methods, indexed by method + * name. See the associated methods for more details. + * + * @see lithium\core\Object::_filter() + * @see lithium\core\Object::applyFilter() + * @var array + */ + protected $_methodFilters = []; - /** - * Parents of the current class. - * - * @see lithium\core\Object::_parents() - * @var array - */ - protected static $_parents = []; + /** + * Parents of the current class. + * + * @see lithium\core\Object::_parents() + * @var array + */ + protected static $_parents = []; - /** - * Initializes class configuration (`$_config`), and assigns object properties using the - * `_init()` method, unless otherwise specified by configuration. See below for details. - * - * @see lithium\core\Object::$_config - * @see lithium\core\Object::_init() - * - * @param array $config The configuration options which will be assigned to the `$_config` - * property. This method accepts one configuration option: - * - `'init'` _boolean_: Controls constructor behavior for calling the `_init()` - * method. If `false`, the method is not called, otherwise it is. Defaults to - * `true`. - */ - public function __construct(array $config = []) - { - $defaults = array('init' => true); - $this->_config = $config + $defaults; + /** + * Initializes class configuration (`$_config`), and assigns object properties using the + * `_init()` method, unless otherwise specified by configuration. See below for details. + * + * @see lithium\core\Object::$_config + * @see lithium\core\Object::_init() + * + * @param array $config The configuration options which will be assigned to the `$_config` + * property. This method accepts one configuration option: + * - `'init'` _boolean_: Controls constructor behavior for calling the `_init()` + * method. If `false`, the method is not called, otherwise it is. Defaults to + * `true`. + */ + public function __construct(array $config = []) + { + $defaults = ['init' => true]; + $this->_config = $config + $defaults; - if ($this->_config['init']) { - $this->_init(); - } - } + if ($this->_config['init']) { + $this->_init(); + } + } - /** - * PHP magic method used in conjunction with `var_export()` to allow objects to be - * re-instantiated with their pre-existing properties and values intact. This method can be - * called statically on any class that extends `Object` to return an instance of it. - * - * @param array $data An array of properties and values with which to re-instantiate the object. - * These properties can be both public and protected. - * - * @return object Returns an instance of the requested object with the given properties set. - */ - public static function __set_state($data) - { - $class = get_called_class(); - $object = new $class(); + /** + * PHP magic method used in conjunction with `var_export()` to allow objects to be + * re-instantiated with their pre-existing properties and values intact. This method can be + * called statically on any class that extends `Object` to return an instance of it. + * + * @param array $data An array of properties and values with which to re-instantiate the object. + * These properties can be both public and protected. + * + * @return object Returns an instance of the requested object with the given properties set. + */ + public static function __set_state($data) + { + $class = get_called_class(); + $object = new $class(); - foreach ($data as $property => $value) { - $object->{$property} = $value; - } - return $object; - } + foreach ($data as $property => $value) { + $object->{$property} = $value; + } - /** - * Apply a closure to a method of the current object instance. - * - * @see lithium\core\Object::_filter() - * @see lithium\util\collection\Filters - * - * @param mixed $method The name of the method to apply the closure to. Can either be a single - * method name as a string, or an array of method names. Can also be false to remove - * all filters on the current object. - * @param Closure $filter The closure that is used to filter the method(s), can also be false - * to remove all the current filters for the given method. - * - * @return void - */ - public function applyFilter($method, $filter = null) - { - if ($method === false) { - $this->_methodFilters = []; - return; - } - foreach ((array)$method as $m) { - if (!isset($this->_methodFilters[$m]) || $filter === false) { - $this->_methodFilters[$m] = []; - } - if ($filter !== false) { - $this->_methodFilters[$m][] = $filter; - } - } - } + return $object; + } - /** - * Calls a method on this object with the given parameters. Provides an OO wrapper - * for call_user_func_array, and improves performance by using straight method calls - * in most cases. - * - * @param string $method Name of the method to call - * @param array $params Parameter list to use when calling $method - * - * @return mixed Returns the result of the method call - */ - public function invokeMethod($method, $params = []) - { - switch (count($params)) { + /** + * Apply a closure to a method of the current object instance. + * + * @see lithium\core\Object::_filter() + * @see lithium\util\collection\Filters + * + * @param mixed $method The name of the method to apply the closure to. Can either be a single + * method name as a string, or an array of method names. Can also be false to remove + * all filters on the current object. + * @param Closure $filter The closure that is used to filter the method(s), can also be false + * to remove all the current filters for the given method. + * + * @return void + */ + public function applyFilter($method, $filter = null) + { + if ($method === false) { + $this->_methodFilters = []; + + return; + } + foreach ((array) $method as $m) { + if (! isset($this->_methodFilters[$m]) || $filter === false) { + $this->_methodFilters[$m] = []; + } + if ($filter !== false) { + $this->_methodFilters[$m][] = $filter; + } + } + } + + /** + * Calls a method on this object with the given parameters. Provides an OO wrapper + * for call_user_func_array, and improves performance by using straight method calls + * in most cases. + * + * @param string $method Name of the method to call + * @param array $params Parameter list to use when calling $method + * + * @return mixed Returns the result of the method call + */ + public function invokeMethod($method, $params = []) + { + switch (count($params)) { case 0: return $this->{$method}(); case 1: @@ -183,138 +186,139 @@ class Object case 5: return $this->{$method}($params[0], $params[1], $params[2], $params[3], $params[4]); default: - return call_user_func_array(array(&$this, $method), $params); + return call_user_func_array([&$this, $method], $params); } - } + } - /** - * Will determine if a method can be called. - * - * @param string $method Method name. - * @param bool $internal Interal call or not. - * - * @return bool - */ - public function respondsTo($method, $internal = false) - { - return Inspector::isCallable($this, $method, $internal); - } + /** + * Will determine if a method can be called. + * + * @param string $method Method name. + * @param bool $internal Interal call or not. + * + * @return bool + */ + public function respondsTo($method, $internal = false) + { + return Inspector::isCallable($this, $method, $internal); + } - /** - * Executes a set of filters against a method by taking a method's main implementation as a - * callback, and iteratively wrapping the filters around it. This, along with the `Filters` - * class, is the core of Lithium's filters system. This system allows you to "reach into" an - * object's methods which are marked as _filterable_, and intercept calls to those methods, - * optionally modifying parameters or return values. - * - * @see lithium\core\Object::applyFilter() - * @see lithium\util\collection\Filters - * - * @param string $method The name of the method being executed, usually the value of - * `__METHOD__`. - * @param array $params An associative array containing all the parameters passed into - * the method. - * @param Closure $callback The method's implementation, wrapped in a closure. - * @param array $filters Additional filters to apply to the method for this call only. - * - * @return mixed Returns the return value of `$callback`, modified by any filters passed in - * `$filters` or applied with `applyFilter()`. - */ - protected function _filter($method, $params, $callback, $filters = []) - { - list($class, $method) = explode('::', $method); + /** + * Executes a set of filters against a method by taking a method's main implementation as a + * callback, and iteratively wrapping the filters around it. This, along with the `Filters` + * class, is the core of Lithium's filters system. This system allows you to "reach into" an + * object's methods which are marked as _filterable_, and intercept calls to those methods, + * optionally modifying parameters or return values. + * + * @see lithium\core\Object::applyFilter() + * @see lithium\util\collection\Filters + * + * @param string $method The name of the method being executed, usually the value of + * `__METHOD__`. + * @param array $params An associative array containing all the parameters passed into + * the method. + * @param Closure $callback The method's implementation, wrapped in a closure. + * @param array $filters Additional filters to apply to the method for this call only. + * + * @return mixed Returns the return value of `$callback`, modified by any filters passed in + * `$filters` or applied with `applyFilter()`. + */ + protected function _filter($method, $params, $callback, $filters = []) + { + list($class, $method) = explode('::', $method); - if (empty($this->_methodFilters[$method]) && empty($filters)) { - return $callback($this, $params, null); - } + if (empty($this->_methodFilters[$method]) && empty($filters)) { + return $callback($this, $params, null); + } - $f = isset($this->_methodFilters[$method]) ? $this->_methodFilters[$method] : []; - $data = array_merge($f, $filters, array($callback)); - return Filters::run($this, $params, compact('data', 'class', 'method')); - } + $f = isset($this->_methodFilters[$method]) ? $this->_methodFilters[$method] : []; + $data = array_merge($f, $filters, [$callback]); - /** - * Initializer function called by the constructor unless the constructor `'init'` flag is set - * to `false`. May be used for testing purposes, where objects need to be manipulated in an - * un-initialized state, or for high-overhead operations that require more control than the - * constructor provides. Additionally, this method iterates over the `$_autoConfig` property - * to automatically assign configuration settings to their corresponding properties. - * - * For example, given the following: {{{ - * class Bar extends \lithium\core\Object { - * protected $_autoConfig = array('foo'); - * protected $_foo; - * } - * - * $instance = new Bar(array('foo' => 'value')); - * }}} - * - * The `$_foo` property of `$instance` would automatically be set to `'value'`. If `$_foo` was - * an array, `$_autoConfig` could be set to `array('foo' => 'merge')`, and the constructor value - * of `'foo'` would be merged with the default value of `$_foo` and assigned to it. - * - * @see lithium\core\Object::$_autoConfig - * @return void - */ - protected function _init() - { - foreach ($this->_autoConfig as $key => $flag) { - if (!isset($this->_config[$key]) && !isset($this->_config[$flag])) { - continue; - } + return Filters::run($this, $params, compact('data', 'class', 'method')); + } - if ($flag === 'merge') { - $this->{"_{$key}"} = $this->_config[$key] + $this->{"_{$key}"}; - } else { - $this->{"_$flag"} = $this->_config[$flag]; - } - } - } + /** + * Initializer function called by the constructor unless the constructor `'init'` flag is set + * to `false`. May be used for testing purposes, where objects need to be manipulated in an + * un-initialized state, or for high-overhead operations that require more control than the + * constructor provides. Additionally, this method iterates over the `$_autoConfig` property + * to automatically assign configuration settings to their corresponding properties. + * + * For example, given the following: {{{ + * class Bar extends \lithium\core\Object { + * protected $_autoConfig = array('foo'); + * protected $_foo; + * } + * + * $instance = new Bar(array('foo' => 'value')); + * }}} + * + * The `$_foo` property of `$instance` would automatically be set to `'value'`. If `$_foo` was + * an array, `$_autoConfig` could be set to `array('foo' => 'merge')`, and the constructor value + * of `'foo'` would be merged with the default value of `$_foo` and assigned to it. + * + * @see lithium\core\Object::$_autoConfig + * @return void + */ + protected function _init() + { + foreach ($this->_autoConfig as $key => $flag) { + if (! isset($this->_config[$key]) && ! isset($this->_config[$flag])) { + continue; + } - /** - * Returns an instance of a class with given `config`. The `name` could be a key from the - * `classes` array, a fully-namespaced class name, or an object. Typically this method is used - * in `_init` to create the dependencies used in the current class. - * - * @param string|object $name A `classes` key or fully-namespaced class name. - * @param array $options The configuration passed to the constructor. - * - * @return object - */ - protected function _instance($name, array $options = []) - { - if (is_string($name) && isset($this->_classes[$name])) { - $name = $this->_classes[$name]; - } - return Libraries::instance(null, $name, $options); - } + if ($flag === 'merge') { + $this->{"_{$key}"} = $this->_config[$key] + $this->{"_{$key}"}; + } else { + $this->{"_$flag"} = $this->_config[$flag]; + } + } + } - /** - * Gets and caches an array of the parent methods of a class. - * - * @return array Returns an array of parent classes for the current class. - */ - protected static function _parents() - { - $class = get_called_class(); + /** + * Returns an instance of a class with given `config`. The `name` could be a key from the + * `classes` array, a fully-namespaced class name, or an object. Typically this method is used + * in `_init` to create the dependencies used in the current class. + * + * @param string|object $name A `classes` key or fully-namespaced class name. + * @param array $options The configuration passed to the constructor. + * + * @return object + */ + protected function _instance($name, array $options = []) + { + if (is_string($name) && isset($this->_classes[$name])) { + $name = $this->_classes[$name]; + } - if (!isset(self::$_parents[$class])) { - self::$_parents[$class] = class_parents($class); - } - return self::$_parents[$class]; - } + return Libraries::instance(null, $name, $options); + } - /** - * Exit immediately. Primarily used for overrides during testing. - * - * @param integer $status integer range 0 to 254, string printed on exit - * - * @return void - */ - protected function _stop($status = 0) - { - exit($status); - } + /** + * Gets and caches an array of the parent methods of a class. + * + * @return array Returns an array of parent classes for the current class. + */ + protected static function _parents() + { + $class = get_called_class(); + + if (! isset(self::$_parents[$class])) { + self::$_parents[$class] = class_parents($class); + } + + return self::$_parents[$class]; + } + + /** + * Exit immediately. Primarily used for overrides during testing. + * + * @param int $status integer range 0 to 254, string printed on exit + * + * @return void + */ + protected function _stop($status = 0) + { + exit($status); + } } - -?> diff --git a/nntmux/PreDb.php b/nntmux/PreDb.php index 3a5706224..f2ac6795b 100755 --- a/nntmux/PreDb.php +++ b/nntmux/PreDb.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; use nntmux\db\DB; @@ -9,12 +10,12 @@ use nntmux\db\DB; * * Class PreDb */ -Class PreDb +class PreDb { - // Nuke status. - const PRE_NONUKE = 0; // Pre is not nuked. + // Nuke status. + const PRE_NONUKE = 0; // Pre is not nuked. const PRE_UNNUKED = 1; // Pre was un nuked. - const PRE_NUKED = 2; // Pre is nuked. + const PRE_NUKED = 2; // Pre is nuked. const PRE_MODNUKE = 3; // Nuke reason was modified. const PRE_RENUKED = 4; // Pre was re nuked. const PRE_OLDNUKE = 5; // Pre is nuked for being old. @@ -22,57 +23,57 @@ Class PreDb /** * @var bool stdClass */ - protected $site; + protected $site; - /** - * @var bool - */ - protected $echooutput; + /** + * @var bool + */ + protected $echooutput; - /** - * @var \nntmux\db\DB - */ - protected $pdo; + /** + * @var \nntmux\db\DB + */ + protected $pdo; - private $dateLimit; + private $dateLimit; - /** - * @param array $options - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - } + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + } - /** - * Attempts to match PreDB titles to releases. - * - * @param $dateLimit - */ - public function checkPre($dateLimit = false): void - { - $this->dateLimit = $dateLimit; + /** + * Attempts to match PreDB titles to releases. + * + * @param $dateLimit + */ + public function checkPre($dateLimit = false): void + { + $this->dateLimit = $dateLimit; - $consoleTools = new ConsoleTools(['ColorCLI' => $this->pdo->log]); - $updated = 0; - $datesql = ''; + $consoleTools = new ConsoleTools(['ColorCLI' => $this->pdo->log]); + $updated = 0; + $datesql = ''; - if ($this->echooutput) { - echo ColorCLI::header('Querying DB for release search names not matched with PreDB titles.'); - } + if ($this->echooutput) { + echo ColorCLI::header('Querying DB for release search names not matched with PreDB titles.'); + } - if ($this->dateLimit !== false && is_numeric($this->dateLimit)) { - $datesql = sprintf('AND adddate > (NOW() - INTERVAL %d DAY)', $this->dateLimit); - } + if ($this->dateLimit !== false && is_numeric($this->dateLimit)) { + $datesql = sprintf('AND adddate > (NOW() - INTERVAL %d DAY)', $this->dateLimit); + } - $res = $this->pdo->queryDirect( + $res = $this->pdo->queryDirect( sprintf(' SELECT p.id AS predb_id, r.id AS releases_id FROM predb p @@ -82,170 +83,170 @@ Class PreDb ) ); - if ($res !== false) { - $total = $res->rowCount(); - echo ColorCLI::primary(number_format($total) . ' releases to match.'); + if ($res !== false) { + $total = $res->rowCount(); + echo ColorCLI::primary(number_format($total).' releases to match.'); - if ($res instanceof \Traversable) { - foreach ($res as $row) { - $this->pdo->queryExec( + if ($res instanceof \Traversable) { + foreach ($res as $row) { + $this->pdo->queryExec( sprintf('UPDATE releases SET predb_id = %d WHERE id = %d', $row['predb_id'], $row['releases_id']) ); - if ($this->echooutput) { - $consoleTools->overWritePrimary( - 'Matching up preDB titles with release searchnames: ' . $consoleTools->percentString( ++$updated, $total) + if ($this->echooutput) { + $consoleTools->overWritePrimary( + 'Matching up preDB titles with release searchnames: '.$consoleTools->percentString(++$updated, $total) ); - } - } - if ($this->echooutput) { - echo PHP_EOL; - } - } + } + } + if ($this->echooutput) { + echo PHP_EOL; + } + } - if ($this->echooutput) { - echo ColorCLI::header( - 'Matched ' . number_format(($updated > 0) ? $updated : 0) . ' PreDB titles to release search names.' + if ($this->echooutput) { + echo ColorCLI::header( + 'Matched '.number_format(($updated > 0) ? $updated : 0).' PreDB titles to release search names.' ); - } - } - } + } + } + } - /** - * Try to match a single release to a PreDB title when the release is created. - * - * @param string $cleanerName - * - * @return array|bool Array with title/id from PreDB if found, bool False if not found. - */ - public function matchPre($cleanerName) - { - if (empty($cleanerName)) { - return false; - } + /** + * Try to match a single release to a PreDB title when the release is created. + * + * @param string $cleanerName + * + * @return array|bool Array with title/id from PreDB if found, bool False if not found. + */ + public function matchPre($cleanerName) + { + if (empty($cleanerName)) { + return false; + } - $titleCheck = $this->pdo->queryOneRow( + $titleCheck = $this->pdo->queryOneRow( sprintf('SELECT id FROM predb WHERE title = %s LIMIT 1', $this->pdo->escapeString($cleanerName)) ); - if ($titleCheck !== false) { - return array( + if ($titleCheck !== false) { + return [ 'title' => $cleanerName, - 'predb_id' => $titleCheck['id'] - ); - } + 'predb_id' => $titleCheck['id'], + ]; + } - // Check if clean name matches a PreDB filename. - $fileCheck = $this->pdo->queryOneRow( + // Check if clean name matches a PreDB filename. + $fileCheck = $this->pdo->queryOneRow( sprintf('SELECT id, title FROM predb WHERE filename = %s LIMIT 1', $this->pdo->escapeString($cleanerName)) ); - if ($fileCheck !== false) { - return array( + if ($fileCheck !== false) { + return [ 'title' => $fileCheck['title'], - 'predb_id' => $fileCheck['id'] - ); - } + 'predb_id' => $fileCheck['id'], + ]; + } - return false; - } + return false; + } - /** - * Matches the hashes within the predb table to release files and subjects (names) which are hashed. - * - * @param $time - * @param $echo - * @param $cats - * @param $namestatus - * @param $show - * - * @return int - */ - public function parseTitles($time, $echo, $cats, $namestatus, $show): int - { - $namefixer = new NameFixer(['Echo' => $this->echooutput, 'ConsoleTools' => $this->pdo->log, 'Settings' => $this->pdo]); - $consoletools = new ConsoleTools(['ColorCLI' => $this->pdo->log]); - $othercats = implode(',', Category::OTHERS_GROUP); - $updated = $checked = 0; + /** + * Matches the hashes within the predb table to release files and subjects (names) which are hashed. + * + * @param $time + * @param $echo + * @param $cats + * @param $namestatus + * @param $show + * + * @return int + */ + public function parseTitles($time, $echo, $cats, $namestatus, $show): int + { + $namefixer = new NameFixer(['Echo' => $this->echooutput, 'ConsoleTools' => $this->pdo->log, 'Settings' => $this->pdo]); + $consoletools = new ConsoleTools(['ColorCLI' => $this->pdo->log]); + $othercats = implode(',', Category::OTHERS_GROUP); + $updated = $checked = 0; - $tq = ''; - if ($time === 1) { - $tq = 'AND r.adddate > (NOW() - INTERVAL 3 HOUR) ORDER BY rf.releases_id, rf.size DESC'; - } - $ct = ''; - if ($cats === 1) { - $ct = sprintf('AND r.categories_id IN (%s)', $othercats); - } + $tq = ''; + if ($time === 1) { + $tq = 'AND r.adddate > (NOW() - INTERVAL 3 HOUR) ORDER BY rf.releases_id, rf.size DESC'; + } + $ct = ''; + if ($cats === 1) { + $ct = sprintf('AND r.categories_id IN (%s)', $othercats); + } - if ($this->echooutput) { - $te = ''; - if ($time === 1) { - $te = ' in the past 3 hours'; - } - echo ColorCLI::header('Fixing search names' . $te . ' using the predb hash.'); - } - $regex = 'AND (r.ishashed = 1 OR rf.ishashed = 1)'; + if ($this->echooutput) { + $te = ''; + if ($time === 1) { + $te = ' in the past 3 hours'; + } + echo ColorCLI::header('Fixing search names'.$te.' using the predb hash.'); + } + $regex = 'AND (r.ishashed = 1 OR rf.ishashed = 1)'; - if ($cats === 3) { - $query = sprintf('SELECT r.id AS releases_id, r.name, r.searchname, r.categories_id, r.groups_id, ' - . 'dehashstatus, rf.name AS filename FROM releases r ' - . 'LEFT OUTER JOIN release_files rf ON r.id = rf.releases_id ' - . 'WHERE nzbstatus = 1 AND dehashstatus BETWEEN -6 AND 0 AND predb_id = 0 %s', $regex); - } else { - $query = sprintf('SELECT r.id AS releases_id, r.name, r.searchname, r.categories_id, r.groups_id, ' - . 'dehashstatus, rf.name AS filename FROM releases r ' - . 'LEFT OUTER JOIN release_files rf ON r.id = rf.releases_id ' - . 'WHERE nzbstatus = 1 AND isrenamed = 0 AND dehashstatus BETWEEN -6 AND 0 %s %s %s', $regex, $ct, $tq); - } + if ($cats === 3) { + $query = sprintf('SELECT r.id AS releases_id, r.name, r.searchname, r.categories_id, r.groups_id, ' + .'dehashstatus, rf.name AS filename FROM releases r ' + .'LEFT OUTER JOIN release_files rf ON r.id = rf.releases_id ' + .'WHERE nzbstatus = 1 AND dehashstatus BETWEEN -6 AND 0 AND predb_id = 0 %s', $regex); + } else { + $query = sprintf('SELECT r.id AS releases_id, r.name, r.searchname, r.categories_id, r.groups_id, ' + .'dehashstatus, rf.name AS filename FROM releases r ' + .'LEFT OUTER JOIN release_files rf ON r.id = rf.releases_id ' + .'WHERE nzbstatus = 1 AND isrenamed = 0 AND dehashstatus BETWEEN -6 AND 0 %s %s %s', $regex, $ct, $tq); + } - $res = $this->pdo->queryDirect($query); - $total = $res->rowCount(); - echo ColorCLI::primary(number_format($total) . ' releases to process.'); - if ($res instanceof \Traversable) { - foreach ($res as $row) { - if (preg_match('/[a-fA-F0-9]{32,40}/i', $row['name'], $matches)) { - $updated += $namefixer->matchPredbHash($matches[0], $row, $echo, $namestatus, $this->echooutput, $show); - } else if (preg_match('/[a-fA-F0-9]{32,40}/i', $row['filename'], $matches)) { - $updated += $namefixer->matchPredbHash($matches[0], $row, $echo, $namestatus, $this->echooutput, $show); - } - if ($show === 2) { - $consoletools->overWritePrimary('Renamed Releases: [' . number_format($updated) . '] ' . $consoletools->percentString($checked++, $total)); - } - } - } - if ($echo === 1) { - echo ColorCLI::header(PHP_EOL . $updated . ' releases have had their names changed out of: ' . number_format($checked) . ' files.'); - } else { - echo ColorCLI::header(PHP_EOL . $updated . ' releases could have their names changed. ' . number_format($checked) . ' files were checked.'); - } + $res = $this->pdo->queryDirect($query); + $total = $res->rowCount(); + echo ColorCLI::primary(number_format($total).' releases to process.'); + if ($res instanceof \Traversable) { + foreach ($res as $row) { + if (preg_match('/[a-fA-F0-9]{32,40}/i', $row['name'], $matches)) { + $updated += $namefixer->matchPredbHash($matches[0], $row, $echo, $namestatus, $this->echooutput, $show); + } elseif (preg_match('/[a-fA-F0-9]{32,40}/i', $row['filename'], $matches)) { + $updated += $namefixer->matchPredbHash($matches[0], $row, $echo, $namestatus, $this->echooutput, $show); + } + if ($show === 2) { + $consoletools->overWritePrimary('Renamed Releases: ['.number_format($updated).'] '.$consoletools->percentString($checked++, $total)); + } + } + } + if ($echo === 1) { + echo ColorCLI::header(PHP_EOL.$updated.' releases have had their names changed out of: '.number_format($checked).' files.'); + } else { + echo ColorCLI::header(PHP_EOL.$updated.' releases could have their names changed. '.number_format($checked).' files were checked.'); + } - return $updated; - } + return $updated; + } - /** - * Get all PRE's in the DB. - * - * @param int $offset OFFSET - * @param int $offset2 LIMIT - * @param string $search Optional title search. - * - * @return array The row count and the query results. - */ - public function getAll($offset, $offset2, $search = ''): array - { - if ($search !== '') { - $search = explode(' ', trim($search)); - if (count($search) > 1) { - $search = "LIKE '%" . implode("%' AND title LIKE '%", $search) . "%'"; - } else { - $search = "LIKE '%" . $search[0] . "%'"; - } - $search = 'WHERE title ' . $search; - } + /** + * Get all PRE's in the DB. + * + * @param int $offset OFFSET + * @param int $offset2 LIMIT + * @param string $search Optional title search. + * + * @return array The row count and the query results. + */ + public function getAll($offset, $offset2, $search = ''): array + { + if ($search !== '') { + $search = explode(' ', trim($search)); + if (count($search) > 1) { + $search = "LIKE '%".implode("%' AND title LIKE '%", $search)."%'"; + } else { + $search = "LIKE '%".$search[0]."%'"; + } + $search = 'WHERE title '.$search; + } - $count = $this->getCount($search); + $count = $this->getCount($search); - $sql = sprintf(' + $sql = sprintf(' SELECT p.*, r.guid FROM predb p LEFT OUTER JOIN releases r ON p.id = r.predb_id %s @@ -256,50 +257,51 @@ Class PreDb $offset2, $offset ); - $parr = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - return ['arr' => $parr, 'count' => $count]; - } + $parr = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - /** - * Get count of all PRE's. - * - * @param string $search - * - * @return int - */ - public function getCount($search = ''): int - { - $count = $this->pdo->query(" + return ['arr' => $parr, 'count' => $count]; + } + + /** + * Get count of all PRE's. + * + * @param string $search + * + * @return int + */ + public function getCount($search = ''): int + { + $count = $this->pdo->query(" SELECT COUNT(id) AS cnt FROM predb {$search}", true, NN_CACHE_EXPIRY_MEDIUM ); - return ($count === false ? 0 : $count[0]['cnt']); - } - /** - * Get all PRE's for a release. - * - * @param int $preID - * - * @return array - */ - public function getForRelease($preID): array - { - return $this->pdo->query(sprintf('SELECT * FROM predb WHERE id = %d', $preID)); - } + return $count === false ? 0 : $count[0]['cnt']; + } - /** - * Return a single PRE for a release. - * - * @param int $preID - * - * @return array - */ - public function getOne($preID): array - { - return $this->pdo->queryOneRow(sprintf('SELECT * FROM predb WHERE id = %d', $preID)); - } + /** + * Get all PRE's for a release. + * + * @param int $preID + * + * @return array + */ + public function getForRelease($preID): array + { + return $this->pdo->query(sprintf('SELECT * FROM predb WHERE id = %d', $preID)); + } + /** + * Return a single PRE for a release. + * + * @param int $preID + * + * @return array + */ + public function getOne($preID): array + { + return $this->pdo->queryOneRow(sprintf('SELECT * FROM predb WHERE id = %d', $preID)); + } } diff --git a/nntmux/Regexes.php b/nntmux/Regexes.php index 2d919ac38..bafe2ddc2 100755 --- a/nntmux/Regexes.php +++ b/nntmux/Regexes.php @@ -1,60 +1,61 @@ <?php + namespace nntmux; use nntmux\db\DB; class Regexes { - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var mixed The ID of the Regex inut string matched or the generic name - */ - public $matchedRegex; + /** + * @var mixed The ID of the Regex inut string matched or the generic name + */ + public $matchedRegex; - /** - * @var string Name of the current table we are working on. - */ - public $tableName; + /** + * @var string Name of the current table we are working on. + */ + public $tableName; - /** - * @var array Cache of regex and their TTL. - */ - protected $_regexCache; + /** + * @var array Cache of regex and their TTL. + */ + protected $_regexCache; - /** - * @var int - */ - protected $_categoriesID = Category::OTHER_MISC; + /** + * @var int + */ + protected $_categoriesID = Category::OTHER_MISC; - /** - * @param array $options - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, 'Table_Name' => '', ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->tableName = $options['Table_Name']; - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->tableName = $options['Table_Name']; + } - /** - * Add a new regex. - * - * @param array $data - * - * @return bool - */ - public function addRegex(array $data): bool - { - return (bool)$this->pdo->queryInsert( + /** + * Add a new regex. + * + * @param array $data + * + * @return bool + */ + public function addRegex(array $data): bool + { + return (bool) $this->pdo->queryInsert( sprintf( 'INSERT INTO %s (group_regex, regex, status, description, ordinal%s) VALUES (%s, %s, %d, %s, %d%s)', $this->tableName, @@ -64,21 +65,21 @@ class Regexes $data['status'], trim($this->pdo->escapeString($data['description'])), $data['ordinal'], - ($this->tableName === 'category_regexes' ? (', ' . $data['categories_id']) : '') + ($this->tableName === 'category_regexes' ? (', '.$data['categories_id']) : '') ) ); - } + } - /** - * Update a regex with new info. - * - * @param array $data - * - * @return bool - */ - public function updateRegex(array $data): bool - { - return (bool)$this->pdo->queryExec( + /** + * Update a regex with new info. + * + * @param array $data + * + * @return bool + */ + public function updateRegex(array $data): bool + { + return (bool) $this->pdo->queryExec( sprintf( 'UPDATE %s SET group_regex = %s, regex = %s, status = %d, description = %s, ordinal = %d %s @@ -89,97 +90,98 @@ class Regexes $data['status'], trim($this->pdo->escapeString($data['description'])), $data['ordinal'], - ($this->tableName === 'category_regexes' ? (', categories_id = ' . $data['categories_id']) : ''), + ($this->tableName === 'category_regexes' ? (', categories_id = '.$data['categories_id']) : ''), $data['id'] ) ); - } + } - /** - * Get a single regex using its id. - * - * @param int $id - * - * @return array - */ - public function getRegexByID($id): array - { - return $this->pdo->queryOneRow(sprintf('SELECT * FROM %s WHERE id = %d', $this->tableName, $id)); - } + /** + * Get a single regex using its id. + * + * @param int $id + * + * @return array + */ + public function getRegexByID($id): array + { + return $this->pdo->queryOneRow(sprintf('SELECT * FROM %s WHERE id = %d', $this->tableName, $id)); + } - /** - * Get all regex. - * - * @param string $group_regex Optional, a keyword to find a group. - * @param int $limit Optional, amount of results to limit. - * @param int $offset Optional, the offset to use when limiting the result set. - * - * @return array - */ - public function getRegex($group_regex = '', $limit = 0, $offset = 0): array - { - return $this->pdo->query( + /** + * Get all regex. + * + * @param string $group_regex Optional, a keyword to find a group. + * @param int $limit Optional, amount of results to limit. + * @param int $offset Optional, the offset to use when limiting the result set. + * + * @return array + */ + public function getRegex($group_regex = '', $limit = 0, $offset = 0): array + { + return $this->pdo->query( sprintf( 'SELECT * FROM %s %s ORDER BY id %s', $this->tableName, $this->_groupQueryString($group_regex), - ($limit ? ('LIMIT ' . $limit . ' OFFSET ' . $offset) : '') + ($limit ? ('LIMIT '.$limit.' OFFSET '.$offset) : '') ) ); - } + } - /** - * Get the count of regex in the DB. - * - * @param string $group_regex Optional, keyword to find a group. - * - * @return int - */ - public function getCount($group_regex = ''): int - { - $query = $this->pdo->queryOneRow( + /** + * Get the count of regex in the DB. + * + * @param string $group_regex Optional, keyword to find a group. + * + * @return int + */ + public function getCount($group_regex = ''): int + { + $query = $this->pdo->queryOneRow( sprintf( 'SELECT COUNT(id) AS count FROM %s %s', $this->tableName, $this->_groupQueryString($group_regex) ) ); - return (int)$query['count']; - } - /** - * Delete a regex using its id. - * - * @param int $id - */ - public function deleteRegex($id): void - { - $this->pdo->queryExec(sprintf('DELETE FROM %s WHERE id = %d', $this->tableName, $id)); - } + return (int) $query['count']; + } - /** - * Test a single collection regex for a group name. - * - * Requires table per group to be on. - * - * @param string $groupName - * @param string $regex - * @param int $limit - * - * @return array - */ - public function testCollectionRegex($groupName, $regex, $limit): array - { - $groups = new Groups(['Settings' => $this->pdo]); - $groupID = $groups->getIDByName($groupName); + /** + * Delete a regex using its id. + * + * @param int $id + */ + public function deleteRegex($id): void + { + $this->pdo->queryExec(sprintf('DELETE FROM %s WHERE id = %d', $this->tableName, $id)); + } - if (!$groupID) { - return []; - } + /** + * Test a single collection regex for a group name. + * + * Requires table per group to be on. + * + * @param string $groupName + * @param string $regex + * @param int $limit + * + * @return array + */ + public function testCollectionRegex($groupName, $regex, $limit): array + { + $groups = new Groups(['Settings' => $this->pdo]); + $groupID = $groups->getIDByName($groupName); - $tableNames = $groups->getCBPTableNames($groupID); + if (! $groupID) { + return []; + } - $rows = $this->pdo->query( + $tableNames = $groups->getCBPTableNames($groupID); + + $rows = $this->pdo->query( sprintf( 'SELECT b.name, b.totalparts, b.currentparts, HEX(b.binaryhash) AS binaryhash, @@ -190,26 +192,26 @@ class Regexes ) ); - $data = []; - if ($rows) { - $limit--; - $hashes = []; - foreach ($rows as $row) { - if (preg_match($regex, $row['name'], $matches)) { - ksort($matches); - $string = $string2 = ''; - foreach ($matches as $key => $match) { - if (!is_int($key)) { - $string .= $match; - $string2 .= '<br/>' . $key . ': ' . $match; - } - } - $files = 0; - if (preg_match('/[[(\s](\d{1,5})(\/|[\s_]of[\s_]|-)(\d{1,5})[])\s$:]/i', $row['name'], $fileCount)) { - $files = $fileCount[3]; - } - $newCollectionHash = sha1($string . $row['fromname'] . $groupID . $files); - $data['New hash: ' . $newCollectionHash . $string2][$row['binaryhash']] = [ + $data = []; + if ($rows) { + $limit--; + $hashes = []; + foreach ($rows as $row) { + if (preg_match($regex, $row['name'], $matches)) { + ksort($matches); + $string = $string2 = ''; + foreach ($matches as $key => $match) { + if (! is_int($key)) { + $string .= $match; + $string2 .= '<br/>'.$key.': '.$match; + } + } + $files = 0; + if (preg_match('/[[(\s](\d{1,5})(\/|[\s_]of[\s_]|-)(\d{1,5})[])\s$:]/i', $row['name'], $fileCount)) { + $files = $fileCount[3]; + } + $newCollectionHash = sha1($string.$row['fromname'].$groupID.$files); + $data['New hash: '.$newCollectionHash.$string2][$row['binaryhash']] = [ 'new_collection_hash' => $newCollectionHash, 'file_name' => $row['name'], 'file_total_parts' => $row['totalparts'], @@ -218,116 +220,118 @@ class Regexes 'old_collection_hash' => $row['collectionhash'], ]; - if ($limit > 0) { - if (count($hashes) > $limit) { - break; - } - $hashes[$newCollectionHash] = ''; - } - } - } - } - return $data; - } + if ($limit > 0) { + if (count($hashes) > $limit) { + break; + } + $hashes[$newCollectionHash] = ''; + } + } + } + } - /** - * Test a single release naming regex for a group name. - * - * @param string $groupName - * @param string $regex - * @param int $displayLimit - * @param int $queryLimit - * - * @return array - * @throws \Exception - */ - public function testReleaseNamingRegex($groupName, $regex, $displayLimit, $queryLimit): array - { - $groups = new Groups(['Settings' => $this->pdo]); - $groupID = $groups->getIDByName($groupName); + return $data; + } - if (!$groupID) { - return []; - } + /** + * Test a single release naming regex for a group name. + * + * @param string $groupName + * @param string $regex + * @param int $displayLimit + * @param int $queryLimit + * + * @return array + * @throws \Exception + */ + public function testReleaseNamingRegex($groupName, $regex, $displayLimit, $queryLimit): array + { + $groups = new Groups(['Settings' => $this->pdo]); + $groupID = $groups->getIDByName($groupName); - $rows = $this->pdo->query( + if (! $groupID) { + return []; + } + + $rows = $this->pdo->query( sprintf( 'SELECT name, searchname, id FROM releases WHERE groups_id = %d %s', $groupID, - (int)$queryLimit === 0 ? '' : sprintf('LIMIT %d', $queryLimit) + (int) $queryLimit === 0 ? '' : sprintf('LIMIT %d', $queryLimit) ) ); - $data = []; - if ($rows) { - $limit = 1; - foreach ($rows as $row) { - $match = $this->_matchRegex($regex, $row['name']); - if ($match) { - $data[$row['id']] = [ + $data = []; + if ($rows) { + $limit = 1; + foreach ($rows as $row) { + $match = $this->_matchRegex($regex, $row['name']); + if ($match) { + $data[$row['id']] = [ 'subject' => $row['name'], 'old_name' => $row['searchname'], - 'new_name' => $match + 'new_name' => $match, ]; - if ((int)$displayLimit > 0 && $limit++ >= (int)$displayLimit) { - break; - } - } - } - } - return $data; - } + if ((int) $displayLimit > 0 && $limit++ >= (int) $displayLimit) { + break; + } + } + } + } - /** - * This will try to find regex in the DB for a group and a usenet subject, attempt to match them and return the matches. - * - * @param string $subject - * @param string $groupName - * - * @return string - * @throws \Exception - */ - public function tryRegex($subject, $groupName): string - { - $this->matchedRegex = 0; + return $data; + } - $this->_fetchRegex($groupName); + /** + * This will try to find regex in the DB for a group and a usenet subject, attempt to match them and return the matches. + * + * @param string $subject + * @param string $groupName + * + * @return string + * @throws \Exception + */ + public function tryRegex($subject, $groupName): string + { + $this->matchedRegex = 0; - $returnString = ''; - // If there are no regex, return and try regex in this file. - if ($this->_regexCache[$groupName]['regex']) { - foreach ($this->_regexCache[$groupName]['regex'] as $regex) { + $this->_fetchRegex($groupName); - if ($this->tableName === 'category_regexes') { - $this->_categoriesID = $regex['categories_id']; - } + $returnString = ''; + // If there are no regex, return and try regex in this file. + if ($this->_regexCache[$groupName]['regex']) { + foreach ($this->_regexCache[$groupName]['regex'] as $regex) { + if ($this->tableName === 'category_regexes') { + $this->_categoriesID = $regex['categories_id']; + } - $returnString = $this->_matchRegex($regex['regex'], $subject); - // If this regex found something, break and return, or else continue trying other regex. - if ($returnString) { - $this->matchedRegex = $regex['id']; - break; - } - } - } - return $returnString; - } + $returnString = $this->_matchRegex($regex['regex'], $subject); + // If this regex found something, break and return, or else continue trying other regex. + if ($returnString) { + $this->matchedRegex = $regex['id']; + break; + } + } + } - /** - * Get the regex from the DB, cache them locally for 15 mins. - * Cache them also in the cache server, as this script might be terminated. - * - * @param string $groupName - */ - protected function _fetchRegex($groupName): void - { - // Check if we need to do an initial cache or refresh our cache. - if (isset($this->_regexCache[$groupName]['ttl']) && (time() - $this->_regexCache[$groupName]['ttl']) < NN_CACHE_EXPIRY_LONG) { - return; - } + return $returnString; + } - // Get all regex from DB which match the current group name. Cache them for 15 minutes. #CACHEDQUERY# - $this->_regexCache[$groupName]['regex'] = $this->pdo->query( + /** + * Get the regex from the DB, cache them locally for 15 mins. + * Cache them also in the cache server, as this script might be terminated. + * + * @param string $groupName + */ + protected function _fetchRegex($groupName): void + { + // Check if we need to do an initial cache or refresh our cache. + if (isset($this->_regexCache[$groupName]['ttl']) && (time() - $this->_regexCache[$groupName]['ttl']) < NN_CACHE_EXPIRY_LONG) { + return; + } + + // Get all regex from DB which match the current group name. Cache them for 15 minutes. #CACHEDQUERY# + $this->_regexCache[$groupName]['regex'] = $this->pdo->query( sprintf( 'SELECT r.id, r.regex%s FROM %s r WHERE %s REGEXP r.group_regex AND r.status = 1 ORDER BY r.ordinal ASC, r.group_regex ASC', ($this->tableName === 'category_regexes' ? ', r.categories_id' : ''), @@ -335,40 +339,40 @@ class Regexes $this->pdo->escapeString($groupName) ), true, NN_CACHE_EXPIRY_LONG ); - // Set the TTL. - $this->_regexCache[$groupName]['ttl'] = time(); - } + // Set the TTL. + $this->_regexCache[$groupName]['ttl'] = time(); + } - /** - * Find matches on a regex taken from the database. - * - * Requires at least 1 named captured group. - * - * @param string $regex - * @param string $subject - * - * @return string - * @throws \Exception - */ - protected function _matchRegex($regex, $subject): string - { - $returnString = ''; - if (@preg_match($regex, $subject, $matches) === false) { - if (NN_LOGGING) { - $message = "Regex match failed - table: {$this->tableName}, regex: $regex"; - $logger = new Logger(); - $logger->log(__CLASS__, __METHOD__, $message, Logger::LOG_ERROR); - } - } else if (count($matches) > 0) { - // Sort the keys, the named key matches will be concatenated in this order. - ksort($matches); - foreach ($matches as $key => $value) { - switch ($this->tableName) { + /** + * Find matches on a regex taken from the database. + * + * Requires at least 1 named captured group. + * + * @param string $regex + * @param string $subject + * + * @return string + * @throws \Exception + */ + protected function _matchRegex($regex, $subject): string + { + $returnString = ''; + if (@preg_match($regex, $subject, $matches) === false) { + if (NN_LOGGING) { + $message = "Regex match failed - table: {$this->tableName}, regex: $regex"; + $logger = new Logger(); + $logger->log(__CLASS__, __METHOD__, $message, Logger::LOG_ERROR); + } + } elseif (count($matches) > 0) { + // Sort the keys, the named key matches will be concatenated in this order. + ksort($matches); + foreach ($matches as $key => $value) { + switch ($this->tableName) { case 'collection_regexes': // Put this at the top since it's the most important for performance. case 'release_naming_regexes': // Ignore non-named capture groups. Only named capture groups are important. if (is_int($key) || preg_match('#reqid|parts#i', $key)) { - continue 2; + continue 2; } $returnString .= $value; // Concatenate the string to return. break; @@ -376,20 +380,21 @@ class Regexes $returnString = $this->_categoriesID; // Regex matched, so return the category ID. break 2; } - } - } - return $returnString; - } + } + } - /** - * Format part of a query. - * - * @param string $group_regex - * - * @return string - */ - protected function _groupQueryString($group_regex): string - { - return ($group_regex ? ('WHERE group_regex ' . $this->pdo->likeString($group_regex)) : ''); - } + return $returnString; + } + + /** + * Format part of a query. + * + * @param string $group_regex + * + * @return string + */ + protected function _groupQueryString($group_regex): string + { + return $group_regex ? ('WHERE group_regex '.$this->pdo->likeString($group_regex)) : ''; + } } diff --git a/nntmux/ReleaseCleaning.php b/nntmux/ReleaseCleaning.php index b3b8b1c13..4dfa3825e 100755 --- a/nntmux/ReleaseCleaning.php +++ b/nntmux/ReleaseCleaning.php @@ -1,174 +1,173 @@ <?php + namespace nntmux; use nntmux\db\DB; /** * Cleans names for releases/imports/namefixer. - * Names of group functions should match between CollectionsCleaning and this file + * Names of group functions should match between CollectionsCleaning and this file. */ - - class ReleaseCleaning { - /** - * Used for matching endings in article subjects. - * @const - * @string - */ - const REGEX_END = '[- ]{0,3}yEnc$/u'; + /** + * Used for matching endings in article subjects. + * @const + * @string + */ + const REGEX_END = '[- ]{0,3}yEnc$/u'; - /** - * Used for matching file extension endings in article subjects. - * @const - * @string - */ - const REGEX_FILE_EXTENSIONS = '([-_](proof|sample|thumbs?))*(\.part\d*(\.rar)?|\.rar|\.7z)?(\d{1,3}\.rev"|\.vol.+?"|\.[A-Za-z0-9]{2,4}"|")'; + /** + * Used for matching file extension endings in article subjects. + * @const + * @string + */ + const REGEX_FILE_EXTENSIONS = '([-_](proof|sample|thumbs?))*(\.part\d*(\.rar)?|\.rar|\.7z)?(\d{1,3}\.rev"|\.vol.+?"|\.[A-Za-z0-9]{2,4}"|")'; - /** - * Used for matching size strings in article subjects. - * @example ' - 365.15 KB - ' - * @const - * @string - */ - const REGEX_SUBJECT_SIZE = '[- ]{0,3}\d+([.,]\d+)? [kKmMgG][bB][- ]{0,3}'; - /** - * @var string - */ - public $e0; + /** + * Used for matching size strings in article subjects. + * @example ' - 365.15 KB - ' + * @const + * @string + */ + const REGEX_SUBJECT_SIZE = '[- ]{0,3}\d+([.,]\d+)? [kKmMgG][bB][- ]{0,3}'; + /** + * @var string + */ + public $e0; - /** - * @var string - */ - public $e1; + /** + * @var string + */ + public $e1; - /** - * @var string - */ - public $e2; + /** + * @var string + */ + public $e2; - /** - * @var string - */ - public $fromName = ''; + /** + * @var string + */ + public $fromName = ''; - /** - * @var string - */ - public $groupName = ''; + /** + * @var string + */ + public $groupName = ''; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var string - */ - public $size = ''; + /** + * @var string + */ + public $size = ''; - /** - * @var string - */ - public $subject = ''; + /** + * @var string + */ + public $subject = ''; - /** - * @var Regexes - */ - protected $_regexes; + /** + * @var Regexes + */ + protected $_regexes; - /** - * @param DB $settings - */ - public function __construct($settings = null) - { - // Extensions. - $this->e0 = CollectionsCleaning::REGEX_FILE_EXTENSIONS; - $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->_regexes = new Regexes(['Settings' => $this->pdo, 'Table_Name' => 'release_naming_regexes']); - } + /** + * @param DB $settings + */ + public function __construct($settings = null) + { + // Extensions. + $this->e0 = CollectionsCleaning::REGEX_FILE_EXTENSIONS; + $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->_regexes = new Regexes(['Settings' => $this->pdo, 'Table_Name' => 'release_naming_regexes']); + } - /** - * @param $subject - * @param $fromName - * @param $size - * @param $groupName - * @param bool $usepre - * - * @return array|bool|null - * @throws \Exception - */ - public function releaseCleaner($subject, $fromName, $size, $groupName, $usepre = false) - { - $match = $matches = []; - $this->groupName = $groupName; - $this->subject = $subject; - $this->fromName = $fromName; - $this->size = $size; - // Get pre style name from releases.name - if (preg_match_all('/([\w\(\)]+[\s\._-]([\w\(\)]+[\s\._-])+[\w\(\)]+-\w+)/', + /** + * @param $subject + * @param $fromName + * @param $size + * @param $groupName + * @param bool $usepre + * + * @return array|bool|null + * @throws \Exception + */ + public function releaseCleaner($subject, $fromName, $size, $groupName, $usepre = false) + { + $match = $matches = []; + $this->groupName = $groupName; + $this->subject = $subject; + $this->fromName = $fromName; + $this->size = $size; + // Get pre style name from releases.name + if (preg_match_all('/([\w\(\)]+[\s\._-]([\w\(\)]+[\s\._-])+[\w\(\)]+-\w+)/', $this->subject, $matches)) { - foreach ($matches as $match) { - foreach ($match as $val) { - $title = $this->pdo->queryOneRow('SELECT title, id from predb WHERE title = ' . + foreach ($matches as $match) { + foreach ($match as $val) { + $title = $this->pdo->queryOneRow('SELECT title, id from predb WHERE title = '. $this->pdo->escapeString(trim($val))); - // don't match against ab.teevee if title is for just the season - if ($this->groupName === 'alt.binaries.teevee' && preg_match('/\.S\d\d\./', $title['title'], $match)) { - $title = false; - } - if ($title !== false) { - return [ + // don't match against ab.teevee if title is for just the season + if ($this->groupName === 'alt.binaries.teevee' && preg_match('/\.S\d\d\./', $title['title'], $match)) { + $title = false; + } + if ($title !== false) { + return [ 'cleansubject' => $title['title'], 'properlynamed' => true, 'increment' => false, 'predb' => $title['id'], - 'requestid' => false + 'requestid' => false, ]; - } - } - } - } - // Get pre style name from requestid - if (preg_match('/^\[ ?(\d{4,6}) ?\]/', $this->subject, $match) || + } + } + } + } + // Get pre style name from requestid + if (preg_match('/^\[ ?(\d{4,6}) ?\]/', $this->subject, $match) || preg_match('/^REQ\s*(\d{4,6})/i', $this->subject, $match) || preg_match('/^(\d{4,6})-\d{1}\[/', $this->subject, $match) || preg_match('/(\d{4,6}) -/', $this->subject, $match) ) { - $title = $this->pdo->queryOneRow( + $title = $this->pdo->queryOneRow( sprintf( 'SELECT p.title , p.id from predb p INNER JOIN groups g on g.id = p.groups_id WHERE p.requestid = %d and g.name = %s', $match[1], $this->pdo->escapeString($this->groupName) ) ); - //check for predb title matches against other groups where it matches relative size / fromname - //known crossposted requests only atm - $reqGname = ''; - switch ($this->groupName) { + //check for predb title matches against other groups where it matches relative size / fromname + //known crossposted requests only atm + $reqGname = ''; + switch ($this->groupName) { case 'alt.binaries.etc': if ($this->fromName === 'kingofpr0n (brian@iamking.ws)') { - $reqGname = 'alt.binaries.teevee'; + $reqGname = 'alt.binaries.teevee'; } break; case 'alt.binaries.mom': if ($this->fromName === 'Yenc@power-post.org (Yenc-PP-A&A)' || $this->fromName === 'yEncBin@Poster.com (yEncBin)' ) { - $reqGname = 'alt.binaries.moovee'; + $reqGname = 'alt.binaries.moovee'; } break; case 'alt.binaries.hdtv.x264': if ($this->fromName === 'moovee@4u.tv (moovee)') { - $reqGname = 'alt.binaries.moovee'; + $reqGname = 'alt.binaries.moovee'; } break; } - if ($title === false && !empty($reqGname)) { - $title = $this->pdo->queryOneRow( + if ($title === false && ! empty($reqGname)) { + $title = $this->pdo->queryOneRow( sprintf( 'SELECT p.title as title, p.id as id from predb p INNER JOIN groups g on g.id = p.groups_id WHERE p.requestid = %d and g.name = %s', @@ -176,254 +175,260 @@ class ReleaseCleaning $this->pdo->escapeString($reqGname) ) ); - } - // don't match against ab.teevee if title is for just the season - if ($this->groupName === 'alt.binaries.teevee' && preg_match('/\.S\d\d\./', $title['title'], $match)) { - $title = false; - } - if ($title !== false) { - return [ + } + // don't match against ab.teevee if title is for just the season + if ($this->groupName === 'alt.binaries.teevee' && preg_match('/\.S\d\d\./', $title['title'], $match)) { + $title = false; + } + if ($title !== false) { + return [ 'cleansubject' => $title['title'], 'properlynamed' => true, 'increment' => false, 'predb' => $title['id'], - 'requestid' => true + 'requestid' => true, ]; - } - } - if ($usepre === true) { - return false; - } + } + } + if ($usepre === true) { + return false; + } - // Try DB regex. - $potentialName = $this->_regexes->tryRegex($subject, $groupName); - if ($potentialName) { - return [ + // Try DB regex. + $potentialName = $this->_regexes->tryRegex($subject, $groupName); + if ($potentialName) { + return [ 'id' => $this->_regexes->matchedRegex, 'cleansubject' => $potentialName, - 'properlynamed' => false + 'properlynamed' => false, ]; - } + } - //if www.town.ag releases check against generic_town regexes - if (preg_match('/www\.town\.ag/i', $this->subject)) { - return $this->generic_town(); - } - switch ($groupName) { + //if www.town.ag releases check against generic_town regexes + if (preg_match('/www\.town\.ag/i', $this->subject)) { + return $this->generic_town(); + } + switch ($groupName) { case 'alt.binaries.teevee': return $this->teevee(); default: return $this->generic(); } - } + } - /** - * @return array - */ - public function teevee(): array - { - //[140022]-[04] - [01/40] - "140022-04.nfo" yEnc - if (preg_match('/\[\d+\]-\[.+\] - \[\d+\/\d+\] - "\d+-.+" yEnc/', $this->subject)) { - return [ + /** + * @return array + */ + public function teevee(): array + { + //[140022]-[04] - [01/40] - "140022-04.nfo" yEnc + if (preg_match('/\[\d+\]-\[.+\] - \[\d+\/\d+\] - "\d+-.+" yEnc/', $this->subject)) { + return [ 'cleansubject' => $this->subject, 'properlynamed' => false, - 'ignore' => true + 'ignore' => true, ]; - } - return [ - 'cleansubject' => $this->releaseCleanerHelper($this->subject), - 'properlynamed' => false - ]; - } + } - /** - * @return array|string - */ - public function generic_town() - { - //<TOWN><www.town.ag > <download all our files with>>> www.ssl-news.info <<< > [05/87] - "Deep.Black.Ass.5.XXX.1080p.WEBRip.x264-TBP.part03.rar" - 7,87 GB yEnc - //<TOWN><www.town.ag > <partner of www.ssl-news.info > [02/24] - "Dragons.Den.UK.S11E02.HDTV.x264-ANGELiC.nfo" - 288,96 MB yEnc - //<TOWN><www.town.ag > <SSL - News.Info> [6/6] - "TTT.Magazine.2013.08.vol0+1.par2" - 33,47 MB yEnc - if (preg_match('/^<TOWN>.+?town\.ag.+?(www\..+?|News)\.[iI]nfo.+? \[\d+\/\d+\]( -)? "(.+?)(-sample)?' . $this->e0 . ' - \d+[.,]\d+ [kKmMgG][bB]M? yEnc$/', $this->subject, $match)) { - return $match[3]; - } //[ TOWN ]-[ www.town.ag ]-[ partner of www.ssl-news.info ]-[ 1080p ] - [320/352] - "Gq7YGEWLy8wAA2NhbZx5LukEa.vol000+5.par2" - 17.09 GB yEnc - if (preg_match('/^\[\s*TOWN\s*\][-_\s]{0,3}\[\s*www\.town\.ag\s*\][-_\s]{0,3}\[\s*partner of www\.ssl-news\.info\s*\][-_\s]{0,3}\[\s* .*\s*\][-_\s]{0,3}\[\d+\/\d+\][-_\s]{0,4}"([\w\säöüÄÖÜß+¤ƒ¶!.,&_()\[\]\'\`{}#-]{8,}?\b.?)' . $this->e2, $this->subject, $match)) { - return $match[1]; - } //<TOWN><www.town.ag > <download all our files with>>> www.ssl-news.info <<< >IP Scanner Pro 3.21-Sebaro - [1/3] - "IP Scanner Pro 3.21-Sebaro.rar" yEnc - if (preg_match('/^<TOWN>.+?town\.ag.+?(www\..+?|News)\.[iI]nfo.+? \[\d+\/\d+\]( -)? "(.+?)(-sample)?' . + return [ + 'cleansubject' => $this->releaseCleanerHelper($this->subject), + 'properlynamed' => false, + ]; + } + + /** + * @return array|string + */ + public function generic_town() + { + //<TOWN><www.town.ag > <download all our files with>>> www.ssl-news.info <<< > [05/87] - "Deep.Black.Ass.5.XXX.1080p.WEBRip.x264-TBP.part03.rar" - 7,87 GB yEnc + //<TOWN><www.town.ag > <partner of www.ssl-news.info > [02/24] - "Dragons.Den.UK.S11E02.HDTV.x264-ANGELiC.nfo" - 288,96 MB yEnc + //<TOWN><www.town.ag > <SSL - News.Info> [6/6] - "TTT.Magazine.2013.08.vol0+1.par2" - 33,47 MB yEnc + if (preg_match('/^<TOWN>.+?town\.ag.+?(www\..+?|News)\.[iI]nfo.+? \[\d+\/\d+\]( -)? "(.+?)(-sample)?'.$this->e0.' - \d+[.,]\d+ [kKmMgG][bB]M? yEnc$/', $this->subject, $match)) { + return $match[3]; + } //[ TOWN ]-[ www.town.ag ]-[ partner of www.ssl-news.info ]-[ 1080p ] - [320/352] - "Gq7YGEWLy8wAA2NhbZx5LukEa.vol000+5.par2" - 17.09 GB yEnc + if (preg_match('/^\[\s*TOWN\s*\][-_\s]{0,3}\[\s*www\.town\.ag\s*\][-_\s]{0,3}\[\s*partner of www\.ssl-news\.info\s*\][-_\s]{0,3}\[\s* .*\s*\][-_\s]{0,3}\[\d+\/\d+\][-_\s]{0,4}"([\w\säöüÄÖÜß+¤ƒ¶!.,&_()\[\]\'\`{}#-]{8,}?\b.?)'.$this->e2, $this->subject, $match)) { + return $match[1]; + } //<TOWN><www.town.ag > <download all our files with>>> www.ssl-news.info <<< >IP Scanner Pro 3.21-Sebaro - [1/3] - "IP Scanner Pro 3.21-Sebaro.rar" yEnc + if (preg_match('/^<TOWN>.+?town\.ag.+?(www\..+?|News)\.[iI]nfo.+? \[\d+\/\d+\]( -)? "(.+?)(-sample)?'. $this->e1, $this->subject, $match) ) { - return $match[3]; - } //(05/10) -<TOWN><www.town.ag > <partner of www.ssl-news.info > - "D.Olivier.Wer Boeses.saet-gsx-.part4.rar" - 741,51 kB - yEnc - if (preg_match('/^\(\d+\/\d+\) -<TOWN><www\.town\.ag >\s+<partner.+> - ("|#34;)([\w. ()-]{8,}?\b)(\.par2|-\.part\d+\.rar|\.nfo)("|#34;) - \d+[.,]\d+ [kKmMgG][bB]( -)? yEnc$/', + return $match[3]; + } //(05/10) -<TOWN><www.town.ag > <partner of www.ssl-news.info > - "D.Olivier.Wer Boeses.saet-gsx-.part4.rar" - 741,51 kB - yEnc + if (preg_match('/^\(\d+\/\d+\) -<TOWN><www\.town\.ag >\s+<partner.+> - ("|#34;)([\w. ()-]{8,}?\b)(\.par2|-\.part\d+\.rar|\.nfo)("|#34;) - \d+[.,]\d+ [kKmMgG][bB]( -)? yEnc$/', $this->subject, $match) ) { - return $match[2]; - } //[ TOWN ]-[ www.town.ag ]-[ partner of www.ssl-news.info ]-[ MOVIE ] [14/19] - "Night.Vision.2011.DVDRip.x264-IGUANA.part12.rar" - 660,80 MB yEnc - if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ partner of www\.ssl-news\.info \][ _-]{0,3}\[ .* \] \[\d+\/\d+\][ _-]{0,3}("|#34;)(.+)((\.part\d+\.rar)|(\.vol\d+\+\d+\.par2))("|#34;)[ _-]{0,3}\d+[.,]\d+ [kKmMgG][bB][ _-]{0,3}yEnc$/i', + return $match[2]; + } //[ TOWN ]-[ www.town.ag ]-[ partner of www.ssl-news.info ]-[ MOVIE ] [14/19] - "Night.Vision.2011.DVDRip.x264-IGUANA.part12.rar" - 660,80 MB yEnc + if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ partner of www\.ssl-news\.info \][ _-]{0,3}\[ .* \] \[\d+\/\d+\][ _-]{0,3}("|#34;)(.+)((\.part\d+\.rar)|(\.vol\d+\+\d+\.par2))("|#34;)[ _-]{0,3}\d+[.,]\d+ [kKmMgG][bB][ _-]{0,3}yEnc$/i', $this->subject, $match) ) { - return $match[2]; - } //[ TOWN ]-[ www.town.ag ]-[ partner of www.ssl-news.info ]-[ MOVIE ] [01/84] - "The.Butterfly.Effect.2.2006.1080p.BluRay.x264-LCHD.par2" - 7,49 GB yEnc - if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ partner of www\.ssl-news\.info \][ _-]{0,3}\[ .* \] \[\d+\/\d+\][ _-]{0,3}("|#34;)(.+)\.(par2|rar|nfo|nzb)("|#34;)[ _-]{0,3}\d+[.,]\d+ [kKmMgG][bB][ _-]{0,3}yEnc$/i', + return $match[2]; + } //[ TOWN ]-[ www.town.ag ]-[ partner of www.ssl-news.info ]-[ MOVIE ] [01/84] - "The.Butterfly.Effect.2.2006.1080p.BluRay.x264-LCHD.par2" - 7,49 GB yEnc + if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ partner of www\.ssl-news\.info \][ _-]{0,3}\[ .* \] \[\d+\/\d+\][ _-]{0,3}("|#34;)(.+)\.(par2|rar|nfo|nzb)("|#34;)[ _-]{0,3}\d+[.,]\d+ [kKmMgG][bB][ _-]{0,3}yEnc$/i', $this->subject, $match) ) { - return $match[2]; - } //[ TOWN ]-[ www.town.ag ]-[ partner of www.ssl-news.info ] [22/22] - "Arsenio.Hall.2013.09.11.Magic.Johnson.720p.HDTV.x264-2HD.vol31+11.par2" - 1,45 GB yEnc - if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ partner of www\.ssl-news\.info \][ _-]{0,3}(\[ TV \] )?\[\d+\/\d+\][ _-]{0,3}("|#34;)(.+)((\.part\d+\.rar)|(\.vol\d+\+\d+\.par2)|\.nfo|\.vol\d+\+\.par2)("|#34;)[ _-]{0,3}\d+[.,]\d+ [kKmMgG][bB][ _-]{0,3}yEnc$/i', + return $match[2]; + } //[ TOWN ]-[ www.town.ag ]-[ partner of www.ssl-news.info ] [22/22] - "Arsenio.Hall.2013.09.11.Magic.Johnson.720p.HDTV.x264-2HD.vol31+11.par2" - 1,45 GB yEnc + if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ partner of www\.ssl-news\.info \][ _-]{0,3}(\[ TV \] )?\[\d+\/\d+\][ _-]{0,3}("|#34;)(.+)((\.part\d+\.rar)|(\.vol\d+\+\d+\.par2)|\.nfo|\.vol\d+\+\.par2)("|#34;)[ _-]{0,3}\d+[.,]\d+ [kKmMgG][bB][ _-]{0,3}yEnc$/i', $this->subject, $match) ) { - return $match[3]; - } //[ TOWN ]-[ www.town.ag ]-[ partner of www.ssl-news.info ] [01/28] - "Arsenio.Hall.2013.09.18.Dr.Phil.McGraw.HDTV.x264-2HD.par2" - 352,58 MB yEnc - if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ partner of www\.ssl-news\.info \][ _-]{0,3}(\[ TV \] )?\[\d+\/\d+\][ _-]{0,3}("|#34;)(.+)\.par2("|#34;)[ _-]{0,3}\d+[.,]\d+ [kKmMgG][bB][ _-]{0,3}yEnc$/i', + return $match[3]; + } //[ TOWN ]-[ www.town.ag ]-[ partner of www.ssl-news.info ] [01/28] - "Arsenio.Hall.2013.09.18.Dr.Phil.McGraw.HDTV.x264-2HD.par2" - 352,58 MB yEnc + if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ partner of www\.ssl-news\.info \][ _-]{0,3}(\[ TV \] )?\[\d+\/\d+\][ _-]{0,3}("|#34;)(.+)\.par2("|#34;)[ _-]{0,3}\d+[.,]\d+ [kKmMgG][bB][ _-]{0,3}yEnc$/i', $this->subject, $match) ) { - return $match[3]; - } //4675.-.Wedding.Planner.multi3.(EU) <TOWN><www.town.ag > <partner of www.ssl-news.info > <Games-NDS > [01/10] - "4675.-.Wedding.Planner.multi3.(EU).par2" - 72,80 MB - yEnc - if (preg_match('/^\d+\.-\.(.+) <TOWN><www\.town\.ag >\s+<partner .+>\s+<.+>\s+\[\d+\/\d+\] - ("|#34;).+("|#34;).+yEnc$/', + return $match[3]; + } //4675.-.Wedding.Planner.multi3.(EU) <TOWN><www.town.ag > <partner of www.ssl-news.info > <Games-NDS > [01/10] - "4675.-.Wedding.Planner.multi3.(EU).par2" - 72,80 MB - yEnc + if (preg_match('/^\d+\.-\.(.+) <TOWN><www\.town\.ag >\s+<partner .+>\s+<.+>\s+\[\d+\/\d+\] - ("|#34;).+("|#34;).+yEnc$/', $this->subject, $match) ) { - return $match[1]; - } - //4675.-.Wedding.Planner.multi3.(EU) <TOWN><www.town.ag > <partner of www.ssl-news.info > <Games-NDS > [01/10] - "4675.-.Wedding.Planner.multi3.(EU).par2" - 72,80 MB - yEnc - // Some have no yEnc - if (preg_match('/^\d+\.-\.(.+) <TOWN><www\.town\.ag >\s+<partner .+>\s+<.+>\s+\[\d+\/\d+\] - ("|#34;).+/', + return $match[1]; + } + //4675.-.Wedding.Planner.multi3.(EU) <TOWN><www.town.ag > <partner of www.ssl-news.info > <Games-NDS > [01/10] - "4675.-.Wedding.Planner.multi3.(EU).par2" - 72,80 MB - yEnc + // Some have no yEnc + if (preg_match('/^\d+\.-\.(.+) <TOWN><www\.town\.ag >\s+<partner .+>\s+<.+>\s+\[\d+\/\d+\] - ("|#34;).+/', $this->subject, $match) ) { - return $match[1]; - } //Marco.Fehr.-.In.the.Mix.at.Der.Club-09-01-SAT-2012-XDS <TOWN><www.town.ag > <partner of www.ssl-news.info > [01/13] - "Marco.Fehr.-.In.the.Mix.at.Der.Club-09-01-SAT-2012-XDS.par2" - 92,12 MB - yEnc - if (preg_match('/^(\w.+) <TOWN><www\.town\.ag >\s+<partner.+>\s+\[\d+\/\d+\] - ("|#34;).+("|#34;).+yEnc$/', + return $match[1]; + } //Marco.Fehr.-.In.the.Mix.at.Der.Club-09-01-SAT-2012-XDS <TOWN><www.town.ag > <partner of www.ssl-news.info > [01/13] - "Marco.Fehr.-.In.the.Mix.at.Der.Club-09-01-SAT-2012-XDS.par2" - 92,12 MB - yEnc + if (preg_match('/^(\w.+) <TOWN><www\.town\.ag >\s+<partner.+>\s+\[\d+\/\d+\] - ("|#34;).+("|#34;).+yEnc$/', $this->subject, $match) ) { - return $match[1]; - } - //Marco.Fehr.-.In.the.Mix.at.Der.Club-09-01-SAT-2012-XDS <TOWN><www.town.ag > <partner of www.ssl-news.info > [01/13] - "Marco.Fehr.-.In.the.Mix.at.Der.Club-09-01-SAT-2012-XDS.par2" - 92,12 MB - yEnc - // Some have no yEnc - if (preg_match('/^(\w.+) <TOWN><www\.town\.ag >\s+<partner.+>\s+\[\d+\/\d+\] - ("|#34;).+/', + return $match[1]; + } + //Marco.Fehr.-.In.the.Mix.at.Der.Club-09-01-SAT-2012-XDS <TOWN><www.town.ag > <partner of www.ssl-news.info > [01/13] - "Marco.Fehr.-.In.the.Mix.at.Der.Club-09-01-SAT-2012-XDS.par2" - 92,12 MB - yEnc + // Some have no yEnc + if (preg_match('/^(\w.+) <TOWN><www\.town\.ag >\s+<partner.+>\s+\[\d+\/\d+\] - ("|#34;).+/', $this->subject, $match) ) { - return $match[1]; - } //<TOWN><www.town.ag > <partner of www.ssl-news.info > JetBrains.IntelliJ.IDEA.v11.1.4.Ultimate.Edition.MacOSX.Incl.Keymaker-EMBRACE [01/18] - "JetBrains.IntelliJ.IDEA.v11.1.4.Ultimate.Edition.MacOSX.Incl.Keymaker-EMBRACE.par2" - 200,77 MB - yEnc - if (preg_match('/^<TOWN><www\.town\.ag >\s+<partner .+>\s+(.+)\s+\[\d+\/\d+\] - ("|#34;).+("|#34;).+yEnc$/', + return $match[1]; + } //<TOWN><www.town.ag > <partner of www.ssl-news.info > JetBrains.IntelliJ.IDEA.v11.1.4.Ultimate.Edition.MacOSX.Incl.Keymaker-EMBRACE [01/18] - "JetBrains.IntelliJ.IDEA.v11.1.4.Ultimate.Edition.MacOSX.Incl.Keymaker-EMBRACE.par2" - 200,77 MB - yEnc + if (preg_match('/^<TOWN><www\.town\.ag >\s+<partner .+>\s+(.+)\s+\[\d+\/\d+\] - ("|#34;).+("|#34;).+yEnc$/', $this->subject, $match) ) { - return $match[1]; - } - //<TOWN><www.town.ag > <partner of www.ssl-news.info > JetBrains.IntelliJ.IDEA.v11.1.4.Ultimate.Edition.MacOSX.Incl.Keymaker-EMBRACE [01/18] - "JetBrains.IntelliJ.IDEA.v11.1.4.Ultimate.Edition.MacOSX.Incl.Keymaker-EMBRACE.par2" - 200,77 MB - yEnc - // Some have no yEnc - if (preg_match('/^<TOWN><www\.town\.ag >\s+<partner .+>\s+(.+)\s+\[\d+\/\d+\] - ("|#34;).+/', + return $match[1]; + } + //<TOWN><www.town.ag > <partner of www.ssl-news.info > JetBrains.IntelliJ.IDEA.v11.1.4.Ultimate.Edition.MacOSX.Incl.Keymaker-EMBRACE [01/18] - "JetBrains.IntelliJ.IDEA.v11.1.4.Ultimate.Edition.MacOSX.Incl.Keymaker-EMBRACE.par2" - 200,77 MB - yEnc + // Some have no yEnc + if (preg_match('/^<TOWN><www\.town\.ag >\s+<partner .+>\s+(.+)\s+\[\d+\/\d+\] - ("|#34;).+/', $this->subject, $match) ) { - return $match[1]; - } //<TOWN><www.town.ag > <partner of www.ssl-news.info > [01/18] - "2012-11.-.Supurbia.-.Volume.Tw o.Digital-1920.K6-Empire.par2" - 421,98 MB yEnc - if (preg_match('/^[ <\[]{0,2}TOWN[ >\]]{0,2}[ _-]{0,3}[ <\[]{0,2}www\.town\.ag[ >\]]{0,2}[ _-]{0,3}[ <\[]{0,2}partner of www.ssl-news\.info[ >\]]{0,2}[ _-]{0,3}\[\d+\/\d+\][ _-]{0,3}("|#34;)(.+)\.(par|vol|rar|nfo).*?("|#34;).+?yEnc$/i', + return $match[1]; + } //<TOWN><www.town.ag > <partner of www.ssl-news.info > [01/18] - "2012-11.-.Supurbia.-.Volume.Tw o.Digital-1920.K6-Empire.par2" - 421,98 MB yEnc + if (preg_match('/^[ <\[]{0,2}TOWN[ >\]]{0,2}[ _-]{0,3}[ <\[]{0,2}www\.town\.ag[ >\]]{0,2}[ _-]{0,3}[ <\[]{0,2}partner of www.ssl-news\.info[ >\]]{0,2}[ _-]{0,3}\[\d+\/\d+\][ _-]{0,3}("|#34;)(.+)\.(par|vol|rar|nfo).*?("|#34;).+?yEnc$/i', $this->subject, $match) ) { - return $match[2]; - } //<TOWN> www.town.ag > sponsored by www.ssl-news.info > (1/3) "HolzWerken_40.par2" - 43,89 MB - yEnc - if (preg_match('/^<TOWN> www\.town\.ag > sponsored by www\.ssl-news\.info > \(\d+\/\d+\) "([\w\säöüÄÖÜß+¤ƒ¶!.,&_()\[\]\'\`{}#-]{8,}?\b.?)' . - $this->e0 . ' - \d+[,.]\d+ [mMkKgG][bB] - yEnc$/', + return $match[2]; + } //<TOWN> www.town.ag > sponsored by www.ssl-news.info > (1/3) "HolzWerken_40.par2" - 43,89 MB - yEnc + if (preg_match('/^<TOWN> www\.town\.ag > sponsored by www\.ssl-news\.info > \(\d+\/\d+\) "([\w\säöüÄÖÜß+¤ƒ¶!.,&_()\[\]\'\`{}#-]{8,}?\b.?)'. + $this->e0.' - \d+[,.]\d+ [mMkKgG][bB] - yEnc$/', $this->subject, $match) ) { - return $match[1]; - } //(1/9)<<<www.town.ag>>> sponsored by ssl-news.info<<<[HorribleSubs]_AIURA_-_01_[480p].mkv "[HorribleSubs]_AIURA_-_01_[480p].par2" yEnc - if (preg_match('/^\(\d+\/\d+\).+?www\.town\.ag.+?sponsored by (www\.)?ssl-news\.info<+?.+? "([\w\säöüÄÖÜß+¤ƒ¶!.,&_()\[\]\'\`{}#-]{8,}?\b.?)' . + return $match[1]; + } //(1/9)<<<www.town.ag>>> sponsored by ssl-news.info<<<[HorribleSubs]_AIURA_-_01_[480p].mkv "[HorribleSubs]_AIURA_-_01_[480p].par2" yEnc + if (preg_match('/^\(\d+\/\d+\).+?www\.town\.ag.+?sponsored by (www\.)?ssl-news\.info<+?.+? "([\w\säöüÄÖÜß+¤ƒ¶!.,&_()\[\]\'\`{}#-]{8,}?\b.?)'. $this->e1, $this->subject, $match) ) { - return $match[2]; - } //[ TOWN ]-[ www.town.ag ]-[ Assassins.Creed.IV.Black.Flag.XBOX360-COMPLEX ]-[ partner of www.ssl-news.info ] [074/195]- "complex-ac4.bf.d1.r71" yEnc - if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ (.+?) \][ _-]{0,3}\[ partner of www\.ssl-news\.info \][ _-]{0,3}\[\d+\/(\d+\])[ _-]{0,3}"(.+)(\.part\d*|\.rar)?(\.vol.+ \(\d+\/\d+\) "|\.[A-Za-z0-9]{2,4}")[ _-]{0,3}yEnc$/i', + return $match[2]; + } //[ TOWN ]-[ www.town.ag ]-[ Assassins.Creed.IV.Black.Flag.XBOX360-COMPLEX ]-[ partner of www.ssl-news.info ] [074/195]- "complex-ac4.bf.d1.r71" yEnc + if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ (.+?) \][ _-]{0,3}\[ partner of www\.ssl-news\.info \][ _-]{0,3}\[\d+\/(\d+\])[ _-]{0,3}"(.+)(\.part\d*|\.rar)?(\.vol.+ \(\d+\/\d+\) "|\.[A-Za-z0-9]{2,4}")[ _-]{0,3}yEnc$/i', $this->subject, $match) ) { - return $match[1]; - } //(TOWN)(www.town.ag ) (partner of www.ssl-news.info ) Twinz-Conversation-CD-FLAC-1995-CUSTODES [01/23] - #34;Twinz-Conversation-CD-FLAC-1995-CUSTODES.par2#34; - 266,00 MB - yEnc - if (preg_match('/^\(TOWN\)\(www\.town\.ag \)[ _-]{0,3}\(partner of www\.ssl-news\.info \)[ _-]{0,3} (.+?) \[\d+\/(\d+\][ _-]{0,3}("|#34;).+?)\.(par2|rar|nfo|nzb)("|#34;)[ _-]{0,3}\d+[.,]\d+ [kKmMgG][bB][ _-]{0,3}yEnc$/', + return $match[1]; + } //(TOWN)(www.town.ag ) (partner of www.ssl-news.info ) Twinz-Conversation-CD-FLAC-1995-CUSTODES [01/23] - #34;Twinz-Conversation-CD-FLAC-1995-CUSTODES.par2#34; - 266,00 MB - yEnc + if (preg_match('/^\(TOWN\)\(www\.town\.ag \)[ _-]{0,3}\(partner of www\.ssl-news\.info \)[ _-]{0,3} (.+?) \[\d+\/(\d+\][ _-]{0,3}("|#34;).+?)\.(par2|rar|nfo|nzb)("|#34;)[ _-]{0,3}\d+[.,]\d+ [kKmMgG][bB][ _-]{0,3}yEnc$/', $this->subject, $match) ) { - return $match[1]; - } //<TOWN><www.town.ag > <partner of www.ssl-news.info > Greek.S04E06.Katerstimmung.German.DL.Dubbed.WEB-DL.XviD-GEZ [01/22] - "Greek.S04E06.Katerstimmung.German.DL.Dubbed.WEB-DL.XviD-GEZ.par2" - 526,99 MB - yEnc - if (preg_match('/^<TOWN><www\.town\.ag > <partner of www\.ssl-news\.info > (.+) \[\d+\/\d+\][ _-]{0,3}("|#34;).+?("|#34;).+?yEnc$/i', + return $match[1]; + } //<TOWN><www.town.ag > <partner of www.ssl-news.info > Greek.S04E06.Katerstimmung.German.DL.Dubbed.WEB-DL.XviD-GEZ [01/22] - "Greek.S04E06.Katerstimmung.German.DL.Dubbed.WEB-DL.XviD-GEZ.par2" - 526,99 MB - yEnc + if (preg_match('/^<TOWN><www\.town\.ag > <partner of www\.ssl-news\.info > (.+) \[\d+\/\d+\][ _-]{0,3}("|#34;).+?("|#34;).+?yEnc$/i', $this->subject, $match) ) { - return $match[1]; - } //[ TOWN ]-[ www.town.ag ]-[ ANIME ] [01/17] - "[Chyuu] Nanatsu no Taizai - 12 [720p][D1F49539].par2" - 585,03 MB yEnc - if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ .* \][ _-]{0,3}\[\d+\/\d+\][ _-]{0,3}"([\w\säöüÄÖÜß+¤ƒ¶!.,&_()\[\]\'\`{}#-]{8,}?\b.?)' . $this->e2, + return $match[1]; + } //[ TOWN ]-[ www.town.ag ]-[ ANIME ] [01/17] - "[Chyuu] Nanatsu no Taizai - 12 [720p][D1F49539].par2" - 585,03 MB yEnc + if (preg_match('/^\[ TOWN \][ _-]{0,3}\[ www\.town\.ag \][ _-]{0,3}\[ .* \][ _-]{0,3}\[\d+\/\d+\][ _-]{0,3}"([\w\säöüÄÖÜß+¤ƒ¶!.,&_()\[\]\'\`{}#-]{8,}?\b.?)'.$this->e2, $this->subject, $match) ) { - return $match[1]; - } - return [ - 'cleansubject' => $this->releaseCleanerHelper($this->subject), - 'properlynamed' => false - ]; - } - // Run at the end because this can be dangerous. In the future it's better to make these per group. There should not be numbers after yEnc because we remove them as well before inserting (even when importing). - public function generic() - { - // This regex gets almost all of the predb release names also keep in mind that not every subject ends with yEnc, some are truncated, because of the 255 character limit and some have extra charaters tacked onto the end, like (5/10). - if (preg_match('/^\[\d+\][-_\s]{0,3}(\[(reup|full|repost.+?|part|re-repost|xtr|sample)(\])?[-_\s]{0,3}\[[- #@\.\w]+\][-_\s]{0,3}|\[[- #@\.\w]+\][-_\s]{0,3}\[(reup|full|repost.+?|part|re-repost|xtr|sample)(\])?[-_\s]{0,3}|\[.+?efnet\][-_\s]{0,3}|\[(reup|full|repost.+?|part|re-repost|xtr|sample)(\])?[-_\s]{0,3})(\[FULL\])?[-_\s]{0,3}(\[ )?(\[)? ?(\/sz\/)?(F: - )?(?P<title>[- _!@\.\'\w\(\)~]{10,}) ?(\])?[-_\s]{0,3}(\[)? ?(REPOST|REPACK|SCENE|EXTRA PARS|REAL)? ?(\])?[-_\s]{0,3}?(\[\d+[-\/~]\d+\])?[-_\s]{0,3}["|#34;]*.+["|#34;]* ?[yEnc]{0,4}/i', - $this->subject, - $match) - ) { - return $match['title']; - } - return [ - 'cleansubject' => $this->releaseCleanerHelper($this->subject), - 'properlynamed' => false - ]; - } + return $match[1]; + } - /** - * @param $subject - * - * @return string - */ - public function releaseCleanerHelper($subject): string - { - $cleanerName = preg_replace('/(- )?yEnc$/', '', $subject); - return trim(preg_replace('/\s\s+/', ' ', $cleanerName)); - } + return [ + 'cleansubject' => $this->releaseCleanerHelper($this->subject), + 'properlynamed' => false, + ]; + } - /** - * Cleans release name for the namefixer class. - * - * @param $name - * - * @return mixed|string - */ - public function fixerCleaner($name) - { - //Extensions. - $cleanerName = preg_replace('/([-_](proof|sample|thumbs?))*(\.part\d*(\.rar)?|\.rar)?(\d{1,3}\.rev"|\.vol.+?"|\.[A-Za-z0-9]{2,4}$|$)/i', + // Run at the end because this can be dangerous. In the future it's better to make these per group. There should not be numbers after yEnc because we remove them as well before inserting (even when importing). + public function generic() + { + // This regex gets almost all of the predb release names also keep in mind that not every subject ends with yEnc, some are truncated, because of the 255 character limit and some have extra charaters tacked onto the end, like (5/10). + if (preg_match('/^\[\d+\][-_\s]{0,3}(\[(reup|full|repost.+?|part|re-repost|xtr|sample)(\])?[-_\s]{0,3}\[[- #@\.\w]+\][-_\s]{0,3}|\[[- #@\.\w]+\][-_\s]{0,3}\[(reup|full|repost.+?|part|re-repost|xtr|sample)(\])?[-_\s]{0,3}|\[.+?efnet\][-_\s]{0,3}|\[(reup|full|repost.+?|part|re-repost|xtr|sample)(\])?[-_\s]{0,3})(\[FULL\])?[-_\s]{0,3}(\[ )?(\[)? ?(\/sz\/)?(F: - )?(?P<title>[- _!@\.\'\w\(\)~]{10,}) ?(\])?[-_\s]{0,3}(\[)? ?(REPOST|REPACK|SCENE|EXTRA PARS|REAL)? ?(\])?[-_\s]{0,3}?(\[\d+[-\/~]\d+\])?[-_\s]{0,3}["|#34;]*.+["|#34;]* ?[yEnc]{0,4}/i', + $this->subject, + $match) + ) { + return $match['title']; + } + + return [ + 'cleansubject' => $this->releaseCleanerHelper($this->subject), + 'properlynamed' => false, + ]; + } + + /** + * @param $subject + * + * @return string + */ + public function releaseCleanerHelper($subject): string + { + $cleanerName = preg_replace('/(- )?yEnc$/', '', $subject); + + return trim(preg_replace('/\s\s+/', ' ', $cleanerName)); + } + + /** + * Cleans release name for the namefixer class. + * + * @param $name + * + * @return mixed|string + */ + public function fixerCleaner($name) + { + //Extensions. + $cleanerName = preg_replace('/([-_](proof|sample|thumbs?))*(\.part\d*(\.rar)?|\.rar)?(\d{1,3}\.rev"|\.vol.+?"|\.[A-Za-z0-9]{2,4}$|$)/i', ' ', $name); - //Remove stuff from the start. - $cleanerName = preg_replace('/^(Release Name|sample-)/i', ' ', $cleanerName); - //Replace multiple spaces with 1 space - $cleanerName = preg_replace('/\s\s+/i', ' ', $cleanerName); - //Remove invalid characters. - $cleanerName = trim(utf8_encode(preg_replace('/[^(\x20-\x7F)]*/', '', $cleanerName))); - return $cleanerName; - } + //Remove stuff from the start. + $cleanerName = preg_replace('/^(Release Name|sample-)/i', ' ', $cleanerName); + //Replace multiple spaces with 1 space + $cleanerName = preg_replace('/\s\s+/i', ' ', $cleanerName); + //Remove invalid characters. + $cleanerName = trim(utf8_encode(preg_replace('/[^(\x20-\x7F)]*/', '', $cleanerName))); + + return $cleanerName; + } } diff --git a/nntmux/ReleaseComments.php b/nntmux/ReleaseComments.php index c8b716900..153a91a77 100755 --- a/nntmux/ReleaseComments.php +++ b/nntmux/ReleaseComments.php @@ -1,174 +1,173 @@ <?php + namespace nntmux; -use App\Models\Settings; use nntmux\db\DB; - +use App\Models\Settings; /** * This class handles storage and retrieval of release comments. */ class ReleaseComments { + /** + * @var DB|null + */ + public $pdo; - /** - * @var DB|null - */ - public $pdo; + /** + * ReleaseComments constructor. + * @param null $settings + */ + public function __construct($settings = null) + { + $this->pdo = ($settings instanceof DB ? $settings : new DB()); + } - /** - * ReleaseComments constructor. - * @param null $settings - */ - public function __construct($settings = null) - { - $this->pdo = ($settings instanceof DB ? $settings : new DB()); - } + /** + * Get a comment by id. + * + * @param $id + * + * @return array|bool + */ + public function getCommentById($id) + { + return $this->pdo->queryOneRow(sprintf('SELECT * FROM release_comments WHERE id = %d', $id)); + } - /** - * Get a comment by id. - * - * @param $id - * - * @return array|bool - */ - public function getCommentById($id) - { - return $this->pdo->queryOneRow(sprintf('SELECT * FROM release_comments WHERE id = %d', $id)); - } + /** + * Get all comments for a GID. + * + * @param $gid + * + * @return array + */ + public function getCommentsByGid($gid): array + { + return $this->pdo->query(sprintf("SELECT rc.id, text, createddate, sourceid, CASE WHEN sourceid = 0 THEN (SELECT username FROM users WHERE id = users_id) ELSE username END AS username, CASE WHEN sourceid = 0 THEN (SELECT role FROM users WHERE id = users_id) ELSE '-1' END AS role, CASE WHEN sourceid =0 THEN (SELECT r.name AS rolename FROM users AS u LEFT JOIN user_roles AS r ON r.id = u.role WHERE u.id = users_id) ELSE (SELECT description AS rolename FROM spotnabsources WHERE id = sourceid) END AS rolename FROM release_comments rc WHERE isvisible = 1 AND gid = %s AND (users_id IN (SELECT id FROM users) OR rc.username IS NOT NULL) ORDER BY createddate DESC LIMIT 100", $this->pdo->escapeString($gid))); + } - /** - * Get all comments for a GID. - * - * @param $gid - * - * @return array - */ - public function getCommentsByGid($gid): array - { - return $this->pdo->query(sprintf("SELECT rc.id, text, createddate, sourceid, CASE WHEN sourceid = 0 THEN (SELECT username FROM users WHERE id = users_id) ELSE username END AS username, CASE WHEN sourceid = 0 THEN (SELECT role FROM users WHERE id = users_id) ELSE '-1' END AS role, CASE WHEN sourceid =0 THEN (SELECT r.name AS rolename FROM users AS u LEFT JOIN user_roles AS r ON r.id = u.role WHERE u.id = users_id) ELSE (SELECT description AS rolename FROM spotnabsources WHERE id = sourceid) END AS rolename FROM release_comments rc WHERE isvisible = 1 AND gid = %s AND (users_id IN (SELECT id FROM users) OR rc.username IS NOT NULL) ORDER BY createddate DESC LIMIT 100", $this->pdo->escapeString($gid))); - } + /** + * Get all comments for a release.GUID. + * + * @param $guid + * + * @return array + */ + public function getCommentsByGuid($guid): array + { + return $this->pdo->query(sprintf('SELECT rc.id, text, createddate, sourceid, CASE WHEN sourceid = 0 THEN (SELECT username FROM users WHERE id = users_id) ELSE username END AS username FROM release_comments rc LEFT JOIN releases r ON r.gid = rc.gid WHERE isvisible = 1 AND guid = %s AND (users_id IN (SELECT id FROM users) OR rc.username IS NOT NULL) ORDER BY createddate DESC LIMIT 100', $this->pdo->escapeString($guid))); + } - /** - * Get all comments for a release.GUID. - * - * @param $guid - * - * @return array - */ - public function getCommentsByGuid($guid): array - { - return $this->pdo->query(sprintf('SELECT rc.id, text, createddate, sourceid, CASE WHEN sourceid = 0 THEN (SELECT username FROM users WHERE id = users_id) ELSE username END AS username FROM release_comments rc LEFT JOIN releases r ON r.gid = rc.gid WHERE isvisible = 1 AND guid = %s AND (users_id IN (SELECT id FROM users) OR rc.username IS NOT NULL) ORDER BY createddate DESC LIMIT 100', $this->pdo->escapeString($guid))); - } + /** + * @param null|string|bool|int $refdate + * @param null $localOnly + * @return mixed + */ + public function getCommentCount($refdate = null, $localOnly = null) + { + if ($refdate !== null) { + if (is_string($refdate)) { + // ensure we're in the right format + $refdate = date('Y-m-d H:i:s', strtotime($refdate)); + } elseif (is_int($refdate)) { + // ensure we're in the right format + $refdate = date('Y-m-d H:i:s', $refdate); + } else { + // leave it as null (bad content anyhow) + $refdate = null; + } + } - /** - * @param null|string|bool|int $refdate - * @param null $localOnly - * @return mixed - */ - public function getCommentCount($refdate = null, $localOnly = null) - { - if ($refdate !== null) { - if (is_string($refdate)) { - // ensure we're in the right format - $refdate = date('Y-m-d H:i:s', strtotime($refdate)); - } else if (is_int($refdate)) { - // ensure we're in the right format - $refdate = date('Y-m-d H:i:s', $refdate); - } else { - // leave it as null (bad content anyhow) - $refdate = null; - } - } - - $q = 'SELECT count(id) AS num FROM release_comments'; - $clause = []; - if($refdate !== null) { - $clause[] = "createddate >= '$refdate'"; - } + $q = 'SELECT count(id) AS num FROM release_comments'; + $clause = []; + if ($refdate !== null) { + $clause[] = "createddate >= '$refdate'"; + } // set localOnly to null to include both local and remote // set localOnly to true to only receive local comment count // set localOnly to false to only receive remote comment count - $clause[] = $localOnly === true ? 'sourceid = 0' : 'sourceid != 0'; + $clause[] = $localOnly === true ? 'sourceid = 0' : 'sourceid != 0'; + if (count($clause)) { + $q .= ' WHERE '.implode('AND ', $clause); + } - if (count($clause)) { - $q .= ' WHERE ' . implode('AND ', $clause); - } + $res = $this->pdo->queryOneRow($q); - $res = $this->pdo->queryOneRow($q); - return $res['num']; - } + return $res['num']; + } - /** - * Delete single comment on the site. - * - * @param $id - */ - public function deleteComment($id): void - { - $res = $this->getCommentById($id); - if ($res) { - $this->pdo->queryExec(sprintf('DELETE FROM release_comments WHERE id = %d', $id)); - $this->updateReleaseCommentCount($res['gid']); - } - } + /** + * Delete single comment on the site. + * + * @param $id + */ + public function deleteComment($id): void + { + $res = $this->getCommentById($id); + if ($res) { + $this->pdo->queryExec(sprintf('DELETE FROM release_comments WHERE id = %d', $id)); + $this->updateReleaseCommentCount($res['gid']); + } + } - /** - * Delete all comments for a release.id. - * - * @param $id - */ - public function deleteCommentsForRelease($id): void - { - $res = $this->getCommentById($id); - if ($res) { - $this->pdo->queryExec(sprintf('DELETE rc.* FROM release_comments rc JOIN releases r ON r.gid = rc.gid WHERE r.id = %d', $id)); - $this->updateReleaseCommentCount($res['gid']); - } - } + /** + * Delete all comments for a release.id. + * + * @param $id + */ + public function deleteCommentsForRelease($id): void + { + $res = $this->getCommentById($id); + if ($res) { + $this->pdo->queryExec(sprintf('DELETE rc.* FROM release_comments rc JOIN releases r ON r.gid = rc.gid WHERE r.id = %d', $id)); + $this->updateReleaseCommentCount($res['gid']); + } + } - /** - * Delete all comments for a users.id. - * - * @param $id - */ - public function deleteCommentsForUser($id): void - { - $numcomments = $this->getCommentCountForUser($id); - if ($numcomments > 0) { - $comments = $this->getCommentsForUserRange($id, 0, $numcomments); - foreach ($comments as $comment) { - $this->deleteComment($comment['id']); - $this->updateReleaseCommentCount($comment['gid']); - } - } - } + /** + * Delete all comments for a users.id. + * + * @param $id + */ + public function deleteCommentsForUser($id): void + { + $numcomments = $this->getCommentCountForUser($id); + if ($numcomments > 0) { + $comments = $this->getCommentsForUserRange($id, 0, $numcomments); + foreach ($comments as $comment) { + $this->deleteComment($comment['id']); + $this->updateReleaseCommentCount($comment['gid']); + } + } + } - /** - * Add a release_comments row. - * - * @param $id - * @param $gid - * @param $text - * @param $userid - * @param $host - * - * @return bool|int - * @throws \Exception - */ - public function addComment($id, $gid, $text, $userid, $host) - { - if ((int)Settings::value('..storeuserips') !== 1) { - $host = ''; - } + /** + * Add a release_comments row. + * + * @param $id + * @param $gid + * @param $text + * @param $userid + * @param $host + * + * @return bool|int + * @throws \Exception + */ + public function addComment($id, $gid, $text, $userid, $host) + { + if ((int) Settings::value('..storeuserips') !== 1) { + $host = ''; + } - $username = $this->pdo->queryOneRow(sprintf('SELECT username FROM users WHERE id = %d', $userid)); - $username = ($username === false ? 'ANON' : $username['username']); + $username = $this->pdo->queryOneRow(sprintf('SELECT username FROM users WHERE id = %d', $userid)); + $username = ($username === false ? 'ANON' : $username['username']); - $comid = $this->pdo->queryInsert( + $comid = $this->pdo->queryInsert( sprintf(' INSERT INTO release_comments (releases_id, gid, text, users_id, createddate, host, username) VALUES (%d, %s, %s, %d, NOW(), %s, %s)', @@ -180,72 +179,74 @@ class ReleaseComments $this->pdo->escapeString($username) ) ); - $this->updateReleaseCommentCount($id); - return $comid; - } + $this->updateReleaseCommentCount($id); - /** - * Get release_comments rows by limit. - * - * @param $start - * @param $num - * - * @return array - */ - public function getCommentsRange($start, $num): array - { - return $this->pdo->query( + return $comid; + } + + /** + * Get release_comments rows by limit. + * + * @param $start + * @param $num + * + * @return array + */ + public function getCommentsRange($start, $num): array + { + return $this->pdo->query( sprintf(' SELECT rc.*, r.guid FROM release_comments rc LEFT JOIN releases r on r.id = rc.releases_id ORDER BY rc.createddate DESC %s', - ($start === false ? '' : ' LIMIT ' . $num . ' OFFSET ' . $start) + ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start) ) ); - } + } - /** - * Update the denormalised count of comments for a release. - * - * @param $gid - */ - public function updateReleaseCommentCount($gid): void - { - $this->pdo->queryExec(sprintf('UPDATE releases + /** + * Update the denormalised count of comments for a release. + * + * @param $gid + */ + public function updateReleaseCommentCount($gid): void + { + $this->pdo->queryExec(sprintf('UPDATE releases SET comments = (SELECT count(id) FROM release_comments WHERE release_comments.gid = releases.gid AND isvisible = 1) - WHERE releases.gid = %s', $this->pdo->escapeString($gid) )); - } + WHERE releases.gid = %s', $this->pdo->escapeString($gid))); + } - /** - * Get a count of all comments for a user. - * - * @param $uid - * @return mixed - */ - public function getCommentCountForUser($uid) - { - $res = $this->pdo->queryOneRow(sprintf('SELECT count(id) AS num FROM release_comments WHERE users_id = %d AND isvisible = 1', $uid)); - return $res['num']; - } + /** + * Get a count of all comments for a user. + * + * @param $uid + * @return mixed + */ + public function getCommentCountForUser($uid) + { + $res = $this->pdo->queryOneRow(sprintf('SELECT count(id) AS num FROM release_comments WHERE users_id = %d AND isvisible = 1', $uid)); - /** - * Get comments for a user by limit. - * - * @param $uid - * @param $start - * @param $num - * - * @return array - */ - public function getCommentsForUserRange($uid, $start, $num): array - { - if ($start === false) { - $limit = ''; - } else { - $limit = ' LIMIT ' . $start . ',' . $num; - } + return $res['num']; + } - return $this->pdo->query(sprintf('SELECT release_comments.*, r.guid, r.searchname, users.username FROM release_comments INNER JOIN releases r ON r.id = release_comments.releases_id LEFT OUTER JOIN users ON users.id = release_comments.users_id WHERE users_id = %d ORDER BY release_comments.createddate DESC ' .$limit, $uid)); - } + /** + * Get comments for a user by limit. + * + * @param $uid + * @param $start + * @param $num + * + * @return array + */ + public function getCommentsForUserRange($uid, $start, $num): array + { + if ($start === false) { + $limit = ''; + } else { + $limit = ' LIMIT '.$start.','.$num; + } + + return $this->pdo->query(sprintf('SELECT release_comments.*, r.guid, r.searchname, users.username FROM release_comments INNER JOIN releases r ON r.id = release_comments.releases_id LEFT OUTER JOIN users ON users.id = release_comments.users_id WHERE users_id = %d ORDER BY release_comments.createddate DESC '.$limit, $uid)); + } } diff --git a/nntmux/ReleaseExtra.php b/nntmux/ReleaseExtra.php index 0800dc62f..50eaef297 100755 --- a/nntmux/ReleaseExtra.php +++ b/nntmux/ReleaseExtra.php @@ -1,51 +1,52 @@ <?php + namespace nntmux; -use App\Models\AudioData; -use App\Models\ReleaseExtraFull; -use App\Models\ReleaseSubtitle; -use App\Models\VideoData; use nntmux\db\DB; +use App\Models\AudioData; +use App\Models\VideoData; use nntmux\utility\Utility; +use App\Models\ReleaseSubtitle; +use App\Models\ReleaseExtraFull; class ReleaseExtra { - /** - * @var DB|null - */ - public $pdo; + /** + * @var DB|null + */ + public $pdo; - /** - * ReleaseExtra constructor. - * - * @param null $settings - */ - public function __construct($settings = null) - { - $this->pdo = $settings instanceof DB ? $settings : new DB(); - } + /** + * ReleaseExtra constructor. + * + * @param null $settings + */ + public function __construct($settings = null) + { + $this->pdo = $settings instanceof DB ? $settings : new DB(); + } - /** - * @param $codec - * - * @return string - */ - public function makeCodecPretty($codec): string - { - switch (true) { + /** + * @param $codec + * + * @return string + */ + public function makeCodecPretty($codec): string + { + switch (true) { case preg_match('#(?:^36$|HEVC)#i', $codec): $codec = 'HEVC'; break; - case preg_match('#(?:^(?:7|27|H264)$|AVC)#i', $codec); + case preg_match('#(?:^(?:7|27|H264)$|AVC)#i', $codec): $codec = 'h.264'; break; case preg_match('#(?:^(?:20|FMP4|MP42|MP43|MPG4)$|ASP)#i', $codec): $codec = 'MPEG-4'; break; - case preg_match('#^2$#i', $codec); + case preg_match('#^2$#i', $codec): $codec = 'MPEG-2'; break; - case preg_match('#^MPEG$#', $codec); + case preg_match('#^MPEG$#', $codec): $codec = 'MPEG-1'; break; case preg_match('#DX50|DIVX|DIV3#i', $codec): @@ -54,212 +55,210 @@ class ReleaseExtra case preg_match('#XVID#i', $codec): $codec = 'XviD'; break; - case preg_match('#(?:wmv|WVC1)#i', $codec); + case preg_match('#(?:wmv|WVC1)#i', $codec): $codec = 'wmv'; break; - default; + default: } - return $codec; - } + return $codec; + } - /** - * @param $id - * - * @return \Illuminate\Database\Eloquent\Model|null|static - */ - public function get($id) - { - // hopefully nothing will use this soon and it can be deleted - return VideoData::query()->where('releases_id', $id)->first(); - } + /** + * @param $id + * + * @return \Illuminate\Database\Eloquent\Model|null|static + */ + public function get($id) + { + // hopefully nothing will use this soon and it can be deleted + return VideoData::query()->where('releases_id', $id)->first(); + } - /** - * @param $id - * - * @return \Illuminate\Database\Eloquent\Model|null|static - */ - public function getVideo($id) - { - return VideoData::query()->where('releases_id', $id)->first(); - } + /** + * @param $id + * + * @return \Illuminate\Database\Eloquent\Model|null|static + */ + public function getVideo($id) + { + return VideoData::query()->where('releases_id', $id)->first(); + } - /** - * @param $id - * - * @return \Illuminate\Database\Eloquent\Collection|static[] - */ - public function getAudio($id) - { - return AudioData::query()->where('releases_id', $id)->orderBy('audioid')->get(); - } + /** + * @param $id + * + * @return \Illuminate\Database\Eloquent\Collection|static[] + */ + public function getAudio($id) + { + return AudioData::query()->where('releases_id', $id)->orderBy('audioid')->get(); + } - /** - * @param $id - * - * @return \Illuminate\Database\Eloquent\Model|null|static - */ - public function getSubs($id) - { - return ReleaseSubtitle::query()->where('releases_id', $id)->selectRaw("GROUP_CONCAT(subslanguage SEPARATOR ', ') AS subs")->orderBy('subsid')->first(); - } + /** + * @param $id + * + * @return \Illuminate\Database\Eloquent\Model|null|static + */ + public function getSubs($id) + { + return ReleaseSubtitle::query()->where('releases_id', $id)->selectRaw("GROUP_CONCAT(subslanguage SEPARATOR ', ') AS subs")->orderBy('subsid')->first(); + } - /** - * @param $guid - * - * @return array|bool - */ - public function getBriefByGuid($guid) - { - return $this->pdo->queryOneRow(sprintf("SELECT containerformat, videocodec, videoduration, videoaspect, CONCAT(video_data.videowidth,'x',video_data.videoheight,' @',format(videoframerate,0),'fps') AS size, GROUP_CONCAT(DISTINCT audio_data.audiolanguage SEPARATOR ', ') AS audio, GROUP_CONCAT(DISTINCT audio_data.audioformat,' (',SUBSTRING(audio_data.audiochannels,1,1),' ch)' SEPARATOR ', ') AS audioformat, GROUP_CONCAT(DISTINCT audio_data.audioformat,' (',SUBSTRING(audio_data.audiochannels,1,1),' ch)' SEPARATOR ', ') AS audioformat, GROUP_CONCAT(DISTINCT release_subtitles.subslanguage SEPARATOR ', ') AS subs FROM video_data LEFT OUTER JOIN release_subtitles ON video_data.releases_id = release_subtitles.releases_id LEFT OUTER JOIN audio_data ON video_data.releases_id = audio_data.releases_id INNER JOIN releases r ON r.id = video_data.releases_id WHERE r.guid = %s GROUP BY r.id", $this->pdo->escapeString($guid))); - } + /** + * @param $guid + * + * @return array|bool + */ + public function getBriefByGuid($guid) + { + return $this->pdo->queryOneRow(sprintf("SELECT containerformat, videocodec, videoduration, videoaspect, CONCAT(video_data.videowidth,'x',video_data.videoheight,' @',format(videoframerate,0),'fps') AS size, GROUP_CONCAT(DISTINCT audio_data.audiolanguage SEPARATOR ', ') AS audio, GROUP_CONCAT(DISTINCT audio_data.audioformat,' (',SUBSTRING(audio_data.audiochannels,1,1),' ch)' SEPARATOR ', ') AS audioformat, GROUP_CONCAT(DISTINCT audio_data.audioformat,' (',SUBSTRING(audio_data.audiochannels,1,1),' ch)' SEPARATOR ', ') AS audioformat, GROUP_CONCAT(DISTINCT release_subtitles.subslanguage SEPARATOR ', ') AS subs FROM video_data LEFT OUTER JOIN release_subtitles ON video_data.releases_id = release_subtitles.releases_id LEFT OUTER JOIN audio_data ON video_data.releases_id = audio_data.releases_id INNER JOIN releases r ON r.id = video_data.releases_id WHERE r.guid = %s GROUP BY r.id", $this->pdo->escapeString($guid))); + } - /** - * @param $guid - * - * @return array|bool - */ - public function getByGuid($guid) - { - return $this->pdo->queryOneRow(sprintf('SELECT video_data.* FROM video_data INNER JOIN releases r ON r.id = video_data.releases_id WHERE r.guid = %s', $this->pdo->escapeString($guid))); - } + /** + * @param $guid + * + * @return array|bool + */ + public function getByGuid($guid) + { + return $this->pdo->queryOneRow(sprintf('SELECT video_data.* FROM video_data INNER JOIN releases r ON r.id = video_data.releases_id WHERE r.guid = %s', $this->pdo->escapeString($guid))); + } - /** - * @param $id - * - * @return mixed - */ - public function delete($id) - { - AudioData::query()->where('releases_id', $id)->delete(); - ReleaseSubtitle::query()->where('releases_id', $id)->delete(); - VideoData::query()->where('releases_id', $id)->delete(); - } + /** + * @param $id + * + * @return mixed + */ + public function delete($id) + { + AudioData::query()->where('releases_id', $id)->delete(); + ReleaseSubtitle::query()->where('releases_id', $id)->delete(); + VideoData::query()->where('releases_id', $id)->delete(); + } - /** - * @param $releaseID - * @param $xml - */ - public function addFromXml($releaseID, $xml) - { - $xmlObj = @simplexml_load_string($xml); - $arrXml = Utility::objectsIntoArray($xmlObj); - $containerformat = ''; - $overallbitrate = ''; + /** + * @param $releaseID + * @param $xml + */ + public function addFromXml($releaseID, $xml) + { + $xmlObj = @simplexml_load_string($xml); + $arrXml = Utility::objectsIntoArray($xmlObj); + $containerformat = ''; + $overallbitrate = ''; - if (isset($arrXml['File']) && isset($arrXml['File']['track'])) { - foreach ($arrXml['File']['track'] as $track) { - if (isset($track['@attributes']) && isset($track['@attributes']['type'])) { + if (isset($arrXml['File']) && isset($arrXml['File']['track'])) { + foreach ($arrXml['File']['track'] as $track) { + if (isset($track['@attributes']) && isset($track['@attributes']['type'])) { + if ($track['@attributes']['type'] === 'General') { + if (isset($track['Format'])) { + $containerformat = $track['Format']; + } + if (isset($track['Overall_bit_rate'])) { + $overallbitrate = $track['Overall_bit_rate']; + } + if (isset($track['Unique_ID'])) { + if (preg_match('/\(0x(?P<hash>[0-9a-f]{32})\)/i', $track['Unique_ID'], $matches)) { + $uniqueid = $matches['hash']; + $this->addUID($releaseID, $uniqueid); + } + } + } elseif ($track['@attributes']['type'] === 'Video') { + $videoduration = $videoformat = $videocodec = $videowidth = $videoheight = $videoaspect = $videoframerate = $videolibrary = ''; + if (isset($track['Duration'])) { + $videoduration = $track['Duration']; + } + if (isset($track['Format'])) { + $videoformat = $track['Format']; + } + if (isset($track['Codec_ID'])) { + $videocodec = $track['Codec_ID']; + } + if (isset($track['Width'])) { + $videowidth = preg_replace('/[^0-9]/', '', $track['Width']); + } + if (isset($track['Height'])) { + $videoheight = preg_replace('/[^0-9]/', '', $track['Height']); + } + if (isset($track['Display_aspect_ratio'])) { + $videoaspect = $track['Display_aspect_ratio']; + } + if (isset($track['Frame_rate'])) { + $videoframerate = str_replace(' fps', '', $track['Frame_rate']); + } + if (isset($track['Writing_library'])) { + $videolibrary = $track['Writing_library']; + } + $this->addVideo($releaseID, $containerformat, $overallbitrate, $videoduration, $videoformat, $videocodec, $videowidth, $videoheight, $videoaspect, $videoframerate, $videolibrary); + } elseif ($track['@attributes']['type'] === 'Audio') { + $audioID = 1; + $audioformat = $audiomode = $audiobitratemode = $audiobitrate = $audiochannels = $audiosamplerate = $audiolibrary = $audiolanguage = $audiotitle = ''; + if (isset($track['@attributes']['streamid'])) { + $audioID = $track['@attributes']['streamid']; + } + if (isset($track['Format'])) { + $audioformat = $track['Format']; + } + if (isset($track['Mode'])) { + $audiomode = $track['Mode']; + } + if (isset($track['Bit_rate_mode'])) { + $audiobitratemode = $track['Bit_rate_mode']; + } + if (isset($track['Bit_rate'])) { + $audiobitrate = $track['Bit_rate']; + } + if (isset($track['Channel_s_'])) { + $audiochannels = $track['Channel_s_']; + } + if (isset($track['Sampling_rate'])) { + $audiosamplerate = $track['Sampling_rate']; + } + if (isset($track['Writing_library'])) { + $audiolibrary = $track['Writing_library']; + } + if (isset($track['Language'])) { + $audiolanguage = $track['Language']; + } + if (isset($track['Title'])) { + $audiotitle = $track['Title']; + } + $this->addAudio($releaseID, $audioID, $audioformat, $audiomode, $audiobitratemode, $audiobitrate, $audiochannels, $audiosamplerate, $audiolibrary, $audiolanguage, $audiotitle); + } elseif ($track['@attributes']['type'] === 'Text') { + $subsID = 1; + $subslanguage = 'Unknown'; + if (isset($track['@attributes']['streamid'])) { + $subsID = $track['@attributes']['streamid']; + } + if (isset($track['Language'])) { + $subslanguage = $track['Language']; + } + $this->addSubs($releaseID, $subsID, $subslanguage); + } + } + } + } + } - - if ($track['@attributes']['type'] === 'General') { - if (isset($track['Format'])) { - $containerformat = $track['Format']; - } - if (isset($track['Overall_bit_rate'])) { - $overallbitrate = $track['Overall_bit_rate']; - } - if (isset($track['Unique_ID'])) { - if(preg_match('/\(0x(?P<hash>[0-9a-f]{32})\)/i', $track['Unique_ID'], $matches)){ - $uniqueid = $matches['hash']; - $this->addUID($releaseID, $uniqueid); - } - } - } else if ($track['@attributes']['type'] === 'Video') { - $videoduration = $videoformat = $videocodec = $videowidth = $videoheight = $videoaspect = $videoframerate = $videolibrary = ''; - if (isset($track['Duration'])) { - $videoduration = $track['Duration']; - } - if (isset($track['Format'])) { - $videoformat = $track['Format']; - } - if (isset($track['Codec_ID'])) { - $videocodec = $track['Codec_ID']; - } - if (isset($track['Width'])) { - $videowidth = preg_replace('/[^0-9]/', '', $track['Width']); - } - if (isset($track['Height'])) { - $videoheight = preg_replace('/[^0-9]/', '', $track['Height']); - } - if (isset($track['Display_aspect_ratio'])) { - $videoaspect = $track['Display_aspect_ratio']; - } - if (isset($track['Frame_rate'])) { - $videoframerate = str_replace(' fps', '', $track['Frame_rate']); - } - if (isset($track['Writing_library'])) { - $videolibrary = $track['Writing_library']; - } - $this->addVideo($releaseID, $containerformat, $overallbitrate, $videoduration, $videoformat, $videocodec, $videowidth, $videoheight, $videoaspect, $videoframerate, $videolibrary); - } else if ($track['@attributes']['type'] === 'Audio') { - $audioID = 1; - $audioformat = $audiomode = $audiobitratemode = $audiobitrate = $audiochannels = $audiosamplerate = $audiolibrary = $audiolanguage = $audiotitle = ''; - if (isset($track['@attributes']['streamid'])) { - $audioID = $track['@attributes']['streamid']; - } - if (isset($track['Format'])) { - $audioformat = $track['Format']; - } - if (isset($track['Mode'])) { - $audiomode = $track['Mode']; - } - if (isset($track['Bit_rate_mode'])) { - $audiobitratemode = $track['Bit_rate_mode']; - } - if (isset($track['Bit_rate'])) { - $audiobitrate = $track['Bit_rate']; - } - if (isset($track['Channel_s_'])) { - $audiochannels = $track['Channel_s_']; - } - if (isset($track['Sampling_rate'])) { - $audiosamplerate = $track['Sampling_rate']; - } - if (isset($track['Writing_library'])) { - $audiolibrary = $track['Writing_library']; - } - if (isset($track['Language'])) { - $audiolanguage = $track['Language']; - } - if (isset($track['Title'])) { - $audiotitle = $track['Title']; - } - $this->addAudio($releaseID, $audioID, $audioformat, $audiomode, $audiobitratemode, $audiobitrate, $audiochannels, $audiosamplerate, $audiolibrary, $audiolanguage, $audiotitle); - } else if ($track['@attributes']['type'] === 'Text') { - $subsID = 1; - $subslanguage = 'Unknown'; - if (isset($track['@attributes']['streamid'])) { - $subsID = $track['@attributes']['streamid']; - } - if (isset($track['Language'])) { - $subslanguage = $track['Language']; - } - $this->addSubs($releaseID, $subsID, $subslanguage); - } - } - } - } - } - - /** - * @param $releaseID - * @param $containerformat - * @param $overallbitrate - * @param $videoduration - * @param $videoformat - * @param $videocodec - * @param $videowidth - * @param $videoheight - * @param $videoaspect - * @param $videoframerate - * @param $videolibrary - */ - public function addVideo($releaseID, $containerformat, $overallbitrate, $videoduration, $videoformat, $videocodec, $videowidth, $videoheight, $videoaspect, $videoframerate, $videolibrary) - { - $ckid = VideoData::query()->where('releases_id', $releaseID)->value('releases_id'); - if (!isset($ckid)) { - VideoData::query()->insert(['releases_id' => $releaseID, + /** + * @param $releaseID + * @param $containerformat + * @param $overallbitrate + * @param $videoduration + * @param $videoformat + * @param $videocodec + * @param $videowidth + * @param $videoheight + * @param $videoaspect + * @param $videoframerate + * @param $videolibrary + */ + public function addVideo($releaseID, $containerformat, $overallbitrate, $videoduration, $videoformat, $videocodec, $videowidth, $videoheight, $videoaspect, $videoframerate, $videolibrary) + { + $ckid = VideoData::query()->where('releases_id', $releaseID)->value('releases_id'); + if (! isset($ckid)) { + VideoData::query()->insert(['releases_id' => $releaseID, 'containerformat' => $containerformat, 'overallbitrate' => $overallbitrate, 'videoduration' => $videoduration, @@ -269,32 +268,32 @@ class ReleaseExtra 'videoheight' => $videoheight, 'videoaspect' => $videoaspect, 'videoframerate' => $videoframerate, - 'videolibrary' => substr($videolibrary, 0, 50) + 'videolibrary' => substr($videolibrary, 0, 50), ] ); - } - } + } + } - /** - * @param $releaseID - * @param $audioID - * @param $audioformat - * @param $audiomode - * @param $audiobitratemode - * @param $audiobitrate - * @param $audiochannels - * @param $audiosamplerate - * @param $audiolibrary - * @param $audiolanguage - * @param $audiotitle - * - * @return bool|\PDOStatement - */ - public function addAudio($releaseID, $audioID, $audioformat, $audiomode, $audiobitratemode, $audiobitrate, $audiochannels, $audiosamplerate, $audiolibrary, $audiolanguage, $audiotitle) - { - $ckid = AudioData::query()->where('releases_id', $releaseID)->value('releases_id'); - if (!isset($ckid)) { - return AudioData::query()->insert( + /** + * @param $releaseID + * @param $audioID + * @param $audioformat + * @param $audiomode + * @param $audiobitratemode + * @param $audiobitrate + * @param $audiochannels + * @param $audiosamplerate + * @param $audiolibrary + * @param $audiolanguage + * @param $audiotitle + * + * @return bool|\PDOStatement + */ + public function addAudio($releaseID, $audioID, $audioformat, $audiomode, $audiobitratemode, $audiobitrate, $audiochannels, $audiosamplerate, $audiolibrary, $audiolanguage, $audiotitle) + { + $ckid = AudioData::query()->where('releases_id', $releaseID)->value('releases_id'); + if (! isset($ckid)) { + return AudioData::query()->insert( [ 'releases_id' => $releaseID, 'audioid' => $audioID, @@ -306,34 +305,34 @@ class ReleaseExtra 'audiosamplerate' => substr($audiosamplerate, 0, 25), 'audiolibrary' => substr($audiolibrary, 0, 50), 'audiolanguage' => $audiolanguage, - 'audiotitle' => substr($audiotitle, 0, 50) + 'audiotitle' => substr($audiotitle, 0, 50), ] ); - } - } + } + } - /** - * @param $releaseID - * @param $subsID - * @param $subslanguage - * - * @return bool|\PDOStatement - */ - public function addSubs($releaseID, $subsID, $subslanguage) - { - $ckid = ReleaseSubtitle::query()->where('releases_id', $releaseID)->value('releases_id'); - if (!isset($ckid)) { - return ReleaseSubtitle::query()->insert(['releases_id' => $releaseID, 'subsid' => $subsID, 'subslanguage' => $subslanguage]); - } - } + /** + * @param $releaseID + * @param $subsID + * @param $subslanguage + * + * @return bool|\PDOStatement + */ + public function addSubs($releaseID, $subsID, $subslanguage) + { + $ckid = ReleaseSubtitle::query()->where('releases_id', $releaseID)->value('releases_id'); + if (! isset($ckid)) { + return ReleaseSubtitle::query()->insert(['releases_id' => $releaseID, 'subsid' => $subsID, 'subslanguage' => $subslanguage]); + } + } - /** - * @param $releaseID - * @param $uniqueid - */ - public function addUID($releaseID, $uniqueid) - { - $dupecheck = $this->pdo->queryOneRow(" + /** + * @param $releaseID + * @param $uniqueid + */ + public function addUID($releaseID, $uniqueid) + { + $dupecheck = $this->pdo->queryOneRow(" SELECT releases_id FROM release_unique WHERE releases_id = {$releaseID} @@ -343,43 +342,43 @@ class ReleaseExtra )" ); - if ($dupecheck === false) { - $this->pdo->queryExec(" + if ($dupecheck === false) { + $this->pdo->queryExec(" INSERT INTO release_unique (releases_id, uniqueid) VALUES ({$releaseID}, UNHEX('{$uniqueid}'))" ); - } - } + } + } - /** - * @param $id - * - * @return \Illuminate\Database\Eloquent\Model|null|static - */ - public function getFull($id) - { - return ReleaseExtraFull::query()->where('releases_id', $id)->first(); - } + /** + * @param $id + * + * @return \Illuminate\Database\Eloquent\Model|null|static + */ + public function getFull($id) + { + return ReleaseExtraFull::query()->where('releases_id', $id)->first(); + } - /*** - * @param $id - * - * @return mixed - */ - public function deleteFull($id) - { - return ReleaseExtraFull::query()->where('releases_id', $id)->delete(); - } + /*** + * @param $id + * + * @return mixed + */ + public function deleteFull($id) + { + return ReleaseExtraFull::query()->where('releases_id', $id)->delete(); + } - /** - * @param $id - * @param $xml - */ - public function addFull($id, $xml) - { - $ckid = ReleaseExtraFull::query()->where('releases_id', $id)->first(); - if (!isset($ckid['releases_id'])) { - ReleaseExtraFull::query()->insert(['releases_id' => $id, 'mediainfo' => $xml]); - } - } + /** + * @param $id + * @param $xml + */ + public function addFull($id, $xml) + { + $ckid = ReleaseExtraFull::query()->where('releases_id', $id)->first(); + if (! isset($ckid['releases_id'])) { + ReleaseExtraFull::query()->insert(['releases_id' => $id, 'mediainfo' => $xml]); + } + } } diff --git a/nntmux/ReleaseFiles.php b/nntmux/ReleaseFiles.php index 805b710e6..5a0e8497d 100755 --- a/nntmux/ReleaseFiles.php +++ b/nntmux/ReleaseFiles.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; use nntmux\db\DB; @@ -8,81 +9,81 @@ use nntmux\db\DB; */ class ReleaseFiles { - /** - * @var \nntmux\db\Settings - */ - protected $pdo; + /** + * @var \nntmux\db\Settings + */ + protected $pdo; - /** - * @var SphinxSearch - */ - public $sphinxSearch; + /** + * @var SphinxSearch + */ + public $sphinxSearch; - /** - * @param \nntmux\db\DB $settings - */ - public function __construct($settings = null) - { - $this->pdo = ($settings instanceof DB ? $settings : new DB()); - $this->sphinxSearch = new SphinxSearch(); - } + /** + * @param \nntmux\db\DB $settings + */ + public function __construct($settings = null) + { + $this->pdo = ($settings instanceof DB ? $settings : new DB()); + $this->sphinxSearch = new SphinxSearch(); + } + /** + * Get releasefiles row by id. + * + * @param $id + * + * @return array + */ + public function get($id) + { + return $this->pdo->query(sprintf('SELECT * FROM release_files WHERE releases_id = %d ORDER BY release_files.name ', $id)); + } - /** - * Get releasefiles row by id. - * - * @param $id - * - * @return array - */ - public function get($id) - { - return $this->pdo->query(sprintf("SELECT * FROM release_files WHERE releases_id = %d ORDER BY release_files.name ", $id)); - } + /** + * Get releasefiles row by release.GUID. + * + * @param $guid + * + * @return array + */ + public function getByGuid($guid) + { + return $this->pdo->query(sprintf('SELECT release_files.* FROM release_files INNER JOIN releases r ON r.id = release_files.releases_id WHERE r.guid = %s ORDER BY release_files.name ', $this->pdo->escapeString($guid))); + } - /** - * Get releasefiles row by release.GUID. - * - * @param $guid - * - * @return array - */ - public function getByGuid($guid) - { - return $this->pdo->query(sprintf("SELECT release_files.* FROM release_files INNER JOIN releases r ON r.id = release_files.releases_id WHERE r.guid = %s ORDER BY release_files.name ", $this->pdo->escapeString($guid))); - } + /** + * Delete a releasefiles row. + * + * @param $id + * + * @return bool|\PDOStatement + */ + public function delete($id) + { + $res = $this->pdo->queryExec(sprintf('DELETE FROM release_files WHERE releases_id = %d', $id)); + $this->sphinxSearch->updateRelease($id, $this->pdo); - /** - * Delete a releasefiles row. - * - * @param $id - * - * @return bool|\PDOStatement - */ - public function delete($id) - { - $res = $this->pdo->queryExec(sprintf("DELETE FROM release_files WHERE releases_id = %d", $id)); - $this->sphinxSearch->updateRelease($id, $this->pdo); - return $res; - } + return $res; + } - /** - * Add new files for a release ID. - * - * @param int $id The ID of the release. - * @param string $name Name of the file. - * @param string $hash hash_16k of par2 - * @param int $size Size of the file. - * @param int $createdTime Unix time the file was created. - * @param int $hasPassword Does it have a password (see Releases class constants)? - * - * @return mixed - */ - public function add($id, $name, $hash = '', $size, $createdTime, $hasPassword) - { - $insert = 0; + /** + * Add new files for a release ID. + * + * @param int $id The ID of the release. + * @param string $name Name of the file. + * @param string $hash hash_16k of par2 + * @param int $size Size of the file. + * @param int $createdTime Unix time the file was created. + * @param int $hasPassword Does it have a password (see Releases class constants)? + * + * @return mixed + */ + public function add($id, $name, $hash = '', $size, $createdTime, $hasPassword) + { + $insert = 0; - $duplicateCheck = $this->pdo->queryOneRow( + $duplicateCheck = $this->pdo->queryOneRow( sprintf(' SELECT releases_id FROM release_files @@ -92,8 +93,8 @@ class ReleaseFiles ) ); - if ($duplicateCheck === false) { - $insert = $this->pdo->queryInsert( + if ($duplicateCheck === false) { + $insert = $this->pdo->queryInsert( sprintf(' INSERT INTO release_files (releases_id, name, size, createddate, passworded) @@ -107,8 +108,8 @@ class ReleaseFiles ) ); - if (strlen($hash) === 32) { - $this->pdo->queryExec( + if (strlen($hash) === 32) { + $this->pdo->queryExec( sprintf(' INSERT INTO par_hashes (releases_id, hash) @@ -117,9 +118,10 @@ class ReleaseFiles $this->pdo->escapeString($hash) ) ); - } - $this->sphinxSearch->updateRelease($id, $this->pdo); - } - return $insert; - } + } + $this->sphinxSearch->updateRelease($id, $this->pdo); + } + + return $insert; + } } diff --git a/nntmux/ReleaseImage.php b/nntmux/ReleaseImage.php index fae1d0472..071bcdc1d 100755 --- a/nntmux/ReleaseImage.php +++ b/nntmux/ReleaseImage.php @@ -1,9 +1,10 @@ <?php + namespace nntmux; +use nntmux\db\DB; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; -use nntmux\db\DB; /** * Resize/save/delete images to disk. @@ -12,63 +13,62 @@ use nntmux\db\DB; */ class ReleaseImage { - /** - * Path to save ogg audio samples. - * - * @var string - */ - public $audSavePath; + /** + * Path to save ogg audio samples. + * + * @var string + */ + public $audSavePath; - /** - * Path to save video preview jpg pictures. - * - * @var string - */ - public $imgSavePath; + /** + * Path to save video preview jpg pictures. + * + * @var string + */ + public $imgSavePath; - /** - * Path to save large jpg pictures(xxx). - * - * @var string - */ - public $jpgSavePath; + /** + * Path to save large jpg pictures(xxx). + * + * @var string + */ + public $jpgSavePath; - /** - * Path to save movie jpg covers. - * - * @var string - */ - public $movieImgSavePath; + /** + * Path to save movie jpg covers. + * + * @var string + */ + public $movieImgSavePath; - /** - * Path to save video ogv files. - * - * @var string - */ - public $vidSavePath; + /** + * Path to save video ogv files. + * + * @var string + */ + public $vidSavePath; - /** - * @var Client - */ - protected $client; + /** + * @var Client + */ + protected $client; - /** - * Construct. - * - * @param \DB() - */ - public function __construct(&$pdo) - { - - $this->pdo = ($pdo instanceof DB ? $pdo : new DB()); - $this->client = new Client(); - // Creates the NN_COVERS constant + /** + * Construct. + * + * @param \DB() + */ + public function __construct(&$pdo) + { + $this->pdo = ($pdo instanceof DB ? $pdo : new DB()); + $this->client = new Client(); + // Creates the NN_COVERS constant // Table | Column - $this->audSavePath = NN_COVERS . 'audiosample' . DS; // releases guid - $this->imgSavePath = NN_COVERS . 'preview' . DS; // releases guid - $this->jpgSavePath = NN_COVERS . 'sample' . DS; // releases guid - $this->movieImgSavePath = NN_COVERS . 'movies' . DS; // releases imdbid - $this->vidSavePath = NN_COVERS . 'video' . DS; // releases guid + $this->audSavePath = NN_COVERS.'audiosample'.DS; // releases guid + $this->imgSavePath = NN_COVERS.'preview'.DS; // releases guid + $this->jpgSavePath = NN_COVERS.'sample'.DS; // releases guid + $this->movieImgSavePath = NN_COVERS.'movies'.DS; // releases imdbid + $this->vidSavePath = NN_COVERS.'video'.DS; // releases guid /* For reference. * $this->anidbImgPath = NN_COVERS . 'anime' . DS; // anidb anidbid | used in populate_anidb.php, not anidb.php @@ -79,138 +79,141 @@ class ReleaseImage $this->audioImgPath = NN_COVERS . 'audio' . DS; // unused folder, music folder already exists. **/ - } + } - /** - * Get a URL or file image and convert it to string. - * - * @param string $imgLoc URL or file location. - * - * @return bool|mixed|string - */ - protected function fetchImage($imgLoc) - { - $img = false; - if (strpos(strtolower($imgLoc), 'http:') === 0 || strpos(strtolower($imgLoc), 'https:') === 0) { - try { - $img = $this->client->get($imgLoc)->getBody()->getContents(); - } catch (RequestException $e) { - if ($e->hasResponse()) { - if($e->getCode() === 404) { - ColorCLI::doEcho(ColorCLI::notice('Data not available on server')); - } else if ($e->getCode() === 503) { - ColorCLI::doEcho(ColorCLI::notice('Service unavailable')); - } else { - ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data, server responded with code: ' . $e->getCode())); - } - return false; - } - } catch (\RuntimeException $e) { - ColorCLI::doEcho(ColorCLI::notice('Runtime error: ' . $e->getCode())); - return false; - } + /** + * Get a URL or file image and convert it to string. + * + * @param string $imgLoc URL or file location. + * + * @return bool|mixed|string + */ + protected function fetchImage($imgLoc) + { + $img = false; + if (strpos(strtolower($imgLoc), 'http:') === 0 || strpos(strtolower($imgLoc), 'https:') === 0) { + try { + $img = $this->client->get($imgLoc)->getBody()->getContents(); + } catch (RequestException $e) { + if ($e->hasResponse()) { + if ($e->getCode() === 404) { + ColorCLI::doEcho(ColorCLI::notice('Data not available on server')); + } elseif ($e->getCode() === 503) { + ColorCLI::doEcho(ColorCLI::notice('Service unavailable')); + } else { + ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data, server responded with code: '.$e->getCode())); + } - } else if (is_file($imgLoc)) { - $img = @file_get_contents($imgLoc); - } - if ($img !== false) { - $imagick = new \Imagick(); - $imgFail = false; - try { - $imagick->readImageBlob($img); - } catch (\ImagickException $imgError) { - ColorCLI::doEcho(ColorCLI::notice('Invalid image data, skipping processing') . PHP_EOL); - $imgFail = true; - } - if ($imgFail === false) { - $im = $imagick->readImageBlob($img); - if ($im === true) { - $imagick->clear(); - return $img; - } - } - } + return false; + } + } catch (\RuntimeException $e) { + ColorCLI::doEcho(ColorCLI::notice('Runtime error: '.$e->getCode())); - return false; - } + return false; + } + } elseif (is_file($imgLoc)) { + $img = @file_get_contents($imgLoc); + } + if ($img !== false) { + $imagick = new \Imagick(); + $imgFail = false; + try { + $imagick->readImageBlob($img); + } catch (\ImagickException $imgError) { + ColorCLI::doEcho(ColorCLI::notice('Invalid image data, skipping processing').PHP_EOL); + $imgFail = true; + } + if ($imgFail === false) { + $im = $imagick->readImageBlob($img); + if ($im === true) { + $imagick->clear(); - /** - * Save an image to disk, optionally resizing it. - * - * @param string $imgName What to name the new image. - * @param string $imgLoc URL or location on the disk the original image is in. - * @param string $imgSavePath Folder to save the new image in. - * @param string $imgMaxWidth Max width to resize image to. (OPTIONAL) - * @param string $imgMaxHeight Max height to resize image to. (OPTIONAL) - * @param bool $saveThumb Save a thumbnail of this image? (OPTIONAL) - * - * @return int 1 on success, 0 on failure Used on site to check if there is an image. - */ - public function saveImage($imgName, $imgLoc, $imgSavePath, $imgMaxWidth = '', $imgMaxHeight = '', $saveThumb = false) - { - // Try to get the image as a string. - $cover = $this->fetchImage($imgLoc); - if ($cover === false) { - return 0; - } + return $img; + } + } + } - // Check if we need to resize it. - if ($imgMaxWidth != '' && $imgMaxHeight != '') { - $imagick = new \Imagick(); - $imagick->readImageBlob($cover); - $width = $imagick->getImageWidth(); - $height = $imagick->getImageHeight(); - $ratio = min($imgMaxHeight / $height, $imgMaxWidth / $width); - // New dimensions - $new_width = (int)($ratio * $width); - $new_height = (int)($ratio * $height); - if ($new_width < $width && $new_width > 10 && $new_height > 10) { - $imagick->thumbnailImage($new_width, $new_height, true); - $imagick->setImageFormat('jpeg'); - $thumb = $imagick->getImageBlob(); - $imagick->clear(); + return false; + } - if ($saveThumb) { - @file_put_contents($imgSavePath . $imgName . '_thumb.jpg', $thumb); - } else { - $cover = $thumb; - } + /** + * Save an image to disk, optionally resizing it. + * + * @param string $imgName What to name the new image. + * @param string $imgLoc URL or location on the disk the original image is in. + * @param string $imgSavePath Folder to save the new image in. + * @param string $imgMaxWidth Max width to resize image to. (OPTIONAL) + * @param string $imgMaxHeight Max height to resize image to. (OPTIONAL) + * @param bool $saveThumb Save a thumbnail of this image? (OPTIONAL) + * + * @return int 1 on success, 0 on failure Used on site to check if there is an image. + */ + public function saveImage($imgName, $imgLoc, $imgSavePath, $imgMaxWidth = '', $imgMaxHeight = '', $saveThumb = false) + { + // Try to get the image as a string. + $cover = $this->fetchImage($imgLoc); + if ($cover === false) { + return 0; + } - unset($thumb); - } - $imagick->clear(); - } - // Store it on the hard drive. - $coverPath = $imgSavePath . $imgName . '.jpg'; - $coverSave = @file_put_contents($coverPath, $cover); - // Check if it's on the drive. - if ($coverSave === false || !is_file($coverPath)) { - return 0; - } - return 1; - } + // Check if we need to resize it. + if ($imgMaxWidth != '' && $imgMaxHeight != '') { + $imagick = new \Imagick(); + $imagick->readImageBlob($cover); + $width = $imagick->getImageWidth(); + $height = $imagick->getImageHeight(); + $ratio = min($imgMaxHeight / $height, $imgMaxWidth / $width); + // New dimensions + $new_width = (int) ($ratio * $width); + $new_height = (int) ($ratio * $height); + if ($new_width < $width && $new_width > 10 && $new_height > 10) { + $imagick->thumbnailImage($new_width, $new_height, true); + $imagick->setImageFormat('jpeg'); + $thumb = $imagick->getImageBlob(); + $imagick->clear(); - /** - * Delete images for the release. - * - * @param string $guid The GUID of the release. - * - * @return void - */ - public function delete($guid) - { - $thumb = $guid . '_thumb.jpg'; + if ($saveThumb) { + @file_put_contents($imgSavePath.$imgName.'_thumb.jpg', $thumb); + } else { + $cover = $thumb; + } - // Audiosample folder. - @unlink($this->audSavePath . $guid . '.ogg'); + unset($thumb); + } + $imagick->clear(); + } + // Store it on the hard drive. + $coverPath = $imgSavePath.$imgName.'.jpg'; + $coverSave = @file_put_contents($coverPath, $cover); + // Check if it's on the drive. + if ($coverSave === false || ! is_file($coverPath)) { + return 0; + } - // Preview folder. - @unlink($this->imgSavePath . $thumb); + return 1; + } - // Sample folder. - @unlink($this->jpgSavePath . $thumb); + /** + * Delete images for the release. + * + * @param string $guid The GUID of the release. + * + * @return void + */ + public function delete($guid) + { + $thumb = $guid.'_thumb.jpg'; - // Video folder. - @unlink($this->vidSavePath . $guid . '.ogv'); - } + // Audiosample folder. + @unlink($this->audSavePath.$guid.'.ogg'); + + // Preview folder. + @unlink($this->imgSavePath.$thumb); + + // Sample folder. + @unlink($this->jpgSavePath.$thumb); + + // Video folder. + @unlink($this->vidSavePath.$guid.'.ogv'); + } } diff --git a/nntmux/ReleaseRemover.php b/nntmux/ReleaseRemover.php index 9ae169e65..554262f90 100755 --- a/nntmux/ReleaseRemover.php +++ b/nntmux/ReleaseRemover.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; use nntmux\db\DB; @@ -10,112 +11,112 @@ use nntmux\db\DB; */ class ReleaseRemover { - /** - * @const New line. - */ - const N = PHP_EOL; + /** + * @const New line. + */ + const N = PHP_EOL; - /** - * @var string - */ - protected $blacklistID; + /** + * @var string + */ + protected $blacklistID; - /** - * Is is run from the browser? - * - * @var bool - */ - protected $browser; + /** + * Is is run from the browser? + * + * @var bool + */ + protected $browser; - /** - * @var ConsoleTools - */ - protected $consoleTools; + /** + * @var ConsoleTools + */ + protected $consoleTools; - /** - * @var string - */ - protected $crapTime = ''; + /** + * @var string + */ + protected $crapTime = ''; - /** - * @var bool - */ - protected $delete; + /** + * @var bool + */ + protected $delete; - /** - * @var int - */ - protected $deletedCount = 0; + /** + * @var int + */ + protected $deletedCount = 0; - /** - * @var bool - */ - protected $echoCLI; + /** + * @var bool + */ + protected $echoCLI; - /** - * If an error occurred, store it here. - * - * @var string - */ - protected $error; + /** + * If an error occurred, store it here. + * + * @var string + */ + protected $error; - /** - * Ignore user check? - * - * @var bool - */ - protected $ignoreUserCheck; + /** + * Ignore user check? + * + * @var bool + */ + protected $ignoreUserCheck; - /** - * @var string - */ - protected $method = ''; + /** + * @var string + */ + protected $method = ''; - /** - * @var DB - */ - protected $pdo; + /** + * @var DB + */ + protected $pdo; - /** - * The query we will use to select unwanted releases. - * - * @var string - */ - protected $query; + /** + * The query we will use to select unwanted releases. + * + * @var string + */ + protected $query; - /** - * @var Releases - */ - protected $releases; + /** + * @var Releases + */ + protected $releases; - /** - * Result of the select query. - * - * @var array - */ - protected $result; + /** + * Result of the select query. + * + * @var array + */ + protected $result; - /** - * Time we started. - * - * @var int - */ - protected $timeStart; + /** + * Time we started. + * + * @var int + */ + protected $timeStart; - /** - * @var NZB - */ - private $nzb; + /** + * @var NZB + */ + private $nzb; - /** - * Construct. - * - * @param array $options Class instances / various options. - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Construct. + * + * @param array $options Class instances / various options. + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Browser' => false, // Are we coming from the web script. 'ConsoleTools' => null, 'Echo' => true, // Echo to CLI? @@ -124,129 +125,128 @@ class ReleaseRemover 'Releases' => null, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->consoleTools = ($options['ConsoleTools'] instanceof ConsoleTools ? $options['ConsoleTools'] : new ConsoleTools(['ColorCLI' => $this->pdo->log])); - $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)); - $this->releaseImage = ($options['ReleaseImage'] instanceof ReleaseImage ? $options['ReleaseImage'] : new ReleaseImage($this->pdo)); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->consoleTools = ($options['ConsoleTools'] instanceof ConsoleTools ? $options['ConsoleTools'] : new ConsoleTools(['ColorCLI' => $this->pdo->log])); + $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)); + $this->releaseImage = ($options['ReleaseImage'] instanceof ReleaseImage ? $options['ReleaseImage'] : new ReleaseImage($this->pdo)); - $this->query = ''; - $this->error = ''; - $this->ignoreUserCheck = false; - $this->browser = $options['Browser']; - $this->echoCLI = (!$this->browser && NN_ECHOCLI && $options['Echo']); - } + $this->query = ''; + $this->error = ''; + $this->ignoreUserCheck = false; + $this->browser = $options['Browser']; + $this->echoCLI = (! $this->browser && NN_ECHOCLI && $options['Echo']); + } - /** - * Remove releases using user criteria. - * - * @param array $arguments Array of criteria used to delete unwanted releases. - * Criteria muse look like this : columnName=modifier="content" - * columnName is a column name from the releases table. - * modifiers are : equals,like,bigger,smaller - * content is what to change the column content to - * - * @return string|bool - */ - public function removeByCriteria($arguments) - { - $this->delete = true; - $this->ignoreUserCheck = false; - // Time we started. - $this->timeStart = time(); + /** + * Remove releases using user criteria. + * + * @param array $arguments Array of criteria used to delete unwanted releases. + * Criteria muse look like this : columnName=modifier="content" + * columnName is a column name from the releases table. + * modifiers are : equals,like,bigger,smaller + * content is what to change the column content to + * + * @return string|bool + */ + public function removeByCriteria($arguments) + { + $this->delete = true; + $this->ignoreUserCheck = false; + // Time we started. + $this->timeStart = time(); - // Start forming the query. - $this->query = 'SELECT id, guid, searchname FROM releases WHERE 1=1'; + // Start forming the query. + $this->query = 'SELECT id, guid, searchname FROM releases WHERE 1=1'; - // Keep forming the query based on the user's criteria, return if any errors. - foreach ($arguments as $arg) { - $this->error = ''; - $string = $this->formatCriteriaQuery($arg); - if ($string === false) { - return $this->returnError(); - } - $this->query .= $string; - } - $this->query = $this->cleanSpaces($this->query); + // Keep forming the query based on the user's criteria, return if any errors. + foreach ($arguments as $arg) { + $this->error = ''; + $string = $this->formatCriteriaQuery($arg); + if ($string === false) { + return $this->returnError(); + } + $this->query .= $string; + } + $this->query = $this->cleanSpaces($this->query); - // Check if the user wants to run the query. - if ($this->checkUserResponse() === false) { - return false; - } + // Check if the user wants to run the query. + if ($this->checkUserResponse() === false) { + return false; + } - // Check if the query returns results. - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + // Check if the query returns results. + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - $this->method = 'userCriteria'; + $this->method = 'userCriteria'; - $this->deletedCount = 0; - // Delete the releases. - $this->deleteReleases(); + $this->deletedCount = 0; + // Delete the releases. + $this->deleteReleases(); - if ($this->echoCLI) { - echo ColorCLI::headerOver(($this->delete ? 'Deleted ' : 'Would have deleted ') . $this->deletedCount . ' release(s). This script ran for '); - echo ColorCLI::header($this->consoleTools->convertTime(time() - $this->timeStart)); - } + if ($this->echoCLI) { + echo ColorCLI::headerOver(($this->delete ? 'Deleted ' : 'Would have deleted ').$this->deletedCount.' release(s). This script ran for '); + echo ColorCLI::header($this->consoleTools->convertTime(time() - $this->timeStart)); + } - return ($this->browser + return $this->browser ? - 'Success! ' . - ($this->delete ? 'Deleted ' : 'Would have deleted ') . - $this->deletedCount . - ' release(s) in ' . + 'Success! '. + ($this->delete ? 'Deleted ' : 'Would have deleted '). + $this->deletedCount. + ' release(s) in '. $this->consoleTools->convertTime(time() - $this->timeStart) : - true - ); - } + true; + } - /** - * Delete crap releases. - * - * @param bool $delete Delete the release or just show the result? - * @param int|string $time Time in hours (to select old releases) or 'full' for no time limit. - * @param string $type Type of query to run [blacklist, executable, gibberish, hashed, installbin, passworded, - * passwordurl, sample, scr, short, size, ''] ('' runs against all types) - * @param string|int $blacklistID - * - * @return string|bool - */ - public function removeCrap($delete, $time, $type = '', $blacklistID = '') - { - $this->timeStart = time(); - $this->delete = $delete; - $this->blacklistID = ''; + /** + * Delete crap releases. + * + * @param bool $delete Delete the release or just show the result? + * @param int|string $time Time in hours (to select old releases) or 'full' for no time limit. + * @param string $type Type of query to run [blacklist, executable, gibberish, hashed, installbin, passworded, + * passwordurl, sample, scr, short, size, ''] ('' runs against all types) + * @param string|int $blacklistID + * + * @return string|bool + */ + public function removeCrap($delete, $time, $type = '', $blacklistID = '') + { + $this->timeStart = time(); + $this->delete = $delete; + $this->blacklistID = ''; - if ($blacklistID !== '' && is_numeric($blacklistID)) { - $this->blacklistID = sprintf('AND id = %d', $blacklistID); - } + if ($blacklistID !== '' && is_numeric($blacklistID)) { + $this->blacklistID = sprintf('AND id = %d', $blacklistID); + } - $time = trim($time); - $this->crapTime = ''; - $type = strtolower(trim($type)); + $time = trim($time); + $this->crapTime = ''; + $type = strtolower(trim($type)); - if ($time === 'full') { - if ($this->echoCLI) { - echo ColorCLI::header('Removing ' . ($type === '' ? 'All crap releases ' : $type . ' crap releases') . ' - no time limit.\n'); - } - } else { - if (!is_numeric($time)) { - $this->error = 'Error, time must be a number or full.'; + if ($time === 'full') { + if ($this->echoCLI) { + echo ColorCLI::header('Removing '.($type === '' ? 'All crap releases ' : $type.' crap releases').' - no time limit.\n'); + } + } else { + if (! is_numeric($time)) { + $this->error = 'Error, time must be a number or full.'; - return $this->returnError(); - } - if ($this->echoCLI) { - echo ColorCLI::header('Removing ' . ($type === '' ? 'All crap releases ' : $type . ' crap releases') . ' from the past ' . $time . ' hour(s).\n'); - } - $this->crapTime = ' AND r.adddate > (NOW() - INTERVAL ' . $time . ' HOUR)'; - } + return $this->returnError(); + } + if ($this->echoCLI) { + echo ColorCLI::header('Removing '.($type === '' ? 'All crap releases ' : $type.' crap releases').' from the past '.$time.' hour(s).\n'); + } + $this->crapTime = ' AND r.adddate > (NOW() - INTERVAL '.$time.' HOUR)'; + } - $this->deletedCount = 0; - switch ($type) { + $this->deletedCount = 0; + switch ($type) { case 'blacklist': $this->removeBlacklist(); break; @@ -312,37 +312,36 @@ class ReleaseRemover $this->removeCodecPoster(); break; default: - $this->error = 'Wrong type: ' . $type; + $this->error = 'Wrong type: '.$type; return $this->returnError(); } - if ($this->echoCLI) { - echo ColorCLI::headerOver(($this->delete ? 'Deleted ' : 'Would have deleted ') . $this->deletedCount . ' release(s). This script ran for '); - echo ColorCLI::header($this->consoleTools->convertTime(time() - $this->timeStart)); - } + if ($this->echoCLI) { + echo ColorCLI::headerOver(($this->delete ? 'Deleted ' : 'Would have deleted ').$this->deletedCount.' release(s). This script ran for '); + echo ColorCLI::header($this->consoleTools->convertTime(time() - $this->timeStart)); + } - return ($this->browser + return $this->browser ? - 'Success! ' . - ($this->delete ? 'Deleted ' : 'Would have deleted ') . - $this->deletedCount . - ' release(s) in ' . + 'Success! '. + ($this->delete ? 'Deleted ' : 'Would have deleted '). + $this->deletedCount. + ' release(s) in '. $this->consoleTools->convertTime(time() - $this->timeStart) : - true - ); - } + true; + } - /** - * Remove releases with 15 or more letters or numbers, nothing else. - * - * @return boolean|string - */ - protected function removeGibberish() - { - $this->method = 'Gibberish'; - $this->query = sprintf( + /** + * Remove releases with 15 or more letters or numbers, nothing else. + * + * @return bool|string + */ + protected function removeGibberish() + { + $this->method = 'Gibberish'; + $this->query = sprintf( "SELECT r.guid, r.searchname, r.id FROM releases r WHERE r.nfostatus = 0 @@ -355,22 +354,22 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases with 25 or more letters/numbers, probably hashed. - * - * @return boolean|string - */ - protected function removeHashed() - { - $this->method = 'Hashed'; - $this->query = sprintf( + /** + * Remove releases with 25 or more letters/numbers, probably hashed. + * + * @return bool|string + */ + protected function removeHashed() + { + $this->method = 'Hashed'; + $this->query = sprintf( "SELECT r.guid, r.searchname, r.id FROM releases r WHERE r.nfostatus = 0 @@ -382,22 +381,22 @@ class ReleaseRemover Category::OTHER_MISC, Category::OTHER_HASHED, $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases with 5 or less letters/numbers. - * - * @return boolean|string - */ - protected function removeShort() - { - $this->method = 'Short'; - $this->query = sprintf( + /** + * Remove releases with 5 or less letters/numbers. + * + * @return bool|string + */ + protected function removeShort() + { + $this->method = 'Short'; + $this->query = sprintf( "SELECT r.guid, r.searchname, r.id FROM releases r WHERE r.nfostatus = 0 @@ -409,23 +408,23 @@ class ReleaseRemover Category::OTHER_MISC, $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases with an exe file not in other misc or pc apps/games. - * - * @return boolean|string - */ - protected function removeExecutable() - { - $this->method = 'Executable'; + /** + * Remove releases with an exe file not in other misc or pc apps/games. + * + * @return bool|string + */ + protected function removeExecutable() + { + $this->method = 'Executable'; - $this->query = sprintf( + $this->query = sprintf( 'SELECT r.guid, r.searchname, r.id FROM releases r STRAIGHT_JOIN release_files rf ON r.id = rf.releases_id @@ -439,23 +438,23 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases with an install.bin file. - * - * @return boolean|string - */ - protected function removeInstallBin() - { - $this->method = 'Install.bin'; + /** + * Remove releases with an install.bin file. + * + * @return bool|string + */ + protected function removeInstallBin() + { + $this->method = 'Install.bin'; - $this->query = sprintf( + $this->query = sprintf( 'SELECT r.guid, r.searchname, r.id FROM releases r STRAIGHT_JOIN release_files rf ON r.id = rf.releases_id @@ -464,23 +463,23 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases with an password.url file. - * - * @return boolean|string - */ - protected function removePasswordURL() - { - $this->method = 'Password.url'; + /** + * Remove releases with an password.url file. + * + * @return bool|string + */ + protected function removePasswordURL() + { + $this->method = 'Password.url'; - $this->query = sprintf( + $this->query = sprintf( 'SELECT r.guid, r.searchname, r.id FROM releases r STRAIGHT_JOIN release_files rf ON r.id = rf.releases_id @@ -489,23 +488,23 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases with password in the search name. - * - * @return boolean|string - */ - protected function removePassworded() - { - $this->method = 'Passworded'; + /** + * Remove releases with password in the search name. + * + * @return bool|string + */ + protected function removePassworded() + { + $this->method = 'Passworded'; - $this->query = sprintf( + $this->query = sprintf( 'SELECT r.guid, r.searchname, r.id FROM releases r WHERE r.searchname %s @@ -537,22 +536,22 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases smaller than 2MB with 1 part not in MP3/books/misc section. - * - * @return boolean|string - */ - protected function removeSize() - { - $this->method = 'Size'; - $this->query = sprintf( + /** + * Remove releases smaller than 2MB with 1 part not in MP3/books/misc section. + * + * @return bool|string + */ + protected function removeSize() + { + $this->method = 'Size'; + $this->query = sprintf( 'SELECT r.guid, r.searchname, r.id FROM releases r WHERE r.totalpart = 1 @@ -572,22 +571,22 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases bigger than 200MB with just a single file. - * - * @return boolean|string - */ - protected function removeHuge() - { - $this->method = 'Huge'; - $this->query = sprintf( + /** + * Remove releases bigger than 200MB with just a single file. + * + * @return bool|string + */ + protected function removeHuge() + { + $this->method = 'Huge'; + $this->query = sprintf( 'SELECT r.guid, r.searchname, r.id FROM releases r WHERE r.totalpart = 1 @@ -595,22 +594,22 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases that are just a single nzb file. - * - * @return boolean|string - */ - protected function removeSingleNZB() - { - $this->method = '.nzb'; - $this->query = sprintf( + /** + * Remove releases that are just a single nzb file. + * + * @return bool|string + */ + protected function removeSingleNZB() + { + $this->method = '.nzb'; + $this->query = sprintf( 'SELECT r.guid, r.searchname, r.id FROM releases r STRAIGHT_JOIN release_files rf ON r.id = rf.releases_id @@ -620,23 +619,23 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases with more than 1 part, less than 40MB, sample in name. TV/Movie sections. - * - * @return boolean|string - */ - protected function removeSample() - { - $this->method = 'Sample'; + /** + * Remove releases with more than 1 part, less than 40MB, sample in name. TV/Movie sections. + * + * @return bool|string + */ + protected function removeSample() + { + $this->method = 'Sample'; - $this->query = sprintf( + $this->query = sprintf( 'SELECT r.guid, r.searchname, r.id FROM releases r WHERE r.totalpart > 1 @@ -662,23 +661,23 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases with a scr file in the filename/subject. - * - * @return boolean|string - */ - protected function removeSCR() - { - $this->method = '.scr'; + /** + * Remove releases with a scr file in the filename/subject. + * + * @return bool|string + */ + protected function removeSCR() + { + $this->method = '.scr'; - $this->query = sprintf( + $this->query = sprintf( "SELECT r.guid, r.searchname, r.id FROM releases r STRAIGHT_JOIN release_files rf ON r.id = rf.releases_id @@ -687,27 +686,27 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases using the site blacklist regexes. - * - * @return bool - */ - protected function removeBlacklist() - { - $status = sprintf('AND status = %d', Binaries::BLACKLIST_ENABLED); + /** + * Remove releases using the site blacklist regexes. + * + * @return bool + */ + protected function removeBlacklist() + { + $status = sprintf('AND status = %d', Binaries::BLACKLIST_ENABLED); - if (!empty($this->blacklistID) && $this->delete === false) { - $status = ''; - } + if (! empty($this->blacklistID) && $this->delete === false) { + $status = ''; + } - $regexList = $this->pdo->query( + $regexList = $this->pdo->query( sprintf( 'SELECT regex, id, groupname, msgcol FROM binaryblacklist @@ -722,17 +721,15 @@ class ReleaseRemover ) ); - if (count($regexList) > 0) { + if (count($regexList) > 0) { + foreach ($regexList as $regex) { + $regexSQL = $ftMatch = $regexMatch = $opTypeName = ''; + $dbRegex = $this->pdo->escapeString($regex['regex']); - foreach ($regexList as $regex) { - - $regexSQL = $ftMatch = $regexMatch = $opTypeName = ''; - $dbRegex = $this->pdo->escapeString($regex['regex']); - - if ($this->crapTime === '') { - $regexMatch = $this->extractSrchFromRegx($dbRegex); - if ($regexMatch !== '') { - switch (NN_RELEASE_SEARCH_TYPE) { + if ($this->crapTime === '') { + $regexMatch = $this->extractSrchFromRegx($dbRegex); + if ($regexMatch !== '') { + switch (NN_RELEASE_SEARCH_TYPE) { case ReleaseSearch::SPHINX: $ftMatch = sprintf('rse.query = "@(name,searchname) %s;limit=1000000;maxmatches=1000000;mode=any" AND', str_replace('|', ' ', str_replace('"', '', $regexMatch))); break; @@ -740,72 +737,71 @@ class ReleaseRemover $ftMatch = sprintf("(MATCH (rs.name) AGAINST ('%1\$s') OR MATCH (rs.searchname) AGAINST ('%1\$s')) AND", str_replace('|', ' ', $regexMatch)); break; } - } - } + } + } - switch ((int)$regex['msgcol']) { + switch ((int) $regex['msgcol']) { case Binaries::BLACKLIST_FIELD_SUBJECT: - $regexSQL = sprintf("WHERE %s (r.name REGEXP %s OR r.searchname REGEXP %2\$s)", $ftMatch, $dbRegex); + $regexSQL = sprintf('WHERE %s (r.name REGEXP %s OR r.searchname REGEXP %2$s)', $ftMatch, $dbRegex); $opTypeName = 'Subject'; break; case Binaries::BLACKLIST_FIELD_FROM: - $regexSQL = 'WHERE r.fromname REGEXP ' . $dbRegex; + $regexSQL = 'WHERE r.fromname REGEXP '.$dbRegex; $opTypeName = 'Poster'; break; } - if ($regexSQL === '') { - continue; - } + if ($regexSQL === '') { + continue; + } - // Get the group ID if the regex is set to work against a group. - $groupID = ''; - if (strtolower($regex['groupname']) !== 'alt.binaries.*') { - - $groupIDs = $this->pdo->query( - 'SELECT id FROM groups WHERE name REGEXP ' . + // Get the group ID if the regex is set to work against a group. + $groupID = ''; + if (strtolower($regex['groupname']) !== 'alt.binaries.*') { + $groupIDs = $this->pdo->query( + 'SELECT id FROM groups WHERE name REGEXP '. $this->pdo->escapeString($regex['groupname']) ); - $groupIDCount = count($groupIDs); - if ($groupIDCount === 0) { - continue; - } elseif ($groupIDCount === 1) { - $groupIDs = $groupIDs[0]['id']; - } else { - $string = ''; - foreach ($groupIDs as $ID) { - $string .= $ID['id'] . ','; - } - $groupIDs = substr($string, 0, -1); - } + $groupIDCount = count($groupIDs); + if ($groupIDCount === 0) { + continue; + } elseif ($groupIDCount === 1) { + $groupIDs = $groupIDs[0]['id']; + } else { + $string = ''; + foreach ($groupIDs as $ID) { + $string .= $ID['id'].','; + } + $groupIDs = substr($string, 0, -1); + } - $groupID = ' AND r.groups_id in (' . $groupIDs . ') '; - } - $this->method = 'Blacklist [' . $regex['id'] . ']'; + $groupID = ' AND r.groups_id in ('.$groupIDs.') '; + } + $this->method = 'Blacklist ['.$regex['id'].']'; - // Check if using FT Match and declare for echo - if ($ftMatch !== '' && $opTypeName === 'Subject') { - $blType = 'FULLTEXT match with REGEXP'; - $ftUsing = 'Using (' . $regexMatch . ') as interesting words.' . PHP_EOL; - } else { - $blType = 'only REGEXP'; - $ftUsing = PHP_EOL; - } + // Check if using FT Match and declare for echo + if ($ftMatch !== '' && $opTypeName === 'Subject') { + $blType = 'FULLTEXT match with REGEXP'; + $ftUsing = 'Using ('.$regexMatch.') as interesting words.'.PHP_EOL; + } else { + $blType = 'only REGEXP'; + $ftUsing = PHP_EOL; + } - // Provide useful output of operations - echo ColorCLI::header(sprintf("Finding crap releases for %s: Using %s method against release %s.\n" . + // Provide useful output of operations + echo ColorCLI::header(sprintf("Finding crap releases for %s: Using %s method against release %s.\n". '%s', $this->method, $blType, $opTypeName, $ftUsing ) ); - if ($opTypeName === 'Subject') { - $join = (NN_RELEASE_SEARCH_TYPE === ReleaseSearch::SPHINX ? 'INNER JOIN releases_se rse ON rse.id = r.id' : 'INNER JOIN release_search_data rs ON rs.releases_id = r.id'); - } else { - $join = ''; - } + if ($opTypeName === 'Subject') { + $join = (NN_RELEASE_SEARCH_TYPE === ReleaseSearch::SPHINX ? 'INNER JOIN releases_se rse ON rse.id = r.id' : 'INNER JOIN release_search_data rs ON rs.releases_id = r.id'); + } else { + $join = ''; + } - $this->query = sprintf(' + $this->query = sprintf(' SELECT r.guid, r.searchname, r.id FROM releases r %s %s %s %s', $join, @@ -814,27 +810,26 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - continue; - } - $this->deleteReleases(); + if ($this->checkSelectQuery() === false) { + continue; + } + $this->deleteReleases(); + } + } else { + echo ColorCLI::error("No regular expressions were selected for blacklist removal. Make sure you have activated REGEXPs in Site Edit and you're specifying a valid ID.\n"); + } - } - } else { - echo ColorCLI::error("No regular expressions were selected for blacklist removal. Make sure you have activated REGEXPs in Site Edit and you're specifying a valid ID.\n"); - } + return true; + } - return true; - } - - /** - * Remove releases using the site blacklist regexes against file names. - * - * @return bool - */ - protected function removeBlacklistFiles() - { - $allRegex = $this->pdo->query( + /** + * Remove releases using the site blacklist regexes against file names. + * + * @return bool + */ + protected function removeBlacklistFiles() + { + $allRegex = $this->pdo->query( sprintf( 'SELECT regex, id, groupname FROM binaryblacklist @@ -848,55 +843,53 @@ class ReleaseRemover ) ); - if (count($allRegex) > 0) { + if (count($allRegex) > 0) { + foreach ($allRegex as $regex) { + $dbRegex = $this->pdo->escapeString($regex['regex']); - foreach ($allRegex as $regex) { - $dbRegex = $this->pdo->escapeString($regex['regex']); - - $regexSQL = sprintf('STRAIGHT_JOIN release_files rf ON r.id = rf.releases_id + $regexSQL = sprintf('STRAIGHT_JOIN release_files rf ON r.id = rf.releases_id WHERE rf.name REGEXP %s ', $this->pdo->escapeString($regex['regex']) ); - if ($regexSQL === '') { - continue; - } + if ($regexSQL === '') { + continue; + } - // Get the group ID if the regex is set to work against a group. - $groupID = ''; - if (strtolower($regex['groupname']) !== 'alt.binaries.*') { - $groupIDs = $this->pdo->query( - 'SELECT id FROM groups WHERE name REGEXP ' . + // Get the group ID if the regex is set to work against a group. + $groupID = ''; + if (strtolower($regex['groupname']) !== 'alt.binaries.*') { + $groupIDs = $this->pdo->query( + 'SELECT id FROM groups WHERE name REGEXP '. $this->pdo->escapeString($regex['groupname']) ); - $groupIDCount = count($groupIDs); - if ($groupIDCount === 0) { - continue; - } elseif ($groupIDCount === 1) { - $groupIDs = $groupIDs[0]['id']; - } else { - $string = ''; - foreach ($groupIDs as $fID) { - $string .= $fID['id'] . ','; - } - $groupIDs = substr($string, 0, -1); - } + $groupIDCount = count($groupIDs); + if ($groupIDCount === 0) { + continue; + } elseif ($groupIDCount === 1) { + $groupIDs = $groupIDs[0]['id']; + } else { + $string = ''; + foreach ($groupIDs as $fID) { + $string .= $fID['id'].','; + } + $groupIDs = substr($string, 0, -1); + } - $groupID = ' AND r.groups_id in (' . $groupIDs . ') '; - } + $groupID = ' AND r.groups_id in ('.$groupIDs.') '; + } - $this->method = 'Blacklist Files ' . $regex['id']; + $this->method = 'Blacklist Files '.$regex['id']; - $blType = 'only REGEXP'; - $ftUsing = PHP_EOL; + $blType = 'only REGEXP'; + $ftUsing = PHP_EOL; - - // Provide useful output of operations - echo ColorCLI::header(sprintf('Finding crap releases for %s: Using %s method against release filenames.' . PHP_EOL . + // Provide useful output of operations + echo ColorCLI::header(sprintf('Finding crap releases for %s: Using %s method against release filenames.'.PHP_EOL. '%s', $this->method, $blType, $ftUsing ) ); - $this->query = sprintf( + $this->query = sprintf( 'SELECT DISTINCT r.id, r.guid, r.searchname FROM releases r %s %s %s', $regexSQL, @@ -904,51 +897,50 @@ class ReleaseRemover $this->crapTime ); - if ($this->checkSelectQuery() === false) { - continue; - } + if ($this->checkSelectQuery() === false) { + continue; + } - $this->deleteReleases(); - } - } + $this->deleteReleases(); + } + } - return true; - } + return true; + } - /** - * Remove releases that contain .wmv file, aka that spam poster. - * Thanks to dizant from nZEDb forums for the sql query - * - * @return string|boolean - */ - protected function removeWMV() - { - $this->method = 'WMV_ALL'; - $this->query = " + /** + * Remove releases that contain .wmv file, aka that spam poster. + * Thanks to dizant from nZEDb forums for the sql query. + * + * @return string|bool + */ + protected function removeWMV() + { + $this->method = 'WMV_ALL'; + $this->query = " SELECT r.guid, r.searchname FROM releases r LEFT JOIN release_files rf ON (r.id = rf.releases_id) WHERE r.categories_id BETWEEN ' . Category::TV_ROOT . ' AND ' . Category::TV_OTHER . ' AND rf.name REGEXP 'x264.*\.wmv$' - GROUP BY r.id" - ; + GROUP BY r.id"; - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } - /** - * Remove releases that contain .wmv files and Codec\Setup.exe files, aka that spam poster. - * Thanks to dizant from nZEDb forums for parts of the sql query - * - * @return string|boolean - */ - protected function removeCodecPoster() - { - $categories = sprintf('r.categories_id IN (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)', + /** + * Remove releases that contain .wmv files and Codec\Setup.exe files, aka that spam poster. + * Thanks to dizant from nZEDb forums for parts of the sql query. + * + * @return string|bool + */ + protected function removeCodecPoster() + { + $categories = sprintf('r.categories_id IN (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)', Category::MOVIE_3D, Category::MOVIE_BLURAY, Category::MOVIE_DVD, @@ -962,11 +954,11 @@ class ReleaseRemover Category::XXX_OTHER ); - $regex = - '\.*((DVDrip|BRRip)[. ].*[. ](R[56]|HQ)|720p[ .](DVDrip|HQ)|Webrip.*[. ](R[56]|Xvid|AC3|US)' . + $regex = + '\.*((DVDrip|BRRip)[. ].*[. ](R[56]|HQ)|720p[ .](DVDrip|HQ)|Webrip.*[. ](R[56]|Xvid|AC3|US)'. '|720p.*[. ]WEB-DL[. ]Xvid[. ]AC3[. ]US|HDRip.*[. ]Xvid[. ]DD5).*[. ]avi$'; - $this->query = " + $this->query = " SELECT r.guid, r.searchname, r.id FROM releases r LEFT JOIN release_files rf ON r.id = rf.releases_id @@ -994,115 +986,113 @@ class ReleaseRemover ) GROUP BY r.id {$this->crapTime}"; - if ($this->checkSelectQuery() === false) { - return $this->returnError(); - } + if ($this->checkSelectQuery() === false) { + return $this->returnError(); + } - return $this->deleteReleases(); - } + return $this->deleteReleases(); + } + /** + * Delete releases from the database. + */ + protected function deleteReleases() + { + $deletedCount = 0; + foreach ($this->result as $release) { + if ($this->delete) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + if ($this->echoCLI) { + echo ColorCLI::primary('Deleting: '.$this->method.': '.$release['searchname']); + } + } elseif ($this->echoCLI) { + echo ColorCLI::primary('Would be deleting: '.$this->method.': '.$release['searchname']); + } + $deletedCount++; + } - /** - * Delete releases from the database. - */ - protected function deleteReleases() - { - $deletedCount = 0; - foreach ($this->result as $release) { - if ($this->delete) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - if ($this->echoCLI) { - echo ColorCLI::primary('Deleting: ' . $this->method . ': ' . $release['searchname']); - } - } elseif ($this->echoCLI) { - echo ColorCLI::primary('Would be deleting: ' . $this->method . ': ' . $release['searchname']); - } - $deletedCount++; - } + $this->deletedCount += $deletedCount; - $this->deletedCount += $deletedCount; + return true; + } - return true; - } + /** + * Verify if the query has any results. + * + * @return bool False on failure, true on success after setting a count of found releases. + */ + protected function checkSelectQuery() + { + // Run the query, check if it picked up anything. + $result = $this->pdo->query($this->cleanSpaces($this->query)); + if (count($result) <= 0) { + $this->error = ''; + if ($this->method === 'userCriteria') { + $this->error = 'No releases were found to delete, try changing your criteria.'; + } - /** - * Verify if the query has any results. - * - * @return boolean False on failure, true on success after setting a count of found releases. - */ - protected function checkSelectQuery() - { - // Run the query, check if it picked up anything. - $result = $this->pdo->query($this->cleanSpaces($this->query)); - if (count($result) <= 0) { - $this->error = ''; - if ($this->method === 'userCriteria') { - $this->error = 'No releases were found to delete, try changing your criteria.'; - } + return false; + } + $this->result = $result; - return false; - } - $this->result = $result; + return true; + } - return true; - } + /** + * Go through user arguments and format part of the query. + * + * @param string $argument User argument. + * + * @return string|false + */ + protected function formatCriteriaQuery($argument) + { + // Check if the user wants to ignore the check. + if ($argument === 'ignore') { + $this->ignoreUserCheck = true; - /** - * Go through user arguments and format part of the query. - * - * @param string $argument User argument. - * - * @return string|false - */ - protected function formatCriteriaQuery($argument) - { - // Check if the user wants to ignore the check. - if ($argument === 'ignore') { - $this->ignoreUserCheck = true; + return ''; + } - return ''; - } - - $this->error = 'Invalid argument supplied: ' . $argument . self::N; - $args = explode('=', $argument); - if (count($args) === 3) { - - $args[0] = $this->cleanSpaces($args[0]); - $args[1] = $this->cleanSpaces($args[1]); - $args[2] = $this->cleanSpaces($args[2]); - switch ($args[0]) { + $this->error = 'Invalid argument supplied: '.$argument.self::N; + $args = explode('=', $argument); + if (count($args) === 3) { + $args[0] = $this->cleanSpaces($args[0]); + $args[1] = $this->cleanSpaces($args[1]); + $args[2] = $this->cleanSpaces($args[2]); + switch ($args[0]) { case 'categories_id': if ($args[1] === 'equals') { - return ' AND categories_id = ' . $args[2]; + return ' AND categories_id = '.$args[2]; } break; case 'imdbid': if ($args[1] === 'equals') { - if ($args[2] === 'NULL') { - return ' AND imdbid IS NULL '; - } else { - return ' AND imdbid = ' . $args[2]; - } + if ($args[2] === 'NULL') { + return ' AND imdbid IS NULL '; + } else { + return ' AND imdbid = '.$args[2]; + } } break; case 'nzbstatus': if ($args[1] === 'equals') { - return ' AND nzbstatus = ' . $args[2]; + return ' AND nzbstatus = '.$args[2]; } break; case 'videos_id': if ($args[1] === 'equals') { - return ' AND videos_id = ' . $args[2]; + return ' AND videos_id = '.$args[2]; } break; case 'totalpart': switch ($args[1]) { case 'equals': - return ' AND totalpart = ' . $args[2]; + return ' AND totalpart = '.$args[2]; case 'bigger': - return ' AND totalpart > ' . $args[2]; + return ' AND totalpart > '.$args[2]; case 'smaller': - return ' AND totalpart < ' . $args[2]; + return ' AND totalpart < '.$args[2]; default: break; } @@ -1110,32 +1100,32 @@ class ReleaseRemover case 'fromname': switch ($args[1]) { case 'equals': - return ' AND fromname = ' . $this->pdo->escapeString($args[2]); + return ' AND fromname = '.$this->pdo->escapeString($args[2]); case 'like': - return ' AND fromname ' . $this->formatLike($args[2], 'fromname'); + return ' AND fromname '.$this->formatLike($args[2], 'fromname'); } break; case 'groupname': switch ($args[1]) { case 'equals': - $group = $this->pdo->queryOneRow('SELECT id FROM groups WHERE name = ' . $this->pdo->escapeString($args[2])); + $group = $this->pdo->queryOneRow('SELECT id FROM groups WHERE name = '.$this->pdo->escapeString($args[2])); if ($group === false) { - $this->error = 'This group was not found in your database: ' . $args[2] . PHP_EOL; - break; + $this->error = 'This group was not found in your database: '.$args[2].PHP_EOL; + break; } - return ' AND groups_id = ' . $group['id']; + return ' AND groups_id = '.$group['id']; case 'like': - $groups = $this->pdo->query('SELECT id FROM groups WHERE name ' . $this->formatLike($args[2], 'name')); + $groups = $this->pdo->query('SELECT id FROM groups WHERE name '.$this->formatLike($args[2], 'name')); if (count($groups) === 0) { - $this->error = 'No groups were found with this pattern in your database: ' . $args[2] . PHP_EOL; - break; + $this->error = 'No groups were found with this pattern in your database: '.$args[2].PHP_EOL; + break; } $gQuery = ' AND groups_id IN ('; foreach ($groups as $group) { - $gQuery .= $group['id'] . ','; + $gQuery .= $group['id'].','; } - $gQuery = substr($gQuery, 0, -0) . ')'; + $gQuery = substr($gQuery, 0, -0).')'; return $gQuery; default: @@ -1144,15 +1134,15 @@ class ReleaseRemover break; case 'guid': if ($args[1] === 'equals') { - return ' AND guid = ' . $this->pdo->escapeString($args[2]); + return ' AND guid = '.$this->pdo->escapeString($args[2]); } break; case 'name': switch ($args[1]) { case 'equals': - return ' AND name = ' . $this->pdo->escapeString($args[2]); + return ' AND name = '.$this->pdo->escapeString($args[2]); case 'like': - return ' AND name ' . $this->formatLike($args[2], 'name'); + return ' AND name '.$this->formatLike($args[2], 'name'); default: break; } @@ -1160,175 +1150,176 @@ class ReleaseRemover case 'searchname': switch ($args[1]) { case 'equals': - return ' AND searchname = ' . $this->pdo->escapeString($args[2]); + return ' AND searchname = '.$this->pdo->escapeString($args[2]); case 'like': - return ' AND searchname ' . $this->formatLike($args[2], 'searchname'); + return ' AND searchname '.$this->formatLike($args[2], 'searchname'); default: break; } break; case 'size': - if (!is_numeric($args[2])) { - break; + if (! is_numeric($args[2])) { + break; } switch ($args[1]) { case 'equals': - return ' AND size = ' . $args[2]; + return ' AND size = '.$args[2]; case 'bigger': - return ' AND size > ' . $args[2]; + return ' AND size > '.$args[2]; case 'smaller': - return ' AND size < ' . $args[2]; + return ' AND size < '.$args[2]; default: break; } break; case 'adddate': - if (!is_numeric($args[2])) { - break; + if (! is_numeric($args[2])) { + break; } switch ($args[1]) { case 'bigger': - return ' AND adddate < NOW() - INTERVAL ' . $args[2] . ' HOUR'; + return ' AND adddate < NOW() - INTERVAL '.$args[2].' HOUR'; case 'smaller': - return ' AND adddate > NOW() - INTERVAL ' . $args[2] . ' HOUR'; + return ' AND adddate > NOW() - INTERVAL '.$args[2].' HOUR'; default: break; } break; case 'postdate': - if (!is_numeric($args[2])) { - break; + if (! is_numeric($args[2])) { + break; } switch ($args[1]) { case 'bigger': - return ' AND postdate < NOW() - INTERVAL ' . $args[2] . ' HOUR'; + return ' AND postdate < NOW() - INTERVAL '.$args[2].' HOUR'; case 'smaller': - return ' AND postdate > NOW() - INTERVAL ' . $args[2] . ' HOUR'; + return ' AND postdate > NOW() - INTERVAL '.$args[2].' HOUR'; default: break; } break; case 'completion': - if (!is_numeric($args[2])) { - break; + if (! is_numeric($args[2])) { + break; } if ($args[1] === 'smaller') { - return ' AND completion > 0 AND completion < ' . $args[2]; + return ' AND completion > 0 AND completion < '.$args[2]; } } - } + } - return false; - } + return false; + } - /** - * Check if the user wants to run the current query. - * - * @return bool - */ - protected function checkUserResponse() - { - if ($this->ignoreUserCheck || $this->browser) { - return true; - } + /** + * Check if the user wants to run the current query. + * + * @return bool + */ + protected function checkUserResponse() + { + if ($this->ignoreUserCheck || $this->browser) { + return true; + } - // Print the query to the user, ask them if they want to continue using it. - echo ColorCLI::primary( - 'This is the query we have formatted using your criteria, you can run it in SQL to see if you like the results:' . - self::N . $this->query . ';' . self::N . + // Print the query to the user, ask them if they want to continue using it. + echo ColorCLI::primary( + 'This is the query we have formatted using your criteria, you can run it in SQL to see if you like the results:'. + self::N.$this->query.';'.self::N. 'If you are satisfied, type yes and press enter. Anything else will exit.' ); - // Check the users response. - $userInput = trim(fgets(fopen('php://stdin', 'brt'))); - if ($userInput !== 'yes') { - echo ColorCLI::primary('You typed: "' . $userInput . '", the program will exit.'); + // Check the users response. + $userInput = trim(fgets(fopen('php://stdin', 'brt'))); + if ($userInput !== 'yes') { + echo ColorCLI::primary('You typed: "'.$userInput.'", the program will exit.'); - return false; - } + return false; + } - return true; - } + return true; + } - /** - * Remove multiple spaces and trim leading spaces. - * - * @param string $string - * - * @return string - */ - protected function cleanSpaces($string) - { - return trim(preg_replace('/\s{2,}/', ' ', $string)); - } + /** + * Remove multiple spaces and trim leading spaces. + * + * @param string $string + * + * @return string + */ + protected function cleanSpaces($string) + { + return trim(preg_replace('/\s{2,}/', ' ', $string)); + } - /** - * Format a "like" string. ie: "name LIKE '%test%' AND name LIKE '%123%' - * - * @param string $string The string to format. - * @param string $type The column name. - * - * @return string - */ - protected function formatLike($string, $type) - { - $newString = explode(' ', $string); - if (count($newString) > 1) { - $string = implode("%' AND {$type} LIKE '%", array_unique($newString)); - } + /** + * Format a "like" string. ie: "name LIKE '%test%' AND name LIKE '%123%'. + * + * @param string $string The string to format. + * @param string $type The column name. + * + * @return string + */ + protected function formatLike($string, $type) + { + $newString = explode(' ', $string); + if (count($newString) > 1) { + $string = implode("%' AND {$type} LIKE '%", array_unique($newString)); + } - return " LIKE '%" . $string . "%' "; - } + return " LIKE '%".$string."%' "; + } - /** - * Echo the error and return false if on CLI. - * Return the error if on browser. - * - * @return bool/string - */ - protected function returnError() - { - if ($this->browser) { - return $this->error . '<br />'; - } + /** + * Echo the error and return false if on CLI. + * Return the error if on browser. + * + * @return bool/string + */ + protected function returnError() + { + if ($this->browser) { + return $this->error.'<br />'; + } - if ($this->echoCLI && $this->error !== '') { - echo ColorCLI::error($this->error); - } - return false; - } + if ($this->echoCLI && $this->error !== '') { + echo ColorCLI::error($this->error); + } - protected function extractSrchFromRegx($dbRegex = '') - { - $regexMatch = ''; + return false; + } - // Match Regex beginning for long running foreign search - if (substr($dbRegex, 2, 17) === 'brazilian|chinese') { - // Find first brazilian instance position in Regex, then find first closing parenthesis. - // Then substitute all pipes (|) with spaces for FT search and insert into query - $forBegin = strpos($dbRegex, 'brazilian'); - $regexMatch = + protected function extractSrchFromRegx($dbRegex = '') + { + $regexMatch = ''; + + // Match Regex beginning for long running foreign search + if (substr($dbRegex, 2, 17) === 'brazilian|chinese') { + // Find first brazilian instance position in Regex, then find first closing parenthesis. + // Then substitute all pipes (|) with spaces for FT search and insert into query + $forBegin = strpos($dbRegex, 'brazilian'); + $regexMatch = substr($dbRegex, $forBegin, strpos($dbRegex, ')') - $forBegin ); - } else if (substr($dbRegex, 7, 11) === 'bl|cz|de|es') { - // Find first bl|cz instance position in Regex, then find first closing parenthesis. - $forBegin = strpos($dbRegex, 'bl|cz'); - $regexMatch = '"' . + } elseif (substr($dbRegex, 7, 11) === 'bl|cz|de|es') { + // Find first bl|cz instance position in Regex, then find first closing parenthesis. + $forBegin = strpos($dbRegex, 'bl|cz'); + $regexMatch = '"'. str_replace('|', '" "', substr($dbRegex, $forBegin, strpos($dbRegex, ')') - $forBegin) - ) . '"'; - } else if (substr($dbRegex, 8, 5) === '19|20') { - // Find first bl|cz instance position in Regex, then find last closing parenthesis as this is reversed. - $forBegin = strpos($dbRegex, 'bl|cz'); - $regexMatch = '"' . + ).'"'; + } elseif (substr($dbRegex, 8, 5) === '19|20') { + // Find first bl|cz instance position in Regex, then find last closing parenthesis as this is reversed. + $forBegin = strpos($dbRegex, 'bl|cz'); + $regexMatch = '"'. str_replace('|', '" "', substr($dbRegex, $forBegin, strrpos($dbRegex, ')') - $forBegin) - ) . '"'; - } else if (substr($dbRegex, 7, 14) === 'chinese.subbed') { - // Find first brazilian instance position in Regex, then find first closing parenthesis. - $forBegin = strpos($dbRegex, 'chinese'); - $regexMatch = + ).'"'; + } elseif (substr($dbRegex, 7, 14) === 'chinese.subbed') { + // Find first brazilian instance position in Regex, then find first closing parenthesis. + $forBegin = strpos($dbRegex, 'chinese'); + $regexMatch = str_replace('nl subed|bed|s', 'nlsubs|nlsubbed|nlsubed', str_replace('?', '', str_replace('.', ' ', @@ -1339,41 +1330,39 @@ class ReleaseRemover ) ) ) - ) - ; - } else if (substr($dbRegex, 8, 2) === '4u') { - // Find first 4u\.nl instance position in Regex, then find first closing parenthesis. - $forBegin = strpos($dbRegex, '4u'); - $regexMatch = + ); + } elseif (substr($dbRegex, 8, 2) === '4u') { + // Find first 4u\.nl instance position in Regex, then find first closing parenthesis. + $forBegin = strpos($dbRegex, '4u'); + $regexMatch = str_replace('nov[ a]+rip', 'nova', str_replace('4u.nl', '"4u" "nl"', substr($dbRegex, $forBegin, strpos($dbRegex, ')') - $forBegin) ) - ) - ; - } else if (substr($dbRegex, 8, 5) === 'bd|dl') { - // Find first bd|dl instance position in Regex, then find last closing parenthesis as this is reversed. - $forBegin = strpos($dbRegex, 'bd|dl'); - $regexMatch = + ); + } elseif (substr($dbRegex, 8, 5) === 'bd|dl') { + // Find first bd|dl instance position in Regex, then find last closing parenthesis as this is reversed. + $forBegin = strpos($dbRegex, 'bd|dl'); + $regexMatch = str_replace(['\\', ']', '['], '', str_replace('bd|dl)mux', 'bdmux|dlmux', substr($dbRegex, $forBegin, strrpos($dbRegex, ')') - $forBegin ) ) - ) - ; - } else if (substr($dbRegex, 7, 9) === 'imageset|') { - // Find first imageset| instance position in Regex, then find last closing parenthesis. - $forBegin = strpos($dbRegex, 'imageset'); - $regexMatch = substr($dbRegex, $forBegin, strpos($dbRegex, ')') - $forBegin); - } else if (substr($dbRegex, 1, 9) === 'hdnectar|') { - // Find first hdnectar| instance position in Regex. - $regexMatch = str_replace('\'', '', $dbRegex); - } else if (substr($dbRegex, 1, 10) === 'Passworded') { - // Find first Passworded instance position esin Regex, then find last closing parenthesis. - $regexMatch = str_replace('\'', '', $dbRegex); - } - return $regexMatch; - } + ); + } elseif (substr($dbRegex, 7, 9) === 'imageset|') { + // Find first imageset| instance position in Regex, then find last closing parenthesis. + $forBegin = strpos($dbRegex, 'imageset'); + $regexMatch = substr($dbRegex, $forBegin, strpos($dbRegex, ')') - $forBegin); + } elseif (substr($dbRegex, 1, 9) === 'hdnectar|') { + // Find first hdnectar| instance position in Regex. + $regexMatch = str_replace('\'', '', $dbRegex); + } elseif (substr($dbRegex, 1, 10) === 'Passworded') { + // Find first Passworded instance position esin Regex, then find last closing parenthesis. + $regexMatch = str_replace('\'', '', $dbRegex); + } + + return $regexMatch; + } } diff --git a/nntmux/ReleaseSearch.php b/nntmux/ReleaseSearch.php index 4874f94e0..6900f4b61 100755 --- a/nntmux/ReleaseSearch.php +++ b/nntmux/ReleaseSearch.php @@ -1,37 +1,38 @@ <?php + namespace nntmux; use nntmux\db\DB; class ReleaseSearch { - const FULLTEXT = 0; - const LIKE = 1; - const SPHINX = 2; + const FULLTEXT = 0; + const LIKE = 1; + const SPHINX = 2; - /*** - * @var DB - */ - public $pdo; + /*** + * @var DB + */ + public $pdo; - /** - * Array where keys are the column name, and value is the search string. - * @var array - */ - private $searchOptions; + /** + * Array where keys are the column name, and value is the search string. + * @var array + */ + private $searchOptions; - /** - * Sets the string to join the releases table to the release search table if using full text. - * @var string - */ - private $fullTextJoinString; + /** + * Sets the string to join the releases table to the release search table if using full text. + * @var string + */ + private $fullTextJoinString; - /** - * @param DB $settings - */ - public function __construct(DB $settings) - { - switch (NN_RELEASE_SEARCH_TYPE) { + /** + * @param DB $settings + */ + public function __construct(DB $settings) + { + switch (NN_RELEASE_SEARCH_TYPE) { case self::LIKE: $this->fullTextJoinString = ''; break; @@ -44,27 +45,27 @@ class ReleaseSearch break; } - $this->sphinxQueryOpt = ';limit=10000;maxmatches=10000;sort=relevance;mode=extended'; - $this->pdo = ($settings instanceof DB ? $settings : new DB()); - } + $this->sphinxQueryOpt = ';limit=10000;maxmatches=10000;sort=relevance;mode=extended'; + $this->pdo = ($settings instanceof DB ? $settings : new DB()); + } - /** - * Create part of a SQL query for searching releases. - * - * @param array $options Array where keys are the column name, and value is the search string. - * @param bool $forceLike Force a "like" search on the column. - * - * @return string - */ - public function getSearchSQL(array $options = [], $forceLike = false): string - { - $this->searchOptions = $options; + /** + * Create part of a SQL query for searching releases. + * + * @param array $options Array where keys are the column name, and value is the search string. + * @param bool $forceLike Force a "like" search on the column. + * + * @return string + */ + public function getSearchSQL(array $options = [], $forceLike = false): string + { + $this->searchOptions = $options; - if ($forceLike) { - return $this->likeSQL(); - } + if ($forceLike) { + return $this->likeSQL(); + } - switch (NN_RELEASE_SEARCH_TYPE) { + switch (NN_RELEASE_SEARCH_TYPE) { case self::LIKE: $SQL = $this->likeSQL(); break; @@ -76,110 +77,113 @@ class ReleaseSearch $SQL = $this->fullTextSQL(); break; } - return $SQL; - } - /** - * Returns the string for joining the release search table to the releases table. - * @return string - */ - public function getFullTextJoinString(): string - { - return $this->fullTextJoinString; - } + return $SQL; + } - /** - * Create SQL sub-query for full text searching. - * - * @return string - */ - private function fullTextSQL(): string - { - $return = ''; - foreach ($this->searchOptions as $columnName => $searchString) { - $searchWords = ''; + /** + * Returns the string for joining the release search table to the releases table. + * @return string + */ + public function getFullTextJoinString(): string + { + return $this->fullTextJoinString; + } - // At least 1 search term needs to be mandatory. - $words = explode(' ', (!preg_match('/[+!^]/', $searchString) ? '+' : '') . $searchString); - foreach ($words as $word) { - $word = str_replace("'", "\\'", str_replace(['!', '^'], '+', trim($word, "\n\t\r\0\x0B- "))); + /** + * Create SQL sub-query for full text searching. + * + * @return string + */ + private function fullTextSQL(): string + { + $return = ''; + foreach ($this->searchOptions as $columnName => $searchString) { + $searchWords = ''; - if ($word !== '' && $word !== '-' && strlen($word) > 1) { - $searchWords .= ($word . ' '); - } - } - $searchWords = trim($searchWords); - if ($searchWords !== '') { - $return .= sprintf(" AND MATCH(rs.%s) AGAINST('%s' IN BOOLEAN MODE)", $columnName, $searchWords); - } + // At least 1 search term needs to be mandatory. + $words = explode(' ', (! preg_match('/[+!^]/', $searchString) ? '+' : '').$searchString); + foreach ($words as $word) { + $word = str_replace("'", "\\'", str_replace(['!', '^'], '+', trim($word, "\n\t\r\0\x0B- "))); - } - // If we didn't get anything, try the LIKE method. - if ($return === '') { - return $this->likeSQL(); - } - return $return; - } + if ($word !== '' && $word !== '-' && strlen($word) > 1) { + $searchWords .= ($word.' '); + } + } + $searchWords = trim($searchWords); + if ($searchWords !== '') { + $return .= sprintf(" AND MATCH(rs.%s) AGAINST('%s' IN BOOLEAN MODE)", $columnName, $searchWords); + } + } + // If we didn't get anything, try the LIKE method. + if ($return === '') { + return $this->likeSQL(); + } - /** - * Create SQL sub-query for standard search. - * - * @return string - */ - private function likeSQL() - { - $return = ''; - foreach ($this->searchOptions as $columnName => $searchString) { - $wordCount = 0; - $words = explode(' ', $searchString); - foreach ($words as $word) { - if ($word !== '') { - $word = trim($word, "-\n\t\r\0\x0B "); - if ($wordCount === 0 && (strpos($word, '^') === 0)) { - $return .= sprintf(' AND r.%s %s', $columnName, $this->pdo->likeString(substr($word, 1), false)); - } else if (strpos($word, '--') === 0) { - $return .= sprintf(' AND r.%s NOT %s', $columnName, $this->pdo->likeString(substr($word, 2))); - } else { - $return .= sprintf(' AND r.%s %s', $columnName, $this->pdo->likeString($word)); - } - $wordCount++; - } - } - } - return $return; - } + return $return; + } - /** - * Create SQL sub-query using sphinx full text search. - * - * @return string - */ - private function sphinxSQL() - { - $searchQuery = $fullReturn = ''; + /** + * Create SQL sub-query for standard search. + * + * @return string + */ + private function likeSQL() + { + $return = ''; + foreach ($this->searchOptions as $columnName => $searchString) { + $wordCount = 0; + $words = explode(' ', $searchString); + foreach ($words as $word) { + if ($word !== '') { + $word = trim($word, "-\n\t\r\0\x0B "); + if ($wordCount === 0 && (strpos($word, '^') === 0)) { + $return .= sprintf(' AND r.%s %s', $columnName, $this->pdo->likeString(substr($word, 1), false)); + } elseif (strpos($word, '--') === 0) { + $return .= sprintf(' AND r.%s NOT %s', $columnName, $this->pdo->likeString(substr($word, 2))); + } else { + $return .= sprintf(' AND r.%s %s', $columnName, $this->pdo->likeString($word)); + } + $wordCount++; + } + } + } - foreach ($this->searchOptions as $columnName => $searchString) { - $searchWords = ''; - $words = explode(' ', $searchString); - foreach ($words as $word) { - $word = str_replace("'", "\\'", trim($word, "\n\t\r\0\x0B ")); - if ($word !== '') { - $searchWords .= ($word . ' '); - } - } - $searchWords = rtrim($searchWords, "\n\t\r\0\x0B "); - if ($searchWords !== '') { - $searchQuery .= sprintf('@%s %s ', + return $return; + } + + /** + * Create SQL sub-query using sphinx full text search. + * + * @return string + */ + private function sphinxSQL() + { + $searchQuery = $fullReturn = ''; + + foreach ($this->searchOptions as $columnName => $searchString) { + $searchWords = ''; + $words = explode(' ', $searchString); + foreach ($words as $word) { + $word = str_replace("'", "\\'", trim($word, "\n\t\r\0\x0B ")); + if ($word !== '') { + $searchWords .= ($word.' '); + } + } + $searchWords = rtrim($searchWords, "\n\t\r\0\x0B "); + if ($searchWords !== '') { + $searchQuery .= sprintf('@%s %s ', $columnName, $searchWords ); - } - } - if ($searchQuery !== '') { - $fullReturn = sprintf("AND (rse.query = '@@relaxed %s')", trim($searchQuery) . $this->sphinxQueryOpt); - } else { - $fullReturn = $this->likeSQL(); - } - return $fullReturn; - } + } + } + if ($searchQuery !== '') { + $fullReturn = sprintf("AND (rse.query = '@@relaxed %s')", trim($searchQuery).$this->sphinxQueryOpt); + } else { + $fullReturn = $this->likeSQL(); + } + + return $fullReturn; + } } diff --git a/nntmux/Releases.php b/nntmux/Releases.php index b113209bd..bf23820d0 100755 --- a/nntmux/Releases.php +++ b/nntmux/Releases.php @@ -1,93 +1,94 @@ <?php + namespace nntmux; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; use nntmux\utility\Utility; /** - * Class Releases + * Class Releases. */ class Releases { - // RAR/ZIP Passworded indicator. - const PASSWD_NONE = 0; // No password. + // RAR/ZIP Passworded indicator. + const PASSWD_NONE = 0; // No password. const PASSWD_POTENTIAL = 1; // Might have a password. - const BAD_FILE = 2; // Possibly broken RAR/ZIP. - const PASSWD_RAR = 10; // Definitely passworded. + const BAD_FILE = 2; // Possibly broken RAR/ZIP. + const PASSWD_RAR = 10; // Definitely passworded. /** * @var DB */ - public $pdo; + public $pdo; - /** - * @var Groups - */ - public $groups; + /** + * @var Groups + */ + public $groups; - /** - * @var bool - */ - public $updateGrabs; + /** + * @var bool + */ + public $updateGrabs; - /** - * @var ReleaseSearch - */ - public $releaseSearch; + /** + * @var ReleaseSearch + */ + public $releaseSearch; - /** - * @var SphinxSearch - */ - public $sphinxSearch; + /** + * @var SphinxSearch + */ + public $sphinxSearch; - /** - * @var string - */ - public $showPasswords; + /** + * @var string + */ + public $showPasswords; - /** - * @var int - */ - public $passwordStatus; + /** + * @var int + */ + public $passwordStatus; - /** - * @var Category - */ - public $category; + /** + * @var Category + */ + public $category; - /** - * @var array $options Class instances. - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @var array Class instances. + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, - 'Groups' => null + 'Groups' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->groups = ($options['Groups'] instanceof Groups ? $options['Groups'] : new Groups(['Settings' => $this->pdo])); - $this->updateGrabs = ((int)Settings::value('..grabstatus') !== 0); - $this->passwordStatus = ((int)Settings::value('..checkpasswordedrar') === 1 ? -1 : 0); - $this->sphinxSearch = new SphinxSearch(); - $this->releaseSearch = new ReleaseSearch($this->pdo); - $this->category = new Category(['Settings' => $this->pdo]); - $this->showPasswords = self::showPasswords(); - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->groups = ($options['Groups'] instanceof Groups ? $options['Groups'] : new Groups(['Settings' => $this->pdo])); + $this->updateGrabs = ((int) Settings::value('..grabstatus') !== 0); + $this->passwordStatus = ((int) Settings::value('..checkpasswordedrar') === 1 ? -1 : 0); + $this->sphinxSearch = new SphinxSearch(); + $this->releaseSearch = new ReleaseSearch($this->pdo); + $this->category = new Category(['Settings' => $this->pdo]); + $this->showPasswords = self::showPasswords(); + } - /** - * Insert a single release returning the ID on success or false on failure. - * - * @param array $parameters Insert parameters, must be escaped if string. - * - * @return bool|int - */ - public function insertRelease(array $parameters = []) - { - $parameters['id'] = $this->pdo->queryInsert( + /** + * Insert a single release returning the ID on success or false on failure. + * + * @param array $parameters Insert parameters, must be escaped if string. + * + * @return bool|int + */ + public function insertRelease(array $parameters = []) + { + $parameters['id'] = $this->pdo->queryInsert( sprintf( 'INSERT INTO releases (name, searchname, totalpart, groups_id, adddate, guid, leftguid, postdate, fromname, @@ -111,29 +112,29 @@ class Releases $parameters['predb_id'] ) ); - $this->sphinxSearch->insertRelease($parameters); - return $parameters['id']; - } + $this->sphinxSearch->insertRelease($parameters); - /** - * Create a GUID for a release. - * @return string - */ - public function createGUID(): string - { - $data = openssl_random_pseudo_bytes(16); - $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100 + return $parameters['id']; + } + + /** + * Create a GUID for a release. + * @return string + */ + public function createGUID(): string + { + $data = openssl_random_pseudo_bytes(16); + $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100 $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10 return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); + } - } - - /** - * @return array - */ - public function get(): array - { - return $this->pdo->query( + /** + * @return array + */ + public function get(): array + { + return $this->pdo->query( sprintf( 'SELECT r.*, g.name AS group_name, c.title AS category_name FROM releases r @@ -143,19 +144,19 @@ class Releases NZB::NZB_ADDED ), true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * Used for admin page release-list. - * - * @param $start - * @param $num - * - * @return array - */ - public function getRange($start, $num): array - { - return $this->pdo->query( + /** + * Used for admin page release-list. + * + * @param $start + * @param $num + * + * @return array + */ + public function getRange($start, $num): array + { + return $this->pdo->query( sprintf( "SELECT r.*, CONCAT(cp.title, ' > ', c.title) AS category_name FROM releases r @@ -164,24 +165,24 @@ class Releases WHERE r.nzbstatus = %d ORDER BY r.postdate DESC %s", NZB::NZB_ADDED, - ($start === false ? '' : 'LIMIT ' . $num . ' OFFSET ' . $start) + ($start === false ? '' : 'LIMIT '.$num.' OFFSET '.$start) ), true, NN_CACHE_EXPIRY_MEDIUM ); - } + } - /** - * Used for pager on browse page. - * - * @param array $cat - * @param int $maxAge - * @param array $excludedCats - * @param string|int $groupName - * - * @return int - */ - public function getBrowseCount($cat, $maxAge = -1, array $excludedCats = [], $groupName = ''): int - { - $count = $this->pdo->query( + /** + * Used for pager on browse page. + * + * @param array $cat + * @param int $maxAge + * @param array $excludedCats + * @param string|int $groupName + * + * @return int + */ + public function getBrowseCount($cat, $maxAge = -1, array $excludedCats = [], $groupName = ''): int + { + $count = $this->pdo->query( sprintf( 'SELECT COUNT(r.id) AS count FROM releases r @@ -194,33 +195,33 @@ class Releases $this->showPasswords, ($groupName !== -1 ? sprintf(' AND g.name = %s', $this->pdo->escapeString($groupName)) : ''), $this->category->getCategorySearch($cat), - ($maxAge > 0 ? (' AND r.postdate > NOW() - INTERVAL ' . $maxAge . ' DAY ') : ''), - (count($excludedCats) ? (' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')') : '') + ($maxAge > 0 ? (' AND r.postdate > NOW() - INTERVAL '.$maxAge.' DAY ') : ''), + (count($excludedCats) ? (' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')') : '') ), true, NN_CACHE_EXPIRY_SHORT ); - return $count[0]['count'] ?? 0; - } + return $count[0]['count'] ?? 0; + } - /** - * Used for browse results. - * - * @param array $cat - * @param $start - * @param $num - * @param string|array $orderBy - * @param int $maxAge - * @param array $excludedCats - * @param string|int $groupName - * @param int $minSize - * - * @return array - */ - public function getBrowseRange($cat, $start, $num, $orderBy, $maxAge = -1, array $excludedCats = [], $groupName = -1, $minSize = 0): array - { - $orderBy = $this->getBrowseOrder($orderBy); + /** + * Used for browse results. + * + * @param array $cat + * @param $start + * @param $num + * @param string|array $orderBy + * @param int $maxAge + * @param array $excludedCats + * @param string|int $groupName + * @param int $minSize + * + * @return array + */ + public function getBrowseRange($cat, $start, $num, $orderBy, $maxAge = -1, array $excludedCats = [], $groupName = -1, $minSize = 0): array + { + $orderBy = $this->getBrowseOrder($orderBy); - $qry = sprintf( + $qry = sprintf( "SELECT r.*, CONCAT(cp.title, ' > ', c.title) AS category_name, CONCAT(cp.id, ',', c.id) AS category_ids, @@ -251,57 +252,58 @@ class Releases NZB::NZB_ADDED, $this->showPasswords, $this->category->getCategorySearch($cat), - ($maxAge > 0 ? (' AND postdate > NOW() - INTERVAL ' . $maxAge . ' DAY ') : ''), - (count($excludedCats) ? (' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')') : ''), - ((int)$groupName !== -1 ? sprintf(' AND g.name = %s ', $this->pdo->escapeString($groupName)) : ''), + ($maxAge > 0 ? (' AND postdate > NOW() - INTERVAL '.$maxAge.' DAY ') : ''), + (count($excludedCats) ? (' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')') : ''), + ((int) $groupName !== -1 ? sprintf(' AND g.name = %s ', $this->pdo->escapeString($groupName)) : ''), ($minSize > 0 ? sprintf('AND r.size >= %d', $minSize) : ''), $orderBy[0], $orderBy[1], - ($start === false ? '' : ' LIMIT ' . $num . ' OFFSET ' . $start) + ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start) ); - $sql = $this->pdo->query($qry, true, NN_CACHE_EXPIRY_MEDIUM); - if (count($sql) > 0) { - $possibleRows = $this->getBrowseCount($cat, $maxAge, $excludedCats, $groupName); - $sql[0]['_totalcount'] = $sql[0]['_totalrows'] = $possibleRows; - } - return $sql; - } + $sql = $this->pdo->query($qry, true, NN_CACHE_EXPIRY_MEDIUM); + if (count($sql) > 0) { + $possibleRows = $this->getBrowseCount($cat, $maxAge, $excludedCats, $groupName); + $sql[0]['_totalcount'] = $sql[0]['_totalrows'] = $possibleRows; + } - /** - * Return site setting for hiding/showing passworded releases. - * - * @return string - * @throws \Exception - */ - public static function showPasswords(): ?string - { - $setting = Settings::value('..showpasswordedrelease', true); - $setting = (isset($setting) && is_numeric($setting)) ? $setting : 10; + return $sql; + } - switch ($setting) { + /** + * Return site setting for hiding/showing passworded releases. + * + * @return string + * @throws \Exception + */ + public static function showPasswords(): ?string + { + $setting = Settings::value('..showpasswordedrelease', true); + $setting = (isset($setting) && is_numeric($setting)) ? $setting : 10; + + switch ($setting) { case 0: // Hide releases with a password or a potential password (Hide unprocessed releases). - return ('= ' . self::PASSWD_NONE); + return '= '.self::PASSWD_NONE; case 1: // Show releases with no password or a potential password (Show unprocessed releases). - return ('<= ' . self::PASSWD_POTENTIAL); + return '<= '.self::PASSWD_POTENTIAL; case 2: // Hide releases with a password or a potential password (Show unprocessed releases). - return ('<= ' . self::PASSWD_NONE); + return '<= '.self::PASSWD_NONE; case 10: // Shows everything. default: - return ('<= ' . self::PASSWD_RAR); + return '<= '.self::PASSWD_RAR; } - } + } - /** - * Use to order releases on site. - * - * @param string|array $orderBy - * - * @return array - */ - public function getBrowseOrder($orderBy): array - { - $orderArr = explode('_', ($orderBy === '' ? 'posted_desc' : $orderBy)); - switch ($orderArr[0]) { + /** + * Use to order releases on site. + * + * @param string|array $orderBy + * + * @return array + */ + public function getBrowseOrder($orderBy): array + { + $orderArr = explode('_', ($orderBy === '' ? 'posted_desc' : $orderBy)); + switch ($orderArr[0]) { case 'cat': $orderField = 'categories_id'; break; @@ -322,17 +324,18 @@ class Releases $orderField = 'postdate'; break; } - return [$orderField, isset($orderArr[1]) && preg_match('/^(asc|desc)$/i', $orderArr[1]) ? $orderArr[1] : 'desc']; - } - /** - * Return ordering types usable on site. - * - * @return string[] - */ - public function getBrowseOrdering(): array - { - return [ + return [$orderField, isset($orderArr[1]) && preg_match('/^(asc|desc)$/i', $orderArr[1]) ? $orderArr[1] : 'desc']; + } + + /** + * Return ordering types usable on site. + * + * @return string[] + */ + public function getBrowseOrdering(): array + { + return [ 'name_asc', 'name_desc', 'cat_asc', @@ -344,22 +347,22 @@ class Releases 'files_asc', 'files_desc', 'stats_asc', - 'stats_desc' + 'stats_desc', ]; - } + } - /** - * Get list of releases available for export. - * - * @param string $postFrom (optional) Date in this format : 01/01/2014 - * @param string $postTo (optional) Date in this format : 01/01/2014 - * @param string|int $groupID (optional) Group ID. - * - * @return array - */ - public function getForExport($postFrom = '', $postTo = '', $groupID = ''): array - { - return $this->pdo->query( + /** + * Get list of releases available for export. + * + * @param string $postFrom (optional) Date in this format : 01/01/2014 + * @param string $postTo (optional) Date in this format : 01/01/2014 + * @param string|int $groupID (optional) Group ID. + * + * @return array + */ + public function getForExport($postFrom = '', $postTo = '', $groupID = ''): array + { + return $this->pdo->query( sprintf( "SELECT searchname, guid, groups.name AS gname, CONCAT(cp.title,'_',categories.title) AS catName FROM releases r @@ -374,102 +377,104 @@ class Releases $groupID !== '' && $groupID !== -1 ? sprintf(' AND r.groups_id = %d ', $groupID) : '' ) ); - } + } - /** - * Create a date query string for exporting. - * - * @param string $date - * @param bool $from - * - * @return string - */ - private function exportDateString($date = '', $from = true): string - { - if ($date !== '') { - $dateParts = explode('/', $date); - if (count($dateParts) === 3) { - $date = sprintf( + /** + * Create a date query string for exporting. + * + * @param string $date + * @param bool $from + * + * @return string + */ + private function exportDateString($date = '', $from = true): string + { + if ($date !== '') { + $dateParts = explode('/', $date); + if (count($dateParts) === 3) { + $date = sprintf( ' AND postdate %s %s ', ($from ? '>' : '<'), $this->pdo->escapeString( - $dateParts[2] . '-' . $dateParts[1] . '-' . $dateParts[0] . + $dateParts[2].'-'.$dateParts[1].'-'.$dateParts[0]. ($from ? ' 00:00:00' : ' 23:59:59') ) ); - } - } - return $date; - } + } + } - /** - * Get date in this format : 01/01/2014 of the oldest release. - * - * @note Used for exporting NZB's. - * @return mixed - */ - public function getEarliestUsenetPostDate() - { - $row = $this->pdo->queryOneRow("SELECT DATE_FORMAT(min(postdate), '%d/%m/%Y') AS postdate FROM releases LIMIT 1"); + return $date; + } - return ($row === false ? '01/01/2014' : $row['postdate']); - } + /** + * Get date in this format : 01/01/2014 of the oldest release. + * + * @note Used for exporting NZB's. + * @return mixed + */ + public function getEarliestUsenetPostDate() + { + $row = $this->pdo->queryOneRow("SELECT DATE_FORMAT(min(postdate), '%d/%m/%Y') AS postdate FROM releases LIMIT 1"); - /** - * Get date in this format : 01/01/2014 of the newest release. - * - * @note Used for exporting NZB's. - * @return mixed - */ - public function getLatestUsenetPostDate() - { - $row = $this->pdo->queryOneRow("SELECT DATE_FORMAT(max(postdate), '%d/%m/%Y') AS postdate FROM releases LIMIT 1"); + return $row === false ? '01/01/2014' : $row['postdate']; + } - return ($row === false ? '01/01/2014' : $row['postdate']); - } + /** + * Get date in this format : 01/01/2014 of the newest release. + * + * @note Used for exporting NZB's. + * @return mixed + */ + public function getLatestUsenetPostDate() + { + $row = $this->pdo->queryOneRow("SELECT DATE_FORMAT(max(postdate), '%d/%m/%Y') AS postdate FROM releases LIMIT 1"); - /** - * Gets all groups for drop down selection on NZB-Export web page. - * - * @param bool $blnIncludeAll - * - * @note Used for exporting NZB's. - * @return array - */ - public function getReleasedGroupsForSelect($blnIncludeAll = true): array - { - $groups = $this->pdo->query( + return $row === false ? '01/01/2014' : $row['postdate']; + } + + /** + * Gets all groups for drop down selection on NZB-Export web page. + * + * @param bool $blnIncludeAll + * + * @note Used for exporting NZB's. + * @return array + */ + public function getReleasedGroupsForSelect($blnIncludeAll = true): array + { + $groups = $this->pdo->query( 'SELECT DISTINCT g.id, g.name FROM releases r LEFT JOIN groups g ON g.id = r.groups_id' ); - $temp_array = []; + $temp_array = []; - if ($blnIncludeAll) { - $temp_array[-1] = '--All Groups--'; - } + if ($blnIncludeAll) { + $temp_array[-1] = '--All Groups--'; + } - foreach ($groups as $group) { - $temp_array[$group['id']] = $group['name']; - } - return $temp_array; - } + foreach ($groups as $group) { + $temp_array[$group['id']] = $group['name']; + } - /** - * Cache of concatenated category ID's used in queries. - * @var null|array - */ - private $concatenatedCategoryIDsCache = null; + return $temp_array; + } - /** - * Gets / sets a string of concatenated category ID's used in queries. - * - * @return array|null|string - */ - public function getConcatenatedCategoryIDs() - { - if ($this->concatenatedCategoryIDsCache === null) { - $result = $this->pdo->query( + /** + * Cache of concatenated category ID's used in queries. + * @var null|array + */ + private $concatenatedCategoryIDsCache = null; + + /** + * Gets / sets a string of concatenated category ID's used in queries. + * + * @return array|null|string + */ + public function getConcatenatedCategoryIDs() + { + if ($this->concatenatedCategoryIDsCache === null) { + $result = $this->pdo->query( "SELECT CONCAT(cp.id, ',', c.id) AS category_ids FROM categories c LEFT JOIN categories cp ON cp.id = c.parentid @@ -477,29 +482,31 @@ class Releases AND cp.id IS NOT NULL", true, NN_CACHE_EXPIRY_LONG ); - if (isset($result[0]['category_ids'])) { - $this->concatenatedCategoryIDsCache = $result[0]['category_ids']; - } - } - return $this->concatenatedCategoryIDsCache; - } + if (isset($result[0]['category_ids'])) { + $this->concatenatedCategoryIDsCache = $result[0]['category_ids']; + } + } - /** - * Get TV for my shows page. - * - * @param $userShows - * @param int|bool $offset - * @param int $limit - * @param string|array $orderBy - * @param int $maxAge - * @param array $excludedCats - * - * @return array - */ - public function getShowsRange($userShows, $offset, $limit, $orderBy, $maxAge = -1, array $excludedCats = []): array - { - $orderBy = $this->getBrowseOrder($orderBy); - return $this->pdo->query( + return $this->concatenatedCategoryIDsCache; + } + + /** + * Get TV for my shows page. + * + * @param $userShows + * @param int|bool $offset + * @param int $limit + * @param string|array $orderBy + * @param int $maxAge + * @param array $excludedCats + * + * @return array + */ + public function getShowsRange($userShows, $offset, $limit, $orderBy, $maxAge = -1, array $excludedCats = []): array + { + $orderBy = $this->getBrowseOrder($orderBy); + + return $this->pdo->query( sprintf( "SELECT r.*, CONCAT(cp.title, '-', c.title) AS category_name, @@ -524,29 +531,29 @@ class Releases ORDER BY %s %s %s", $this->getConcatenatedCategoryIDs(), $this->uSQL($userShows, 'videos_id'), - (count($excludedCats) ? ' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')' : ''), + (count($excludedCats) ? ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')' : ''), NZB::NZB_ADDED, $this->showPasswords, ($maxAge > 0 ? sprintf(' AND r.postdate > NOW() - INTERVAL %d DAY ', $maxAge) : ''), $orderBy[0], $orderBy[1], - ($offset === false ? '' : (' LIMIT ' . $limit . ' OFFSET ' . $offset)) + ($offset === false ? '' : (' LIMIT '.$limit.' OFFSET '.$offset)) ), true, NN_CACHE_EXPIRY_MEDIUM ); - } + } - /** - * Get count for my shows page pagination. - * - * @param $userShows - * @param int $maxAge - * @param array $excludedCats - * - * @return int - */ - public function getShowsCount($userShows, $maxAge = -1, array $excludedCats = []): int - { - return $this->getPagerCount( + /** + * Get count for my shows page pagination. + * + * @param $userShows + * @param int $maxAge + * @param array $excludedCats + * + * @return int + */ + public function getShowsCount($userShows, $maxAge = -1, array $excludedCats = []): int + { + return $this->getPagerCount( sprintf( 'SELECT r.id FROM releases PARTITION (tv) r @@ -555,26 +562,26 @@ class Releases AND r.passwordstatus %s %s', $this->uSQL($userShows, 'videos_id'), - (count($excludedCats) ? ' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')' : ''), + (count($excludedCats) ? ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')' : ''), NZB::NZB_ADDED, $this->showPasswords, ($maxAge > 0 ? sprintf(' AND r.postdate > NOW() - INTERVAL %d DAY ', $maxAge) : '') ) ); - } + } - /** - * Get count for my shows page pagination. - * - * @param $userMovies - * @param int $maxAge - * @param array $excludedCats - * - * @return int - */ - public function getMovieCount($userMovies, $maxAge = -1, array $excludedCats = []): int - { - return $this->getPagerCount( + /** + * Get count for my shows page pagination. + * + * @param $userMovies + * @param int $maxAge + * @param array $excludedCats + * + * @return int + */ + public function getMovieCount($userMovies, $maxAge = -1, array $excludedCats = []): int + { + return $this->getPagerCount( sprintf( 'SELECT r.id FROM releases PARTITION (movies) r @@ -583,118 +590,118 @@ class Releases AND r.passwordstatus %s %s', $this->uSQL($userMovies, 'imdbid'), - (count($excludedCats) ? ' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')' : ''), + (count($excludedCats) ? ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')' : ''), NZB::NZB_ADDED, $this->showPasswords, ($maxAge > 0 ? sprintf(' AND r.postdate > NOW() - INTERVAL %d DAY ', $maxAge) : '') ) ); - } + } - /** - * Get count for admin release list page. - * - * @return int - */ - public function getCount(): int - { - $res = $this->pdo->query( + /** + * Get count for admin release list page. + * + * @return int + */ + public function getCount(): int + { + $res = $this->pdo->query( 'SELECT COUNT(id) AS num FROM releases', true, NN_CACHE_EXPIRY_MEDIUM ); - return (empty($res) ? 0 : $res[0]['num']); - } - /** - * Delete multiple releases, or a single by ID. - * - * @param array|int|string $list Array of GUID or ID of releases to delete. - * @param bool $isGUID Are the identifiers GUID or ID? - * - * @throws \Exception - */ - public function deleteMultiple($list, $isGUID = false): void - { - if (!is_array($list)) { - $list = [$list]; - } + return empty($res) ? 0 : $res[0]['num']; + } - $nzb = new NZB($this->pdo); - $releaseImage = new ReleaseImage($this->pdo); + /** + * Delete multiple releases, or a single by ID. + * + * @param array|int|string $list Array of GUID or ID of releases to delete. + * @param bool $isGUID Are the identifiers GUID or ID? + * + * @throws \Exception + */ + public function deleteMultiple($list, $isGUID = false): void + { + if (! is_array($list)) { + $list = [$list]; + } - foreach ($list as $identifier) { - if ($isGUID) { - $this->deleteSingle(['g' => $identifier, 'i' => false], $nzb, $releaseImage); - } else { - $release = $this->pdo->queryOneRow(sprintf('SELECT guid FROM releases WHERE id = %d', $identifier)); - if ($release === false) { - continue; - } - $this->deleteSingle(['g' => $release['guid'], 'i' => false], $nzb, $releaseImage); - } - } - } + $nzb = new NZB($this->pdo); + $releaseImage = new ReleaseImage($this->pdo); - /** - * Deletes a single release by GUID, and all the corresponding files. - * - * @param array $identifiers ['g' => Release GUID(mandatory), 'id => ReleaseID(optional, pass false)] - * @param NZB $nzb - * @param ReleaseImage $releaseImage - */ - public function deleteSingle($identifiers, $nzb, $releaseImage): void - { - // Delete NZB from disk. - $nzbPath = $nzb->NZBPath($identifiers['g']); - if ($nzbPath) { - @unlink($nzbPath); - } + foreach ($list as $identifier) { + if ($isGUID) { + $this->deleteSingle(['g' => $identifier, 'i' => false], $nzb, $releaseImage); + } else { + $release = $this->pdo->queryOneRow(sprintf('SELECT guid FROM releases WHERE id = %d', $identifier)); + if ($release === false) { + continue; + } + $this->deleteSingle(['g' => $release['guid'], 'i' => false], $nzb, $releaseImage); + } + } + } - // Delete images. - $releaseImage->delete($identifiers['g']); + /** + * Deletes a single release by GUID, and all the corresponding files. + * + * @param array $identifiers ['g' => Release GUID(mandatory), 'id => ReleaseID(optional, pass false)] + * @param NZB $nzb + * @param ReleaseImage $releaseImage + */ + public function deleteSingle($identifiers, $nzb, $releaseImage): void + { + // Delete NZB from disk. + $nzbPath = $nzb->NZBPath($identifiers['g']); + if ($nzbPath) { + @unlink($nzbPath); + } - // Delete from sphinx. - $this->sphinxSearch->deleteRelease($identifiers, $this->pdo); + // Delete images. + $releaseImage->delete($identifiers['g']); - if (isset($identifiers['i']) && $identifiers['i'] > 0) { - $param1 = true; - $param2 = $identifiers['i']; - } else { - $param1 = false; - $param2 = $identifiers['g']; - } + // Delete from sphinx. + $this->sphinxSearch->deleteRelease($identifiers, $this->pdo); - // Delete from DB. - $query = $this->pdo->Prepare('CALL delete_release(:is_numeric, :identifier)'); - $query->bindParam(':is_numeric', $param1, \PDO::PARAM_BOOL); - $query->bindParam(':identifier', $param2); + if (isset($identifiers['i']) && $identifiers['i'] > 0) { + $param1 = true; + $param2 = $identifiers['i']; + } else { + $param1 = false; + $param2 = $identifiers['g']; + } - $query->execute(); - } + // Delete from DB. + $query = $this->pdo->Prepare('CALL delete_release(:is_numeric, :identifier)'); + $query->bindParam(':is_numeric', $param1, \PDO::PARAM_BOOL); + $query->bindParam(':identifier', $param2); - /** - * Used for release edit page on site. - * - * @param int $ID - * @param string $name - * @param string $searchName - * @param string $fromName - * @param int $categoryID - * @param int $parts - * @param int $grabs - * @param int $size - * @param string $postedDate - * @param string $addedDate - * @param $videoId - * @param $episodeId - * @param int $imDbID - * @param int $aniDbID - * - */ - public function update($ID, $name, $searchName, $fromName, $categoryID, $parts, $grabs, $size, + $query->execute(); + } + + /** + * Used for release edit page on site. + * + * @param int $ID + * @param string $name + * @param string $searchName + * @param string $fromName + * @param int $categoryID + * @param int $parts + * @param int $grabs + * @param int $size + * @param string $postedDate + * @param string $addedDate + * @param $videoId + * @param $episodeId + * @param int $imDbID + * @param int $aniDbID + */ + public function update($ID, $name, $searchName, $fromName, $categoryID, $parts, $grabs, $size, $postedDate, $addedDate, $videoId, $episodeId, $imDbID, $aniDbID): void - { - $this->pdo->queryExec( + { + $this->pdo->queryExec( sprintf( 'UPDATE releases SET name = %s, searchname = %s, fromname = %s, categories_id = %d, @@ -717,116 +724,116 @@ class Releases $ID ) ); - $this->sphinxSearch->updateRelease($ID, $this->pdo); - } + $this->sphinxSearch->updateRelease($ID, $this->pdo); + } - /** - * @param $guids - * @param $category - * @param $grabs - * @param $videoId - * @param $episodeId - * @param $anidbId - * @param $imdbId - * - * @return array|bool|int - */ - public function updateMulti($guids, $category, $grabs, $videoId, $episodeId, $anidbId, $imdbId) - { - if (!is_array($guids) || count($guids) < 1) { - return false; - } + /** + * @param $guids + * @param $category + * @param $grabs + * @param $videoId + * @param $episodeId + * @param $anidbId + * @param $imdbId + * + * @return array|bool|int + */ + public function updateMulti($guids, $category, $grabs, $videoId, $episodeId, $anidbId, $imdbId) + { + if (! is_array($guids) || count($guids) < 1) { + return false; + } - $update = [ + $update = [ 'categories_id' => $category === -1 ? 'categories_id' : $category, 'grabs' => $grabs, 'videos_id' => $videoId, 'tv_episodes_id' => $episodeId, 'anidbid' => $anidbId, - 'imdbid' => $imdbId + 'imdbid' => $imdbId, ]; - $updateSql = []; - foreach ($update as $key => $value) { - if ($value !== '') { - $updateSql[] = sprintf($key . '=%s', $this->pdo->escapeString($value)); - } - } + $updateSql = []; + foreach ($update as $key => $value) { + if ($value !== '') { + $updateSql[] = sprintf($key.'=%s', $this->pdo->escapeString($value)); + } + } - if (count($updateSql) < 1) { - return -1; - } + if (count($updateSql) < 1) { + return -1; + } - $updateGuids = []; - foreach ($guids as $guid) { - $updateGuids[] = $this->pdo->escapeString($guid); - } + $updateGuids = []; + foreach ($guids as $guid) { + $updateGuids[] = $this->pdo->escapeString($guid); + } - return $this->pdo->queryExec( + return $this->pdo->queryExec( sprintf( 'UPDATE releases SET %s WHERE guid IN (%s)', implode(', ', $updateSql), implode(', ', $updateGuids) ) ); - } + } - /** - * Creates part of a query for some functions. - * - * @param array $userQuery - * @param string $type - * - * @return string - */ - public function uSQL($userQuery, $type): string - { - $sql = '(1=2 '; - foreach ($userQuery as $query) { - $sql .= sprintf('OR (r.%s = %d', $type, $query[$type]); - if ($query['categories'] !== '') { - $catsArr = explode('|', $query['categories']); - if (count($catsArr) > 1) { - $sql .= sprintf(' AND r.categories_id IN (%s)', implode(',', $catsArr)); - } else { - $sql .= sprintf(' AND r.categories_id = %d', $catsArr[0]); - } - } - $sql .= ') '; - } - $sql .= ') '; + /** + * Creates part of a query for some functions. + * + * @param array $userQuery + * @param string $type + * + * @return string + */ + public function uSQL($userQuery, $type): string + { + $sql = '(1=2 '; + foreach ($userQuery as $query) { + $sql .= sprintf('OR (r.%s = %d', $type, $query[$type]); + if ($query['categories'] !== '') { + $catsArr = explode('|', $query['categories']); + if (count($catsArr) > 1) { + $sql .= sprintf(' AND r.categories_id IN (%s)', implode(',', $catsArr)); + } else { + $sql .= sprintf(' AND r.categories_id = %d', $catsArr[0]); + } + } + $sql .= ') '; + } + $sql .= ') '; - return $sql; - } + return $sql; + } - /** - * Function for searching on the site (by subject, searchname or advanced). - * - * @param string $searchName - * @param string $usenetName - * @param string $posterName - * @param string $fileName - * @param string|int $groupName - * @param int $sizeFrom - * @param int $sizeTo - * @param int $hasNfo - * @param int $hasComments - * @param int $daysNew - * @param int $daysOld - * @param int $offset - * @param int $limit - * @param string|array $orderBy - * @param int $maxAge - * @param integer|array $excludedCats - * @param string $type - * @param array $cat - * - * @param int $minSize - * @return array - */ - public function search($searchName, $usenetName, $posterName, $fileName, $groupName, $sizeFrom, $sizeTo, $hasNfo, $hasComments, $daysNew, $daysOld, $offset = 0, $limit = 1000, $orderBy = '', $maxAge = -1, array $excludedCats = [], $type = 'basic', array $cat = [-1], $minSize = 0): array - { - $sizeRange = [ + /** + * Function for searching on the site (by subject, searchname or advanced). + * + * @param string $searchName + * @param string $usenetName + * @param string $posterName + * @param string $fileName + * @param string|int $groupName + * @param int $sizeFrom + * @param int $sizeTo + * @param int $hasNfo + * @param int $hasComments + * @param int $daysNew + * @param int $daysOld + * @param int $offset + * @param int $limit + * @param string|array $orderBy + * @param int $maxAge + * @param int|array $excludedCats + * @param string $type + * @param array $cat + * + * @param int $minSize + * @return array + */ + public function search($searchName, $usenetName, $posterName, $fileName, $groupName, $sizeFrom, $sizeTo, $hasNfo, $hasComments, $daysNew, $daysOld, $offset = 0, $limit = 1000, $orderBy = '', $maxAge = -1, array $excludedCats = [], $type = 'basic', array $cat = [-1], $minSize = 0): array + { + $sizeRange = [ 1 => 1, 2 => 2.5, 3 => 5, @@ -840,55 +847,55 @@ class Releases 11 => 640, ]; - if ($orderBy === '') { - $orderBy = []; - $orderBy[0] = 'postdate '; - $orderBy[1] = 'desc '; - } else { - $orderBy = $this->getBrowseOrder($orderBy); - } + if ($orderBy === '') { + $orderBy = []; + $orderBy[0] = 'postdate '; + $orderBy[1] = 'desc '; + } else { + $orderBy = $this->getBrowseOrder($orderBy); + } - $searchOptions = []; - if ($searchName !== -1) { - $searchOptions['searchname'] = $searchName; - } - if ($usenetName !== -1) { - $searchOptions['name'] = $usenetName; - } - if ($posterName !== -1) { - $searchOptions['fromname'] = $posterName; - } - if ($fileName !== -1) { - $searchOptions['filename'] = $fileName; - } + $searchOptions = []; + if ($searchName !== -1) { + $searchOptions['searchname'] = $searchName; + } + if ($usenetName !== -1) { + $searchOptions['name'] = $usenetName; + } + if ($posterName !== -1) { + $searchOptions['fromname'] = $posterName; + } + if ($fileName !== -1) { + $searchOptions['filename'] = $fileName; + } - $catQuery = ''; - if ($type === 'basic' ){ - $catQuery = $this->category->getCategorySearch($cat); - } else if ($type === 'advanced' && (int)$cat[0] !== -1) { - $catQuery = sprintf('AND r.categories_id = %d', $cat[0]); - } + $catQuery = ''; + if ($type === 'basic') { + $catQuery = $this->category->getCategorySearch($cat); + } elseif ($type === 'advanced' && (int) $cat[0] !== -1) { + $catQuery = sprintf('AND r.categories_id = %d', $cat[0]); + } - $whereSql = sprintf( + $whereSql = sprintf( '%s WHERE r.passwordstatus %s AND r.nzbstatus = %d %s %s %s %s %s %s %s %s %s %s %s %s', $this->releaseSearch->getFullTextJoinString(), $this->showPasswords, NZB::NZB_ADDED, ($maxAge > 0 ? sprintf(' AND r.postdate > (NOW() - INTERVAL %d DAY) ', $maxAge) : ''), - ((int)$groupName !== -1 ? sprintf(' AND r.groups_id = %d ', $this->groups->getIDByName($groupName)) : ''), - (array_key_exists($sizeFrom, $sizeRange) ? ' AND r.size > ' . (string)(104857600 * (int)$sizeRange[$sizeFrom]) . ' ' : ''), - (array_key_exists($sizeTo, $sizeRange) ? ' AND r.size < ' . (string)(104857600 * (int)$sizeRange[$sizeTo]) . ' ' : ''), - ((int)$hasNfo !== 0 ? ' AND r.nfostatus = 1 ' : ''), - ((int)$hasComments !== 0 ? ' AND r.comments > 0 ' : ''), + ((int) $groupName !== -1 ? sprintf(' AND r.groups_id = %d ', $this->groups->getIDByName($groupName)) : ''), + (array_key_exists($sizeFrom, $sizeRange) ? ' AND r.size > '.(string) (104857600 * (int) $sizeRange[$sizeFrom]).' ' : ''), + (array_key_exists($sizeTo, $sizeRange) ? ' AND r.size < '.(string) (104857600 * (int) $sizeRange[$sizeTo]).' ' : ''), + ((int) $hasNfo !== 0 ? ' AND r.nfostatus = 1 ' : ''), + ((int) $hasComments !== 0 ? ' AND r.comments > 0 ' : ''), $catQuery, - ((int)$daysNew !== -1 ? sprintf(' AND r.postdate < (NOW() - INTERVAL %d DAY) ', $daysNew) : ''), - ((int)$daysOld !== -1 ? sprintf(' AND r.postdate > (NOW() - INTERVAL %d DAY) ', $daysOld) : ''), - (count($excludedCats) > 0 ? ' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')' : ''), + ((int) $daysNew !== -1 ? sprintf(' AND r.postdate < (NOW() - INTERVAL %d DAY) ', $daysNew) : ''), + ((int) $daysOld !== -1 ? sprintf(' AND r.postdate > (NOW() - INTERVAL %d DAY) ', $daysOld) : ''), + (count($excludedCats) > 0 ? ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')' : ''), (count($searchOptions) > 0 ? $this->releaseSearch->getSearchSQL($searchOptions) : ''), ($minSize > 0 ? sprintf('AND r.size >= %d', $minSize) : '') ); - $baseSql = sprintf( + $baseSql = sprintf( "SELECT r.*, CONCAT(cp.title, ' > ', c.title) AS category_name, %s AS category_ids, @@ -913,7 +920,7 @@ class Releases $whereSql ); - $sql = sprintf( + $sql = sprintf( 'SELECT * FROM ( %s ) r @@ -926,48 +933,48 @@ class Releases $offset ); - $releases = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - if (!empty($releases) && count($releases)) { - $releases[0]['_totalrows'] = $this->getPagerCount($baseSql); - } - return $releases; - } + $releases = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); + if (! empty($releases) && count($releases)) { + $releases[0]['_totalrows'] = $this->getPagerCount($baseSql); + } - /** - * Search TV Shows via the API - * - * @param array $siteIdArr Array containing all possible TV Processing site IDs desired - * @param string $series The series or season number requested - * @param string $episode The episode number requested - * @param string $airdate The airdate of the episode requested - * @param int $offset Skip this many releases - * @param int $limit Return this many releases - * @param string $name The show name to search - * @param array $cat The category to search - * @param int $maxAge The maximum age of releases to be returned - * @param int $minSize The minimum size of releases to be returned - * - * @return array - */ - public function searchShows( + return $releases; + } + + /** + * Search TV Shows via the API. + * + * @param array $siteIdArr Array containing all possible TV Processing site IDs desired + * @param string $series The series or season number requested + * @param string $episode The episode number requested + * @param string $airdate The airdate of the episode requested + * @param int $offset Skip this many releases + * @param int $limit Return this many releases + * @param string $name The show name to search + * @param array $cat The category to search + * @param int $maxAge The maximum age of releases to be returned + * @param int $minSize The minimum size of releases to be returned + * + * @return array + */ + public function searchShows( array $siteIdArr = [], $series = '', $episode = '', $airdate = '', $offset = 0, $limit = 100, $name = '', array $cat = [-1], $maxAge = -1, $minSize = 0 - ): array - { - $siteSQL = []; - $showSql = ''; + ): array { + $siteSQL = []; + $showSql = ''; - if (is_array($siteIdArr)) { - foreach ($siteIdArr as $column => $Id) { - if ($Id > 0) { - $siteSQL[] = sprintf('v.%s = %d', $column, $Id); - } - } - } + if (is_array($siteIdArr)) { + foreach ($siteIdArr as $column => $Id) { + if ($Id > 0) { + $siteSQL[] = sprintf('v.%s = %d', $column, $Id); + } + } + } - if (count($siteSQL) > 0) { - // If we have show info, find the Episode ID/Video ID first to avoid table scans - $showQry = sprintf(" + if (count($siteSQL) > 0) { + // If we have show info, find the Episode ID/Video ID first to avoid table scans + $showQry = sprintf(" SELECT v.id AS video, GROUP_CONCAT(tve.id SEPARATOR ',') AS episodes @@ -976,43 +983,43 @@ class Releases WHERE (%s) %s %s %s GROUP BY v.id", implode(' OR ', $siteSQL), - ($series !== '' ? sprintf('AND tve.series = %d', (int)preg_replace('/^s0*/i', '', $series)) : ''), - ($episode !== '' ? sprintf('AND tve.episode = %d', (int)preg_replace('/^e0*/i', '', $episode)) : ''), + ($series !== '' ? sprintf('AND tve.series = %d', (int) preg_replace('/^s0*/i', '', $series)) : ''), + ($episode !== '' ? sprintf('AND tve.episode = %d', (int) preg_replace('/^e0*/i', '', $episode)) : ''), ($airdate !== '' ? sprintf('AND DATE(tve.firstaired) = %s', $this->pdo->escapeString($airdate)) : '') ); - $show = $this->pdo->queryOneRow($showQry); - if ($show !== false) { - if ((!empty($series) || !empty($episode) || !empty($airdate)) && strlen((string)$show['episodes']) > 0) { - $showSql = sprintf('AND r.tv_episodes_id IN (%s)', $show['episodes']); - } else if ((int)$show['video'] > 0) { - $showSql = 'AND r.videos_id = ' . $show['video']; - // If $series is set but episode is not, return Season Packs only - if (!empty($series) && empty($episode)) { - $showSql .= ' AND r.tv_episodes_id = 0'; - } - } else { - // If we were passed Episode Info and no match was found, do not run the query - return []; - } - } else { - // If we were passed Site ID Info and no match was found, do not run the query - return []; - } - } + $show = $this->pdo->queryOneRow($showQry); + if ($show !== false) { + if ((! empty($series) || ! empty($episode) || ! empty($airdate)) && strlen((string) $show['episodes']) > 0) { + $showSql = sprintf('AND r.tv_episodes_id IN (%s)', $show['episodes']); + } elseif ((int) $show['video'] > 0) { + $showSql = 'AND r.videos_id = '.$show['video']; + // If $series is set but episode is not, return Season Packs only + if (! empty($series) && empty($episode)) { + $showSql .= ' AND r.tv_episodes_id = 0'; + } + } else { + // If we were passed Episode Info and no match was found, do not run the query + return []; + } + } else { + // If we were passed Site ID Info and no match was found, do not run the query + return []; + } + } - // If $name is set it is a fallback search, add available SxxExx/airdate info to the query - if (!empty($name) && $showSql === '') { - if (!empty($series) && (int)$series < 1900) { - $name .= sprintf(' S%s', str_pad($series, 2, '0', STR_PAD_LEFT)); - if (!empty($episode) && strpos($episode, '/') === false) { - $name .= sprintf('E%s', str_pad($episode, 2, '0', STR_PAD_LEFT)); - } - } else if (!empty($airdate)) { - $name .= sprintf(' %s', str_replace(['/', '-', '.', '_'], ' ', $airdate)); - } - } + // If $name is set it is a fallback search, add available SxxExx/airdate info to the query + if (! empty($name) && $showSql === '') { + if (! empty($series) && (int) $series < 1900) { + $name .= sprintf(' S%s', str_pad($series, 2, '0', STR_PAD_LEFT)); + if (! empty($episode) && strpos($episode, '/') === false) { + $name .= sprintf('E%s', str_pad($episode, 2, '0', STR_PAD_LEFT)); + } + } elseif (! empty($airdate)) { + $name .= sprintf(' %s', str_replace(['/', '-', '.', '_'], ' ', $airdate)); + } + } - $whereSql = sprintf( + $whereSql = sprintf( '%s WHERE r.nzbstatus = %d AND r.passwordstatus %s @@ -1027,7 +1034,7 @@ class Releases ($minSize > 0 ? sprintf('AND r.size >= %d', $minSize) : '') ); - $baseSql = sprintf( + $baseSql = sprintf( "SELECT r.*, v.title, v.countries_id, v.started, v.tvdb, v.trakt, v.imdb, v.tmdb, v.tvmaze, v.tvrage, v.source, @@ -1052,7 +1059,7 @@ class Releases $whereSql ); - $sql = sprintf( + $sql = sprintf( '%s ORDER BY postdate DESC LIMIT %d OFFSET %d', @@ -1061,28 +1068,29 @@ class Releases $offset ); - $releases = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - if (!empty($releases) && count($releases)) { - $releases[0]['_totalrows'] = $this->getPagerCount( + $releases = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); + if (! empty($releases) && count($releases)) { + $releases[0]['_totalrows'] = $this->getPagerCount( preg_replace('#LEFT(\s+OUTER)?\s+JOIN\s+(?!tv_episodes)\s+.*ON.*=.*\n#i', ' ', $baseSql) ); - } - return $releases; - } + } - /** - * @param $aniDbID - * @param int $offset - * @param int $limit - * @param string $name - * @param array $cat - * @param int $maxAge - * - * @return array - */ - public function searchbyAnidbId($aniDbID, $offset = 0, $limit = 100, $name = '', array $cat = [-1], $maxAge = -1): array - { - $whereSql = sprintf( + return $releases; + } + + /** + * @param $aniDbID + * @param int $offset + * @param int $limit + * @param string $name + * @param array $cat + * @param int $maxAge + * + * @return array + */ + public function searchbyAnidbId($aniDbID, $offset = 0, $limit = 100, $name = '', array $cat = [-1], $maxAge = -1): array + { + $whereSql = sprintf( '%s WHERE r.passwordstatus %s AND r.nzbstatus = %d @@ -1096,7 +1104,7 @@ class Releases ($maxAge > 0 ? sprintf(' AND r.postdate > NOW() - INTERVAL %d DAY ', $maxAge) : '') ); - $baseSql = sprintf( + $baseSql = sprintf( "SELECT r.*, CONCAT(cp.title, ' > ', c.title) AS category_name, %s AS category_ids, @@ -1114,7 +1122,7 @@ class Releases $whereSql ); - $sql = sprintf( + $sql = sprintf( '%s ORDER BY postdate DESC LIMIT %d OFFSET %d', @@ -1122,28 +1130,29 @@ class Releases $limit, $offset ); - $releases = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); + $releases = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - if (!empty($releases) && count($releases)) { - $releases[0]['_totalrows'] = $this->getPagerCount($baseSql); - } - return $releases; - } + if (! empty($releases) && count($releases)) { + $releases[0]['_totalrows'] = $this->getPagerCount($baseSql); + } - /** - * @param int $imDbId - * @param int $offset - * @param int $limit - * @param string $name - * @param array $cat - * @param int $maxAge - * @param int $minSize - * - * @return array - */ - public function searchbyImdbId($imDbId, $offset = 0, $limit = 100, $name = '', array $cat = [-1], $maxAge = -1, $minSize = 0): array - { - $whereSql = sprintf( + return $releases; + } + + /** + * @param int $imDbId + * @param int $offset + * @param int $limit + * @param string $name + * @param array $cat + * @param int $maxAge + * @param int $minSize + * + * @return array + */ + public function searchbyImdbId($imDbId, $offset = 0, $limit = 100, $name = '', array $cat = [-1], $maxAge = -1, $minSize = 0): array + { + $whereSql = sprintf( '%s WHERE r.nzbstatus = %d AND r.passwordstatus %s @@ -1158,7 +1167,7 @@ class Releases ($minSize > 0 ? sprintf('AND r.size >= %d', $minSize) : '') ); - $baseSql = sprintf( + $baseSql = sprintf( "SELECT r.*, concat(cp.title, ' > ', c.title) AS category_name, %s AS category_ids, @@ -1174,7 +1183,7 @@ class Releases $whereSql ); - $sql = sprintf( + $sql = sprintf( '%s ORDER BY postdate DESC LIMIT %d OFFSET %d', @@ -1182,91 +1191,94 @@ class Releases $limit, $offset ); - $releases = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); + $releases = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - if (!empty($releases) && count($releases)) { - $releases[0]['_totalrows'] = $this->getPagerCount($baseSql); - } - return $releases; - } + if (! empty($releases) && count($releases)) { + $releases[0]['_totalrows'] = $this->getPagerCount($baseSql); + } - /** - * Get count of releases for pager. - * - * @param string $query The query to get the count from. - * - * @return int - */ - private function getPagerCount($query): int - { - $count = $this->pdo->query( + return $releases; + } + + /** + * Get count of releases for pager. + * + * @param string $query The query to get the count from. + * + * @return int + */ + private function getPagerCount($query): int + { + $count = $this->pdo->query( sprintf( 'SELECT COUNT(z.id) AS count FROM (%s LIMIT %s) z', preg_replace('/SELECT.+?FROM\s+releases/is', 'SELECT r.id FROM releases', $query), NN_MAX_PAGER_RESULTS ), true, NN_CACHE_EXPIRY_SHORT ); - return $count[0]['count'] ?? 0; - } - /** - * @param $currentID - * @param $name - * @param int $limit - * @param array $excludedCats - * - * @return array - */ - public function searchSimilar($currentID, $name, $limit = 6, array $excludedCats = []): array - { - // Get the category for the parent of this release. - $currRow = $this->getById($currentID); - $catRow = (new Category(['Settings' => $this->pdo]))->getById($currRow['categories_id']); - $parentCat = $catRow['parentid']; + return $count[0]['count'] ?? 0; + } - $results = $this->search( + /** + * @param $currentID + * @param $name + * @param int $limit + * @param array $excludedCats + * + * @return array + */ + public function searchSimilar($currentID, $name, $limit = 6, array $excludedCats = []): array + { + // Get the category for the parent of this release. + $currRow = $this->getById($currentID); + $catRow = (new Category(['Settings' => $this->pdo]))->getById($currRow['categories_id']); + $parentCat = $catRow['parentid']; + + $results = $this->search( $this->getSimilarName($name), -1, -1, -1, -1, -1, -1, 0, 0, -1, -1, 0, $limit, '', -1, $excludedCats, null, [$parentCat] ); - if (!$results) { - return $results; - } + if (! $results) { + return $results; + } - $ret = []; - foreach ($results as $res) { - if ($res['id'] !== $currentID && $res['categoryparentid'] === $parentCat) { - $ret[] = $res; - } - } - return $ret; - } + $ret = []; + foreach ($results as $res) { + if ($res['id'] !== $currentID && $res['categoryparentid'] === $parentCat) { + $ret[] = $res; + } + } - /** - * @param string $name - * - * @return string - */ - public function getSimilarName($name): string - { - return implode(' ', array_slice(str_word_count(str_replace(['.', '_'], ' ', $name), 2), 0, 2)); - } + return $ret; + } - /** - * @param array|string $guid - * - * @return array|bool - */ - public function getByGuid($guid) - { - if (is_array($guid)) { - $tempGuids = []; - foreach ($guid as $identifier) { - $tempGuids[] = $this->pdo->escapeString($identifier); - } - $gSql = sprintf('r.guid IN (%s)', implode(',', $tempGuids)); - } else { - $gSql = sprintf('r.guid = %s', $this->pdo->escapeString($guid)); - } - $sql = sprintf( + /** + * @param string $name + * + * @return string + */ + public function getSimilarName($name): string + { + return implode(' ', array_slice(str_word_count(str_replace(['.', '_'], ' ', $name), 2), 0, 2)); + } + + /** + * @param array|string $guid + * + * @return array|bool + */ + public function getByGuid($guid) + { + if (is_array($guid)) { + $tempGuids = []; + foreach ($guid as $identifier) { + $tempGuids[] = $this->pdo->escapeString($identifier); + } + $gSql = sprintf('r.guid IN (%s)', implode(',', $tempGuids)); + } else { + $gSql = sprintf('r.guid = %s', $this->pdo->escapeString($guid)); + } + $sql = sprintf( "SELECT r.*, CONCAT(cp.title, ' > ', c.title) AS category_name, CONCAT(cp.id, ',', c.id) AS category_ids, @@ -1289,68 +1301,69 @@ class Releases $gSql ); - return is_array($guid) ? $this->pdo->query($sql) : $this->pdo->queryOneRow($sql); - } + return is_array($guid) ? $this->pdo->query($sql) : $this->pdo->queryOneRow($sql); + } - /** - * Writes a zip file of an array of release guids directly to the stream. - * - * @param $guids - * - * @return string - * @throws \Exception - */ - public function getZipped($guids): string - { - $nzb = new NZB($this->pdo); - $zipFile = new \ZipFile(); + /** + * Writes a zip file of an array of release guids directly to the stream. + * + * @param $guids + * + * @return string + * @throws \Exception + */ + public function getZipped($guids): string + { + $nzb = new NZB($this->pdo); + $zipFile = new \ZipFile(); - foreach ($guids as $guid) { - $nzbPath = $nzb->NZBPath($guid); + foreach ($guids as $guid) { + $nzbPath = $nzb->NZBPath($guid); - if ($nzbPath) { - $nzbContents = Utility::unzipGzipFile($nzbPath); + if ($nzbPath) { + $nzbContents = Utility::unzipGzipFile($nzbPath); - if ($nzbContents) { - $filename = $guid; - $r = $this->getByGuid($guid); - if ($r) { - $filename = $r['searchname']; - } - $zipFile->addFile($nzbContents, $filename . '.nzb'); - } - } - } - return $zipFile->file(); - } + if ($nzbContents) { + $filename = $guid; + $r = $this->getByGuid($guid); + if ($r) { + $filename = $r['searchname']; + } + $zipFile->addFile($nzbContents, $filename.'.nzb'); + } + } + } - /** - * @param $rageID - * @param string $series - * @param string $episode - * - * @return array|bool - */ - public function getbyRageId($rageID, $series = '', $episode = '') - { - if ($series !== '') { - // Exclude four digit series, which will be the year 2010 etc. - if (is_numeric($series) && strlen($series) !== 4) { - $series = sprintf('S%02d', $series); - } + return $zipFile->file(); + } - $series = sprintf(' AND UPPER(r.season) = UPPER(%s)', $this->pdo->escapeString($series)); - } + /** + * @param $rageID + * @param string $series + * @param string $episode + * + * @return array|bool + */ + public function getbyRageId($rageID, $series = '', $episode = '') + { + if ($series !== '') { + // Exclude four digit series, which will be the year 2010 etc. + if (is_numeric($series) && strlen($series) !== 4) { + $series = sprintf('S%02d', $series); + } - if ($episode !== '') { - if (is_numeric($episode)) { - $episode = sprintf('E%02d', $episode); - } + $series = sprintf(' AND UPPER(r.season) = UPPER(%s)', $this->pdo->escapeString($series)); + } - $episode = sprintf(' AND UPPER(r.episode) = UPPER(%s)', $this->pdo->escapeString($episode)); - } + if ($episode !== '') { + if (is_numeric($episode)) { + $episode = sprintf('E%02d', $episode); + } - return $this->pdo->queryOneRow( + $episode = sprintf(' AND UPPER(r.episode) = UPPER(%s)', $this->pdo->escapeString($episode)); + } + + return $this->pdo->queryOneRow( sprintf( "SELECT r.*, CONCAT(cp.title, ' > ', c.title) AS category_name, g.name AS group_name @@ -1366,16 +1379,16 @@ class Releases $episode ) ); - } + } - /** - * @param $videoId - * - * @return bool|\PDOStatement - */ - public function removeVideoIdFromReleases($videoId) - { - return $this->pdo->queryExec( + /** + * @param $videoId + * + * @return bool|\PDOStatement + */ + public function removeVideoIdFromReleases($videoId) + { + return $this->pdo->queryExec( sprintf(' UPDATE releases SET videos_id = 0, tv_episodes_id = 0 @@ -1383,16 +1396,16 @@ class Releases $videoId ) ); - } + } - /** - * @param $anidbID - * - * @return bool|\PDOStatement - */ - public function removeAnidbIdFromReleases($anidbID) - { - return $this->pdo->queryExec( + /** + * @param $anidbID + * + * @return bool|\PDOStatement + */ + public function removeAnidbIdFromReleases($anidbID) + { + return $this->pdo->queryExec( sprintf(' UPDATE releases SET anidbid = -1 @@ -1400,60 +1413,61 @@ class Releases $anidbID ) ); - } + } - /** - * @param int $id - * - * @return array|bool - */ - public function getById($id) - { - $qry = sprintf(' + /** + * @param int $id + * + * @return array|bool + */ + public function getById($id) + { + $qry = sprintf(' SELECT r.*, g.name AS group_name FROM releases r LEFT JOIN groups g ON g.id = r.groups_id WHERE r.id = %d', $id ); - return $this->pdo->queryOneRow($qry); - } - /** - * @param int $id - * @param bool $getNfoString - * - * @return array|bool - */ - public function getReleaseNfo($id, $getNfoString = true) - { - return $this->pdo->queryOneRow( + return $this->pdo->queryOneRow($qry); + } + + /** + * @param int $id + * @param bool $getNfoString + * + * @return array|bool + */ + public function getReleaseNfo($id, $getNfoString = true) + { + return $this->pdo->queryOneRow( sprintf( 'SELECT releases_id %s FROM release_nfos WHERE releases_id = %d AND nfo IS NOT NULL', $getNfoString ? ', UNCOMPRESS(nfo) AS nfo' : '', $id ) ); - } + } - /** - * @param string $guid - */ - public function updateGrab($guid): void - { - if ($this->updateGrabs) { - $this->pdo->queryExec( + /** + * @param string $guid + */ + public function updateGrab($guid): void + { + if ($this->updateGrabs) { + $this->pdo->queryExec( sprintf('UPDATE releases SET grabs = grabs + 1 WHERE guid = %s', $this->pdo->escapeString($guid)) ); - } - } + } + } - /** - * @return array - */ - public function getTopDownloads(): array - { - return $this->pdo->query( + /** + * @return array + */ + public function getTopDownloads(): array + { + return $this->pdo->query( 'SELECT id, searchname, guid, adddate, SUM(grabs) AS grabs FROM releases WHERE grabs > 0 @@ -1462,14 +1476,14 @@ class Releases ORDER BY grabs DESC LIMIT 10', true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * @return array - */ - public function getTopComments(): array - { - return $this->pdo->query( + /** + * @return array + */ + public function getTopComments(): array + { + return $this->pdo->query( 'SELECT id, guid, searchname, adddate, SUM(comments) AS comments FROM releases WHERE comments > 0 @@ -1478,14 +1492,14 @@ class Releases ORDER BY comments DESC LIMIT 10', true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * @return array - */ - public function getRecentlyAdded(): array - { - return $this->pdo->query( + /** + * @return array + */ + public function getRecentlyAdded(): array + { + return $this->pdo->query( "SELECT CONCAT(cp.title, ' > ', categories.title) AS title, COUNT(r.id) AS count FROM categories INNER JOIN categories cp ON cp.id = categories.parentid @@ -1494,16 +1508,16 @@ class Releases GROUP BY CONCAT(cp.title, ' > ', categories.title) ORDER BY count DESC", true, NN_CACHE_EXPIRY_MEDIUM ); - } + } - /** - * Get all newest movies with coves for poster wall. - * - * @return array - */ - public function getNewestMovies(): array - { - return $this->pdo->query( + /** + * Get all newest movies with coves for poster wall. + * + * @return array + */ + public function getNewestMovies(): array + { + return $this->pdo->query( 'SELECT r.imdbid, r.guid, r.name, r.searchname, r.size, r.completion, postdate, categories_id, comments, grabs, m.cover @@ -1515,16 +1529,16 @@ class Releases ORDER BY r.postdate DESC LIMIT 24', true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * Get all newest xxx with covers for poster wall. - * - * @return array - */ - public function getNewestXXX(): array - { - return $this->pdo->query( + /** + * Get all newest xxx with covers for poster wall. + * + * @return array + */ + public function getNewestXXX(): array + { + return $this->pdo->query( 'SELECT r.xxxinfo_id, r.guid, r.name, r.searchname, r.size, r.completion, r.postdate, r.categories_id, r.comments, r.grabs, xxx.cover, xxx.title @@ -1536,16 +1550,16 @@ class Releases ORDER BY r.postdate DESC LIMIT 20', true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * Get all newest console games with covers for poster wall. - * - * @return array - */ - public function getNewestConsole(): array - { - return $this->pdo->query( + /** + * Get all newest console games with covers for poster wall. + * + * @return array + */ + public function getNewestConsole(): array + { + return $this->pdo->query( 'SELECT r.consoleinfo_id, r.guid, r.name, r.searchname, r.size, r.completion, r.postdate, r.categories_id, r.comments, r.grabs, con.cover @@ -1557,16 +1571,16 @@ class Releases ORDER BY r.postdate DESC LIMIT 35' ); - } + } - /** - * Get all newest PC games with covers for poster wall. - * - * @return array - */ - public function getNewestGames(): array - { - return $this->pdo->query( + /** + * Get all newest PC games with covers for poster wall. + * + * @return array + */ + public function getNewestGames(): array + { + return $this->pdo->query( 'SELECT r.gamesinfo_id, r.guid, r.name, r.searchname, r.size, r.completion, r.postdate, r.categories_id, r.comments, r.grabs, gi.cover @@ -1579,16 +1593,16 @@ class Releases ORDER BY r.postdate DESC LIMIT 24', true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * Get all newest music with covers for poster wall. - * - * @return array - */ - public function getNewestMP3s(): array - { - return $this->pdo->query( + /** + * Get all newest music with covers for poster wall. + * + * @return array + */ + public function getNewestMP3s(): array + { + return $this->pdo->query( sprintf('SELECT r.musicinfo_id, r.guid, r.name, r.searchname, r.size, r.completion, r.postdate, r.categories_id, r.comments, r.grabs, m.cover @@ -1601,16 +1615,16 @@ class Releases ORDER BY r.postdate DESC LIMIT 24', Category::MUSIC_AUDIOBOOK), true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * Get all newest books with covers for poster wall. - * - * @return array - */ - public function getNewestBooks(): array - { - return $this->pdo->query( + /** + * Get all newest books with covers for poster wall. + * + * @return array + */ + public function getNewestBooks(): array + { + return $this->pdo->query( sprintf('SELECT r.bookinfo_id, r.guid, r.name, r.searchname, r.size, r.completion, r.postdate, r.categories_id, r.comments, r.grabs, b.url, b.cover, b.title as booktitle, b.author @@ -1623,16 +1637,16 @@ class Releases ORDER BY r.postdate DESC LIMIT 24', Category::MUSIC_AUDIOBOOK), true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * Get all newest TV with covers for poster wall. - * - * @return array - */ - public function getNewestTV(): array - { - return $this->pdo->query( + /** + * Get all newest TV with covers for poster wall. + * + * @return array + */ + public function getNewestTV(): array + { + return $this->pdo->query( 'SELECT r.videos_id, r.guid, r.name, r.searchname, r.size, r.completion, r.postdate, r.categories_id, r.comments, r.grabs, v.id AS tvid, v.title AS tvtitle, v.tvdb, v.trakt, v.tvrage, v.tvmaze, v.imdb, v.tmdb, @@ -1647,16 +1661,16 @@ class Releases ORDER BY r.postdate DESC LIMIT 24', true, NN_CACHE_EXPIRY_LONG ); - } + } - /** - * Get all newest anime with covers for poster wall. - * - * @return array - */ - public function getNewestAnime(): array - { - return $this->pdo->query( + /** + * Get all newest anime with covers for poster wall. + * + * @return array + */ + public function getNewestAnime(): array + { + return $this->pdo->query( "SELECT r.anidbid, r.guid, r.name, r.searchname, r.size, r.completion, r.postdate, r.categories_id, r.comments, r.grabs, at.title FROM releases r @@ -1671,5 +1685,5 @@ class Releases ORDER BY r.postdate DESC LIMIT 24", true, NN_CACHE_EXPIRY_LONG ); - } + } } diff --git a/nntmux/RequestID.php b/nntmux/RequestID.php index d38dd2934..1d3bcc56c 100755 --- a/nntmux/RequestID.php +++ b/nntmux/RequestID.php @@ -1,21 +1,22 @@ <?php + namespace nntmux; -use GuzzleHttp\Client; use nntmux\db\DB; +use GuzzleHttp\Client; /** - * Class RequestID + * Class RequestID. */ abstract class RequestID { - // Request id. - const REQID_OLD = -4; // We rechecked the web a second time and didn't find a title so don't process it again. - const REQID_NONE = -3; // The Request id was not found locally or via web lookup. - const REQID_ZERO = -2; // The Request id was 0. - const REQID_NOLL = -1; // Request id was not found via local lookup. - const REQID_UPROC = 0; // Release has not been processed. - const REQID_FOUND = 1; // Request id found and release was updated. + // Request id. + const REQID_OLD = -4; // We rechecked the web a second time and didn't find a title so don't process it again. + const REQID_NONE = -3; // The Request id was not found locally or via web lookup. + const REQID_ZERO = -2; // The Request id was 0. + const REQID_NOLL = -1; // Request id was not found via local lookup. + const REQID_UPROC = 0; // Release has not been processed. + const REQID_FOUND = 1; // Request id found and release was updated. const IS_REQID_TRUE = 1; // releases.isrequestid is 1 const IS_REQID_FALSE = 0; // releases.isrequestid is 0 @@ -23,19 +24,19 @@ abstract class RequestID /** * @var Groups */ - public $groups; + public $groups; - /** - * @var Client - */ - public $client; + /** + * @var Client + */ + public $client; - /** - * @param array $options Class instances / Echo to cli? - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances / Echo to cli? + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => true, 'Categorize' => null, 'ConsoleTools' => null, @@ -43,195 +44,202 @@ abstract class RequestID 'Settings' => null, 'SphinxSearch' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echoOutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->category = ($options['Categorize'] instanceof Categorize ? $options['Categorize'] : new Categorize(['Settings' => $this->pdo])); - $this->groups = ($options['Groups'] instanceof Groups ? $options['Groups'] : new Groups(['Settings' => $this->pdo])); - $this->consoleTools = ($options['ConsoleTools'] instanceof ConsoleTools ? $options['ConsoleTools'] : new ConsoleTools(['ColorCLI' => $this->pdo->log])); - $this->sphinx = ($options['SphinxSearch'] instanceof SphinxSearch ? $options['SphinxSearch'] : new SphinxSearch()); - $this->client = new Client(); - } + $this->echoOutput = ($options['Echo'] && NN_ECHOCLI); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->category = ($options['Categorize'] instanceof Categorize ? $options['Categorize'] : new Categorize(['Settings' => $this->pdo])); + $this->groups = ($options['Groups'] instanceof Groups ? $options['Groups'] : new Groups(['Settings' => $this->pdo])); + $this->consoleTools = ($options['ConsoleTools'] instanceof ConsoleTools ? $options['ConsoleTools'] : new ConsoleTools(['ColorCLI' => $this->pdo->log])); + $this->sphinx = ($options['SphinxSearch'] instanceof SphinxSearch ? $options['SphinxSearch'] : new SphinxSearch()); + $this->client = new Client(); + } - /** - * Look up request id's for releases. - * - * @param array $options - * - * @return int Quantity of releases matched to a request id. - */ - public function lookupRequestIDs(array $options = []) - { - $curOptions = [ + /** + * Look up request id's for releases. + * + * @param array $options + * + * @return int Quantity of releases matched to a request id. + */ + public function lookupRequestIDs(array $options = []) + { + $curOptions = [ 'charGUID' => '', 'GroupID' => '', 'limit' => '', 'show' => 1, 'time' => 0, ]; - $curOptions = array_replace($curOptions, $options); + $curOptions = array_replace($curOptions, $options); - $startTime = time(); - $renamed = 0; + $startTime = time(); + $renamed = 0; - $this->_charGUID = $curOptions['charGUID']; - $this->_groupID = $curOptions['GroupID']; - $this->_show = $curOptions['show']; - $this->_maxTime = $curOptions['time']; - $this->_limit = $curOptions['limit']; + $this->_charGUID = $curOptions['charGUID']; + $this->_groupID = $curOptions['GroupID']; + $this->_show = $curOptions['show']; + $this->_maxTime = $curOptions['time']; + $this->_limit = $curOptions['limit']; - $this->_getReleases(); + $this->_getReleases(); - if ($this->_releases !== false && $this->_releases->rowCount() > 0) { - $this->_totalReleases = $this->_releases->rowCount(); - ColorCLI::doEcho(ColorCLI::primary('Processing ' . $this->_totalReleases . " releases for RequestID's.")); - $renamed = $this->_processReleases(); - if ($this->echoOutput) { - echo ColorCLI::header( - "\nRenamed " . number_format($renamed) . " releases in " . $this->consoleTools->convertTime(time() - $startTime) . "." + if ($this->_releases !== false && $this->_releases->rowCount() > 0) { + $this->_totalReleases = $this->_releases->rowCount(); + ColorCLI::doEcho(ColorCLI::primary('Processing '.$this->_totalReleases." releases for RequestID's.")); + $renamed = $this->_processReleases(); + if ($this->echoOutput) { + echo ColorCLI::header( + "\nRenamed ".number_format($renamed).' releases in '.$this->consoleTools->convertTime(time() - $startTime).'.' ); - } - } elseif ($this->echoOutput) { - ColorCLI::doEcho(ColorCLI::primary("No RequestID's to process.")); - } + } + } elseif ($this->echoOutput) { + ColorCLI::doEcho(ColorCLI::primary("No RequestID's to process.")); + } - return $renamed; - } + return $renamed; + } - /** - * Fetch releases with requestid's from MySQL. - */ - protected function _getReleases() { } + /** + * Fetch releases with requestid's from MySQL. + */ + protected function _getReleases() + { + } - /** - * Process releases for requestid's. - * - * @return int How many did we rename? - */ - protected function _processReleases() { } + /** + * Process releases for requestid's. + * + * @return int How many did we rename? + */ + protected function _processReleases() + { + } - /** - * No request id was found, update the release. - * - * @param int $releaseID - * @param int $status - */ - protected function _requestIdNotFound($releaseID, $status) - { - if ($releaseID == 0) { - return; - } + /** + * No request id was found, update the release. + * + * @param int $releaseID + * @param int $status + */ + protected function _requestIdNotFound($releaseID, $status) + { + if ($releaseID == 0) { + return; + } - $this->pdo->queryExec( + $this->pdo->queryExec( sprintf(' UPDATE releases SET reqidstatus = %d WHERE id = %d', $status, $releaseID ) ); - } + } - /** - * Get a new title / pre id for a release. - * - * @return array|bool - */ - protected function _getNewTitle() { } + /** + * Get a new title / pre id for a release. + * + * @return array|bool + */ + protected function _getNewTitle() + { + } - /** - * Find a RequestID in a usenet subject. - * - * @return int - */ - protected function _siftReqId() - { - $requestID = []; - switch (true) { + /** + * Find a RequestID in a usenet subject. + * + * @return int + */ + protected function _siftReqId() + { + $requestID = []; + switch (true) { case preg_match('/\[\s*#?scnzb@?efnet\s*\]\[(\d+)\]/', $this->_release['name'], $requestID): case preg_match('/\[\s*(\d+)\s*\]/', $this->_release['name'], $requestID): case preg_match('/^REQ\s*(\d{4,6})/i', $this->_release['name'], $requestID): case preg_match('/^(\d{4,6})-\d{1}\[/', $this->_release['name'], $requestID): - case preg_match('/(\d{4,6}) -/',$this->_release['name'], $requestID): + case preg_match('/(\d{4,6}) -/', $this->_release['name'], $requestID): if ((int) $requestID[1] > 0) { - return (int) $requestID[1]; + return (int) $requestID[1]; } } - return self::REQID_ZERO; - } - /** - * @var bool Echo to CLI? - */ - protected $echoOutput; + return self::REQID_ZERO; + } - /** - * @var Categorize - */ - protected $category; + /** + * @var bool Echo to CLI? + */ + protected $echoOutput; - /** - * @var \nntmux\db\Settings - */ - protected $pdo; + /** + * @var Categorize + */ + protected $category; - /** - * @var ConsoleTools - */ - protected $consoleTools; + /** + * @var \nntmux\db\Settings + */ + protected $pdo; - /** - * @var ColorCLI - */ - protected $colorCLI; + /** + * @var ConsoleTools + */ + protected $consoleTools; - /** - * The found request id for the release. - * @var int - */ - protected $_requestID = self::REQID_ZERO; + /** + * @var ColorCLI + */ + protected $colorCLI; - /** - * The title found from a request id lookup. - * @var bool|string|array - */ - protected $_newTitle = false; + /** + * The found request id for the release. + * @var int + */ + protected $_requestID = self::REQID_ZERO; - /** - * Releases with potential Request id's we can work on. - * @var \PDOStatement|bool - */ - protected $_releases; + /** + * The title found from a request id lookup. + * @var bool|string|array + */ + protected $_newTitle = false; - /** - * Total amount of releases we will be working on. - * @var int - */ - protected $_totalReleases; + /** + * Releases with potential Request id's we can work on. + * @var \PDOStatement|bool + */ + protected $_releases; - /** - * Release we are currently working on. - * @var array - */ - protected $_release; + /** + * Total amount of releases we will be working on. + * @var int + */ + protected $_totalReleases; - /** - * @var int To show the result or not. - */ - protected $_show = 0; + /** + * Release we are currently working on. + * @var array + */ + protected $_release; - /** - * GroupID, which is optional, to limit query results. - * @var string - */ - protected $_groupID; + /** + * @var int To show the result or not. + */ + protected $_show = 0; - /** - * First character of a release GUID, which is optional, to limit query results. - * @var string - */ - protected $_charGUID; + /** + * GroupID, which is optional, to limit query results. + * @var string + */ + protected $_groupID; - protected $_limit; + /** + * First character of a release GUID, which is optional, to limit query results. + * @var string + */ + protected $_charGUID; - protected $_maxTime; + protected $_limit; + + protected $_maxTime; } diff --git a/nntmux/RequestIDLocal.php b/nntmux/RequestIDLocal.php index 8738e96a0..9f7ade614 100755 --- a/nntmux/RequestIDLocal.php +++ b/nntmux/RequestIDLocal.php @@ -1,42 +1,41 @@ <?php + namespace nntmux; /** * Attempts to find a PRE name for a release using a request id from our local pre database, - * or internet request id database using a Standalone -- more intensive methods + * or internet request id database using a Standalone -- more intensive methods. * * Class RequestIDLocal */ class RequestIDLocal extends RequestID { + /** + * @param array $options Class instances / Echo to cli? + */ + public function __construct(array $options = []) + { + parent::__construct($options); + } - /** - * @param array $options Class instances / Echo to cli? - */ - public function __construct(array $options = []) - { - parent::__construct($options); - } - - /** - * Fetch releases with requestid's from MySQL. - */ - protected function _getReleases() - { - $query = + /** + * Fetch releases with requestid's from MySQL. + */ + protected function _getReleases() + { + $query = 'SELECT r.id, r.name, r.fromname, r.categories_id, r.reqidstatus, g.name AS groupname, g.id as gid FROM releases r LEFT JOIN groups g ON r.groups_id = g.id WHERE r.nzbstatus = 1 AND r.predb_id = 0 - AND r.isrequestID = 1' - ; + AND r.isrequestID = 1'; - $query .= ($this->_charGUID === '' ? '' : ' AND r.leftguid = ' . $this->pdo->escapeString($this->_charGUID)); - $query .= ($this->_groupID === '' ? '' : ' AND r.groups_id = ' . $this->_groupID); - $query .= ($this->_maxTime === 0 ? '' : sprintf(' AND r.adddate > NOW() - INTERVAL %d HOUR', $this->_maxTime)); + $query .= ($this->_charGUID === '' ? '' : ' AND r.leftguid = '.$this->pdo->escapeString($this->_charGUID)); + $query .= ($this->_groupID === '' ? '' : ' AND r.groups_id = '.$this->_groupID); + $query .= ($this->_maxTime === 0 ? '' : sprintf(' AND r.adddate > NOW() - INTERVAL %d HOUR', $this->_maxTime)); - switch ($this->_limit) { + switch ($this->_limit) { case 'full': $query .= sprintf( ' AND r.reqidstatus in (%d, %d, %d)', @@ -58,56 +57,55 @@ class RequestIDLocal extends RequestID default: break; } - $this->_releases = $this->pdo->queryDirect($query); - } + $this->_releases = $this->pdo->queryDirect($query); + } - /** - * Process releases for requestid's. - * - * @return int How many did we rename? - */ - protected function _processReleases() - { - $renamed = $checked = 0; - if ($this->_releases instanceof \Traversable) { - foreach ($this->_releases as $this->_release) { - $this->_requestID = $this->_siftReqId(); + /** + * Process releases for requestid's. + * + * @return int How many did we rename? + */ + protected function _processReleases() + { + $renamed = $checked = 0; + if ($this->_releases instanceof \Traversable) { + foreach ($this->_releases as $this->_release) { + $this->_requestID = $this->_siftReqId(); - // Do a local lookup using multiple possible methods - $this->_newTitle = $this->_getNewTitle(); + // Do a local lookup using multiple possible methods + $this->_newTitle = $this->_getNewTitle(); - if ($this->_newTitle !== false && isset($this->_newTitle['title'])) { - $this->_updateRelease(); - $renamed++; - } else { - $this->_requestIdNotFound($this->_release['id'], ($this->_release['reqidstatus'] === self::REQID_UPROC ? self::REQID_NOLL : self::REQID_NONE)); - } + if ($this->_newTitle !== false && isset($this->_newTitle['title'])) { + $this->_updateRelease(); + $renamed++; + } else { + $this->_requestIdNotFound($this->_release['id'], ($this->_release['reqidstatus'] === self::REQID_UPROC ? self::REQID_NOLL : self::REQID_NONE)); + } - if ($this->echoOutput && $this->_show === 0) { - $this->consoleTools->overWritePrimary( - 'Checked Releases: [' . number_format($checked) . '] ' . + if ($this->echoOutput && $this->_show === 0) { + $this->consoleTools->overWritePrimary( + 'Checked Releases: ['.number_format($checked).'] '. $this->consoleTools->percentString(++$checked, $this->_totalReleases) ); - } + } + } + } - } - } + return $renamed; + } - return $renamed; - } + /** + * Get a new title / pre id for a release. + * + * @return array|bool + */ + protected function _getNewTitle() + { + if ($this->_requestID === -2) { + return $this->_multiLookup(); + } - /** - * Get a new title / pre id for a release. - * - * @return array|bool - */ - protected function _getNewTitle() - { - if ($this->_requestID === -2) { - return $this->_multiLookup(); - } - - $check = $this->pdo->queryDirect( + $check = $this->pdo->queryDirect( sprintf( 'SELECT id, title FROM predb WHERE requestid = %d AND groups_id = %d', $this->_requestID, @@ -115,53 +113,53 @@ class RequestIDLocal extends RequestID ) ); - if ($check instanceof \Traversable) { - if ($check->rowCount() === 1) { - foreach ($check as $row) { - if (preg_match('/s\d+/i', $row['title']) && !preg_match('/s\d+e\d+/i', $row['title'])) { - return false; - } - return array('title' => $row['title'], 'id' => $row['id']); - } - } else { - //Prevents multiple releases with the same request id/group from being renamed to the same Pre. - return $this->_multiLookup(); - } - } else { - $result = $this->_singleAltLookup(); - if (is_array($result) && is_numeric($result['id']) && $result['title'] !== '') { - return $result; - } else { - return $this->_multiLookup(); - } - } - return false; - } + if ($check instanceof \Traversable) { + if ($check->rowCount() === 1) { + foreach ($check as $row) { + if (preg_match('/s\d+/i', $row['title']) && ! preg_match('/s\d+e\d+/i', $row['title'])) { + return false; + } - /** - * Sub function that attempts to match RequestID Releases - * by preg_matching the title from the usenet name - * - * @return array|bool - */ - protected function _multiLookup() - { - $regex1 = - '/^\[\s*\d+\s*\][ -]+(\[(ISO|FULL|PART|MP3|0DAY|android)\][ -]+)?\[(alt-?bin| ?#?a[a-z0-9. -]+)((@?ef{1,2})?net)? ?\]' . - '[ -]+(\[(ISO|FULL|PART|MP3|0DAY|android)\][ -]+)?(\[\s*\d+\s*\][ -]+)?(\[\d+\/\d+\][ -]+)?(\"|\[)\s*' . - '(?P<title>.+?)(\.+(vol\d+\+\d+\.)?(-cd\d\.)?(avi|jpg|nzb|m3u|mkv|par2|part\d+|nfo|sample|sfv|rar|r?\d{1,3}|\d+|zip)*)?\s*(\"|\])' . - '[ -]*(\[\d+\/\d+\][ -]*)?((\"\s*(?P<filename1>.+?)([-.]sample)?([-.]cd(\d|[ab]))?(\.+(vol\d+\+\d+\.)?([-.]d\d\.)?([-.]part\d+)?' . - '(avi|jpg|nzb|m3u|mkv|par2|nfo|sample|sfv|rar|r?\d{1,3}|\d+|zip)*)?\s*\")| - (?P<filename2>.+?) (yEnc|\(\d+\/\d+\)))?.*/i' - ; + return ['title' => $row['title'], 'id' => $row['id']]; + } + } else { + //Prevents multiple releases with the same request id/group from being renamed to the same Pre. + return $this->_multiLookup(); + } + } else { + $result = $this->_singleAltLookup(); + if (is_array($result) && is_numeric($result['id']) && $result['title'] !== '') { + return $result; + } else { + return $this->_multiLookup(); + } + } - $regex2 = - '/^\[\s*\d+\s*\].*' . - '\"\s*(?P<title>.+?)(\.+(vol\d+\+\d+\.)?(-cd\d\.)?' . - '(avi|jpg|nzb|m3u|mkv|par2|part\d+|nfo|sample|sfv|rar|r?\d{1,3}|\d+|zip)*)\s*\".*/i' - ; + return false; + } - $matches = []; - switch (true) { + /** + * Sub function that attempts to match RequestID Releases + * by preg_matching the title from the usenet name. + * + * @return array|bool + */ + protected function _multiLookup() + { + $regex1 = + '/^\[\s*\d+\s*\][ -]+(\[(ISO|FULL|PART|MP3|0DAY|android)\][ -]+)?\[(alt-?bin| ?#?a[a-z0-9. -]+)((@?ef{1,2})?net)? ?\]'. + '[ -]+(\[(ISO|FULL|PART|MP3|0DAY|android)\][ -]+)?(\[\s*\d+\s*\][ -]+)?(\[\d+\/\d+\][ -]+)?(\"|\[)\s*'. + '(?P<title>.+?)(\.+(vol\d+\+\d+\.)?(-cd\d\.)?(avi|jpg|nzb|m3u|mkv|par2|part\d+|nfo|sample|sfv|rar|r?\d{1,3}|\d+|zip)*)?\s*(\"|\])'. + '[ -]*(\[\d+\/\d+\][ -]*)?((\"\s*(?P<filename1>.+?)([-.]sample)?([-.]cd(\d|[ab]))?(\.+(vol\d+\+\d+\.)?([-.]d\d\.)?([-.]part\d+)?'. + '(avi|jpg|nzb|m3u|mkv|par2|nfo|sample|sfv|rar|r?\d{1,3}|\d+|zip)*)?\s*\")| - (?P<filename2>.+?) (yEnc|\(\d+\/\d+\)))?.*/i'; + + $regex2 = + '/^\[\s*\d+\s*\].*'. + '\"\s*(?P<title>.+?)(\.+(vol\d+\+\d+\.)?(-cd\d\.)?'. + '(avi|jpg|nzb|m3u|mkv|par2|part\d+|nfo|sample|sfv|rar|r?\d{1,3}|\d+|zip)*)\s*\".*/i'; + + $matches = []; + switch (true) { case preg_match($regex1, $this->_release['name'], $matches): case preg_match($regex2, $this->_release['name'], $matches): $check = $this->pdo->queryOneRow( @@ -171,36 +169,37 @@ class RequestIDLocal extends RequestID $this->pdo->escapeString($matches['title']), ( isset($matches['filename1']) && $matches['filename1'] !== '' - ? 'OR filename = ' . $this->pdo->escapeString($matches['filename1']) + ? 'OR filename = '.$this->pdo->escapeString($matches['filename1']) : ( isset($matches['filename2']) && $matches['filename2'] !== '' - ? 'OR filename = ' . $this->pdo->escapeString($matches['filename2']) + ? 'OR filename = '.$this->pdo->escapeString($matches['filename2']) : '' ) ) ) ); if ($check !== false) { - return array('title' => $check['title'], 'id' => $check['id']); + return ['title' => $check['title'], 'id' => $check['id']]; } continue; default: return false; } - return false; - } - private $groupIDCache = []; + return false; + } - /** - * Attempts to remap the release groups_id by extracting the new group name from the release usenet name. - * - * @return array|bool - */ - protected function _singleAltLookup() - { - switch (true) { + private $groupIDCache = []; + + /** + * Attempts to remap the release groups_id by extracting the new group name from the release usenet name. + * + * @return array|bool + */ + protected function _singleAltLookup() + { + switch (true) { case $this->_release['name'] === 'alt.binaries.etc': $groupName = 'alt.binaries.teevee'; break; @@ -231,33 +230,34 @@ class RequestIDLocal extends RequestID default: return false; } - if (isset($this->groupIDCache[$groupName])) { - $groupID = $this->groupIDCache[$groupName]; - } else { - $groupID = $this->groups->getIDByName($groupName); - } - $check = $this->pdo->queryOneRow( + if (isset($this->groupIDCache[$groupName])) { + $groupID = $this->groupIDCache[$groupName]; + } else { + $groupID = $this->groups->getIDByName($groupName); + } + $check = $this->pdo->queryOneRow( sprintf(' SELECT id, title FROM predb WHERE requestid = %d AND groups_id = %d', $this->_requestID, ($groupID === '' ? 0 : $groupID) ) ); - if ($check !== false) { - return array('title' => $check['title'], 'id' => $check['id']); - } - return false; - } + if ($check !== false) { + return ['title' => $check['title'], 'id' => $check['id']]; + } - /** - * Updates release information when a proper Request id match is found. - */ - protected function _updateRelease() - { - $determinedCat = $this->category->determineCategory($this->_release['gid'], $this->_newTitle['title'], $this->_release['fromname']); - if ($determinedCat === $this->_release['categories_id']) { - $newTitle = $this->pdo->escapeString($this->_newTitle['title']); - $this->pdo->queryExec( + return false; + } + + /** + * Updates release information when a proper Request id match is found. + */ + protected function _updateRelease() + { + $determinedCat = $this->category->determineCategory($this->_release['gid'], $this->_newTitle['title'], $this->_release['fromname']); + if ($determinedCat === $this->_release['categories_id']) { + $newTitle = $this->pdo->escapeString($this->_newTitle['title']); + $this->pdo->queryExec( sprintf(' UPDATE releases SET predb_id = %d, reqidstatus = %d, isrenamed = 1, iscategorized = 1, searchname = %s @@ -268,10 +268,10 @@ class RequestIDLocal extends RequestID $this->_release['id'] ) ); - $this->sphinx->updateRelease($this->_release['id'], $this->pdo); - } else { - $newTitle = $this->pdo->escapeString($this->_newTitle['title']); - $this->pdo->queryExec( + $this->sphinx->updateRelease($this->_release['id'], $this->pdo); + } else { + $newTitle = $this->pdo->escapeString($this->_newTitle['title']); + $this->pdo->queryExec( sprintf(' UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, @@ -285,21 +285,21 @@ class RequestIDLocal extends RequestID $this->_release['id'] ) ); - $this->sphinx->updateRelease($this->_release['id'], $this->pdo); - } + $this->sphinx->updateRelease($this->_release['id'], $this->pdo); + } - if ($this->_show === 1 && $this->_release['name'] !== $this->_newTitle['title']) { - NameFixer::echoChangedReleaseName( - array( + if ($this->_show === 1 && $this->_release['name'] !== $this->_newTitle['title']) { + NameFixer::echoChangedReleaseName( + [ 'new_name' => $this->_newTitle['title'], 'old_name' => $this->_release['name'], 'new_category' => $this->category->getNameByID($determinedCat), 'old_category' => $this->category->getNameByID($this->_release['categories_id']), 'group' => $this->_release['groupname'], 'releases_id' => $this->_release['id'], - 'method' => 'RequestIDLocal' - ) + 'method' => 'RequestIDLocal', + ] ); - } - } + } + } } diff --git a/nntmux/RequestIDWeb.php b/nntmux/RequestIDWeb.php index fd4792d9a..778687150 100755 --- a/nntmux/RequestIDWeb.php +++ b/nntmux/RequestIDWeb.php @@ -1,4 +1,5 @@ <?php + namespace nntmux; use App\Models\Settings; @@ -12,37 +13,37 @@ use GuzzleHttp\Exception\RequestException; */ class RequestIDWeb extends RequestID { - const MAX_WEB_LOOKUPS = 75; // Please don't exceed this, not to be to harsh on the Request id server. + const MAX_WEB_LOOKUPS = 75; // Please don't exceed this, not to be to harsh on the Request id server. - /** - * The id of the PRE entry the found request id belongs to. - * @var bool|int - */ - protected $_preDbID = false; + /** + * The id of the PRE entry the found request id belongs to. + * @var bool|int + */ + protected $_preDbID = false; - /** - * @var int - */ - protected $_request_hours; + /** + * @var int + */ + protected $_request_hours; - /** - * Construct. - * - * @param array $options Class instances / Echo to cli? - */ - public function __construct(array $options = []) - { - parent::__construct($options); - $this->_request_hours = (Settings::value('..request_hours') != '') ? (int)Settings::value('..request_hours') : 1; - } + /** + * Construct. + * + * @param array $options Class instances / Echo to cli? + */ + public function __construct(array $options = []) + { + parent::__construct($options); + $this->_request_hours = (Settings::value('..request_hours') != '') ? (int) Settings::value('..request_hours') : 1; + } - /** - * Get all results from the releases table that have request id's to be processed. - */ - protected function _getReleases() - { - $this->_releases = $this->pdo->queryDirect( - sprintf (' + /** + * Get all results from the releases table that have request id's to be processed. + */ + protected function _getReleases() + { + $this->_releases = $this->pdo->queryDirect( + sprintf(' SELECT r.id, r.name, r.searchname, r.fromname, g.name AS groupname, r.groups_id, r.categories_id FROM releases r LEFT JOIN groups g ON r.groups_id = g.id @@ -59,23 +60,23 @@ class RequestIDWeb extends RequestID self::REQID_NOLL, self::REQID_NONE, $this->_request_hours, - (empty($this->_groupID) ? '' : ('AND r.groups_id = ' . $this->_groupID)), + (empty($this->_groupID) ? '' : ('AND r.groups_id = '.$this->_groupID)), $this->_getReqIdGroups(), ($this->_maxTime === 0 ? '' : sprintf(' AND r.adddate > NOW() - INTERVAL %d HOUR', $this->_maxTime)), (empty($this->_limit) || $this->_limit > 1000 ? 1000 : $this->_limit) ) ); - } + } - /** - * Create "AND" part of query for request id groups. - * Less load on the request id web server, by limiting results. - * - * @return string - */ - protected function _getReqIdGroups() - { - return ( + /** + * Create "AND" part of query for request id groups. + * Less load on the request id web server, by limiting results. + * + * @return string + */ + protected function _getReqIdGroups() + { + return "AND g.name IN ( 'alt.binaries.boneless', 'alt.binaries.cd.image', @@ -92,173 +93,170 @@ class RequestIDWeb extends RequestID 'alt.binaries.sounds.mp3.complete_cd', 'alt.binaries.sounds.flac', 'alt.binaries.teevee', - 'alt.binaries.warez'," . + 'alt.binaries.warez',". // Extra groups we will need to remap later, etc is teevee for example. "'alt.binaries.etc' - )" - ); - } + )"; + } - /** - * Process releases for requestid's. - * - * @return int How many did we rename? - */ - protected function _processReleases() - { - // Array to store results. - $requestArray = []; + /** + * Process releases for requestid's. + * + * @return int How many did we rename? + */ + protected function _processReleases() + { + // Array to store results. + $requestArray = []; - if ($this->_releases instanceof \Traversable) { - // Loop all the results. - foreach($this->_releases as $release) { + if ($this->_releases instanceof \Traversable) { + // Loop all the results. + foreach ($this->_releases as $release) { + $this->_release['name'] = $release['name']; + // Try to find a request id for the release. + $requestId = $this->_siftReqId(); - $this->_release['name'] = $release['name']; - // Try to find a request id for the release. - $requestId = $this->_siftReqId(); + // If there's none, update the release and continue. + if ($requestId === self::REQID_ZERO) { + $this->_requestIdNotFound($release['id'], self::REQID_NONE); + if ($this->echoOutput) { + echo '-'; + } + continue; + } - // If there's none, update the release and continue. - if ($requestId === self::REQID_ZERO) { - $this->_requestIdNotFound($release['id'], self::REQID_NONE); - if ($this->echoOutput) { - echo '-'; - } - continue; - } + // Change etc to teevee. + if ($release['groupname'] === 'alt.binaries.etc') { + $release['groupname'] = 'alt.binaries.teevee'; + } - // Change etc to teevee. - if ($release['groupname'] === 'alt.binaries.etc') { - $release['groupname'] = 'alt.binaries.teevee'; - } - - // Send the release id so we can track the return data. - $requestArray[$release['id']] = array( + // Send the release id so we can track the return data. + $requestArray[$release['id']] = [ 'reqid' => $requestId, 'ident' => $release['id'], 'group' => $release['groupname'], 'sname' => $release['searchname'], - 'fromname' => $release['fromname'] - ); - } - } + 'fromname' => $release['fromname'], + ]; + } + } - // Check if we requests to send to the web. - if (count($requestArray) < 1) { - return 0; - } + // Check if we requests to send to the web. + if (count($requestArray) < 1) { + return 0; + } - // Mock array for isset check on server. - $requestArray[0] = ['ident' => 0, 'group' => 'none', 'reqid' => 0]; + // Mock array for isset check on server. + $requestArray[0] = ['ident' => 0, 'group' => 'none', 'reqid' => 0]; - // Do a web lookup. - try { - $returnXml = $this->client->request('POST', Settings::value('..request_url'), - ['Link' => 'data=' . serialize($requestArray)] + // Do a web lookup. + try { + $returnXml = $this->client->request('POST', Settings::value('..request_url'), + ['Link' => 'data='.serialize($requestArray)] )->getBody(); + } catch (RequestException $e) { + if ($e->hasResponse()) { + if ($e->getCode() === 404) { + ColorCLI::doEcho(ColorCLI::notice('Data not available on server')); + } elseif ($e->getCode() === 503) { + ColorCLI::doEcho(ColorCLI::notice('Service unavailable')); + } else { + ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data, server responded with code: '.$e->getCode())); + } + } + } - } catch (RequestException $e) { - if ($e->hasResponse()) { - if($e->getCode() === 404) { - ColorCLI::doEcho(ColorCLI::notice('Data not available on server')); - } else if ($e->getCode() === 503) { - ColorCLI::doEcho(ColorCLI::notice('Service unavailable')); - } else { - ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data, server responded with code: ' . $e->getCode())); - } - } - } - - $renamed = 0; - // Change the release titles and insert the PRE's if they don't exist. - if (isset($returnXml) && $returnXml !== false) { - $returnXml = @simplexml_load_string($returnXml); - if ($returnXml !== false) { + $renamed = 0; + // Change the release titles and insert the PRE's if they don't exist. + if (isset($returnXml) && $returnXml !== false) { + $returnXml = @simplexml_load_string($returnXml); + if ($returnXml !== false) { // Store the returned identifiers so we can check which releases we didn't find a request id. - $returnedIdentifiers = []; + $returnedIdentifiers = []; - $groupIDArray = []; - foreach($returnXml->request as $result) { - if (isset($result['name'], $result['ident']) && (int)$result['ident'] > 0) { - $this->_newTitle['title'] = (string)$result['name']; - $this->_requestID = (int)$result['reqid']; - $this->_release['id'] = (int)$result['ident']; + $groupIDArray = []; + foreach ($returnXml->request as $result) { + if (isset($result['name'], $result['ident']) && (int) $result['ident'] > 0) { + $this->_newTitle['title'] = (string) $result['name']; + $this->_requestID = (int) $result['reqid']; + $this->_release['id'] = (int) $result['ident']; - // Buffer groupid queries. - $this->_release['groupname'] = $requestArray[(int)$result['ident']]['group']; - if (isset($groupIDarray[$this->_release['groupname']])) { - $this->_release['groups_id'] = $groupIDArray[$this->_release['groupname']]; - } else { - $this->_release['groups_id'] = $this->groups->getIDByName($this->_release['groupname']); - $groupIDArray[$this->_release['groupname']] = $this->_release['groups_id']; - } - $this->_release['gid'] = $this->_release['groups_id']; + // Buffer groupid queries. + $this->_release['groupname'] = $requestArray[(int) $result['ident']]['group']; + if (isset($groupIDarray[$this->_release['groupname']])) { + $this->_release['groups_id'] = $groupIDArray[$this->_release['groupname']]; + } else { + $this->_release['groups_id'] = $this->groups->getIDByName($this->_release['groupname']); + $groupIDArray[$this->_release['groupname']] = $this->_release['groups_id']; + } + $this->_release['gid'] = $this->_release['groups_id']; - $this->_release['fromname'] = $requestArray[(string)$result['ident']]['fromname']; + $this->_release['fromname'] = $requestArray[(string) $result['ident']]['fromname']; - $this->_release['searchname'] = $requestArray[(int)$result['ident']]['sname']; + $this->_release['searchname'] = $requestArray[(int) $result['ident']]['sname']; - $this->_insertIntoPreDB(); - if ($this->_preDbID === false) { - $this->_preDbID = 0; - } - $this->_newTitle['id'] = $this->_preDbID; - $this->_updateRelease(); - $renamed++; - if ($this->echoOutput) { - echo '+'; - } - $returnedIdentifiers[] = (string)$result['ident']; - } - } + $this->_insertIntoPreDB(); + if ($this->_preDbID === false) { + $this->_preDbID = 0; + } + $this->_newTitle['id'] = $this->_preDbID; + $this->_updateRelease(); + $renamed++; + if ($this->echoOutput) { + echo '+'; + } + $returnedIdentifiers[] = (string) $result['ident']; + } + } - // Check if the WEB didn't send back some titles, update the release. - if (count($returnedIdentifiers) > 0) { - foreach ($returnedIdentifiers as $identifier) { - if (array_key_exists($identifier, $requestArray)) { - unset($requestArray[$identifier]); - } - } - } + // Check if the WEB didn't send back some titles, update the release. + if (count($returnedIdentifiers) > 0) { + foreach ($returnedIdentifiers as $identifier) { + if (array_key_exists($identifier, $requestArray)) { + unset($requestArray[$identifier]); + } + } + } - unset($requestArray[0]); - foreach ($requestArray as $request) { - - $addDate = $this->pdo->queryOneRow( + unset($requestArray[0]); + foreach ($requestArray as $request) { + $addDate = $this->pdo->queryOneRow( sprintf( 'SELECT UNIX_TIMESTAMP(adddate) AS adddate FROM releases WHERE id = %d', $request['ident'] ) ); - $status = self::REQID_NONE; - if ($addDate !== false && !empty($addDate['adddate'])) { - if ((bool) (intval((time() - (int)$addDate['adddate']) / 3600) > $this->_request_hours)) { - $status = self::REQID_OLD; - } - } else { - $status = self::REQID_OLD; - } + $status = self::REQID_NONE; + if ($addDate !== false && ! empty($addDate['adddate'])) { + if ((bool) (intval((time() - (int) $addDate['adddate']) / 3600) > $this->_request_hours)) { + $status = self::REQID_OLD; + } + } else { + $status = self::REQID_OLD; + } - $this->_requestIdNotFound( + $this->_requestIdNotFound( $request['ident'], $status ); - if ($this->echoOutput) { - echo '-'; - } - } - } - } - return $renamed; - } + if ($this->echoOutput) { + echo '-'; + } + } + } + } - /** - * If we found a request id on the internet, check if our PRE database has it, insert it if not. - */ - protected function _insertIntoPreDB() - { - $dupeCheck = $this->pdo->queryOneRow( + return $renamed; + } + + /** + * If we found a request id on the internet, check if our PRE database has it, insert it if not. + */ + protected function _insertIntoPreDB() + { + $dupeCheck = $this->pdo->queryOneRow( sprintf(' SELECT id AS predb_id, requestid, groups_id FROM predb @@ -267,8 +265,8 @@ class RequestIDWeb extends RequestID ) ); - if ($dupeCheck === false) { - $this->_preDbID = (int)$this->pdo->queryInsert( + if ($dupeCheck === false) { + $this->_preDbID = (int) $this->pdo->queryInsert( sprintf(' INSERT INTO predb (title, source, requestid, groups_id, predate) VALUES (%s, %s, %d, %d, NOW())', @@ -278,9 +276,9 @@ class RequestIDWeb extends RequestID $this->_release['groups_id'] ) ); - } else { - $this->_preDbID = $dupeCheck['predb_id']; - $this->pdo->queryExec( + } else { + $this->_preDbID = $dupeCheck['predb_id']; + $this->pdo->queryExec( sprintf(' UPDATE predb SET requestid = %d, groups_id = %d @@ -290,17 +288,17 @@ class RequestIDWeb extends RequestID $this->_preDbID ) ); - } - } + } + } - /** - * If we found a PRE name, update the releases name and reset post processing. - */ - protected function _updateRelease() - { - $determinedCategory = $this->category->determineCategory($this->_release['groups_id'], $this->_newTitle['title'], $this->_release['fromname']); - $newTitle = $this->pdo->escapeString($this->_newTitle['title']); - $this->pdo->queryExec( + /** + * If we found a PRE name, update the releases name and reset post processing. + */ + protected function _updateRelease() + { + $determinedCategory = $this->category->determineCategory($this->_release['groups_id'], $this->_newTitle['title'], $this->_release['fromname']); + $newTitle = $this->pdo->escapeString($this->_newTitle['title']); + $this->pdo->queryExec( sprintf(' UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, bookinfo_id = NULL, anidbid = NULL, @@ -314,19 +312,19 @@ class RequestIDWeb extends RequestID $this->_release['id'] ) ); - $this->sphinx->updateRelease($this->_release['id'], $this->pdo); + $this->sphinx->updateRelease($this->_release['id'], $this->pdo); - if ($this->echoOutput) { - NameFixer::echoChangedReleaseName(array( + if ($this->echoOutput) { + NameFixer::echoChangedReleaseName([ 'new_name' => $this->_newTitle['title'], 'old_name' => $this->_release['searchname'], 'new_category' => $this->category->getNameByID($determinedCategory), 'old_category' => '', 'group' => $this->_release['groupname'], 'releases_id' => $this->_release['id'], - 'method' => 'RequestID->updateRelease<web>' - ) + 'method' => 'RequestID->updateRelease<web>', + ] ); - } - } + } + } } diff --git a/nntmux/SABnzbd.php b/nntmux/SABnzbd.php index 77d7c0766..4725277b1 100755 --- a/nntmux/SABnzbd.php +++ b/nntmux/SABnzbd.php @@ -1,117 +1,117 @@ <?php + namespace nntmux; -use App\Models\Settings; use GuzzleHttp\Client; -use nntmux\utility\Utility; +use App\Models\Settings; /** - * Class SABnzbd + * Class SABnzbd. */ class SABnzbd { - /** - * Type of site integration. - */ - const INTEGRATION_TYPE_NONE = 0; - const INTEGRATION_TYPE_SITEWIDE = 1; - const INTEGRATION_TYPE_USER = 2; - /** - * Type of SAB API key. - */ - const API_TYPE_NZB = 1; - const API_TYPE_FULL = 2; - /** - * Priority to send the NZB to SAB. - */ - const PRIORITY_PAUSED = -2; - const PRIORITY_LOW = -1; - const PRIORITY_NORMAL = 0; - const PRIORITY_HIGH = 1; // Sab is completely disabled - no user can use it. + /** + * Type of site integration. + */ + const INTEGRATION_TYPE_NONE = 0; + const INTEGRATION_TYPE_SITEWIDE = 1; + const INTEGRATION_TYPE_USER = 2; + /** + * Type of SAB API key. + */ + const API_TYPE_NZB = 1; + const API_TYPE_FULL = 2; + /** + * Priority to send the NZB to SAB. + */ + const PRIORITY_PAUSED = -2; + const PRIORITY_LOW = -1; + const PRIORITY_NORMAL = 0; + const PRIORITY_HIGH = 1; // Sab is completely disabled - no user can use it. const PRIORITY_FORCE = 2; // Sab is enabled, 1 remote SAB server for the whole site. /** * URL to the SAB server. * @var string|array|bool */ - public $url = ''; + public $url = ''; - /** - * The SAB API key. - * @var string|array|bool - */ - public $apikey = ''; + /** + * The SAB API key. + * @var string|array|bool + */ + public $apikey = ''; - /** - * Download priority of the sent NZB file. - * @var string|array|bool - */ - public $priority = ''; + /** + * Download priority of the sent NZB file. + * @var string|array|bool + */ + public $priority = ''; - /** - * Type of SAB API key (full/nzb). - * @var string|array|bool - */ - public $apikeytype = ''; + /** + * Type of SAB API key (full/nzb). + * @var string|array|bool + */ + public $apikeytype = ''; - /** - * @var int - */ - public $integrated = self::INTEGRATION_TYPE_NONE; + /** + * @var int + */ + public $integrated = self::INTEGRATION_TYPE_NONE; - /** - * Is sab integrated into the site or not. - * @var bool - */ - public $integratedBool = false; + /** + * Is sab integrated into the site or not. + * @var bool + */ + public $integratedBool = false; - /** - * ID of the current user, to send to SAB when downloading a NZB. - * @var string - */ - protected $uid = ''; + /** + * ID of the current user, to send to SAB when downloading a NZB. + * @var string + */ + protected $uid = ''; - /** - * User's nntmux API key to send to SAB when downloading a NZB. - * @var string - */ - protected $rsstoken = ''; + /** + * User's nntmux API key to send to SAB when downloading a NZB. + * @var string + */ + protected $rsstoken = ''; - /** - * nZEDb Site URL to send to SAB to download the NZB. - * @var string - */ - protected $serverurl = ''; + /** + * nZEDb Site URL to send to SAB to download the NZB. + * @var string + */ + protected $serverurl = ''; - /** - * Construct. - * - * @param \BasePage $page - * - * @throws \Exception - */ - public function __construct(&$page) - { - $this->uid = $page->userdata['id']; - $this->rsstoken = $page->userdata['rsstoken']; - $this->serverurl = $page->serverurl; - $this->client = new Client(['verify' => false]); + /** + * Construct. + * + * @param \BasePage $page + * + * @throws \Exception + */ + public function __construct(&$page) + { + $this->uid = $page->userdata['id']; + $this->rsstoken = $page->userdata['rsstoken']; + $this->serverurl = $page->serverurl; + $this->client = new Client(['verify' => false]); - // Set up properties. - switch (Settings::value('apps.sabnzbplus.integrationtype')) { + // Set up properties. + switch (Settings::value('apps.sabnzbplus.integrationtype')) { case self::INTEGRATION_TYPE_USER: - if (!empty($_COOKIE['sabnzbd_' . $this->uid . '__apikey']) && !empty($_COOKIE['sabnzbd_' . $this->uid . '__host'])) { - $this->url = $_COOKIE['sabnzbd_' . $this->uid . '__host']; - $this->apikey = $_COOKIE['sabnzbd_' . $this->uid . '__apikey']; - $this->priority = $_COOKIE['sabnzbd_' . $this->uid . '__priority'] ?? 0; - $this->apikeytype = $_COOKIE['sabnzbd_' . $this->uid . '__apitype'] ?? 1; - } else if (!empty($page->userdata['sabapikey']) && !empty($page->userdata['saburl'])) { - $this->url = $page->userdata['saburl']; - $this->apikey = $page->userdata['sabapikey']; - $this->priority = $page->userdata['sabpriority']; - $this->apikeytype = $page->userdata['sabapikeytype']; + if (! empty($_COOKIE['sabnzbd_'.$this->uid.'__apikey']) && ! empty($_COOKIE['sabnzbd_'.$this->uid.'__host'])) { + $this->url = $_COOKIE['sabnzbd_'.$this->uid.'__host']; + $this->apikey = $_COOKIE['sabnzbd_'.$this->uid.'__apikey']; + $this->priority = $_COOKIE['sabnzbd_'.$this->uid.'__priority'] ?? 0; + $this->apikeytype = $_COOKIE['sabnzbd_'.$this->uid.'__apitype'] ?? 1; + } elseif (! empty($page->userdata['sabapikey']) && ! empty($page->userdata['saburl'])) { + $this->url = $page->userdata['saburl']; + $this->apikey = $page->userdata['sabapikey']; + $this->priority = $page->userdata['sabpriority']; + $this->apikeytype = $page->userdata['sabapikeytype']; } $this->integrated = self::INTEGRATION_TYPE_USER; - switch ((int)$page->userdata['queuetype']) { + switch ((int) $page->userdata['queuetype']) { case 1: case 2: $this->integratedBool = true; @@ -125,10 +125,10 @@ class SABnzbd case self::INTEGRATION_TYPE_SITEWIDE: if ((Settings::value('apps.sabnzbplus.apikey') !== '') && (Settings::value('apps.sabnzbplus.url') !== '')) { - $this->url = Settings::value('apps.sabnzbplus.url'); - $this->apikey = Settings::value('apps.sabnzbplus.apikey'); - $this->priority = Settings::value('apps.sabnzbplus.priority'); - $this->apikeytype = Settings::value('apps.sabnzbplus.apikeytype'); + $this->url = Settings::value('apps.sabnzbplus.url'); + $this->apikey = Settings::value('apps.sabnzbplus.apikey'); + $this->priority = Settings::value('apps.sabnzbplus.priority'); + $this->apikeytype = Settings::value('apps.sabnzbplus.apikeytype'); } $this->integrated = self::INTEGRATION_TYPE_SITEWIDE; $this->integratedBool = true; @@ -138,214 +138,214 @@ class SABnzbd $this->integrated = self::INTEGRATION_TYPE_NONE; // This is for nzbget. if ($page->userdata['queuetype'] === 2) { - $this->integratedBool = true; + $this->integratedBool = true; } break; } - // Verify the URL is good, fix it if not. - if ($this->url !== '' && preg_match('/(?P<first>\/)?(?P<sab>[a-z]+)?(?P<last>\/)?$/i', $this->url, $matches)) { - if (!isset($matches['first'])) { - $this->url .= '/'; - } - if (!isset($matches['sab'])) { - $this->url .= 'sabnzbd'; - } elseif ($matches['sab'] !== 'sabnzbd') { - $this->url .= 'sabnzbd'; - } - if (!isset($matches['last'])) { - $this->url .= '/'; - } - } - } + // Verify the URL is good, fix it if not. + if ($this->url !== '' && preg_match('/(?P<first>\/)?(?P<sab>[a-z]+)?(?P<last>\/)?$/i', $this->url, $matches)) { + if (! isset($matches['first'])) { + $this->url .= '/'; + } + if (! isset($matches['sab'])) { + $this->url .= 'sabnzbd'; + } elseif ($matches['sab'] !== 'sabnzbd') { + $this->url .= 'sabnzbd'; + } + if (! isset($matches['last'])) { + $this->url .= '/'; + } + } + } - /** - * Send a release to SAB. - * - * @param string $guid Release identifier. - * - * @return bool|mixed - */ - public function sendToSab($guid) - { - return $this->client->post( - $this->url . - 'api?mode=addurl&priority=' . - $this->priority . - '&apikey=' . - $this->apikey . - '&name=' . + /** + * Send a release to SAB. + * + * @param string $guid Release identifier. + * + * @return bool|mixed + */ + public function sendToSab($guid) + { + return $this->client->post( + $this->url. + 'api?mode=addurl&priority='. + $this->priority. + '&apikey='. + $this->apikey. + '&name='. urlencode( - $this->serverurl . - 'getnzb/' . - $guid . - '&i=' . - $this->uid . - '&r=' . + $this->serverurl. + 'getnzb/'. + $guid. + '&i='. + $this->uid. + '&r='. $this->rsstoken ) ); - } + } - /** - * Get JSON representation of the full SAB queue. - * - * @return bool|mixed - */ - public function getAdvQueue() - { - return $this->client->get( - $this->url . - 'api?mode=queue&start=START&limit=LIMIT&output=json&apikey=' . + /** + * Get JSON representation of the full SAB queue. + * + * @return bool|mixed + */ + public function getAdvQueue() + { + return $this->client->get( + $this->url. + 'api?mode=queue&start=START&limit=LIMIT&output=json&apikey='. $this->apikey ); - } + } - /** - * Get JSON representation of SAB history. - * - * @return bool|mixed - */ - public function getHistory() - { - return $this->client->get( - $this->url . - 'api?mode=history&start=START&limit=LIMIT&category=CATEGORY&search=SEARCH&failed_only=0&output=json&apikey=' . + /** + * Get JSON representation of SAB history. + * + * @return bool|mixed + */ + public function getHistory() + { + return $this->client->get( + $this->url. + 'api?mode=history&start=START&limit=LIMIT&category=CATEGORY&search=SEARCH&failed_only=0&output=json&apikey='. $this->apikey ); - } + } - /** - * Delete a single NZB from the SAB queue. - * - * @param int $id - * - * @return bool|mixed - */ - public function delFromQueue($id) - { - return $this->client->get( - $this->url . - 'api?mode=queue&name=delete&value=' . - $id . - '&apikey=' . + /** + * Delete a single NZB from the SAB queue. + * + * @param int $id + * + * @return bool|mixed + */ + public function delFromQueue($id) + { + return $this->client->get( + $this->url. + 'api?mode=queue&name=delete&value='. + $id. + '&apikey='. $this->apikey); - } + } - /** - * Pause a single NZB in the SAB queue. - * - * @param int $id - * - * @return bool|mixed - */ - public function pauseFromQueue($id) - { - return $this->client->get( - $this->url . - 'api?mode=queue&name=pause&value=' . - $id . - '&apikey=' . + /** + * Pause a single NZB in the SAB queue. + * + * @param int $id + * + * @return bool|mixed + */ + public function pauseFromQueue($id) + { + return $this->client->get( + $this->url. + 'api?mode=queue&name=pause&value='. + $id. + '&apikey='. $this->apikey); - } + } - /** - * Resume a single NZB in the SAB queue. - * - * @param int $id - * - * @return bool|mixed - */ - public function resumeFromQueue($id) - { - return $this->client->get( - $this->url . - 'api?mode=queue&name=resume&value=' . - $id . - '&apikey=' . + /** + * Resume a single NZB in the SAB queue. + * + * @param int $id + * + * @return bool|mixed + */ + public function resumeFromQueue($id) + { + return $this->client->get( + $this->url. + 'api?mode=queue&name=resume&value='. + $id. + '&apikey='. $this->apikey ); - } + } - /** - * Pause all NZB's in the SAB queue. - * - * @return bool|mixed - */ - public function pauseAll() - { - return $this->client->get( - $this->url . - 'api?mode=pause' . - '&apikey=' . + /** + * Pause all NZB's in the SAB queue. + * + * @return bool|mixed + */ + public function pauseAll() + { + return $this->client->get( + $this->url. + 'api?mode=pause'. + '&apikey='. $this->apikey ); - } + } - /** - * Resume all NZB's in the SAB queue. - * - * @return bool|mixed - */ - public function resumeAll() - { - return $this->client->get( - $this->url . - 'api?mode=resume' . - '&apikey=' . + /** + * Resume all NZB's in the SAB queue. + * + * @return bool|mixed + */ + public function resumeAll() + { + return $this->client->get( + $this->url. + 'api?mode=resume'. + '&apikey='. $this->apikey ); - } + } - /** - * Check if the SAB cookies are in the User's browser. - * - * @return bool - */ - public function checkCookie() - { - $res = false; - if (isset($_COOKIE['sabnzbd_' . $this->uid . '__apikey'])) { - $res = true; - } - if (isset($_COOKIE['sabnzbd_' . $this->uid . '__host'])) { - $res = true; - } - if (isset($_COOKIE['sabnzbd_' . $this->uid . '__priority'])) { - $res = true; - } - if (isset($_COOKIE['sabnzbd_' . $this->uid . '__apitype'])) { - $res = true; - } + /** + * Check if the SAB cookies are in the User's browser. + * + * @return bool + */ + public function checkCookie() + { + $res = false; + if (isset($_COOKIE['sabnzbd_'.$this->uid.'__apikey'])) { + $res = true; + } + if (isset($_COOKIE['sabnzbd_'.$this->uid.'__host'])) { + $res = true; + } + if (isset($_COOKIE['sabnzbd_'.$this->uid.'__priority'])) { + $res = true; + } + if (isset($_COOKIE['sabnzbd_'.$this->uid.'__apitype'])) { + $res = true; + } - return $res; - } + return $res; + } - /** - * Creates the SAB cookies for the user's browser. - * - * @param $host - * @param $apikey - * @param $priority - * @param $apitype - */ - public function setCookie($host, $apikey, $priority, $apitype) - { - setcookie('sabnzbd_' . $this->uid . '__host', $host, time() + 2592000); - setcookie('sabnzbd_' . $this->uid . '__apikey', $apikey, time() + 2592000); - setcookie('sabnzbd_' . $this->uid . '__priority', $priority, time() + 2592000); - setcookie('sabnzbd_' . $this->uid . '__apitype', $apitype, time() + 2592000); - } + /** + * Creates the SAB cookies for the user's browser. + * + * @param $host + * @param $apikey + * @param $priority + * @param $apitype + */ + public function setCookie($host, $apikey, $priority, $apitype) + { + setcookie('sabnzbd_'.$this->uid.'__host', $host, time() + 2592000); + setcookie('sabnzbd_'.$this->uid.'__apikey', $apikey, time() + 2592000); + setcookie('sabnzbd_'.$this->uid.'__priority', $priority, time() + 2592000); + setcookie('sabnzbd_'.$this->uid.'__apitype', $apitype, time() + 2592000); + } - /** - * Deletes the SAB cookies from the user's browser. - */ - public function unsetCookie() - { - setcookie('sabnzbd_' . $this->uid . '__host', '', time() - 2592000); - setcookie('sabnzbd_' . $this->uid . '__apikey', '', time() - 2592000); - setcookie('sabnzbd_' . $this->uid . '__priority', '', time() - 2592000); - setcookie('sabnzbd_' . $this->uid . '__apitype', '', time() - 2592000); - } + /** + * Deletes the SAB cookies from the user's browser. + */ + public function unsetCookie() + { + setcookie('sabnzbd_'.$this->uid.'__host', '', time() - 2592000); + setcookie('sabnzbd_'.$this->uid.'__apikey', '', time() - 2592000); + setcookie('sabnzbd_'.$this->uid.'__priority', '', time() - 2592000); + setcookie('sabnzbd_'.$this->uid.'__apitype', '', time() - 2592000); + } } diff --git a/nntmux/Sharing.php b/nntmux/Sharing.php index a5a5a3598..de0fcff7c 100755 --- a/nntmux/Sharing.php +++ b/nntmux/Sharing.php @@ -1,156 +1,152 @@ <?php + namespace nntmux; use nntmux\db\DB; - /** - * - * - * Class Sharing + * Class Sharing. */ -Class Sharing +class Sharing { - /** - * -------------------------------------------- - * sharing_sites table (contains remote sites): - * -------------------------------------------- - * id id of the site. - * site_name Name of the site. - * site_guid Unique hash identifier for the site. - * last_time Newest comment time for this site. - * first_time Oldest comment time for this site. - * enabled Have we enabled this site? - * comments How many comments has this site given us so far? - * - * ------------------------------------------- - * sharing table (contains local settings): - * ------------------------------------------- - * site_guid Unique identifier for our site. - * site_name Our site name. - * enabled Is sharing/fetching enabled or disabled (overrides settings below)? - * posting Should we upload our comments? - * fetching Should we fetch remote comments? - * auto_enable Should we auto_enable new sites? - * hide_users Hide usernames before uploading comments? - * last_article Last article number we downloaded from usenet. - * max_push Max comments to upload per run. - * max_pull Max articles to download per run. - * - * ------------------------------------------- - * release_comments table (modifications) - * ------------------------------------------- - * shared Has this comment been shared or have we received it from another site. (0 not shared, 1 shared, 2 received) - * shareid Unique identifier to know if we already have the comment or not. - * nzb_guid Guid of the NZB's first message-id. - */ + /** + * -------------------------------------------- + * sharing_sites table (contains remote sites): + * -------------------------------------------- + * id id of the site. + * site_name Name of the site. + * site_guid Unique hash identifier for the site. + * last_time Newest comment time for this site. + * first_time Oldest comment time for this site. + * enabled Have we enabled this site? + * comments How many comments has this site given us so far? + * + * ------------------------------------------- + * sharing table (contains local settings): + * ------------------------------------------- + * site_guid Unique identifier for our site. + * site_name Our site name. + * enabled Is sharing/fetching enabled or disabled (overrides settings below)? + * posting Should we upload our comments? + * fetching Should we fetch remote comments? + * auto_enable Should we auto_enable new sites? + * hide_users Hide usernames before uploading comments? + * last_article Last article number we downloaded from usenet. + * max_push Max comments to upload per run. + * max_pull Max articles to download per run. + * + * ------------------------------------------- + * release_comments table (modifications) + * ------------------------------------------- + * shared Has this comment been shared or have we received it from another site. (0 not shared, 1 shared, 2 received) + * shareid Unique identifier to know if we already have the comment or not. + * nzb_guid Guid of the NZB's first message-id. + */ - /** - * @var \nntmux\db\Settings - */ - protected $pdo; + /** + * @var \nntmux\db\Settings + */ + protected $pdo; - /** - * @var NNTP - */ - protected $nntp; + /** + * @var NNTP + */ + protected $nntp; - /** - * Array containing site settings. - * - * @var array - */ - protected $siteSettings = []; + /** + * Array containing site settings. + * + * @var array + */ + protected $siteSettings = []; - /** - * Group to work in. - * - * @const - */ - const group = 'alt.binaries.zines'; + /** + * Group to work in. + * + * @const + */ + const group = 'alt.binaries.zines'; - /** - * Construct. - * - * @param array $options Class instances. - * - * @access public - */ - public function __construct(array $options = []) - { - $defaults= [ + /** + * Construct. + * + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, 'NNTP' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - // Get all sharing info from DB. - $check = $this->pdo->queryOneRow('SELECT * FROM sharing'); + // Get all sharing info from DB. + $check = $this->pdo->queryOneRow('SELECT * FROM sharing'); - // Initiate sharing settings if this is the first time.. - if (empty($check)) { - $check = $this->initSettings(); - } + // Initiate sharing settings if this is the first time.. + if (empty($check)) { + $check = $this->initSettings(); + } - // Second check to make sure nothing went wrong. - if (empty($check)) { - return; - } + // Second check to make sure nothing went wrong. + if (empty($check)) { + return; + } - $this->nntp = ($options['NNTP'] instanceof NNTP ? $options['NNTP'] : new NNTP(['Settings' => $this->pdo])); + $this->nntp = ($options['NNTP'] instanceof NNTP ? $options['NNTP'] : new NNTP(['Settings' => $this->pdo])); - // Cache sharing settings. - $this->siteSettings = $check; - unset($check); + // Cache sharing settings. + $this->siteSettings = $check; + unset($check); - // Convert to bool to speed up checking. - $this->siteSettings['hide_users'] = ($this->siteSettings['hide_users'] == 1 ? true : false); - $this->siteSettings['auto_enable'] = ($this->siteSettings['auto_enable'] == 1 ? true : false); - $this->siteSettings['posting'] = ($this->siteSettings['posting'] == 1 ? true : false); - $this->siteSettings['fetching'] = ($this->siteSettings['fetching'] == 1 ? true : false); - $this->siteSettings['enabled'] = ($this->siteSettings['enabled'] == 1 ? true : false); - $this->siteSettings['start_position'] = ($this->siteSettings['start_position'] == 1 ? true : false); - } + // Convert to bool to speed up checking. + $this->siteSettings['hide_users'] = ($this->siteSettings['hide_users'] == 1 ? true : false); + $this->siteSettings['auto_enable'] = ($this->siteSettings['auto_enable'] == 1 ? true : false); + $this->siteSettings['posting'] = ($this->siteSettings['posting'] == 1 ? true : false); + $this->siteSettings['fetching'] = ($this->siteSettings['fetching'] == 1 ? true : false); + $this->siteSettings['enabled'] = ($this->siteSettings['enabled'] == 1 ? true : false); + $this->siteSettings['start_position'] = ($this->siteSettings['start_position'] == 1 ? true : false); + } - /** - * Main method. - */ - public function start() - { - // Admin has disabled sharing so return. - if ($this->siteSettings['enabled'] === false) { - return; - } + /** + * Main method. + */ + public function start() + { + // Admin has disabled sharing so return. + if ($this->siteSettings['enabled'] === false) { + return; + } - if (is_null($this->nntp)) { - $this->nntp = new NNTP(); - $this->nntp->doConnect(); - } + if (is_null($this->nntp)) { + $this->nntp = new NNTP(); + $this->nntp->doConnect(); + } - if ($this->siteSettings['fetching']) { - $this->fetchAll(); - } - $this->matchComments(); - if ($this->siteSettings['posting']) { - $this->postAll(); - $this->postSC(); - } - } + if ($this->siteSettings['fetching']) { + $this->fetchAll(); + } + $this->matchComments(); + if ($this->siteSettings['posting']) { + $this->postAll(); + $this->postSC(); + } + } - /** - * Initialise of reset sharing settings. - * - * @param string $siteGuid Optional hash (must be sha1) we can set the site guid to. - * - * @return array|bool - */ - public function initSettings(&$siteGuid = '') - { - $this->pdo->queryExec('TRUNCATE TABLE sharing'); - $siteName = uniqid('newznab_', true); - $this->pdo->queryExec( + /** + * Initialise of reset sharing settings. + * + * @param string $siteGuid Optional hash (must be sha1) we can set the site guid to. + * + * @return array|bool + */ + public function initSettings(&$siteGuid = '') + { + $this->pdo->queryExec('TRUNCATE TABLE sharing'); + $siteName = uniqid('newznab_', true); + $this->pdo->queryExec( sprintf(' INSERT INTO sharing (site_name, site_guid, max_push, max_pull, hide_users, start_position, auto_enable, fetching, max_download) @@ -160,16 +156,16 @@ Class Sharing ) ); - return $this->pdo->queryOneRow('SELECT * FROM sharing'); - } + return $this->pdo->queryOneRow('SELECT * FROM sharing'); + } - /** - * Post all new comments to usenet. - */ - protected function postAll() - { - // Get all comments that we have not posted yet. - $newComments = $this->pdo->query( + /** + * Post all new comments to usenet. + */ + protected function postAll() + { + // Get all comments that we have not posted yet. + $newComments = $this->pdo->query( sprintf( 'SELECT rc.text, rc.id, %s, u.username, HEX(r.nzb_guid) AS nzb_guid FROM release_comments rc @@ -181,32 +177,28 @@ Class Sharing ) ); - // Check if we have any comments to push. - if (count($newComments) === 0) { - return; - } + // Check if we have any comments to push. + if (count($newComments) === 0) { + return; + } + echo '(Sharing) Starting to upload comments.'.PHP_EOL; - echo '(Sharing) Starting to upload comments.' . PHP_EOL; + // Loop over the comments. + foreach ($newComments as $comment) { + $this->postComment($comment); + } + echo PHP_EOL.'(Sharing) Finished uploading comments.'.PHP_EOL; + } - // Loop over the comments. - foreach ($newComments as $comment) { - $this->postComment($comment); - } - - - echo PHP_EOL . '(Sharing) Finished uploading comments.' . PHP_EOL; - - } - - /** - * Post all new comments to usenet. - */ - protected function postSC() - { - // Get all comments from spotnab that we have not posted yet. - $newComments = $this->pdo->query( + /** + * Post all new comments to usenet. + */ + protected function postSC() + { + // Get all comments from spotnab that we have not posted yet. + $newComments = $this->pdo->query( sprintf( 'SELECT id, text, UNIX_TIMESTAMP(createddate) AS unix_time, username, nzb_guid FROM release_comments @@ -215,63 +207,59 @@ Class Sharing ) ); - // Check if we have any comments to push. - if (count($newComments) === 0) { - return; - } + // Check if we have any comments to push. + if (count($newComments) === 0) { + return; + } + echo '(Sharing) Starting to upload spotnab comments.'.PHP_EOL; - echo '(Sharing) Starting to upload spotnab comments.' . PHP_EOL; + // Loop over the comments. + foreach ($newComments as $comment) { + $this->postComment($comment); + } + echo PHP_EOL.'(Sharing) Finished uploading spotnab comments.'.PHP_EOL; + } - // Loop over the comments. - foreach ($newComments as $comment) { - $this->postComment($comment); - } + /** + * Post a comment to usenet. + * + * @param array $row + */ + protected function postComment(&$row) + { + // Create a unique identifier for this comment. + $sid = sha1($row['unix_time'].$row['text'].$row['nzb_guid']); - - echo PHP_EOL . '(Sharing) Finished uploading spotnab comments.' . PHP_EOL; - - } - - /** - * Post a comment to usenet. - * - * @param array $row - */ - protected function postComment(&$row) - { - // Create a unique identifier for this comment. - $sid = sha1($row['unix_time'] . $row['text'] . $row['nzb_guid']); - - // Check if the comment is already shared. - $check = $this->pdo->queryOneRow(sprintf('SELECT id FROM release_comments WHERE shareid = %s', $this->pdo->escapeString($sid))); - if ($check === false) { + // Check if the comment is already shared. + $check = $this->pdo->queryOneRow(sprintf('SELECT id FROM release_comments WHERE shareid = %s', $this->pdo->escapeString($sid))); + if ($check === false) { // Example of a subject. - //(_nZEDb_)nZEDb_533f16e46a5091.73152965_3d12d7c1169d468aaf50d5541ef02cc88f3ede10 - [1/1] "92ba694cebc4fbbd0d9ccabc8604c71b23af1131" (1/1) yEnc + //(_nZEDb_)nZEDb_533f16e46a5091.73152965_3d12d7c1169d468aaf50d5541ef02cc88f3ede10 - [1/1] "92ba694cebc4fbbd0d9ccabc8604c71b23af1131" (1/1) yEnc - // Attempt to upload the comment to usenet. - $success = $this->nntp->postArticle( + // Attempt to upload the comment to usenet. + $success = $this->nntp->postArticle( self::group, - ('(_nZEDb_)' . $this->siteSettings['site_name'] . '_' . $this->siteSettings['site_guid'] . ' - [1/1] "' . $sid . '" yEnc (1/1)'), + ('(_nZEDb_)'.$this->siteSettings['site_name'].'_'.$this->siteSettings['site_guid'].' - [1/1] "'.$sid.'" yEnc (1/1)'), json_encode( [ 'USER' => ($this->siteSettings['hide_users'] ? 'ANON' : $row['username']), 'TIME' => $row['unix_time'], 'SID' => $sid, 'RID' => $row['nzb_guid'], - 'BODY' => $row['text'] + 'BODY' => $row['text'], ] ), '<anon@anon.com>' ); - // Check if we succesfully uploaded it. - if ($this->nntp->isError($success) === false && $success === true) { + // Check if we succesfully uploaded it. + if ($this->nntp->isError($success) === false && $success === true) { // Update DB to say we posted the article. - $this->pdo->queryExec( + $this->pdo->queryExec( sprintf(' UPDATE release_comments SET shared = 1, shareid = %s @@ -281,50 +269,47 @@ Class Sharing ) ); - echo '.'; + echo '.'; + } + } else { + // Update the DB to say it's shared. + $this->pdo->queryExec(sprintf('UPDATE release_comments SET shared = 1 WHERE id = %d', $row['id'])); + } + } - } - } else { - // Update the DB to say it's shared. - $this->pdo->queryExec(sprintf('UPDATE release_comments SET shared = 1 WHERE id = %d', $row['id'])); - } - } - - /** - * Match added comments to releases. - * - * @access protected - */ - protected function matchComments() - { - $res = $this->pdo->query(' + /** + * Match added comments to releases. + */ + protected function matchComments() + { + $res = $this->pdo->query(' SELECT r.id FROM release_comments rc INNER JOIN releases r USING (nzb_guid) WHERE rc.releases_id = 0' ); - $found = count($res); - if ($found > 0) { - foreach ($res as $row) { - $this->pdo->queryExec( - sprintf(" + $found = count($res); + if ($found > 0) { + foreach ($res as $row) { + $this->pdo->queryExec( + sprintf(' UPDATE release_comments rc INNER JOIN releases r USING (nzb_guid) SET rc.releases_id = %d, r.comments = r.comments + 1 WHERE r.id = %d - AND rc.releases_id = 0", + AND rc.releases_id = 0', $row['id'], $row['id'] ) ); - } - if (NN_ECHOCLI) { - echo "(Sharing) Matched $found comments." . PHP_EOL; - } - } + } + if (NN_ECHOCLI) { + echo "(Sharing) Matched $found comments.".PHP_EOL; + } + } - // Update first time seen. - $this->pdo->queryExec( + // Update first time seen. + $this->pdo->queryExec( sprintf(" UPDATE sharing_sites ss INNER JOIN @@ -338,113 +323,111 @@ Class Sharing WHERE ss.first_time IS NULL OR ss.first_time > rc.createddate" ) ); - } + } - /** - * Get all new comments from usenet. - * - * @access protected - */ - protected function fetchAll() - { - // Get NNTP group data. - $group = $this->nntp->selectGroup(self::group, false, true); + /** + * Get all new comments from usenet. + */ + protected function fetchAll() + { + // Get NNTP group data. + $group = $this->nntp->selectGroup(self::group, false, true); - // Check if there's an issue. - if ($this->nntp->isError($group)) { - return; - } + // Check if there's an issue. + if ($this->nntp->isError($group)) { + return; + } - // Check if this is the first time, set our oldest article. - if ($this->siteSettings['last_article'] == 0) { - // If the user picked to start from the oldest, get the oldest. - if ($this->siteSettings['start_position'] === true) { - $this->siteSettings['last_article'] = $ourOldest = $group['first']; - // Else get the newest. - } else { - $this->siteSettings['last_article'] = $ourOldest = (string)($group['last'] - $this->siteSettings['max_download']); - if ($ourOldest < $group['first']) { - $this->siteSettings['last_article'] = $ourOldest = $group['first']; - } - } - } else { - $ourOldest = (string)($this->siteSettings['last_article'] + 1); - } + // Check if this is the first time, set our oldest article. + if ($this->siteSettings['last_article'] == 0) { + // If the user picked to start from the oldest, get the oldest. + if ($this->siteSettings['start_position'] === true) { + $this->siteSettings['last_article'] = $ourOldest = $group['first']; + // Else get the newest. + } else { + $this->siteSettings['last_article'] = $ourOldest = (string) ($group['last'] - $this->siteSettings['max_download']); + if ($ourOldest < $group['first']) { + $this->siteSettings['last_article'] = $ourOldest = $group['first']; + } + } + } else { + $ourOldest = (string) ($this->siteSettings['last_article'] + 1); + } - // Set our newest to our oldest wanted + max pull setting. - $newest = (string)($ourOldest + $this->siteSettings['max_pull']); + // Set our newest to our oldest wanted + max pull setting. + $newest = (string) ($ourOldest + $this->siteSettings['max_pull']); - // Check if our newest wanted is newer than the group's newest, set to group's newest. - if ($newest >= $group['last']) { - $newest = $group['last']; - } + // Check if our newest wanted is newer than the group's newest, set to group's newest. + if ($newest >= $group['last']) { + $newest = $group['last']; + } - // We have nothing to do, so return. - if ($ourOldest > $newest) { - return; - } + // We have nothing to do, so return. + if ($ourOldest > $newest) { + return; + } - if (NN_ECHOCLI) { - echo '(Sharing) Starting to fetch new comments.' . PHP_EOL; - } + if (NN_ECHOCLI) { + echo '(Sharing) Starting to fetch new comments.'.PHP_EOL; + } - // Get the wanted aritcles - $headers = $this->nntp->getOverview($ourOldest . '-' . $newest, true, false); + // Get the wanted aritcles + $headers = $this->nntp->getOverview($ourOldest.'-'.$newest, true, false); - // Check if we received nothing or there was an error. - if ($this->nntp->isError($headers) || count($headers) === 0) { - return; - } + // Check if we received nothing or there was an error. + if ($this->nntp->isError($headers) || count($headers) === 0) { + return; + } - $found = $total = $currentArticle = 0; - // Loop over NNTP headers until we find comments. - foreach ($headers as $header) { + $found = $total = $currentArticle = 0; + // Loop over NNTP headers until we find comments. + foreach ($headers as $header) { // Check if the article is missing. - if (!isset($header['Number'])) { - continue; - } + if (! isset($header['Number'])) { + continue; + } - // Get the current article number. - $currentArticle = $header['Number']; + // Get the current article number. + $currentArticle = $header['Number']; - // Break out of the loop if we have downloaded more comments than the user wants. - if ($found > $this->siteSettings['max_download']) { - break; - } + // Break out of the loop if we have downloaded more comments than the user wants. + if ($found > $this->siteSettings['max_download']) { + break; + } - $matches = []; - //(_nZEDb_)nZEDb_533f16e46a5091.73152965_3d12d7c1169d468aaf50d5541ef02cc88f3ede10 - [1/1] "92ba694cebc4fbbd0d9ccabc8604c71b23af1131" (1/1) yEnc - if ($header['From'] === '<anon@anon.com>' && + $matches = []; + //(_nZEDb_)nZEDb_533f16e46a5091.73152965_3d12d7c1169d468aaf50d5541ef02cc88f3ede10 - [1/1] "92ba694cebc4fbbd0d9ccabc8604c71b23af1131" (1/1) yEnc + if ($header['From'] === '<anon@anon.com>' && preg_match('/^\(_nZEDb_\)(?P<site>.+?)_(?P<guid>[a-f0-9]{40}) - \[1\/1\] "(?P<sid>[a-f0-9]{40})" yEnc \(1\/1\)$/i', $header['Subject'], $matches)) { // Check if this is from our own site. - if ($matches['guid'] === $this->siteSettings['site_guid']) { - continue; - } + if ($matches['guid'] === $this->siteSettings['site_guid']) { + continue; + } - // Check if we already have the comment. - $check = $this->pdo->queryOneRow( + // Check if we already have the comment. + $check = $this->pdo->queryOneRow( sprintf('SELECT id FROM release_comments WHERE shareid = %s', $this->pdo->escapeString($matches['sid']) ) ); - // We don't have it, so insert it. - if ($check === false) { + // We don't have it, so insert it. + if ($check === false) { // Check if we have the site and if it is enabled. - $check = $this->pdo->queryOneRow( + $check = $this->pdo->queryOneRow( sprintf('SELECT enabled FROM sharing_sites WHERE site_guid = %s', $this->pdo->escapeString($matches['guid']) ) ); - if ($check === false) { - // Check if the user has auto enable on. - if ($this->siteSettings['auto_enable'] === false) { - // Insert the site so the admin can enable it later on. - $this->pdo->queryExec( + if ($check === false) { + // Check if the user has auto enable on. + if ($this->siteSettings['auto_enable'] === false) { + // Insert the site so the admin can enable it later on. + $this->pdo->queryExec( sprintf(' INSERT INTO sharing_sites (site_name, site_guid, last_time, first_time, enabled, comments) @@ -453,10 +436,10 @@ Class Sharing $this->pdo->escapeString($matches['guid']) ) ); - continue; - } else { - // Insert the site as enabled since the user has auto enabled on. - $this->pdo->queryExec( + continue; + } else { + // Insert the site as enabled since the user has auto enabled on. + $this->pdo->queryExec( sprintf(' INSERT INTO sharing_sites (site_name, site_guid, last_time, first_time, enabled, comments) @@ -465,93 +448,93 @@ Class Sharing $this->pdo->escapeString($matches['guid']) ) ); - } - } else { - // The user has disabled this site, so continue. - if ($check['enabled'] == 0) { - continue; - } - } + } + } else { + // The user has disabled this site, so continue. + if ($check['enabled'] == 0) { + continue; + } + } - // Insert the comment, if we got it, update the site to increment comment count. - if ($this->insertNewComment($header['Message-ID'], $matches['guid'])) { - $this->pdo->queryExec( + // Insert the comment, if we got it, update the site to increment comment count. + if ($this->insertNewComment($header['Message-ID'], $matches['guid'])) { + $this->pdo->queryExec( sprintf(' UPDATE sharing_sites SET comments = comments + 1, last_time = NOW(), site_name = %s WHERE site_guid = %s', $this->pdo->escapeString($matches['site']), $this->pdo->escapeString($matches['guid']) ) ); - $found++; - if (NN_ECHOCLI) { - echo '.'; - if ($found % 40 == 0) { - echo '[' . $found . ']' . PHP_EOL; - } - } - } - } - } - // Update once in a while in case the user cancels the script. - if ($total++ % 10 == 0) { - $this->siteSettings['lastarticle'] = $currentArticle; - $this->pdo->queryExec(sprintf('UPDATE sharing SET last_article = %d', $currentArticle)); - } - } + $found++; + if (NN_ECHOCLI) { + echo '.'; + if ($found % 40 == 0) { + echo '['.$found.']'.PHP_EOL; + } + } + } + } + } + // Update once in a while in case the user cancels the script. + if ($total++ % 10 == 0) { + $this->siteSettings['lastarticle'] = $currentArticle; + $this->pdo->queryExec(sprintf('UPDATE sharing SET last_article = %d', $currentArticle)); + } + } - if ($currentArticle > 0) { - // Update sharing's last article number. - $this->siteSettings['lastarticle'] = $currentArticle; - $this->pdo->queryExec(sprintf('UPDATE sharing SET last_article = %d', $currentArticle)); - } + if ($currentArticle > 0) { + // Update sharing's last article number. + $this->siteSettings['lastarticle'] = $currentArticle; + $this->pdo->queryExec(sprintf('UPDATE sharing SET last_article = %d', $currentArticle)); + } - if (NN_ECHOCLI) { - if ($found > 0) { - echo PHP_EOL . '(Sharing) Fetched ' . $found . ' new comments.' . PHP_EOL; - } else { - echo '(Sharing) Finish looking for new comments, but did not find any.' . PHP_EOL; - } - } - } + if (NN_ECHOCLI) { + if ($found > 0) { + echo PHP_EOL.'(Sharing) Fetched '.$found.' new comments.'.PHP_EOL; + } else { + echo '(Sharing) Finish looking for new comments, but did not find any.'.PHP_EOL; + } + } + } - /** - * Fetch a comment and insert it. - * - * @param string $messageID Message-ID for the article. - * @param string $siteID id of the site. - * - * @return bool - */ - protected function insertNewComment(&$messageID, &$siteID) - { - // Get the article body. - $body = $this->nntp->getMessages(self::group, $messageID); + /** + * Fetch a comment and insert it. + * + * @param string $messageID Message-ID for the article. + * @param string $siteID id of the site. + * + * @return bool + */ + protected function insertNewComment(&$messageID, &$siteID) + { + // Get the article body. + $body = $this->nntp->getMessages(self::group, $messageID); - // Check if there's an error. - if ($this->nntp->isError($body)) { - return false; - } + // Check if there's an error. + if ($this->nntp->isError($body)) { + return false; + } - // Decompress the body. - $body = @gzinflate($body); - if ($body === false) { - return false; - } + // Decompress the body. + $body = @gzinflate($body); + if ($body === false) { + return false; + } - // JSON Decode the body. - $body = json_decode($body, true); - if ($body === false) { - return false; - } + // JSON Decode the body. + $body = json_decode($body, true); + if ($body === false) { + return false; + } - // Just in case. - if (!isset($body['USER']) || !isset($body['SID']) || !isset($body['RID']) || !isset($body['TIME']) | !isset($body['BODY'])) { - return false; - } - $cid = md5($body['SID'].$body['USER'].$body['TIME'].$siteID); + // Just in case. + if (! isset($body['USER']) || ! isset($body['SID']) || ! isset($body['RID']) || ! isset($body['TIME']) | ! isset($body['BODY'])) { + return false; + } + $cid = md5($body['SID'].$body['USER'].$body['TIME'].$siteID); - // Insert the comment. - if ($this->pdo->queryExec( + // Insert the comment. + if ($this->pdo->queryExec( sprintf(' INSERT IGNORE INTO release_comments (text, createddate, issynced, shareid, cid, gid, nzb_guid, siteid, username, users_id, releases_id, shared, host, sourceID) @@ -563,14 +546,13 @@ Class Sharing $this->pdo->escapeString($body['RID']), $this->pdo->escapeString($body['RID']), $this->pdo->escapeString($siteID), - $this->pdo->escapeString((substr($body['USER'], 0, 3) === 'sn-' ? 'SH_ANON' : 'SH_' . $body['USER'])) + $this->pdo->escapeString((substr($body['USER'], 0, 3) === 'sn-' ? 'SH_ANON' : 'SH_'.$body['USER'])) ) ) ) { - return true; - } - - return false; - } + return true; + } + return false; + } } diff --git a/nntmux/Sitemap.php b/nntmux/Sitemap.php index 34df4d5b1..bec8e3a87 100755 --- a/nntmux/Sitemap.php +++ b/nntmux/Sitemap.php @@ -1,20 +1,21 @@ <?php + namespace nntmux; class Sitemap { - public $type = ''; - public $name = ''; - public $loc = ''; - public $priority = ''; - public $changefreq = ''; + public $type = ''; + public $name = ''; + public $loc = ''; + public $priority = ''; + public $changefreq = ''; - function Sitemap($t, $n, $l, $p, $c) - { - $this->type = $t; - $this->name = $n; - $this->loc = $l; - $this->priority = $p; - $this->changefreq = $c; - } + public function Sitemap($t, $n, $l, $p, $c) + { + $this->type = $t; + $this->name = $n; + $this->loc = $l; + $this->priority = $p; + $this->changefreq = $c; + } } diff --git a/nntmux/Sites.php b/nntmux/Sites.php index 030bb22a9..1ce283531 100755 --- a/nntmux/Sites.php +++ b/nntmux/Sites.php @@ -1,188 +1,201 @@ <?php + namespace nntmux; -use App\Extensions\util\Versions; -use nntmux\libraries\Cache; use nntmux\db\DB; - +use nntmux\libraries\Cache; +use App\Extensions\util\Versions; class Sites { - const REGISTER_STATUS_OPEN = 0; - const REGISTER_STATUS_INVITE = 1; - const REGISTER_STATUS_CLOSED = 2; - const REGISTER_STATUS_API_ONLY = 3; + const REGISTER_STATUS_OPEN = 0; + const REGISTER_STATUS_INVITE = 1; + const REGISTER_STATUS_CLOSED = 2; + const REGISTER_STATUS_API_ONLY = 3; - const ERR_BADUNRARPATH = -1; - const ERR_BADFFMPEGPATH = -2; - const ERR_BADMEDIAINFOPATH = -3; - const ERR_BADNZBPATH = -4; - const ERR_DEEPNOUNRAR = -5; - const ERR_BADTMPUNRARPATH = -6; - const ERR_BADLAMEPATH = -7; - const ERR_SABCOMPLETEPATH = -8; + const ERR_BADUNRARPATH = -1; + const ERR_BADFFMPEGPATH = -2; + const ERR_BADMEDIAINFOPATH = -3; + const ERR_BADNZBPATH = -4; + const ERR_DEEPNOUNRAR = -5; + const ERR_BADTMPUNRARPATH = -6; + const ERR_BADLAMEPATH = -7; + const ERR_SABCOMPLETEPATH = -8; - /** - * @var \nntmux\db\Settings - */ - protected $_db; + /** + * @var \nntmux\db\Settings + */ + protected $_db; - /** - * @var \app\extensions\util\Versions|bool - */ - protected $_versions = false; + /** + * @var \app\extensions\util\Versions|bool + */ + protected $_versions = false; - /** - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->_db = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->_db = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - if (defined('NN_VERSIONS')) { - try { - $this->_versions = new Versions(); - } catch (\Exception $e) { - $this->_versions = false; - } - } - } + if (defined('NN_VERSIONS')) { + try { + $this->_versions = new Versions(); + } catch (\Exception $e) { + $this->_versions = false; + } + } + } + public function version() + { + return $this->_versions === false ? '0.0.0' : $this->_versions->getGitTagInRepo(); + } - public function version() - { - return ($this->_versions === false ? '0.0.0' : $this->_versions->getGitTagInRepo()); - } + public function update($form) + { + $site = $this->row2Object($form); - public function update($form) - { - $site = $this->row2Object($form); + if (substr($site->nzbpath, strlen($site->nzbpath) - 1) != '/') { + $site->nzbpath = $site->nzbpath.'/'; + } - if (substr($site->nzbpath, strlen($site->nzbpath) - 1) != '/') - $site->nzbpath = $site->nzbpath . "/"; + // + // Validate site settings + // + if ($site->mediainfopath != '' && ! is_file($site->mediainfopath)) { + return self::ERR_BADMEDIAINFOPATH; + } - // - // Validate site settings - // - if ($site->mediainfopath != "" && !is_file($site->mediainfopath)) - return Sites::ERR_BADMEDIAINFOPATH; + if ($site->ffmpegpath != '' && ! is_file($site->ffmpegpath)) { + return self::ERR_BADFFMPEGPATH; + } - if ($site->ffmpegpath != "" && !is_file($site->ffmpegpath)) - return Sites::ERR_BADFFMPEGPATH; + if ($site->unrarpath != '' && ! is_file($site->unrarpath)) { + return self::ERR_BADUNRARPATH; + } - if ($site->unrarpath != "" && !is_file($site->unrarpath)) - return Sites::ERR_BADUNRARPATH; + if ($site->nzbpath != '' && ! file_exists($site->nzbpath)) { + return self::ERR_BADNZBPATH; + } - if ($site->nzbpath != "" && !file_exists($site->nzbpath)) - return Sites::ERR_BADNZBPATH; + if ($site->checkpasswordedrar == 2 && ! is_file($site->unrarpath)) { + return self::ERR_DEEPNOUNRAR; + } - if ($site->checkpasswordedrar == 2 && !is_file($site->unrarpath)) - return Sites::ERR_DEEPNOUNRAR; + if ($site->tmpunrarpath != '' && ! file_exists($site->tmpunrarpath)) { + return self::ERR_BADTMPUNRARPATH; + } - if ($site->tmpunrarpath != "" && !file_exists($site->tmpunrarpath)) - return Sites::ERR_BADTMPUNRARPATH; + if ($site->lamepath != '' && ! file_exists($site->lamepath)) { + return self::ERR_BADLAMEPATH; + } - if ($site->lamepath != "" && !file_exists($site->lamepath)) - return Sites::ERR_BADLAMEPATH; + if ($site->sabcompletedir != '' && ! file_exists($site->sabcompletedir)) { + return self::ERR_SABCOMPLETEPATH; + } - if ($site->sabcompletedir != "" && !file_exists($site->sabcompletedir)) - return Sites::ERR_SABCOMPLETEPATH; + $sql = $sqlKeys = []; + foreach ($form as $settingK => $settingV) { + $sql[] = sprintf('WHEN %s THEN %s', $this->_db->escapeString($settingK), $this->_db->escapeString(trim($settingV))); + $sqlKeys[] = $this->_db->escapeString($settingK); + } - $sql = $sqlKeys = []; - foreach ($form as $settingK => $settingV) { - $sql[] = sprintf("WHEN %s THEN %s", $this->_db->escapeString($settingK), $this->_db->escapeString(trim($settingV))); - $sqlKeys[] = $this->_db->escapeString($settingK); - } + $this->_db->exec(sprintf('update site SET value = CASE setting %s END WHERE setting IN (%s)', implode(' ', $sql), implode(', ', $sqlKeys))); - $this->_db->exec(sprintf("update site SET value = CASE setting %s END WHERE setting IN (%s)", implode(' ', $sql), implode(', ', $sqlKeys))); + return $this->get(true); + } - return $this->get(true); - } + public function get($refresh = false) + { + $sql = 'select * from site'; - public function get($refresh = false) - { - $sql = "select * from site"; + if ($refresh) { + $cache = new Cache(); + $cache->delete($sql); + } - if ($refresh) { - $cache = new Cache(); - $cache->delete($sql); - } + $rows = $this->_db->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - $rows = $this->_db->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); + if ($rows === false) { + return false; + } - if ($rows === false) - return false; + return $this->rows2Object($rows); + } - return $this->rows2Object($rows); - } + public function rows2Object($rows) + { + $obj = new \stdClass; + foreach ($rows as $row) { + $obj->{$row['setting']} = $row['value']; + } - public function rows2Object($rows) - { - $obj = new \stdClass; - foreach ($rows as $row) - $obj->{$row['setting']} = $row['value']; + $obj->{'version'} = $this->version(); - $obj->{'version'} = $this->version(); + return $obj; + } - return $obj; - } + public function row2Object($row) + { + $obj = new \stdClass; + $rowKeys = array_keys($row); + foreach ($rowKeys as $key) { + $obj->{$key} = $row[$key]; + } - public function row2Object($row) - { - $obj = new \stdClass; - $rowKeys = array_keys($row); - foreach ($rowKeys as $key) - $obj->{$key} = $row[$key]; + return $obj; + } - return $obj; - } + public function getUnappliedPatches($site) + { + preg_match("/\d+/", $site->dbversion, $matches); + $currentrev = $matches[0]; - public function getUnappliedPatches($site) - { - preg_match("/\d+/", $site->dbversion, $matches); - $currentrev = $matches[0]; + $patchpath = NN_WWW.'../db/patch/0.2.3/'; + $patchfiles = glob($patchpath.'*.sql'); + $missingpatch = []; + foreach ($patchfiles as $file) { + $filecontents = file_get_contents($file); + if (preg_match("/Rev\: (\d+)/", $filecontents, $matches)) { + $patchrev = $matches[1]; + if ($patchrev > $currentrev) { + $missingpatch[] = $file; + } + } + } - $patchpath = NN_WWW . "../db/patch/0.2.3/"; - $patchfiles = glob($patchpath . "*.sql"); - $missingpatch = []; - foreach ($patchfiles as $file) { - $filecontents = file_get_contents($file); - if (preg_match("/Rev\: (\d+)/", $filecontents, $matches)) { - $patchrev = $matches[1]; - if ($patchrev > $currentrev) - $missingpatch[] = $file; - } - } + return $missingpatch; + } - return $missingpatch; - } + public function updateItem($setting, $value) + { + $sql = sprintf('update settings set value = %s where setting = %s', $this->_db->escapeString($value), $this->_db->escapeString($setting)); - public function updateItem($setting, $value) - { - $sql = sprintf("update settings set value = %s where setting = %s", $this->_db->escapeString($value), $this->_db->escapeString($setting)); + return $this->_db->exec($sql); + } - return $this->_db->exec($sql); - } + public function updateLatestRegexRevision($rev) + { + return $this->updateItem('latestregexrevision', $rev); + } - public function updateLatestRegexRevision($rev) - { - return $this->updateItem("latestregexrevision", $rev); - } + public function getLicense($html = false) + { + $n = "\r\n"; + if ($html) { + $n = '<br/>'; + } - public function getLicense($html = false) - { - $n = "\r\n"; - if ($html) - $n = "<br/>"; - - return $n . "newznab " . $this->version() . " Copyright (C) " . date("Y") . " newznab.com" . $n . " + return $n.'newznab '.$this->version().' Copyright (C) '.date('Y').' newznab.com'.$n.' This program is distributed with a commercial licence. See LICENCE.txt for -further details." . $n; - } +further details.'.$n; + } } diff --git a/nntmux/SphinxSearch.php b/nntmux/SphinxSearch.php index 1275fab51..ed05d54a8 100755 --- a/nntmux/SphinxSearch.php +++ b/nntmux/SphinxSearch.php @@ -1,50 +1,51 @@ <?php + namespace nntmux; use nntmux\db\DB; class SphinxSearch { - /** - * SphinxQL connection. - * @var DB - */ - public $sphinxQL = null; + /** + * SphinxQL connection. + * @var DB + */ + public $sphinxQL = null; - /** - * Establish connection to SphinxQL. - */ - public function __construct() - { - if (NN_RELEASE_SEARCH_TYPE === ReleaseSearch::SPHINX) { - if (!defined('NN_SPHINXQL_HOST_NAME')) { - define('NN_SPHINXQL_HOST_NAME', '0'); - } - if (!defined('NN_SPHINXQL_PORT')) { - define('NN_SPHINXQL_PORT', 9306); - } - if (!defined('NN_SPHINXQL_SOCK_FILE')) { - define('NN_SPHINXQL_SOCK_FILE', ''); - } - $this->sphinxQL = new DB( + /** + * Establish connection to SphinxQL. + */ + public function __construct() + { + if (NN_RELEASE_SEARCH_TYPE === ReleaseSearch::SPHINX) { + if (! defined('NN_SPHINXQL_HOST_NAME')) { + define('NN_SPHINXQL_HOST_NAME', '0'); + } + if (! defined('NN_SPHINXQL_PORT')) { + define('NN_SPHINXQL_PORT', 9306); + } + if (! defined('NN_SPHINXQL_SOCK_FILE')) { + define('NN_SPHINXQL_SOCK_FILE', ''); + } + $this->sphinxQL = new DB( [ 'dbname' => '', 'dbport' => NN_SPHINXQL_PORT, 'dbhost' => NN_SPHINXQL_HOST_NAME, - 'dbsock' => NN_SPHINXQL_SOCK_FILE + 'dbsock' => NN_SPHINXQL_SOCK_FILE, ] ); - } - } + } + } - /** - * Insert release into Sphinx RT table. - * @param $parameters - */ - public function insertRelease($parameters): void - { - if ($this->sphinxQL !== null && $parameters['id']) { - $this->sphinxQL->queryExec( + /** + * Insert release into Sphinx RT table. + * @param $parameters + */ + public function insertRelease($parameters): void + { + if ($this->sphinxQL !== null && $parameters['id']) { + $this->sphinxQL->queryExec( sprintf( 'REPLACE INTO releases_rt (id, name, searchname, fromname, filename) VALUES (%d, %s, %s, %s, %s)', $parameters['id'], @@ -54,62 +55,62 @@ class SphinxSearch empty($parameters['filename']) ? "''" : $this->sphinxQL->escapeString($parameters['filename']) ) ); - } - } + } + } - /** - * Delete release from Sphinx RT tables. - * @param array $identifiers ['g' => Release GUID(mandatory), 'id' => ReleaseID(optional, pass false)] - * @param DB $pdo - */ - public function deleteRelease($identifiers, DB $pdo): void - { - if ($this->sphinxQL !== null) { - if ($identifiers['i'] === false) { - $identifiers['i'] = $pdo->queryOneRow( + /** + * Delete release from Sphinx RT tables. + * @param array $identifiers ['g' => Release GUID(mandatory), 'id' => ReleaseID(optional, pass false)] + * @param DB $pdo + */ + public function deleteRelease($identifiers, DB $pdo): void + { + if ($this->sphinxQL !== null) { + if ($identifiers['i'] === false) { + $identifiers['i'] = $pdo->queryOneRow( sprintf('SELECT id FROM releases WHERE guid = %s', $pdo->escapeString($identifiers['g'])) ); - if ($identifiers['i'] !== false) { - $identifiers['i'] = $identifiers['i']['id']; - } - } - if ($identifiers['i'] !== false) { - $this->sphinxQL->queryExec(sprintf('DELETE FROM releases_rt WHERE id = %d', $identifiers['i'])); - } - } - } + if ($identifiers['i'] !== false) { + $identifiers['i'] = $identifiers['i']['id']; + } + } + if ($identifiers['i'] !== false) { + $this->sphinxQL->queryExec(sprintf('DELETE FROM releases_rt WHERE id = %d', $identifiers['i'])); + } + } + } - /** - * @param $string - * - * @return mixed - */ - public static function escapeString($string) - { - $from = [ + /** + * @param $string + * + * @return mixed + */ + public static function escapeString($string) + { + $from = [ '\\', '(', ')', '|', '---', '--', '-', '!', '@', '~', '"', '&', '/', '^', '$', '=', "'", - "\x00", "\n", "\r", "\x1a" + "\x00", "\n", "\r", "\x1a", ]; - $to = [ + $to = [ '\\\\\\\\', '\\\\\\\\(', '\\\\\\\\)', '\\\\\\\\|', '-', '-', '\\\\\\\\-', '\\\\\\\\!', '\\\\\\\\@', '\\\\\\\\~', '\\\\\\\\"', '\\\\\\\\&', '\\\\\\\\/', '\\\\\\\\^', '\\\\\\\\$', '\\\\\\\\=', "\\'", - "\\x00", "\\n", "\\r", "\\x1a" + '\\x00', '\\n', '\\r', '\\x1a', ]; - return str_replace($from, $to, $string); - } + return str_replace($from, $to, $string); + } - /** - * Update Sphinx Relases index for given releases_id. - * - * @param int $releaseID - * @param DB $pdo - */ - public function updateRelease($releaseID, DB $pdo): void - { - if ($this->sphinxQL !== null) { - $new = $pdo->queryOneRow( + /** + * Update Sphinx Relases index for given releases_id. + * + * @param int $releaseID + * @param DB $pdo + */ + public function updateRelease($releaseID, DB $pdo): void + { + if ($this->sphinxQL !== null) { + $new = $pdo->queryOneRow( sprintf(' SELECT r.id, r.name, r.searchname, r.fromname, IFNULL(GROUP_CONCAT(rf.name SEPARATOR " "),"") filename FROM releases r @@ -119,32 +120,32 @@ class SphinxSearch $releaseID ) ); - if ($new !== false) { - $this->insertRelease($new); - } - } - } + if ($new !== false) { + $this->insertRelease($new); + } + } + } - /** - * Truncate a RT index. - * @param string $indexName - */ - public function truncateRTIndex($indexName): void - { - if ($this->sphinxQL !== null) { - $this->sphinxQL->queryExec(sprintf('TRUNCATE RTINDEX %s', $indexName)); - } - } + /** + * Truncate a RT index. + * @param string $indexName + */ + public function truncateRTIndex($indexName): void + { + if ($this->sphinxQL !== null) { + $this->sphinxQL->queryExec(sprintf('TRUNCATE RTINDEX %s', $indexName)); + } + } - /** - * Optimize a RT index. - * @param string $indexName - */ - public function optimizeRTIndex($indexName): void - { - if ($this->sphinxQL !== null) { - $this->sphinxQL->queryExec(sprintf('FLUSH RTINDEX %s', $indexName)); - $this->sphinxQL->queryExec(sprintf('OPTIMIZE INDEX %s', $indexName)); - } - } + /** + * Optimize a RT index. + * @param string $indexName + */ + public function optimizeRTIndex($indexName): void + { + if ($this->sphinxQL !== null) { + $this->sphinxQL->queryExec(sprintf('FLUSH RTINDEX %s', $indexName)); + $this->sphinxQL->queryExec(sprintf('OPTIMIZE INDEX %s', $indexName)); + } + } } diff --git a/nntmux/SpotNab.php b/nntmux/SpotNab.php index 5e11a4ec7..fb560fd7a 100755 --- a/nntmux/SpotNab.php +++ b/nntmux/SpotNab.php @@ -1,691 +1,713 @@ <?php -namespace nntmux; +namespace nntmux; use nntmux\db\DB; use App\Extensions\util\Yenc; // Help out those who don't have SSL enabled -if(!defined('OPENSSL_KEYTYPE_RSA')) { - // OPENSSL_KEYTYPE_RSA is defined as 0 in php v4 and v5 - // so just give it a value to silence possible Notice Errors - // for Windows Users (and give it the correct value) - define('OPENSSL_KEYTYPE_RSA', 0); +if (! defined('OPENSSL_KEYTYPE_RSA')) { + // OPENSSL_KEYTYPE_RSA is defined as 0 in php v4 and v5 + // so just give it a value to silence possible Notice Errors + // for Windows Users (and give it the correct value) + define('OPENSSL_KEYTYPE_RSA', 0); } // Define OpenSSL Config File -define('OPENSSL_CFG_PATH', NN_LIB . '/config/openssl.cnf'); +define('OPENSSL_CFG_PATH', NN_LIB.'/config/openssl.cnf'); // JSON Encode Support (for those missing the constants) -if(!defined('JSON_HEX_TAG')) define('JSON_HEX_TAG', 1); -if(!defined('JSON_HEX_AMP')) define('JSON_HEX_AMP', 2); -if(!defined('JSON_HEX_APOS')) define('JSON_HEX_APOS', 4); -if(!defined('JSON_HEX_QUOT')) define('JSON_HEX_QUOT', 8); -if(!defined('JSON_UNESCAPED_UNICODE')) define('JSON_UNESCAPED_UNICODE', 256); +if (! defined('JSON_HEX_TAG')) { + define('JSON_HEX_TAG', 1); +} +if (! defined('JSON_HEX_AMP')) { + define('JSON_HEX_AMP', 2); +} +if (! defined('JSON_HEX_APOS')) { + define('JSON_HEX_APOS', 4); +} +if (! defined('JSON_HEX_QUOT')) { + define('JSON_HEX_QUOT', 8); +} +if (! defined('JSON_UNESCAPED_UNICODE')) { + define('JSON_UNESCAPED_UNICODE', 256); +} -class SpotNab { - // Segment Identifier domain is used to help build segments - // prior to them being posted. - const SEGID_DOMAIN = 'sample.com'; +class SpotNab +{ + // Segment Identifier domain is used to help build segments + // prior to them being posted. + const SEGID_DOMAIN = 'sample.com'; - // Subject line can look like this: - // 01c9478809c80ccb07246d19852ed33b0a5f5d8d-20130125030511 - // 517a6210bd588e964654f75b807d65d55d420f5e-20130125002943 - // 33012186754c9c75050848d825ad6c2ae1af2e4d-20130125002849 - // To speed up fetch process, we can parse this to determine wether - // or not to continue or not. + // Subject line can look like this: + // 01c9478809c80ccb07246d19852ed33b0a5f5d8d-20130125030511 + // 517a6210bd588e964654f75b807d65d55d420f5e-20130125002943 + // 33012186754c9c75050848d825ad6c2ae1af2e4d-20130125002849 + // To speed up fetch process, we can parse this to determine wether + // or not to continue or not. - // The TYPE is always prefixed on the subject, in this case, all - // Comment types are always 00 - const FETCH_COMMENT_TYPE = "00"; - const FETCH_COMMENT_SUBJECT_REGEX = + // The TYPE is always prefixed on the subject, in this case, all + // Comment types are always 00 + const FETCH_COMMENT_TYPE = '00'; + const FETCH_COMMENT_SUBJECT_REGEX = '/^(?P<checksum>[0-9a-z]{40})-(?P<utcref>[0-9]{14})$/i'; - // Discovery types are always 01 - const FETCH_DISCOVERY_TYPE = "01"; - const FETCH_DISCOVERY_SUBJECT_REGEX = + // Discovery types are always 01 + const FETCH_DISCOVERY_TYPE = '01'; + const FETCH_DISCOVERY_SUBJECT_REGEX = '/^(?P<checksum>[0-9a-z]{40})-(?P<utcref>[0-9]{14})$/i'; - // The Message id can be parsed as follows - const FETCH_MSGID_REGEX = + // The Message id can be parsed as follows + const FETCH_MSGID_REGEX = '/^<(?P<crap>[a-z0-9]{30})\.(?P<type>[0-9]{2})\.(?P<local>[0-9]+)[^@]*@(?P<domain>.*)>$/i'; - // How many consecutive misses in a row do we allow while trying to retrieve - // historic messages do we allow before assuming that we've exceeded the - // the retention area. In which case we just return the last date we - // matched before the miss count started - const FETCH_MAX_MISSES = 15; + // How many consecutive misses in a row do we allow while trying to retrieve + // historic messages do we allow before assuming that we've exceeded the + // the retention area. In which case we just return the last date we + // matched before the miss count started + const FETCH_MAX_MISSES = 15; - // Maximum number of messages to process at one time - // Setting this to too large of a value can cause your usenet to - // ignore and deny your request. - const FETCH_USENET_BATCH = 25000; + // Maximum number of messages to process at one time + // Setting this to too large of a value can cause your usenet to + // ignore and deny your request. + const FETCH_USENET_BATCH = 25000; - // Maximum number of messages to look back if one source - // is lookin like it hasn't posted anything in a very long - // time... we stop counting back headers when we reached - // this figure - const FETCH_MAXIMUM_HEADERS = 200000; + // Maximum number of messages to look back if one source + // is lookin like it hasn't posted anything in a very long + // time... we stop counting back headers when we reached + // this figure + const FETCH_MAXIMUM_HEADERS = 200000; - // Maximum age (in seconds) we look back for a source - const FETCH_MAXIMUM_AGE = 172800; + // Maximum age (in seconds) we look back for a source + const FETCH_MAXIMUM_AGE = 172800; - // The maximum number of comments that can exist within 1 post to usenet - const POST_MAXIMUM_COMMENTS = 500; + // The maximum number of comments that can exist within 1 post to usenet + const POST_MAXIMUM_COMMENTS = 500; - // The number of seconds to wait before sending a new broadcast - const POST_BROADCAST_INTERVAL = 2592000; + // The number of seconds to wait before sending a new broadcast + const POST_BROADCAST_INTERVAL = 2592000; - // Verify Fetch Range; This is the number of records to look back after - // a post to be sure that the post was successful. The number may appear - // kind of high, but consider a large active group and - // this number makes sense. Plus it doesn't take that long to rescan - // a few headers. - const VERIFY_FETCH_HEADER_COUNT = 300; + // Verify Fetch Range; This is the number of records to look back after + // a post to be sure that the post was successful. The number may appear + // kind of high, but consider a large active group and + // this number makes sense. Plus it doesn't take that long to rescan + // a few headers. + const VERIFY_FETCH_HEADER_COUNT = 300; - // The php function openssl_public_encrypt() seems to fail whenever it's - // passed more then this many characters into its buffer, therefore - // we need to encrypt in batches if the content is longer or we - // fail hard. DO NOT CHANGE THIS VALUE!! - EVER - const SSL_MAX_BUF_LEN = 117; + // The php function openssl_public_encrypt() seems to fail whenever it's + // passed more then this many characters into its buffer, therefore + // we need to encrypt in batches if the content is longer or we + // fail hard. DO NOT CHANGE THIS VALUE!! - EVER + const SSL_MAX_BUF_LEN = 117; - // If SSL_MAX_BUF_LEN is to large, we need to use delimiters - // to help separate the batches as they are processed - const SSL_BUF_DELIMITER = "\n"; + // If SSL_MAX_BUF_LEN is to large, we need to use delimiters + // to help separate the batches as they are processed + const SSL_BUF_DELIMITER = "\n"; - // Auto Discovery Functionality - // Autodisovery allows us to post encrypted information other potential - // sources we can use. We also post our source information so others can - // refer to our comments as well. - const AUTODISCOVER_POST_GROUP = "alt.binaries.aac"; + // Auto Discovery Functionality + // Autodisovery allows us to post encrypted information other potential + // sources we can use. We also post our source information so others can + // refer to our comments as well. + const AUTODISCOVER_POST_GROUP = 'alt.binaries.aac'; - const AUTODISCOVER_POST_USER = "auto"; + const AUTODISCOVER_POST_USER = 'auto'; - const AUTODISCOVER_POST_EMAIL = "auto@ohnohs.ru"; + const AUTODISCOVER_POST_EMAIL = 'auto@ohnohs.ru'; - protected $_nntp; - private $_site; - protected $_globals; + protected $_nntp; + private $_site; + protected $_globals; - // Meta Information is fetched from DB - private $_post_site; - private $_post_code; - private $_post_privacy; - private $_post_title; + // Meta Information is fetched from DB + private $_post_site; + private $_post_code; + private $_post_privacy; + private $_post_title; - private $_post_user; - private $_post_email; - private $_post_group; + private $_post_user; + private $_post_email; + private $_post_group; - /* SSL Public & Private Keys */ - private $_ssl_pubkey; - private $_ssl_prvkey; + /* SSL Public & Private Keys */ + private $_ssl_pubkey; + private $_ssl_prvkey; - /* SSL Auto Discovery Public & Private Keys */ - protected $_ssl_auto_pubkey; - protected $_ssl_auto_prvkey; + /* SSL Auto Discovery Public & Private Keys */ + protected $_ssl_auto_pubkey; + protected $_ssl_auto_prvkey; - /* Some booleans to make code reading easier */ - private $_can_post; - private $_can_discover; - private $_can_broadcast; - private $_auto_enable; + /* Some booleans to make code reading easier */ + private $_can_post; + private $_can_discover; + private $_can_broadcast; + private $_auto_enable; - /* Track the last article scanned when preforming a discovery */ - private $_discovery_lastarticle; + /* Track the last article scanned when preforming a discovery */ + private $_discovery_lastarticle; - public function __construct($post_user = NULL, $post_email = NULL, $post_group = NULL) { - $this->_pdo = new DB(); - $this->_nntp = new NNTP(['Settings' => $this->_pdo]); - $this->releaseImage = new ReleaseImage($this->_pdo); - $this->nzb = new NZB($this->_pdo); - $this->releases = new Releases(['Settings' => $this->_pdo]); + public function __construct($post_user = null, $post_email = null, $post_group = null) + { + $this->_pdo = new DB(); + $this->_nntp = new NNTP(['Settings' => $this->_pdo]); + $this->releaseImage = new ReleaseImage($this->_pdo); + $this->nzb = new NZB($this->_pdo); + $this->releases = new Releases(['Settings' => $this->_pdo]); - $this->_post_user = $post_user; - $this->_post_email = $post_email; - $this->_post_group = $post_group; + $this->_post_user = $post_user; + $this->_post_email = $post_email; + $this->_post_group = $post_group; - // Fetch Meta information - $this->_post_code = trim($this->_pdo->getSetting('code'))? - $this->_pdo->getSetting('code'):NULL; - $this->_post_title = trim($this->_pdo->getSetting('title'))? - $this->_pdo->getSetting('title'):NULL; + // Fetch Meta information + $this->_post_code = trim($this->_pdo->getSetting('code')) ? + $this->_pdo->getSetting('code') : null; + $this->_post_title = trim($this->_pdo->getSetting('title')) ? + $this->_pdo->getSetting('title') : null; - if ($this->_post_user === NULL){ - // Fetch the SpotNab UserID - $this->_post_user = trim($this->_pdo->getSetting('spotnabuser'))? - $this->_pdo->getSetting('spotnabuser'):NULL; - } + if ($this->_post_user === null) { + // Fetch the SpotNab UserID + $this->_post_user = trim($this->_pdo->getSetting('spotnabuser')) ? + $this->_pdo->getSetting('spotnabuser') : null; + } - if ($this->_post_email === NULL){ - // Fetch the SpotNab EmailID - $this->_post_email = trim($this->_pdo->getSetting('spotnabemail'))? - $this->_pdo->getSetting('spotnabemail'):NULL; - } + if ($this->_post_email === null) { + // Fetch the SpotNab EmailID + $this->_post_email = trim($this->_pdo->getSetting('spotnabemail')) ? + $this->_pdo->getSetting('spotnabemail') : null; + } - if ($this->_post_group === NULL){ - // Fetch the SpotNab Usenet Group - $this->_post_group = trim($this->_pdo->getSetting('spotnabgroup'))? - $this->_pdo->getSetting('spotnabgroup'):NULL; - } + if ($this->_post_group === null) { + // Fetch the SpotNab Usenet Group + $this->_post_group = trim($this->_pdo->getSetting('spotnabgroup')) ? + $this->_pdo->getSetting('spotnabgroup') : null; + } - // Public Key - $this->_ssl_pubkey = trim($this->_pdo->getSetting('spotnabsitepubkey'))? - $this->_pdo->getSetting('spotnabsitepubkey'):false; - if($this->_ssl_pubkey) - $this->_ssl_pubkey = $this->decompstr($this->_ssl_pubkey); + // Public Key + $this->_ssl_pubkey = trim($this->_pdo->getSetting('spotnabsitepubkey')) ? + $this->_pdo->getSetting('spotnabsitepubkey') : false; + if ($this->_ssl_pubkey) { + $this->_ssl_pubkey = $this->decompstr($this->_ssl_pubkey); + } - // Private Key - $this->_ssl_prvkey = trim($this->_pdo->getSetting('spotnabsiteprvkey'))? - $this->_pdo->getSetting('spotnabsiteprvkey'):false; - if($this->_ssl_prvkey) - $this->_ssl_prvkey = $this->decompstr($this->_ssl_prvkey); + // Private Key + $this->_ssl_prvkey = trim($this->_pdo->getSetting('spotnabsiteprvkey')) ? + $this->_pdo->getSetting('spotnabsiteprvkey') : false; + if ($this->_ssl_prvkey) { + $this->_ssl_prvkey = $this->decompstr($this->_ssl_prvkey); + } - // Track Discovery Article - $this->_discovery_lastarticle = intval($this->_pdo->getSetting('spotnablastarticle')); + // Track Discovery Article + $this->_discovery_lastarticle = intval($this->_pdo->getSetting('spotnablastarticle')); - // Posting Flag - $this->_can_post = (trim($this->_pdo->getSetting('spotnabpost')) == 1)? - true:false; + // Posting Flag + $this->_can_post = (trim($this->_pdo->getSetting('spotnabpost')) == 1) ? + true : false; - // Auto Enable Flag - $this->_auto_enable = (trim($this->_pdo->getSetting('spotnabautoenable')) == 1)? - true:false; + // Auto Enable Flag + $this->_auto_enable = (trim($this->_pdo->getSetting('spotnabautoenable')) == 1) ? + true : false; - // Spotnab Privacy Posting - $this->_post_privacy = (trim($this->_pdo->getSetting('spotnabprivacy')) == 1)? - true:false; + // Spotnab Privacy Posting + $this->_post_privacy = (trim($this->_pdo->getSetting('spotnabprivacy')) == 1) ? + true : false; - // Auto-Discovery Private Key (used for Posting) - $this->_ssl_auto_prvkey = "eJxtk7mOo0AARHO+YnI0Moe5woYGppv7PjLABmzAgDFg" - ."/PU7u/FWWlJJT6X3/f0bWdWR/eUH4Mv1UQxC9ctQs7/FN2EhpKQekgEw5MZTTi+Kt" - ."9pujGz84DeF8xeLY2vXODzDIbvERbWEs4TFGqebjAeXlXjb8Qa7kHrd6P1Ie646ng" - ."DBmYU1zOmZmrJE+7j4yCjf2XgDxbpc4NlVteGVikgTCyLb4z7Q1fPakDGXinjqKkE" - ."riorE1dzA/FHSil5Eu4/yNbRu0UMXlUF7OxLeEQQekAkw6jLAL9gmaRvKca7pyy4D" - ."S9zLoWx4LP/Q67EKaluREVSG8GzXdLOdaVHk2TZE4odQaOQNkc+8nGCxEzWQIsBQk" - ."GNV6vr8fD4K3bpzdrqLG0zNZkhLvxyi5Urz6w5v/Xw+iLW/to9Zv5SqA6kkNbTYg5" - ."Jl66Em2u2cvvAx2EWSM3JxWyiNa0GnAikzHkZdaA4pSIRDlYO0OE8Xf/rkTPth46d" - ."vuTaXPGx20TKXNBszaIKHhl3bAsGJ1zuW3DSGa6lB22Oi1nM0P6al2vEvej16m96i" - ."4/QDynQF49oIw4QaAMiBbYO+T19Xw8NVuyZ9K9zeXKgSMnifYIXbe/PBjIHuvHWTs" - ."/BqUQFJKXy6UiyleDpv5Wo0i+1lnATEps7RVcut8OMgIEyuSRcU90d+rNTGh3g3Yc" - ."/zUyHQLDlxjTazOx2bCZWZqxxgm0PlpRREyAa/w55CEre7Go2DNxWkC9vRVHqhflR" - ."NVduIZhOoJOdho9jeZRjxMtAuNae29fNze0p2Zr6PbFKJJezphdnOgXE+CrFJLq+S" - ."A528knKChLjTlKovVc3gJ5fpX6F8uY/syDXPg/xsu9wpKsEvmznLcENOVUXSVXova" - ."pt/CnrA5O8BuOqAbvAO/Qy8d0j800e14f+1+gPs3xif"; + // Auto-Discovery Private Key (used for Posting) + $this->_ssl_auto_prvkey = 'eJxtk7mOo0AARHO+YnI0Moe5woYGppv7PjLABmzAgDFg' + .'/PU7u/FWWlJJT6X3/f0bWdWR/eUH4Mv1UQxC9ctQs7/FN2EhpKQekgEw5MZTTi+Kt' + .'9pujGz84DeF8xeLY2vXODzDIbvERbWEs4TFGqebjAeXlXjb8Qa7kHrd6P1Ie646ng' + .'DBmYU1zOmZmrJE+7j4yCjf2XgDxbpc4NlVteGVikgTCyLb4z7Q1fPakDGXinjqKkE' + .'riorE1dzA/FHSil5Eu4/yNbRu0UMXlUF7OxLeEQQekAkw6jLAL9gmaRvKca7pyy4D' + .'S9zLoWx4LP/Q67EKaluREVSG8GzXdLOdaVHk2TZE4odQaOQNkc+8nGCxEzWQIsBQk' + .'GNV6vr8fD4K3bpzdrqLG0zNZkhLvxyi5Urz6w5v/Xw+iLW/to9Zv5SqA6kkNbTYg5' + .'Jl66Em2u2cvvAx2EWSM3JxWyiNa0GnAikzHkZdaA4pSIRDlYO0OE8Xf/rkTPth46d' + .'vuTaXPGx20TKXNBszaIKHhl3bAsGJ1zuW3DSGa6lB22Oi1nM0P6al2vEvej16m96i' + .'4/QDynQF49oIw4QaAMiBbYO+T19Xw8NVuyZ9K9zeXKgSMnifYIXbe/PBjIHuvHWTs' + .'/BqUQFJKXy6UiyleDpv5Wo0i+1lnATEps7RVcut8OMgIEyuSRcU90d+rNTGh3g3Yc' + .'/zUyHQLDlxjTazOx2bCZWZqxxgm0PlpRREyAa/w55CEre7Go2DNxWkC9vRVHqhflR' + .'NVduIZhOoJOdho9jeZRjxMtAuNae29fNze0p2Zr6PbFKJJezphdnOgXE+CrFJLq+S' + .'A528knKChLjTlKovVc3gJ5fpX6F8uY/syDXPg/xsu9wpKsEvmznLcENOVUXSVXova' + .'pt/CnrA5O8BuOqAbvAO/Qy8d0j800e14f+1+gPs3xif'; - // Auto-Discovery Public Key (used for discovering) - $this->_ssl_auto_pubkey = "eJxlz7lygkAAgOGep7BnGCEIwXLv2UWOBTk7ZAZkUCKR" - ."Q/L0Odr85d99mvYTJIz7uzCBJ452Lil+n6Z4nDUe0BmKRxbzi4klgUAmAByYDzCCn" - ."XRhK9F+0m3v2n8kvhjsBVnR07PMJnQ3RbqB2mchb46iyExBLXZ6k/g5v/x0wf1Znz" - ."pj3fKbVW+fgOPRxA0ujVF/FBn9CsVWKHoULLbLUwYrMYaE3qfc4dSpijW9xYwc5lZ" - ."NrdwRj75+p1VVq6IeW1wOFwOxKlkjhZfz2euSgTnoTl/BUawcAwmg8ickPv6H/gbI" - ."LVDl"; + // Auto-Discovery Public Key (used for discovering) + $this->_ssl_auto_pubkey = 'eJxlz7lygkAAgOGep7BnGCEIwXLv2UWOBTk7ZAZkUCKR' + .'Q/L0Odr85d99mvYTJIz7uzCBJ452Lil+n6Z4nDUe0BmKRxbzi4klgUAmAByYDzCCn' + .'XRhK9F+0m3v2n8kvhjsBVnR07PMJnQ3RbqB2mchb46iyExBLXZ6k/g5v/x0wf1Znz' + .'pj3fKbVW+fgOPRxA0ujVF/FBn9CsVWKHoULLbLUwYrMYaE3qfc4dSpijW9xYwc5lZ' + .'NrdwRj75+p1VVq6IeW1wOFwOxKlkjhZfz2euSgTnoTl/BUawcAwmg8ickPv6H/gbI' + .'LVDl'; - // Auto-Discovery Flags - $this->_can_broadcast = (trim($this->_pdo->getSetting('spotnabbroadcast')) == 1)? - true:false; - $this->_can_broadcast = ($this->_can_broadcast && $this->_can_post); + // Auto-Discovery Flags + $this->_can_broadcast = (trim($this->_pdo->getSetting('spotnabbroadcast')) == 1) ? + true : false; + $this->_can_broadcast = ($this->_can_broadcast && $this->_can_post); - $this->_can_discover = (trim($this->_pdo->getSetting('spotnabdiscover')) == 1)? - true:false; + $this->_can_discover = (trim($this->_pdo->getSetting('spotnabdiscover')) == 1) ? + true : false; - if (!$this->has_openssl()){ - // Can SpotNab even work; if not, we disable all flags - $this->_can_broadcast = false; - $this->_can_post = false; - } - } + if (! $this->has_openssl()) { + // Can SpotNab even work; if not, we disable all flags + $this->_can_broadcast = false; + $this->_can_post = false; + } + } - // *********************************************************************** - public function has_openssl(){ - // return true if ssl is correctly configured and installed - // otherwise return a fail - return (is_readable(OPENSSL_CFG_PATH) && extension_loaded("openssl")); - } + // *********************************************************************** + public function has_openssl() + { + // return true if ssl is correctly configured and installed + // otherwise return a fail + return is_readable(OPENSSL_CFG_PATH) && extension_loaded('openssl'); + } - // *********************************************************************** - public function auto_clean($max_days=90){ - // 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 " - ."lastbroadcast IS NOT NULL AND " + // *********************************************************************** + public function auto_clean($max_days = 90) + { + // 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 ' + .'lastbroadcast IS NOT NULL AND ' ."lastbroadcast < NOW() - INTERVAL $max_days DAY"; - $res = $this->_pdo->queryExec($sql); - } + $res = $this->_pdo->queryExec($sql); + } - // *********************************************************************** - public function orphan_comment_clean($max_days=1, $batch=500) - { - // Clean out orphan comments that are older then at least 1 day - // this is to address people who do not wish to hold on to - // comments they do not have a release for... Makes sense :) - $offset = 0; - $sql = "SELECT DISTINCT(gid) as gid FROM release_comments " - ."WHERE releases_id = 0 " + // *********************************************************************** + public function orphan_comment_clean($max_days = 1, $batch = 500) + { + // Clean out orphan comments that are older then at least 1 day + // this is to address people who do not wish to hold on to + // comments they do not have a release for... Makes sense :) + $offset = 0; + $sql = 'SELECT DISTINCT(gid) as gid FROM release_comments ' + .'WHERE releases_id = 0 ' ."AND createddate < NOW() - INTERVAL $max_days DAY " - ."ORDER BY createddate " - ."LIMIT %d,%d"; + .'ORDER BY createddate ' + .'LIMIT %d,%d'; - $sql_rel = "SELECT gid FROM releases WHERE gid IN ('%s') "; - $sql_del = "DELETE FROM release_comments WHERE gid IN ('%s')"; - $total_delcnt = 0; - while(1) { - $res = $this->_pdo->query(sprintf($sql, $offset, $batch)); - if(!$res) { - break; - } + $sql_rel = "SELECT gid FROM releases WHERE gid IN ('%s') "; + $sql_del = "DELETE FROM release_comments WHERE gid IN ('%s')"; + $total_delcnt = 0; + while (1) { + $res = $this->_pdo->query(sprintf($sql, $offset, $batch)); + if (! $res) { + break; + } - # Assemble results into list - $gids_found = []; - $gids_matched = []; - foreach($res as $item) { - $gids_found[] = $item['gid']; - } + // Assemble results into list + $gids_found = []; + $gids_matched = []; + foreach ($res as $item) { + $gids_found[] = $item['gid']; + } - #echo 'B:'.sprintf($sql_rel, implode("','", $gids_found))."\n"; - $res2 = $this->_pdo->query(sprintf($sql_rel, implode("','", $gids_found))); - foreach($res2 as $item) { - $gids_matched[] = $item['gid']; - } - # Now we want to create an inverted list by eliminating the - # matches we just fetched - $gids_missing = array_diff($gids_found, $gids_matched); - //print_r($gids_missing); - if(count($gids_missing)) { - $s_gids_missing = implode("','", $gids_missing); - $dresc = $this->_pdo->queryExec(sprintf($sql_del, $s_gids_missing)); - $total_delcnt += count($gids_missing); - $offset += $batch - count($gids_missing); - } else { - $offset += $batch; - } - # make noise - echo '.'; + //echo 'B:'.sprintf($sql_rel, implode("','", $gids_found))."\n"; + $res2 = $this->_pdo->query(sprintf($sql_rel, implode("','", $gids_found))); + foreach ($res2 as $item) { + $gids_matched[] = $item['gid']; + } + // Now we want to create an inverted list by eliminating the + // matches we just fetched + $gids_missing = array_diff($gids_found, $gids_matched); + //print_r($gids_missing); + if (count($gids_missing)) { + $s_gids_missing = implode("','", $gids_missing); + $dresc = $this->_pdo->queryExec(sprintf($sql_del, $s_gids_missing)); + $total_delcnt += count($gids_missing); + $offset += $batch - count($gids_missing); + } else { + $offset += $batch; + } + // make noise + echo '.'; - if(!count($res)) { - break; - } - } - return $total_delcnt; - } + if (! count($res)) { + break; + } + } - // *********************************************************************** - public function soft_reset(){ - // A harmless function that resets spotnab without losing sources - // Calling this function will reset spotnab to think: - // - it hasn't fetched anything yet from existing sources - // - it needs to gracefully build a starting point from scratch - // using existing sources - // - it has never posted discovery information - // - it has never scanned for existing discoveries + return $total_delcnt; + } - // resets sources so they need to query again - $sources = "UPDATE spotnabsources SET " - ."lastupdate = NULL," - ."lastbroadcast = NULL," - ."lastarticle = 0"; - $discovery_a = "UPDATE settings SET " + // *********************************************************************** + public function soft_reset() + { + // A harmless function that resets spotnab without losing sources + // Calling this function will reset spotnab to think: + // - it hasn't fetched anything yet from existing sources + // - it needs to gracefully build a starting point from scratch + // using existing sources + // - it has never posted discovery information + // - it has never scanned for existing discoveries + + // resets sources so they need to query again + $sources = 'UPDATE spotnabsources SET ' + .'lastupdate = NULL,' + .'lastbroadcast = NULL,' + .'lastarticle = 0'; + $discovery_a = 'UPDATE settings SET ' ."value = '0' " ."WHERE setting = 'spotnablastarticle'"; - $broadcast = "Update settings SET " + $broadcast = 'Update settings SET ' ."updateddate = '1980-01-01 00:00:00' " ."WHERE setting = 'spotnabbroadcast'"; - // Discovery should only be set back X days worth defined - // by the maximum age a broadcast can be. - $reftime = date("Y-m-d H:i:s", - time()-(SpotNab::POST_BROADCAST_INTERVAL)); - $discovery_b = "Update settings SET " + // Discovery should only be set back X days worth defined + // by the maximum age a broadcast can be. + $reftime = date('Y-m-d H:i:s', + time() - (self::POST_BROADCAST_INTERVAL)); + $discovery_b = 'Update settings SET ' ."updateddate = '1980-01-01 00:00:00' " ."WHERE setting = 'spotnabdiscover'"; - $post = "Update settings SET " + $post = 'Update settings SET ' ."updateddate = '$reftime' " ."WHERE setting = 'spotnabpost'"; - $this->_pdo->queryExec($sources); - $this->_pdo->queryExec($discovery_a); - $this->_pdo->queryExec($discovery_b); - $this->_pdo->queryExec($broadcast); - $this->_pdo->queryExec($post); - } + $this->_pdo->queryExec($sources); + $this->_pdo->queryExec($discovery_a); + $this->_pdo->queryExec($discovery_b); + $this->_pdo->queryExec($broadcast); + $this->_pdo->queryExec($post); + } - // *********************************************************************** - public function fetch_discovery($reftime = NULL, $retries=3){ - $last = $first = NULL; + // *********************************************************************** + public function fetch_discovery($reftime = null, $retries = 3) + { + $last = $first = null; - // Return Value; Initialize it to Okay - // we'll change it to false if we have to. - $fetch_okay = true; + // Return Value; Initialize it to Okay + // we'll change it to false if we have to. + $fetch_okay = true; - // Track how many records were inserted, updated - $inserted = 0; - $updated = 0; + // Track how many records were inserted, updated + $inserted = 0; + $updated = 0; - if (!$this->_can_discover){ - // discovery disabled - return false; - } + if (! $this->_can_discover) { + // discovery disabled + return false; + } - if($reftime === NULL){ - $q = "SELECT updateddate FROM settings WHERE " + if ($reftime === null) { + $q = 'SELECT updateddate FROM settings WHERE ' ."setting = 'spotnabdiscover'"; - $res = $this->_pdo->queryOneRow($q); - if($res){ - $reftime = $res['updateddate']; - }else{ - // Fetch local time (but look back the maximum duration - // that a discovery message can exist for - $reftime = $this->utc2local((time()-(SpotNab::POST_BROADCAST_INTERVAL))); - } - } + $res = $this->_pdo->queryOneRow($q); + if ($res) { + $reftime = $res['updateddate']; + } else { + // Fetch local time (but look back the maximum duration + // that a discovery message can exist for + $reftime = $this->utc2local((time() - (self::POST_BROADCAST_INTERVAL))); + } + } - // Connect to server - try{ - if (($this->_pdo->getSetting('alternate_nntp') == 1 ? $this->_nntp->doConnect(true, true) : $this->_nntp->doConnect()) !== true) { - exit($this->_pdo->log->error("Unable to connect to usenet." . PHP_EOL)); - } - } - catch(\Exception $e){ - printf("Failed to connect to Usenet\n"); - return false; - } + // Connect to server + try { + if (($this->_pdo->getSetting('alternate_nntp') == 1 ? $this->_nntp->doConnect(true, true) : $this->_nntp->doConnect()) !== true) { + exit($this->_pdo->log->error('Unable to connect to usenet.'.PHP_EOL)); + } + } catch (\Exception $e) { + printf("Failed to connect to Usenet\n"); - echo "Spotnab : Discovery "; - $summary = $this->_nntp->selectGroup( - SpotNab::AUTODISCOVER_POST_GROUP); + return false; + } - $first = $this->_discovery_lastarticle; - if($first <= 0 || $first > $summary['last'] ){ - // Look back until reftime - $first = $this->_first_article_by_date( - SpotNab::AUTODISCOVER_POST_GROUP, + echo 'Spotnab : Discovery '; + $summary = $this->_nntp->selectGroup( + self::AUTODISCOVER_POST_GROUP); + + $first = $this->_discovery_lastarticle; + if ($first <= 0 || $first > $summary['last']) { + // Look back until reftime + $first = $this->_first_article_by_date( + self::AUTODISCOVER_POST_GROUP, $reftime ); - } + } - if($first === false){ - // Fail - echo "Failed\n"; - return false; - } + if ($first === false) { + // Fail + echo "Failed\n"; - // Group Processing Initialization - $processed = 0; - $batch = $last = intval($summary['last']); - $total = abs($last-$first); + return false; + } - // Select Group - while($fetch_okay && $processed < $total) - { - try - { - // Prepare Initial Batch - if ($total > SpotNab::FETCH_USENET_BATCH) - $batch = $first + SpotNab::FETCH_USENET_BATCH; + // Group Processing Initialization + $processed = 0; + $batch = $last = intval($summary['last']); + $total = abs($last - $first); - // Batch Processing - while ($processed < $total) - { - $headers = $this->_get_headers(SpotNab::AUTODISCOVER_POST_GROUP, + // Select Group + while ($fetch_okay && $processed < $total) { + try { + // Prepare Initial Batch + if ($total > self::FETCH_USENET_BATCH) { + $batch = $first + self::FETCH_USENET_BATCH; + } + + // Batch Processing + while ($processed < $total) { + $headers = $this->_get_headers(self::AUTODISCOVER_POST_GROUP, "$first-$batch", $retries); - if($headers === false){ - // Retry Atempts exausted - $fetch_okay = false; - break; - } + if ($headers === false) { + // Retry Atempts exausted + $fetch_okay = false; + break; + } - // Process the header batch - $saved = $this->process_discovery_headers($headers); - if($saved !== false) - { - $inserted += $saved[0]; - $updated += $saved[1]; - } + // Process the header batch + $saved = $this->process_discovery_headers($headers); + if ($saved !== false) { + $inserted += $saved[0]; + $updated += $saved[1]; + } - $processed += ($batch-$first); - // Increment starting index - $first += ($batch-$first); + $processed += ($batch - $first); + // Increment starting index + $first += ($batch - $first); - if ($last-$first >= SpotNab::FETCH_USENET_BATCH){ - // Fetch next batch - $batch = $first + SpotNab::FETCH_USENET_BATCH; - }else{ - $batch = $last; - } - //echo "$first-$batch, processed=$processed\n"; + if ($last - $first >= self::FETCH_USENET_BATCH) { + // Fetch next batch + $batch = $first + self::FETCH_USENET_BATCH; + } else { + $batch = $last; + } + //echo "$first-$batch, processed=$processed\n"; //print_r($headers); - } + } + } catch (\Exception $e) { + // Reset Connection + $fetch_okay = $this->_nntpReset(self::AUTODISCOVER_POST_GROUP); - }catch(\Exception $e){ - // Reset Connection - $fetch_okay = $this->_nntpReset(SpotNab::AUTODISCOVER_POST_GROUP); - - // Track retry attempts - $retries--; - if($retries <= 0){ - // Retry Atempts exausted - $fetch_okay = false; - break; - } - continue; - } - } - $sql = sprintf("Update settings SET value = '%d' " + // Track retry attempts + $retries--; + if ($retries <= 0) { + // Retry Atempts exausted + $fetch_okay = false; + break; + } + continue; + } + } + $sql = sprintf("Update settings SET value = '%d' " ."WHERE setting = 'spotnablastarticle'", $last); - $this->_pdo->queryExec($sql); - printf("%d new and %d updated source(s).\n", $inserted, $updated); + $this->_pdo->queryExec($sql); + printf("%d new and %d updated source(s).\n", $inserted, $updated); - // Update reference point - $q = "Update settings SET updateddate = NOW() WHERE " + // Update reference point + $q = 'Update settings SET updateddate = NOW() WHERE ' ."setting = 'spotnabdiscover'"; - $this->_pdo->queryExec($q); + $this->_pdo->queryExec($q); - return $inserted + $updated; - } + return $inserted + $updated; + } - // *********************************************************************** - public function auto_post_discovery($repost_sec = SpotNab::POST_BROADCAST_INTERVAL){ - // performs a post discovery once the time in seconds has elapsed - $q = "SELECT updateddate FROM settings WHERE " + // *********************************************************************** + public function auto_post_discovery($repost_sec = self::POST_BROADCAST_INTERVAL) + { + // performs a post discovery once the time in seconds has elapsed + $q = 'SELECT updateddate FROM settings WHERE ' ."setting = 'spotnabbroadcast'"; - $res = $this->_pdo->queryOneRow($q); - $then = strtotime($res['updateddate']); - $now = time(); - if(($now - $then) > $repost_sec){ - // perform a post - if($this->post_discovery()) - { - // Update post time - $q = "Update settings SET updateddate = NOW() WHERE " + $res = $this->_pdo->queryOneRow($q); + $then = strtotime($res['updateddate']); + $now = time(); + if (($now - $then) > $repost_sec) { + // perform a post + if ($this->post_discovery()) { + // Update post time + $q = 'Update settings SET updateddate = NOW() WHERE ' ."setting = 'spotnabbroadcast'"; - $res = $this->_pdo->queryExec($q); - } - } - } + $res = $this->_pdo->queryExec($q); + } + } + } - // *********************************************************************** - public function post_discovery($reftime = NULL, $retries=3){ - $reftime_local = $reftime; - $article = NULL; - $rc = new ReleaseComments(); - $us = new Users(); + // *********************************************************************** + public function post_discovery($reftime = null, $retries = 3) + { + $reftime_local = $reftime; + $article = null; + $rc = new ReleaseComments(); + $us = new Users(); - if($reftime_local === NULL){ - // Fetch local time - $reftime_local = $this->utc2local(); - } - // some error checking.... - if(!$this->_can_broadcast){ - // Broadcasting not possible - return false; - } + if ($reftime_local === null) { + // Fetch local time + $reftime_local = $this->utc2local(); + } + // some error checking.... + if (! $this->_can_broadcast) { + // Broadcasting not possible + return false; + } - // Generate keys if one doesn't exist - if(!($this->_ssl_prvkey && $this->_ssl_pubkey)) - if($this->keygen(false, true) === false) - return false; + // Generate keys if one doesn't exist + if (! ($this->_ssl_prvkey && $this->_ssl_pubkey)) { + if ($this->keygen(false, true) === false) { + return false; + } + } - // Get Discovery Private Key - $prvkey = $this->decompstr($this->_ssl_auto_prvkey); - if (!$prvkey){ - // This is a serious problem because the hard-coded discovery - // key should always decrypt! - return false; - } + // Get Discovery Private Key + $prvkey = $this->decompstr($this->_ssl_auto_prvkey); + if (! $prvkey) { + // This is a serious problem because the hard-coded discovery + // key should always decrypt! + return false; + } - printf("Spotnab : Broadcast ..."); + printf('Spotnab : Broadcast ...'); - // Fetch some date ranges - $last_month = date("Y-m-d",strtotime( - date("Y-m-d", time()) . " - 30 day")); - $last_year = date('Y-m-d',strtotime( - date("Y-m-d", time()) . " - 365 day")); + // Fetch some date ranges + $last_month = date('Y-m-d', strtotime( + date('Y-m-d', time()).' - 30 day')); + $last_year = date('Y-m-d', strtotime( + date('Y-m-d', time()).' - 365 day')); - // Header - $message = [ + // Header + $message = [ 'site' => [ // title & code taken out to keep things anonymous for now //'title' => $this->_post_title, //'code' => $this->_post_code, 'id' => md5($this->_pdo->getSetting('siteseed')), - 'users' => $us->getCount() + 'users' => $us->getCount(), ], 'posts' => [ 'user' => $this->_post_user, 'email' => $this->_post_email, 'group' => $this->_post_group, 'privacy' => $this->_post_privacy, - 'public_key' => $this->compstr($this->_ssl_pubkey) + 'public_key' => $this->compstr($this->_ssl_pubkey), ], 'comments' => [ 'past_month' => $rc->getCommentCount($last_month, true), 'past_year' => $rc->getCommentCount($last_year, true), - 'total' => $rc->getCommentCount(NULL, true) + 'total' => $rc->getCommentCount(null, true), ], 'postdate_utc' => $this->local2utc($reftime_local), ]; - // Encode Message so it can be posted - $article = $this->encodePost( + // Encode Message so it can be posted + $article = $this->encodePost( $message, $reftime_local, false, - $prvkey, NULL, true, - SpotNab::FETCH_DISCOVERY_TYPE, - SpotNab::AUTODISCOVER_POST_USER, - SpotNab::AUTODISCOVER_POST_EMAIL, - SpotNab::AUTODISCOVER_POST_GROUP + $prvkey, null, true, + self::FETCH_DISCOVERY_TYPE, + self::AUTODISCOVER_POST_USER, + self::AUTODISCOVER_POST_EMAIL, + self::AUTODISCOVER_POST_GROUP ); - if($article === false){ - echo "Failed.\n"; - return false; - } + if ($article === false) { + echo "Failed.\n"; - // Post message - if ($this->_postArticle($article, $retries)) - { - // Post is good; update database - //echo "Done.\n"; - return true; - } - echo "Failed.\n"; - return false; - } + return false; + } - // *********************************************************************** + // Post message + if ($this->_postArticle($article, $retries)) { + // Post is good; update database + //echo "Done.\n"; + return true; + } + echo "Failed.\n"; - /** - * This function queries all enabled sources and fetches any content - * they are sharing. - * The specified $reftime is presumed to be local *not utc* - * - * @param null $reftime - * @param int $retries - * - * @return int - */ - public function fetch($reftime = NULL, $retries = 3) { + return false; + } - $first = NULL; + // *********************************************************************** - // Return Value; Initialize it to Okay - // we'll change it to false if we have to. - $fetch_okay = true; - $backfill = false; + /** + * This function queries all enabled sources and fetches any content + * they are sharing. + * The specified $reftime is presumed to be local *not utc*. + * + * @param null $reftime + * @param int $retries + * + * @return int + */ + public function fetch($reftime = null, $retries = 3) + { + $first = null; - // We set a cap on how many days in the past we look - $_max_age = time() - SpotNab::FETCH_MAXIMUM_AGE; - if($reftime === NULL){ - // Fetch local time (but look back X days) - $reftime = $this->utc2local($_max_age); - }else{ - // Someone specified a date range to query from - $backfill = true; + // Return Value; Initialize it to Okay + // we'll change it to false if we have to. + $fetch_okay = true; + $backfill = false; - if(is_string($reftime)){ - $reftime = date("Y-m-d H:i:s", strtotime($reftime)); - }else if(is_int($reftime)){ - $reftime = date("Y-m-d H:i:s", $reftime); - } - $_max_age = strtotime($reftime); - } + // We set a cap on how many days in the past we look + $_max_age = time() - self::FETCH_MAXIMUM_AGE; + if ($reftime === null) { + // Fetch local time (but look back X days) + $reftime = $this->utc2local($_max_age); + } else { + // Someone specified a date range to query from + $backfill = true; - // First we find all active sources and build a hash table we can - // use to simplify fetching. - $res = $this->_pdo->query('SELECT * FROM spotnabsources WHERE active = 1 ORDER BY usenetgroup,lastupdate DESC'); - $group_hash = []; - $group_article_start = []; - $id_hash = []; + if (is_string($reftime)) { + $reftime = date('Y-m-d H:i:s', strtotime($reftime)); + } elseif (is_int($reftime)) { + $reftime = date('Y-m-d H:i:s', $reftime); + } + $_max_age = strtotime($reftime); + } - if(!count($res)) - return true; + // First we find all active sources and build a hash table we can + // use to simplify fetching. + $res = $this->_pdo->query('SELECT * FROM spotnabsources WHERE active = 1 ORDER BY usenetgroup,lastupdate DESC'); + $group_hash = []; + $group_article_start = []; + $id_hash = []; - foreach($res as $source){ - $ghash = trim($source['usenetgroup']); - if(!array_key_exists($ghash, $group_hash)){ - // Because our results are sorted by group, if we enter - // here then we're processing a brand new group... - $group_hash[$ghash] = []; + if (! count($res)) { + return true; + } - // Initialize our article start point - $group_article_start[$ghash] = 0; + foreach ($res as $source) { + $ghash = trim($source['usenetgroup']); + if (! array_key_exists($ghash, $group_hash)) { + // Because our results are sorted by group, if we enter + // here then we're processing a brand new group... + $group_hash[$ghash] = []; - // Initialize id Hash - $id_hash[$ghash] = []; - } + // Initialize our article start point + $group_article_start[$ghash] = 0; - // Reference time is in UTC on Usenet but local in our database - // this isn't intentionally confusing, this is done so all our local - // times reflect those across the world, and it also makes joins to - // the table much easier since they join doesn't have to accomodate - // for the utc time itself. + // Initialize id Hash + $id_hash[$ghash] = []; + } - // Therefore, we need to take the lastupdate time and convert it to - // UTC for processing. - $ref = $backfill?date("Y-m-d H:i:s", $_max_age):$source['lastupdate']; + // Reference time is in UTC on Usenet but local in our database + // this isn't intentionally confusing, this is done so all our local + // times reflect those across the world, and it also makes joins to + // the table much easier since they join doesn't have to accomodate + // for the utc time itself. - if(!$ref){ - // We've never fetched from the group before, so we'll use - // the reftime passed to the function - $ref = $reftime; - } + // Therefore, we need to take the lastupdate time and convert it to + // UTC for processing. + $ref = $backfill ? date('Y-m-d H:i:s', $_max_age) : $source['lastupdate']; - // Therefore, we need to take the lastupdate time and convert it to - // UTC for processing. - $article = abs(intval($source['lastarticle'])); - if($article > 0){ - if($group_article_start[$ghash] == 0) - $group_article_start[$ghash] = $article; - else - $group_article_start[$ghash] = ($article < $group_article_start[$ghash])? - $article:$group_article_start[$ghash]; - } + if (! $ref) { + // We've never fetched from the group before, so we'll use + // the reftime passed to the function + $ref = $reftime; + } - // Store id - $id_hash[$ghash][] = $source['id']; + // Therefore, we need to take the lastupdate time and convert it to + // UTC for processing. + $article = abs(intval($source['lastarticle'])); + if ($article > 0) { + if ($group_article_start[$ghash] == 0) { + $group_article_start[$ghash] = $article; + } else { + $group_article_start[$ghash] = ($article < $group_article_start[$ghash]) ? + $article : $group_article_start[$ghash]; + } + } - // Store Source Details - $group_hash[$ghash][] = [ + // Store id + $id_hash[$ghash][] = $source['id']; + + // Store Source Details + $group_hash[$ghash][] = [ 'id' => $source['id'], 'key' => $this->decompstr(trim($source['publickey'])), 'user' => trim($source['username']), @@ -695,206 +717,210 @@ class SpotNab { 'ref' => strtotime($ref), // Store last article reference - 'article' => $article + 'article' => $article, ]; - } + } - // We want to resort the internal arrays by they're ref time - // so that the oldest (longest without an update) is processed - // first - foreach(array_keys($group_hash) as $key){ - $_ref = []; - foreach($group_hash[$key] as $id => $source){ - # Source Time (within reason) - if($backfill) - $_ref[$id] = $_max_age; - else - $_ref[$id] = - ($source['ref'] < $_max_age)?$_max_age:$source['ref']; - } - // Sort results (oldest in time first) - array_multisort($_ref, SORT_ASC, $group_hash[$key]); - } + // We want to resort the internal arrays by they're ref time + // so that the oldest (longest without an update) is processed + // first + foreach (array_keys($group_hash) as $key) { + $_ref = []; + foreach ($group_hash[$key] as $id => $source) { + // Source Time (within reason) + if ($backfill) { + $_ref[$id] = $_max_age; + } else { + $_ref[$id] = + ($source['ref'] < $_max_age) ? $_max_age : $source['ref']; + } + } + // Sort results (oldest in time first) + array_multisort($_ref, SORT_ASC, $group_hash[$key]); + } - // Now we fetch headers + // Now we fetch headers - // Connect to server - try{ - if (($this->_pdo->getSetting('alternate_nntp') == 1 ? $this->_nntp->doConnect(true, true) : $this->_nntp->doConnect()) !== true) { - exit($this->_pdo->log->error("Unable to connect to usenet." . PHP_EOL)); - } - } - catch(\Exception $e){ - printf("Failed to connect to Usenet"); - return false; - } + // Connect to server + try { + if (($this->_pdo->getSetting('alternate_nntp') == 1 ? $this->_nntp->doConnect(true, true) : $this->_nntp->doConnect()) !== true) { + exit($this->_pdo->log->error('Unable to connect to usenet.'.PHP_EOL)); + } + } catch (\Exception $e) { + printf('Failed to connect to Usenet'); - // Track how many records were inserted, updated - $inserted = 0; - $updated = 0; + return false; + } - foreach($group_hash as $group => $hash){ - printf("Spotnab : %d source(s)...", count($hash)); + // Track how many records were inserted, updated + $inserted = 0; + $updated = 0; - $summary = $this->_nntp->selectGroup($group); - // Get our article id - $first = ($backfill)?0:$group_article_start[$group]; - if($first == 0){ - // We can safely use the first $hash entry since we've - // already sorted it in ascending order above, so this - // is the time furthest back - $first = $this->_first_article_by_date($group, $hash[0]['ref']); - if($first === false){ - continue; - } - } + foreach ($group_hash as $group => $hash) { + printf('Spotnab : %d source(s)...', count($hash)); - // Group Processing Initialization - $processed = 0; - $batch = $last = intval($summary['last']); - $total = abs($last-$first); + $summary = $this->_nntp->selectGroup($group); + // Get our article id + $first = ($backfill) ? 0 : $group_article_start[$group]; + if ($first == 0) { + // We can safely use the first $hash entry since we've + // already sorted it in ascending order above, so this + // is the time furthest back + $first = $this->_first_article_by_date($group, $hash[0]['ref']); + if ($first === false) { + continue; + } + } - // Select Group - while($fetch_okay && $processed < $total) - { - try - { - // Prepare Initial Batch - if ($total > SpotNab::FETCH_USENET_BATCH) - $batch = $first + SpotNab::FETCH_USENET_BATCH; + // Group Processing Initialization + $processed = 0; + $batch = $last = intval($summary['last']); + $total = abs($last - $first); - // Batch Processing - while ($processed>=0 && $processed < $total) - { - $headers = $this->_get_headers($group, + // Select Group + while ($fetch_okay && $processed < $total) { + try { + // Prepare Initial Batch + if ($total > self::FETCH_USENET_BATCH) { + $batch = $first + self::FETCH_USENET_BATCH; + } + + // Batch Processing + while ($processed >= 0 && $processed < $total) { + $headers = $this->_get_headers($group, "$first-$batch", $retries); - if($headers === false){ - // Retry Atempts exausted - $fetch_okay = false; - break; - } + if ($headers === false) { + // Retry Atempts exausted + $fetch_okay = false; + break; + } - // Process the header batch - $saved = $this->process_comment_headers($headers, $hash); - if($saved !== false) - { - $inserted += $saved[0]; - $updated += $saved[1]; - } + // Process the header batch + $saved = $this->process_comment_headers($headers, $hash); + if ($saved !== false) { + $inserted += $saved[0]; + $updated += $saved[1]; + } - $processed += ($batch-$first); - // Increment starting index - $first += ($batch-$first); + $processed += ($batch - $first); + // Increment starting index + $first += ($batch - $first); - if ($last-$first >= SpotNab::FETCH_USENET_BATCH){ - // Fetch next batch - $batch = $first + SpotNab::FETCH_USENET_BATCH; - }else{ - $batch = $last; - } - //echo "$first-$batch, processed=$processed\n"; + if ($last - $first >= self::FETCH_USENET_BATCH) { + // Fetch next batch + $batch = $first + self::FETCH_USENET_BATCH; + } else { + $batch = $last; + } + //echo "$first-$batch, processed=$processed\n"; //print_r($headers); - } + } + } catch (\Exception $e) { + // Reset Connection + $fetch_okay = $this->_nntpReset($group); - }catch(\Exception $e){ - // Reset Connection - $fetch_okay = $this->_nntpReset($group); - - // Track retry attempts - $retries--; - if($retries <= 0){ - // Retry Atempts exausted - $fetch_okay = false; - break; - } - continue; - } - } - $this->_pdo->queryExec(sprintf('UPDATE spotnabsources SET lastarticle = %d WHERE id IN (%s)', + // Track retry attempts + $retries--; + if ($retries <= 0) { + // Retry Atempts exausted + $fetch_okay = false; + break; + } + continue; + } + } + $this->_pdo->queryExec(sprintf('UPDATE spotnabsources SET lastarticle = %d WHERE id IN (%s)', $last, - implode(",", $id_hash[$group]))); - echo "\n"; - } + implode(',', $id_hash[$group]))); + echo "\n"; + } - // Ensure We're not connected - try{$this->_nntp->doQuit();} - catch(\Exception $e) - {/* do nothing */} + // Ensure We're not connected + try { + $this->_nntp->doQuit(); + } catch (\Exception $e) {/* do nothing */ + } - return $inserted + $updated; - } + return $inserted + $updated; + } - public function processGID($limit=500, $batch=5000, $delete_broken_releases = false){ - // Process until someone presses cntrl-c + public function processGID($limit = 500, $batch = 5000, $delete_broken_releases = false) + { + // Process until someone presses cntrl-c - $processed = 0; + $processed = 0; - // We need an offset for tracking unhandled issues - $offset = 0; + // We need an offset for tracking unhandled issues + $offset = 0; - $fsql = 'SELECT id, name, guid FROM releases ' + $fsql = 'SELECT id, name, guid FROM releases ' .'WHERE gid IS NULL ORDER BY adddate DESC LIMIT %d,%d'; - $usql = "UPDATE releases SET gid = '%s' WHERE id = %d"; + $usql = "UPDATE releases SET gid = '%s' WHERE id = %d"; - while(1){ - // finish - if($limit > 0 && $processed >= $limit) - break; - $batch=($limit > 0 && $batch > $limit)?$limit:$batch; - $res = $this->_pdo->query(sprintf($fsql, $offset, $batch)); - if(!$res)break; - if(count($res) <= 0)break; - $offset += $batch; + while (1) { + // finish + if ($limit > 0 && $processed >= $limit) { + break; + } + $batch = ($limit > 0 && $batch > $limit) ? $limit : $batch; + $res = $this->_pdo->query(sprintf($fsql, $offset, $batch)); + if (! $res) { + break; + } + if (count($res) <= 0) { + break; + } + $offset += $batch; - foreach ($res as $r){ - $nzbfile = $this->nzb->getNZBPath($r["guid"]); - if($nzbfile === NULL){ - continue; - } + foreach ($res as $r) { + $nzbfile = $this->nzb->getNZBPath($r['guid']); + if ($nzbfile === null) { + continue; + } - $nzbInfo = new NZBInfo(); - if (!$nzbInfo->loadFromFile($nzbfile)) - { - if($delete_broken_releases){ - $this->releases->deleteSingle(['g' => $r['guid'], 'i' => $r['id']], $this->nzb, $this->releaseImage); - // Free the variable in an attempt to recover memory - echo '-'; - }else{ - // Skip over this one for future fetches - $offset++; - } - continue; - } - $gid = false; - if (!empty($nzbInfo->gid)) - $gid = $nzbInfo->gid; - // Free the variable in an attempt to recover memory - unset($nzbInfo); + $nzbInfo = new NZBInfo(); + if (! $nzbInfo->loadFromFile($nzbfile)) { + if ($delete_broken_releases) { + $this->releases->deleteSingle(['g' => $r['guid'], 'i' => $r['id']], $this->nzb, $this->releaseImage); + // Free the variable in an attempt to recover memory + echo '-'; + } else { + // Skip over this one for future fetches + $offset++; + } + continue; + } + $gid = false; + if (! empty($nzbInfo->gid)) { + $gid = $nzbInfo->gid; + } + // Free the variable in an attempt to recover memory + unset($nzbInfo); - if(!$gid){ - if($delete_broken_releases){ - $this->releases->deleteSingle(['g' => $r['guid'], 'i' => $r['id']], $this->nzb, $this->releaseImage); - echo '-'; - }else{ - // Skip over this one for future fetches - $offset++; - } - continue; - } + if (! $gid) { + if ($delete_broken_releases) { + $this->releases->deleteSingle(['g' => $r['guid'], 'i' => $r['id']], $this->nzb, $this->releaseImage); + echo '-'; + } else { + // Skip over this one for future fetches + $offset++; + } + continue; + } - // Update DB With Global Identifer - $ures = $this->_pdo->queryExec(sprintf("UPDATE releases SET gid = %s WHERE id = %d", $this->_pdo->escapeString($gid), $r['id'])); - if($ures->rowCount() == 0){ - printf("\nPostPrc : Failed to update: %s\n", $r['name']); - } - // make noise... - echo '.'; - $processed += 1; - } - } + // Update DB With Global Identifer + $ures = $this->_pdo->queryExec(sprintf('UPDATE releases SET gid = %s WHERE id = %d', $this->_pdo->escapeString($gid), $r['id'])); + if ($ures->rowCount() == 0) { + printf("\nPostPrc : Failed to update: %s\n", $r['name']); + } + // make noise... + echo '.'; + $processed += 1; + } + } - $affected = $this->_pdo->queryExec(sprintf('UPDATE release_comments, releases SET release_comments.gid = UNHEX(releases.nzb_guid), + $affected = $this->_pdo->queryExec(sprintf('UPDATE release_comments, releases SET release_comments.gid = UNHEX(releases.nzb_guid), release_comments.nzb_guid = UNHEX(releases.nzb_guid) WHERE releases.id = release_comments.releases_id AND release_comments.gid IS NULL @@ -903,479 +929,494 @@ class SpotNab { AND releases.gid IS NOT NULL ' ) ); - $rows = $affected->rowCount(); - if($rows > 0) - $processed += $rows; - return $processed; - } + $rows = $affected->rowCount(); + if ($rows > 0) { + $processed += $rows; + } - // *********************************************************************** - public function keygen($print = true, $force_regen = false){ - // Simply generate a Public/Private Key pair if they don't already - // exist + return $processed; + } - // A small boolean we safely toggle after performing - // a few checks first to make sure it's safe to do so - $do_keygen = true; + // *********************************************************************** + public function keygen($print = true, $force_regen = false) + { + // Simply generate a Public/Private Key pair if they don't already + // exist - if($force_regen === false){ - // Not forcing, so we immediately toggle the keygen - // flag, we'll toggle it back if we feel the need - $do_keygen = false; + // A small boolean we safely toggle after performing + // a few checks first to make sure it's safe to do so + $do_keygen = true; - if($this->_ssl_pubkey && $this->_ssl_prvkey){ + if ($force_regen === false) { + // Not forcing, so we immediately toggle the keygen + // flag, we'll toggle it back if we feel the need + $do_keygen = false; - $str_in = $this->getRandomStr(80); - $str_out = $this->decrypt($this->encrypt($str_in)); + if ($this->_ssl_pubkey && $this->_ssl_prvkey) { + $str_in = $this->getRandomStr(80); + $str_out = $this->decrypt($this->encrypt($str_in)); - if($str_in != $str_out){ - // Our key isn't good for nothin... - // regen a new one - $do_keygen = true; - } - } - } + if ($str_in != $str_out) { + // Our key isn't good for nothin... + // regen a new one + $do_keygen = true; + } + } + } - if($do_keygen) - { - // Set new Key - $keys = $this->_keygen(); - if(is_array($keys)){ - // Force New Username - $sql = sprintf("Update settings SET value = %s " + if ($do_keygen) { + // Set new Key + $keys = $this->_keygen(); + if (is_array($keys)) { + // Force New Username + $sql = sprintf('Update settings SET value = %s ' ."WHERE setting = 'spotnabuser'", - $this->_pdo->escapeString(sprintf("nntp-%s",substr(md5($keys['pubkey']), 0, 4)))); - $this->_pdo->queryExec($sql); - // Force New Email - $sql = sprintf("Update settings SET value = %s " + $this->_pdo->escapeString(sprintf('nntp-%s', substr(md5($keys['pubkey']), 0, 4)))); + $this->_pdo->queryExec($sql); + // Force New Email + $sql = sprintf('Update settings SET value = %s ' ."WHERE setting = 'spotnabemail'", - $this->_pdo->escapeString(sprintf("nntp-%s@%s.com", + $this->_pdo->escapeString(sprintf('nntp-%s@%s.com', substr(md5($keys['pubkey']), 4, 8), substr(md5($keys['pubkey']), 8, 16) ))); - $this->_pdo->queryExec($sql); - // Save Keys - $sql = sprintf("Update settings SET value = %s ". + $this->_pdo->queryExec($sql); + // Save Keys + $sql = sprintf('Update settings SET value = %s '. "WHERE setting = 'spotnabsitepubkey'", $this->_pdo->escapeString($keys['pubkey'])); - $this->_pdo->queryExec($sql); - //echo $keys['pubkey']."\n"; + $this->_pdo->queryExec($sql); + //echo $keys['pubkey']."\n"; - $sql = sprintf("Update settings SET value = %s ". + $sql = sprintf('Update settings SET value = %s '. "WHERE setting = 'spotnabsiteprvkey'", $this->_pdo->escapeString($keys['prvkey'])); - $this->_pdo->queryExec($sql); + $this->_pdo->queryExec($sql); - // Update settings Information - $this->_post_user = trim($this->_pdo->getSetting('spotnabuser')); - $this->_post_email = trim($this->_pdo->getSetting('spotnabemail')); - $this->_ssl_pubkey = $this->decompstr($this->_pdo->getSetting('spotnabsitepubkey')); - $this->_ssl_prvkey = $this->decompstr($this->_pdo->getSetting('spotnabsiteprvkey')); - }else{ - // echo "Failed."; - return false; - } - } + // Update settings Information + $this->_post_user = trim($this->_pdo->getSetting('spotnabuser')); + $this->_post_email = trim($this->_pdo->getSetting('spotnabemail')); + $this->_ssl_pubkey = $this->decompstr($this->_pdo->getSetting('spotnabsitepubkey')); + $this->_ssl_prvkey = $this->decompstr($this->_pdo->getSetting('spotnabsiteprvkey')); + } else { + // echo "Failed."; + return false; + } + } - if($print){ - printf("SPOTNAB USER : %s\n", $this->_post_user); - printf("SPOTNAB EMAIL : %s\n", $this->_post_email); - printf("SPOTNAB GROUP : %s\n", $this->_post_group); - printf("SPOTNAB PUBLIC KEY (Begin copy from next line):\n%s\n", + if ($print) { + printf("SPOTNAB USER : %s\n", $this->_post_user); + printf("SPOTNAB EMAIL : %s\n", $this->_post_email); + printf("SPOTNAB GROUP : %s\n", $this->_post_group); + printf("SPOTNAB PUBLIC KEY (Begin copy from next line):\n%s\n", $this->_pdo->getSetting('spotnabsitepubkey')); - } + } - return [ + return [ 'pubkey' => $this->_pdo->getSetting('spotnabsitepubkey'), - 'prvkey' => $this->_pdo->getSetting('spotnabsiteprvkey') + 'prvkey' => $this->_pdo->getSetting('spotnabsiteprvkey'), ]; - } + } - // *********************************************************************** - protected function _first_article_by_date($group, $refdate, $limit = SpotNab::FETCH_MAXIMUM_HEADERS, $retries=3){ - // fetches the first article starting at the time specified - // by ref time. - // - // ref time is expected to be a local time in format: - // YYYY-MM-DD hh:mm:ss or as integer - // - // This function returns the first message id to scan from - // based on the time specified. If no articles are found - // or something bad happens, false is returned. + // *********************************************************************** + protected function _first_article_by_date($group, $refdate, $limit = self::FETCH_MAXIMUM_HEADERS, $retries = 3) + { + // fetches the first article starting at the time specified + // by ref time. + // + // ref time is expected to be a local time in format: + // YYYY-MM-DD hh:mm:ss or as integer + // + // This function returns the first message id to scan from + // based on the time specified. If no articles are found + // or something bad happens, false is returned. - $interval = 1; + $interval = 1; - // if we start charting into an area where retention period - // isn't present, we're dealing with a blank/dead record that - // is lost.... to many blanks and we have to abort. - $misses = 0; + // if we start charting into an area where retention period + // isn't present, we're dealing with a blank/dead record that + // is lost.... to many blanks and we have to abort. + $misses = 0; - // curfews are a way of not letting an infinit while - // loop from taking over while we hunt for a date... - // since usenet is not always listed chronologically - // we can get in endless loops trying to find the ealiest - // date. To handle that we set a curfew and drop back - // a set amount of records and work with that - // no one is perfect right? - $curfew = 10; + // curfews are a way of not letting an infinit while + // loop from taking over while we hunt for a date... + // since usenet is not always listed chronologically + // we can get in endless loops trying to find the ealiest + // date. To handle that we set a curfew and drop back + // a set amount of records and work with that + // no one is perfect right? + $curfew = 10; - if(is_string($refdate)){ - // Convert to Integer (Local Time) - $refdate = strtotime($refdate); - } + if (is_string($refdate)) { + // Convert to Integer (Local Time) + $refdate = strtotime($refdate); + } - while(($retries > 0) && ($interval > 0)){ - $summary = $this->_nntp->selectGroup($group); + while (($retries > 0) && ($interval > 0)) { + $summary = $this->_nntp->selectGroup($group); - $_last = $last = intval($summary['last']); - $first = intval($summary['first']); + $_last = $last = intval($summary['last']); + $first = intval($summary['first']); - $curdate = $lastdate = NULL; - $curid = $lastid = $first; - $interval = 0; - while($retries > 0){ + $curdate = $lastdate = null; + $curid = $lastid = $first; + $interval = 0; + while ($retries > 0) { // Save Last Interval - $lastinterval = $interval; + $lastinterval = $interval; - // Adjust Interval - if(($last - $first) > 3) - $interval = floor(($last - $first)/2); - else - $interval = 1; + // Adjust Interval + if (($last - $first) > 3) { + $interval = floor(($last - $first) / 2); + } else { + $interval = 1; + } - if($misses >= SpotNab::FETCH_MAX_MISSES){ - // Misses reached - $last = intval($summary['last']); - // Adjust pointer - $lastid = ($lastid=== false)?$first:$lastid; - if($lastid >0){ - if (($last-$lastid) > $limit){ - // We exceeded our maximum header limit - // adjust accordingly - $lastid = $last - $limit; - } - echo " ".(abs($last-$lastid))." record(s) back."; - return $lastid; - }else{ - if (($_last-$last) > $limit){ - // We exceeded our maximum header limit - // adjust accordingly - $last = $_last - $limit; - } - echo " ".(abs($_last-$last))." record(s) back."; - return $last; - } - } + if ($misses >= self::FETCH_MAX_MISSES) { + // Misses reached + $last = intval($summary['last']); + // Adjust pointer + $lastid = ($lastid === false) ? $first : $lastid; + if ($lastid > 0) { + if (($last - $lastid) > $limit) { + // We exceeded our maximum header limit + // adjust accordingly + $lastid = $last - $limit; + } + echo ' '.(abs($last - $lastid)).' record(s) back.'; - // Swap - $lastdate = $curdate; - if($curid > 0) - $lastid = $curid; + return $lastid; + } else { + if (($_last - $last) > $limit) { + // We exceeded our maximum header limit + // adjust accordingly + $last = $_last - $limit; + } + echo ' '.(abs($_last - $last)).' record(s) back.'; - $msgs = $this->_get_headers( - $group, ($last-$interval), $retries); + return $last; + } + } - if($msgs === false){ - if (($_last-$last) > $limit){ - // We exceeded our maximum header limit - // adjust accordingly - $last = $_last - $limit; - } - echo " ".(abs($_last-$last))." record(s) back."; - return $last; - } + // Swap + $lastdate = $curdate; + if ($curid > 0) { + $lastid = $curid; + } - // Reset Miss Count - $misses = 0; + $msgs = $this->_get_headers( + $group, ($last - $interval), $retries); - // Save Tracker - $curdate = strtotime($msgs[0]['Date']); - $curid = intval($msgs[0]['Number']); - if($curid <= 0){ - $lastid = ($lastid=== false)?$first:$lastid; - if($lastid >0){ - if (($_last-$lastid) > $limit){ - // We exceeded our maximum header limit - // adjust accordingly - $lastid = $_last - $limit; - } - echo " ".(abs($_last-$lastid))." record(s) back."; - return $lastid; - }else{ - if (($_last-$last) > $limit){ - // We exceeded our maximum header limit - // adjust accordingly - $last = $_last - $limit; - } - echo " ".(abs($_last-$last))." record(s) back."; - return $last; - } - } + if ($msgs === false) { + if (($_last - $last) > $limit) { + // We exceeded our maximum header limit + // adjust accordingly + $last = $_last - $limit; + } + echo ' '.(abs($_last - $last)).' record(s) back.'; - if($interval == 1){ - // We're soo close now... - $curfew --; - if($curfew <= 0) - { - if (($_last-$curid) > $limit){ - // We exceeded our maximum header limit - // adjust accordingly - $curid = $_last - $limit; - } - // curfew met... just deal with our current spot - echo " ".($_last-$curid)." record(s) back."; - return $curid; - } + return $last; + } - if($refdate > $curdate && $refdate > $lastdate){ - if (($_last-$curid) > $limit){ - // We exceeded our maximum header limit - // adjust accordingly - $curid = $_last - $limit; - } - // Found content - echo " ".($_last-$curid)." record(s) back."; - return $curid; - }else if($refdate > $curdate && $refdate > $lastdate){ - // Close... Shuffle forward a bit - $first+=2; - }else{ - // Slide window and try again - $last-=2; - } - $interval=2; - continue; - } + // Reset Miss Count + $misses = 0; - // Make some noise - if($interval%2)echo "."; + // Save Tracker + $curdate = strtotime($msgs[0]['Date']); + $curid = intval($msgs[0]['Number']); + if ($curid <= 0) { + $lastid = ($lastid === false) ? $first : $lastid; + if ($lastid > 0) { + if (($_last - $lastid) > $limit) { + // We exceeded our maximum header limit + // adjust accordingly + $lastid = $_last - $limit; + } + echo ' '.(abs($_last - $lastid)).' record(s) back.'; - // Adjust Boundaries - if($curdate > $refdate){ - // We need to look further forward - $last = $curid+1; - }else if ($curdate <= $refdate){ - // We need To look further back - $first = $curid-1; - } - } - } - //echo "n/a m:$misses,i:$interval\n"; - return false; - } + return $lastid; + } else { + if (($_last - $last) > $limit) { + // We exceeded our maximum header limit + // adjust accordingly + $last = $_last - $limit; + } + echo ' '.(abs($_last - $last)).' record(s) back.'; - // *********************************************************************** - public function process_comment_headers($headers, $group_hash, $save = true){ - /* - * We iterate over the provided headers (generated by - * $this->_get_headers() to a structure that is at the very - * minimum looking like this: - * - * array ( - * [0] => array ( - * 'Number': <int> - * 'Subject': <string> - * 'From': <string> - * 'Date': <string> - * 'Message-ID': <string> - * 'Bytes': <int> - * 'Lines': <int> - * 'Epoch': <int> - * ), - * ... - * ) - * From the structure above, we process our group hash and retrieve - * all the binary data we need on valid content. - * - * A group_hash() record looks like this: - * array( - * array( - * 'id': <int>, - * 'key': <string>, - * 'user': <string>, - * 'email': <string>, - * 'ref': <int>, - * ), - * array( - * 'id': <int>, - * 'key': <string>, - * 'user': <string>, - * 'email': <string>, - * 'ref': <int>, - * ), - * ) - */ + return $last; + } + } - if(!count($group_hash)){ - // Nothing to process - return []; - } + if ($interval == 1) { + // We're soo close now... + $curfew--; + if ($curfew <= 0) { + if (($_last - $curid) > $limit) { + // We exceeded our maximum header limit + // adjust accordingly + $curid = $_last - $limit; + } + // curfew met... just deal with our current spot + echo ' '.($_last - $curid).' record(s) back.'; - // - // Prepare some general SQL Commands for saving later if all goes well - // + return $curid; + } + if ($refdate > $curdate && $refdate > $lastdate) { + if (($_last - $curid) > $limit) { + // We exceeded our maximum header limit + // adjust accordingly + $curid = $_last - $limit; + } + // Found content + echo ' '.($_last - $curid).' record(s) back.'; - // Comments - $sql_new_cmt = "INSERT INTO release_comments (". - "id, sourceid, username, users_id, gid, cid, isvisible, ". - "releases_id, text, createddate, issynced, nzb_guid) VALUES (". - "NULL, %d, %s, 0, %s, %s, %d, 0, %s, %s, 1, UNHEX(%s))"; - $sql_upd_cmt = "UPDATE release_comments SET ". - "isvisible = %d, text = %s". - "WHERE sourceid = %d AND gid = %s AND cid = %s AND nzb_guid = UNHEX(%s)"; - $sql_fnd_cmt = "SELECT count(id) as cnt FROM release_comments ". - "WHERE sourceid = %d AND gid = %s AND cid = %s"; + return $curid; + } elseif ($refdate > $curdate && $refdate > $lastdate) { + // Close... Shuffle forward a bit + $first += 2; + } else { + // Slide window and try again + $last -= 2; + } + $interval = 2; + continue; + } - // Sync Times - $sql_sync = "UPDATE spotnabsources SET lastupdate = %s ". - "WHERE id = %d"; + // Make some noise + if ($interval % 2) { + echo '.'; + } - $matches = NULL; - $processed = 0; - $updates = 0; - $inserts = 0; - foreach ($headers as $header){ - // Preform some general scanning the header to determine - // if it could possibly be a valid post. - if(!preg_match(SpotNab::FETCH_MSGID_REGEX, - $header['Message-ID'], $matches)){ - continue; - } - if($matches['domain'] != SpotNab::SEGID_DOMAIN) - continue; + // Adjust Boundaries + if ($curdate > $refdate) { + // We need to look further forward + $last = $curid + 1; + } elseif ($curdate <= $refdate) { + // We need To look further back + $first = $curid - 1; + } + } + } + //echo "n/a m:$misses,i:$interval\n"; + return false; + } - if($matches['type'] != SpotNab::FETCH_COMMENT_TYPE) - continue; + // *********************************************************************** + public function process_comment_headers($headers, $group_hash, $save = true) + { + /* + * We iterate over the provided headers (generated by + * $this->_get_headers() to a structure that is at the very + * minimum looking like this: + * + * array ( + * [0] => array ( + * 'Number': <int> + * 'Subject': <string> + * 'From': <string> + * 'Date': <string> + * 'Message-ID': <string> + * 'Bytes': <int> + * 'Lines': <int> + * 'Epoch': <int> + * ), + * ... + * ) + * From the structure above, we process our group hash and retrieve + * all the binary data we need on valid content. + * + * A group_hash() record looks like this: + * array( + * array( + * 'id': <int>, + * 'key': <string>, + * 'user': <string>, + * 'email': <string>, + * 'ref': <int>, + * ), + * array( + * 'id': <int>, + * 'key': <string>, + * 'user': <string>, + * 'email': <string>, + * 'ref': <int>, + * ), + * ) + */ - // Now we check the subject line; it provides the first part of - // the key to determining if we should handle the message or not - if(!preg_match(SpotNab::FETCH_COMMENT_SUBJECT_REGEX, - $header['Subject'], $matches)){ - continue; - } + if (! count($group_hash)) { + // Nothing to process + return []; + } - // We have a match; So populate potential variables - $checksum = $matches['checksum']; - $refdate = $matches['utcref']; - $refdate_epoch = @strtotime($matches['utcref']. " UTC"); - if($refdate_epoch === false || $refdate_epoch < 0){ - // Bad time specified - continue; - } - // PreKey is used to attempt to run the decode algorithm - // a head of time.. if we can decrypt this we can probably - // assume the body will decode too (and won't be a waste of - // time to download it) + // + // Prepare some general SQL Commands for saving later if all goes well + // - foreach($group_hash as $hash){ - // Track how many records we handled - $processed++; + // Comments + $sql_new_cmt = 'INSERT INTO release_comments ('. + 'id, sourceid, username, users_id, gid, cid, isvisible, '. + 'releases_id, text, createddate, issynced, nzb_guid) VALUES ('. + 'NULL, %d, %s, 0, %s, %s, %d, 0, %s, %s, 1, UNHEX(%s))'; + $sql_upd_cmt = 'UPDATE release_comments SET '. + 'isvisible = %d, text = %s'. + 'WHERE sourceid = %d AND gid = %s AND cid = %s AND nzb_guid = UNHEX(%s)'; + $sql_fnd_cmt = 'SELECT count(id) as cnt FROM release_comments '. + 'WHERE sourceid = %d AND gid = %s AND cid = %s'; - // First check the ref date... if it's newer then what we've - // already processed, then we'll just keep on chugging along. - if($refdate_epoch <= $hash['ref']){ - continue; - } + // Sync Times + $sql_sync = 'UPDATE spotnabsources SET lastupdate = %s '. + 'WHERE id = %d'; - // Scan header information for supported matches - if(!preg_match('/^(?P<user>[^<]+)<(?P<email>[^>]+)>$/', - $header['From'], $matches)) - continue; + $matches = null; + $processed = 0; + $updates = 0; + $inserts = 0; + foreach ($headers as $header) { + // Preform some general scanning the header to determine + // if it could possibly be a valid post. + if (! preg_match(self::FETCH_MSGID_REGEX, + $header['Message-ID'], $matches)) { + continue; + } + if ($matches['domain'] != self::SEGID_DOMAIN) { + continue; + } - // Match against our sources posts - if(trim($matches['user']) != $hash['user']) { - continue; - } - if(trim($matches['email']) != $hash['email']) { - continue; - } + if ($matches['type'] != self::FETCH_COMMENT_TYPE) { + continue; + } - // If we reach here, we've found a header we can process - // The next step is to download the header's body + // Now we check the subject line; it provides the first part of + // the key to determining if we should handle the message or not + if (! preg_match(self::FETCH_COMMENT_SUBJECT_REGEX, + $header['Subject'], $matches)) { + continue; + } - // We'll do some final verifications on it such as detect - // if the checksum is okay, and verify that the timestamp - // within the body matches that of the header... then we - // can start processing the guts of the body. + // We have a match; So populate potential variables + $checksum = $matches['checksum']; + $refdate = $matches['utcref']; + $refdate_epoch = @strtotime($matches['utcref'].' UTC'); + if ($refdate_epoch === false || $refdate_epoch < 0) { + // Bad time specified + continue; + } + // PreKey is used to attempt to run the decode algorithm + // a head of time.. if we can decrypt this we can probably + // assume the body will decode too (and won't be a waste of + // time to download it) - if($save) { - // Download Body - $body = $this->_get_body($header['Group'], $header['Message-ID']); - if($body === false) { - continue; - } + foreach ($group_hash as $hash) { + // Track how many records we handled + $processed++; - // Decode Body - $body = $this->decodePost($body, $hash['key']); - if($body === false) { - continue; // Decode failed - } + // First check the ref date... if it's newer then what we've + // already processed, then we'll just keep on chugging along. + if ($refdate_epoch <= $hash['ref']) { + continue; + } - // Verify Body - if(!is_array($body)) { - continue; // not any array - } + // Scan header information for supported matches + if (! preg_match('/^(?P<user>[^<]+)<(?P<email>[^>]+)>$/', + $header['From'], $matches)) { + continue; + } - if(!(bool)count(array_filter(array_keys($body), 'is_string'))) { - continue; // not an associative array - } + // Match against our sources posts + if (trim($matches['user']) != $hash['user']) { + continue; + } + if (trim($matches['email']) != $hash['email']) { + continue; + } - if((!array_key_exists('server', $body)) || (!array_key_exists('postdate_utc', $body))) { - continue; // base structure missing - } + // If we reach here, we've found a header we can process + // The next step is to download the header's body - // Compare postdate_utc and ensure it matches header - // timestamp - if(preg_replace('/[^0-9]/', '', $body['postdate_utc']) != $refdate) { - continue; - } + // We'll do some final verifications on it such as detect + // if the checksum is okay, and verify that the timestamp + // within the body matches that of the header... then we + // can start processing the guts of the body. - // Comment Handling - if(array_key_exists('comments',$body) && is_array($body['comments'])) { - $rc = new ReleaseComments(); + if ($save) { + // Download Body + $body = $this->_get_body($header['Group'], $header['Message-ID']); + if ($body === false) { + continue; + } - foreach($body['comments'] as $comment){ + // Decode Body + $body = $this->decodePost($body, $hash['key']); + if ($body === false) { + continue; // Decode failed + } + + // Verify Body + if (! is_array($body)) { + continue; // not any array + } + + if (! (bool) count(array_filter(array_keys($body), 'is_string'))) { + continue; // not an associative array + } + + if ((! array_key_exists('server', $body)) || (! array_key_exists('postdate_utc', $body))) { + continue; // base structure missing + } + + // Compare postdate_utc and ensure it matches header + // timestamp + if (preg_replace('/[^0-9]/', '', $body['postdate_utc']) != $refdate) { + continue; + } + + // Comment Handling + if (array_key_exists('comments', $body) && is_array($body['comments'])) { + $rc = new ReleaseComments(); + + foreach ($body['comments'] as $comment) { // Verify Comment is parseable - if(!is_array($comment)) { - continue; // not an array - } - if(!count(array_filter(array_keys($comment)))) { - continue; // not an associative array - } + if (! is_array($comment)) { + continue; // not an array + } + if (! count(array_filter(array_keys($comment)))) { + continue; // not an associative array + } - // Store isvisible flag - $is_visible = 1; - if(array_key_exists('is_visible', $comment)) { - $is_visible = (intval($comment['is_visible']) > 0) ? 1 : 0; - } + // Store isvisible flag + $is_visible = 1; + if (array_key_exists('is_visible', $comment)) { + $is_visible = (intval($comment['is_visible']) > 0) ? 1 : 0; + } - // Check that comment doesn't already exist - $res = $this->_pdo->queryOneRow(sprintf( + // Check that comment doesn't already exist + $res = $this->_pdo->queryOneRow(sprintf( $sql_fnd_cmt, $hash['id'], $this->_pdo->escapeString($comment['gid']), $this->_pdo->escapeString($comment['cid']))); - // Store Results in DB - if($res && intval($res['cnt'])>0) { - // Make some noise - echo '.'; - $updates += ($this->_pdo->queryExec(sprintf($sql_upd_cmt, + // Store Results in DB + if ($res && intval($res['cnt']) > 0) { + // Make some noise + echo '.'; + $updates += ($this->_pdo->queryExec(sprintf($sql_upd_cmt, $is_visible, $this->_pdo->escapeString($comment['comment']), $hash['id'], $this->_pdo->escapeString($comment['gid']), $this->_pdo->escapeString($comment['cid']), $this->_pdo->escapeString($comment['gid']) - ))>0)?1:0; - } else { - // Make some noise - echo '+'; - // Perform Insert - $res = $this->_pdo->queryInsert(sprintf($sql_new_cmt, + )) > 0) ? 1 : 0; + } else { + // Make some noise + echo '+'; + // Perform Insert + $res = $this->_pdo->queryInsert(sprintf($sql_new_cmt, $hash['id'], $this->_pdo->escapeString($comment['username']), $this->_pdo->escapeString($comment['gid']), @@ -1387,202 +1428,217 @@ class SpotNab { $comment['postdate_utc'])), $this->_pdo->escapeString($comment['gid']) )); - $inserts += 1; - } - $rc->updateReleaseCommentCount($comment['gid']); - } - } + $inserts += 1; + } + $rc->updateReleaseCommentCount($comment['gid']); + } + } - // Update spotnabsources table, set lastupdate to the - // timestamp parsed from the header. - $this->_pdo->queryExec(sprintf($sql_sync, + // Update spotnabsources table, set lastupdate to the + // timestamp parsed from the header. + $this->_pdo->queryExec(sprintf($sql_sync, $this->_pdo->escapeString($this->utc2local($body['postdate_utc'])), $hash['id'] ) ); - }else{ - // Debug non/save mode; mark update - $updates += 1; - } + } else { + // Debug non/save mode; mark update + $updates += 1; + } - // always break if we made it this far... no mater how many - // other groups are being processed, we've already matched - // for this article, so we don't need to process it for - // other sources. - break; - } - } - return [$inserts, $updates]; - } + // always break if we made it this far... no mater how many + // other groups are being processed, we've already matched + // for this article, so we don't need to process it for + // other sources. + break; + } + } - // *********************************************************************** - public function process_discovery_headers($headers, $save = true){ - /* - * We iterate over the provided headers (generated by - * $this->_get_headers() to a structure that is at the very - * minimum looking like this: - * - * array ( - * [0] => array ( - * 'Number': <int> - * 'Subject': <string> - * 'From': <string> - * 'Date': <string> - * 'Message-ID': <string> - * 'Bytes': <int> - * 'Lines': <int> - * 'Epoch': <int> - * ), - * ... - * ) - */ + return [$inserts, $updates]; + } - // - // Prepare some general SQL Commands for saving later if all goes well - // + // *********************************************************************** + public function process_discovery_headers($headers, $save = true) + { + /* + * We iterate over the provided headers (generated by + * $this->_get_headers() to a structure that is at the very + * minimum looking like this: + * + * array ( + * [0] => array ( + * 'Number': <int> + * 'Subject': <string> + * 'From': <string> + * 'Date': <string> + * 'Message-ID': <string> + * 'Bytes': <int> + * 'Lines': <int> + * 'Epoch': <int> + * ), + * ... + * ) + */ - // Auto Enable Flag (used for inserts only) - $auto_enable = ($this->_auto_enable)?"1":"0"; + // + // Prepare some general SQL Commands for saving later if all goes well + // - // Spotnab Sources - $sql_new_cmt = "INSERT INTO spotnabsources (". - "id, username, useremail, usenetgroup, publickey, ". - "active, description, lastupdate, lastbroadcast, dateadded) VALUES (". + // Auto Enable Flag (used for inserts only) + $auto_enable = ($this->_auto_enable) ? '1' : '0'; + + // Spotnab Sources + $sql_new_cmt = 'INSERT INTO spotnabsources ('. + 'id, username, useremail, usenetgroup, publickey, '. + 'active, description, lastupdate, lastbroadcast, dateadded) VALUES ('. "NULL, %s, %s, %s, %s, $auto_enable, %s, NULL, %s, NOW())"; - $sql_upd_cmt = "UPDATE spotnabsources SET ". - "lastbroadcast = %s ". - "WHERE username = %s AND useremail = %s AND usenetgroup = %s"; - $sql_fnd_cmt = "SELECT count(id) as cnt FROM spotnabsources ". - "WHERE username = %s AND useremail = %s AND usenetgroup = %s"; + $sql_upd_cmt = 'UPDATE spotnabsources SET '. + 'lastbroadcast = %s '. + 'WHERE username = %s AND useremail = %s AND usenetgroup = %s'; + $sql_fnd_cmt = 'SELECT count(id) as cnt FROM spotnabsources '. + 'WHERE username = %s AND useremail = %s AND usenetgroup = %s'; - $matches = NULL; - $processed = 0; - $inserts = 0; - $updates = 0; - foreach ($headers as $header){ - // Preform some general scanning the header to determine - // if it could possibly be a valid post. + $matches = null; + $processed = 0; + $inserts = 0; + $updates = 0; + foreach ($headers as $header) { + // Preform some general scanning the header to determine + // if it could possibly be a valid post. - // Now we check the subject line; it provides the first part of - // the key to determining if we should handle the message or not - if(!preg_match(SpotNab::FETCH_MSGID_REGEX, - $header['Message-ID'], $matches)){ - continue; - } - if($matches['domain'] != SpotNab::SEGID_DOMAIN) - continue; + // Now we check the subject line; it provides the first part of + // the key to determining if we should handle the message or not + if (! preg_match(self::FETCH_MSGID_REGEX, + $header['Message-ID'], $matches)) { + continue; + } + if ($matches['domain'] != self::SEGID_DOMAIN) { + continue; + } - if($matches['type'] != SpotNab::FETCH_DISCOVERY_TYPE) - continue; + if ($matches['type'] != self::FETCH_DISCOVERY_TYPE) { + continue; + } - // Now we check the subject line; it provides the first part of - // the key to determining if we should handle the message or not - if(!preg_match(SpotNab::FETCH_DISCOVERY_SUBJECT_REGEX, - $header['Subject'], $matches)){ - continue; - } + // Now we check the subject line; it provides the first part of + // the key to determining if we should handle the message or not + if (! preg_match(self::FETCH_DISCOVERY_SUBJECT_REGEX, + $header['Subject'], $matches)) { + continue; + } - // We have a match; So populate potential variables - $checksum = $matches['checksum']; - $refdate = $matches['utcref']; - $refdate_epoch = @strtotime($matches['utcref']. " UTC"); - if($refdate_epoch === false || $refdate_epoch < 0){ - // Bad time specified - continue; - } - // PreKey is used to attempt to run the decode algorithm - // a head of time.. if we can decrypt this we can probably - // assume the body will decode too (and won't be a waste of - // time to download it) + // We have a match; So populate potential variables + $checksum = $matches['checksum']; + $refdate = $matches['utcref']; + $refdate_epoch = @strtotime($matches['utcref'].' UTC'); + if ($refdate_epoch === false || $refdate_epoch < 0) { + // Bad time specified + continue; + } + // PreKey is used to attempt to run the decode algorithm + // a head of time.. if we can decrypt this we can probably + // assume the body will decode too (and won't be a waste of + // time to download it) - // Track how many records we handled - $processed++; + // Track how many records we handled + $processed++; - // Scan header information for supported matches - if(!preg_match('/^(?P<user>[^<]+)<(?P<email>[^>]+)>$/', - $header['From'], $matches)) - continue; + // Scan header information for supported matches + if (! preg_match('/^(?P<user>[^<]+)<(?P<email>[^>]+)>$/', + $header['From'], $matches)) { + continue; + } - // Match against our sources posts - if(trim($matches['user']) != SpotNab::AUTODISCOVER_POST_USER) - continue; - if(trim($matches['email']) != SpotNab::AUTODISCOVER_POST_EMAIL) - continue; + // Match against our sources posts + if (trim($matches['user']) != self::AUTODISCOVER_POST_USER) { + continue; + } + if (trim($matches['email']) != self::AUTODISCOVER_POST_EMAIL) { + continue; + } - // If we reach here, we've found a header we can process - // The next step is to download the header's body + // If we reach here, we've found a header we can process + // The next step is to download the header's body - // We'll do some final verifications on it such as detect - // if the checksum is okay, and verify that the timestamp - // within the body matches that of the header... then we - // can start processing the guts of the body. + // We'll do some final verifications on it such as detect + // if the checksum is okay, and verify that the timestamp + // within the body matches that of the header... then we + // can start processing the guts of the body. - if($save){ - // Download Body - $body = $this->_get_body($header['Group'], + if ($save) { + // Download Body + $body = $this->_get_body($header['Group'], $header['Message-ID']); - if($body === false){ - continue; - } + if ($body === false) { + continue; + } - // Decode Body - $body = $this->decodePost( + // Decode Body + $body = $this->decodePost( $body, $this->decompstr($this->_ssl_auto_pubkey) ); - if($body === false) - continue; // Decode failed + if ($body === false) { + continue; + } // Decode failed - // Verify Body - if(!is_array($body)) - continue; // not any array + // Verify Body + if (! is_array($body)) { + continue; + } // not any array - if(!(bool)count(array_filter(array_keys($body), 'is_string'))) - continue; // not an associative array + if (! (bool) count(array_filter(array_keys($body), 'is_string'))) { + continue; + } // not an associative array - if(!(array_key_exists('site', $body) && + if (! (array_key_exists('site', $body) && array_key_exists('posts', $body) && array_key_exists('comments', $body) && - array_key_exists('postdate_utc', $body))) - continue; // base structure missing + array_key_exists('postdate_utc', $body))) { + continue; + } // base structure missing - // Compare postdate_utc and ensure it matches header - // timestamp - if(preg_replace('/[^0-9]/', '', - $body['postdate_utc']) != $refdate) - continue; + // Compare postdate_utc and ensure it matches header + // timestamp + if (preg_replace('/[^0-9]/', '', + $body['postdate_utc']) != $refdate) { + continue; + } - $posts = $body['posts']; - $p_user = array_key_exists('user', $posts)?trim($posts['user']):NULL; - $p_email = array_key_exists('email', $posts)?trim($posts['email']):NULL; - $p_group = array_key_exists('group', $posts)?trim($posts['group']):NULL; - $p_key = array_key_exists('public_key', $posts)?trim($posts['public_key']):NULL; + $posts = $body['posts']; + $p_user = array_key_exists('user', $posts) ? trim($posts['user']) : null; + $p_email = array_key_exists('email', $posts) ? trim($posts['email']) : null; + $p_group = array_key_exists('group', $posts) ? trim($posts['group']) : null; + $p_key = array_key_exists('public_key', $posts) ? trim($posts['public_key']) : null; - if(!($p_user && $p_email && $p_group && $p_key)) - // basic error checking - continue; + if (! ($p_user && $p_email && $p_group && $p_key)) { + // basic error checking + continue; + } - // Check to make sure the discovery isn't 'this' site - if($p_user == $this->_post_user && $p_email == $this->_post_email) - continue; + // Check to make sure the discovery isn't 'this' site + if ($p_user == $this->_post_user && $p_email == $this->_post_email) { + continue; + } - // Check that comment doesn't already exist - $res = $this->_pdo->queryOneRow(sprintf($sql_fnd_cmt, + // Check that comment doesn't already exist + $res = $this->_pdo->queryOneRow(sprintf($sql_fnd_cmt, $this->_pdo->escapeString($p_user), $this->_pdo->escapeString($p_email), $this->_pdo->escapeString($p_group)) ); - if(!$res) - // Uh oh - continue; + if (! $res) { + // Uh oh + continue; + } - // Store Results in DB - if(intval($res['cnt'])==0){ - // Make some noise - echo '+'; - // Perform Insert - $res = $this->_pdo->queryInsert(sprintf($sql_new_cmt, + // Store Results in DB + if (intval($res['cnt']) == 0) { + // Make some noise + echo '+'; + // Perform Insert + $res = $this->_pdo->queryInsert(sprintf($sql_new_cmt, $this->_pdo->escapeString($p_user), $this->_pdo->escapeString($p_email), $this->_pdo->escapeString($p_group), @@ -1591,437 +1647,455 @@ class SpotNab { $this->_pdo->escapeString($p_user), $this->_pdo->escapeString($this->utc2local($refdate))) ); - $inserts += 1; - }else{ - echo '.'; - $res = $this->_pdo->queryExec(sprintf($sql_upd_cmt, + $inserts += 1; + } else { + echo '.'; + $res = $this->_pdo->queryExec(sprintf($sql_upd_cmt, $this->_pdo->escapeString($this->utc2local($refdate)), $this->_pdo->escapeString($p_user), $this->_pdo->escapeString($p_email), $this->_pdo->escapeString($p_group))); - $updates += 1; - } - } - } - return [$inserts, $updates]; - } + $updates += 1; + } + } + } - // *********************************************************************** - protected function _get_body($group, $id, $retries=3){ - /* - * Fetch the body of a given Message-ID taken from the headers - * The function then returns the raw content - */ + return [$inserts, $updates]; + } - $matches = NULL; - if(preg_match("/^\s*<(.*)>\s*$/", $id, $matches)) - // Ensure we're always dealing with a properly - // formatted id - $id = $matches[1]; + // *********************************************************************** + protected function _get_body($group, $id, $retries = 3) + { + /* + * Fetch the body of a given Message-ID taken from the headers + * The function then returns the raw content + */ - // The returned result will be stored in $raw - $raw = NULL; - do - { - $raw = $this->_nntp->getBody("<".$id.">", true); - // Retrieved Data - return $raw; - } while($retries > 0); - // Fail - return false; - } + $matches = null; + if (preg_match("/^\s*<(.*)>\s*$/", $id, $matches)) { + // Ensure we're always dealing with a properly + // formatted id + $id = $matches[1]; + } - // *********************************************************************** - protected function _get_headers($group, $range, $retries=3, $sort = true){ - /* - * - * There is to much involved with fetching article headers - * that bloat and make a lot of code repetative... - * This function returns the headers of the specified range - * in an [] of associative [] always to make life - * easy... alternativly, if this function fails then false - * is returned. - * - * We also convert all time scanned into its Epoch value - * with the returned results for easier parsing; this - * is done to order results as well. - */ + // The returned result will be stored in $raw + $raw = null; + do { + $raw = $this->_nntp->getBody('<'.$id.'>', true); + // Retrieved Data + return $raw; + } while ($retries > 0); + // Fail + return false; + } - // epoch array is used for sorting fetched results - $epoch = []; + // *********************************************************************** + protected function _get_headers($group, $range, $retries = 3, $sort = true) + { + /* + * + * There is to much involved with fetching article headers + * that bloat and make a lot of code repetative... + * This function returns the headers of the specified range + * in an [] of associative [] always to make life + * easy... alternativly, if this function fails then false + * is returned. + * + * We also convert all time scanned into its Epoch value + * with the returned results for easier parsing; this + * is done to order results as well. + */ - // Header parsing for associative array returned - $min_headers = ['Number', 'Subject', 'From', 'Date', - 'Message-ID', 'Bytes', 'Lines' + // epoch array is used for sorting fetched results + $epoch = []; + + // Header parsing for associative array returned + $min_headers = ['Number', 'Subject', 'From', 'Date', + 'Message-ID', 'Bytes', 'Lines', ]; - do - { - $msgs = $this->_nntp->getOverview($range, true, false); - // If we get here, then we fetched the header block okay + do { + $msgs = $this->_nntp->getOverview($range, true, false); + // If we get here, then we fetched the header block okay - // Clean up bad results but don't mark fetch as a failure - // just report what it found.. (nothing). We do this because - // NNTP::isError() never threw, so the response has to be valid - // even though it's inconsistent - if(!$msgs)return []; - if(!is_array($msgs))return []; + // Clean up bad results but don't mark fetch as a failure + // just report what it found.. (nothing). We do this because + // NNTP::isError() never threw, so the response has to be valid + // even though it's inconsistent + if (! $msgs) { + return []; + } + if (! is_array($msgs)) { + return []; + } - // For whatever reason, we sometimes get an array of - // associative array returned, and all other times we just - // get an associative array. Convert the associative array - // if we get one to an array of associative array just to - // simplify the response and make it esier to work with - if((bool)count(array_filter(array_keys($msgs), 'is_string'))){ - // convert to an array of assocative array - $msgs = [$msgs]; - } + // For whatever reason, we sometimes get an array of + // associative array returned, and all other times we just + // get an associative array. Convert the associative array + // if we get one to an array of associative array just to + // simplify the response and make it esier to work with + if ((bool) count(array_filter(array_keys($msgs), 'is_string'))) { + // convert to an array of assocative array + $msgs = [$msgs]; + } - for($i=0;$i<count($msgs);$i++){ - $skip = false; - foreach($min_headers as $key){ - if(!array_key_exists($key, $msgs[$i])){ - unset($msgs[$i]); - $i--; - $skip = true; - break; - } - } - if($skip)continue; + for ($i = 0; $i < count($msgs); $i++) { + $skip = false; + foreach ($min_headers as $key) { + if (! array_key_exists($key, $msgs[$i])) { + unset($msgs[$i]); + $i--; + $skip = true; + break; + } + } + if ($skip) { + continue; + } - // Update Record With Epoch Value (# of sec from Jan, 1980) - $epoch[$i] = $msgs[$i]['Epoch'] = strtotime($msgs[$i]['Date']); - // It's easier to track the group information if it's - // stored with the header segment - $epoch[$i] = $msgs[$i]['Group'] = $group; - } + // Update Record With Epoch Value (# of sec from Jan, 1980) + $epoch[$i] = $msgs[$i]['Epoch'] = strtotime($msgs[$i]['Date']); + // It's easier to track the group information if it's + // stored with the header segment + $epoch[$i] = $msgs[$i]['Group'] = $group; + } - if($sort && count($msgs)>1) - // Content is already sorted by articles, but if the - // sort flag is specified, then content is re-sorted by the - // messages stored epoch time - array_multisort($epoch, SORT_ASC, $msgs); + if ($sort && count($msgs) > 1) { + // Content is already sorted by articles, but if the + // sort flag is specified, then content is re-sorted by the + // messages stored epoch time + array_multisort($epoch, SORT_ASC, $msgs); + } - return $msgs; + return $msgs; + } while ($retries > 0); - }while($retries >0); + return false; + } - return false; - } + // *********************************************************************** + public function post($reftime = null, $retries = 3) + { + /* + * This function posts to usenet if there are any new updates + * to report that are flagged for transmit. + * + * The specified $reftime is presumed to be local *not utc* + */ - // *********************************************************************** - public function post($reftime = NULL, $retries=3){ - /* - * This function posts to usenet if there are any new updates - * to report that are flagged for transmit. - * - * The specified $reftime is presumed to be local *not utc* - */ + // Make sure we can post + if (! $this->_can_post) { + // Disabled + return false; + } - // Make sure we can post - if(!$this->_can_post){ - // Disabled - return false; - } - - $reftime_local = $reftime; - $article = NULL; - if($reftime_local === NULL){ - // Fetch local time - $reftime_local = $this->utc2local(); - } - // Header - $message = [ + $reftime_local = $reftime; + $article = null; + if ($reftime_local === null) { + // Fetch local time + $reftime_local = $this->utc2local(); + } + // Header + $message = [ 'server' => [ 'code' => $this->_post_site, 'title' => $this->_post_title, ], 'postdate_utc' => $this->local2utc($reftime_local), - 'comments' => [] + 'comments' => [], ]; - // Store Comments - while(($data = $this->unPostedComments()) !== NULL) - { - $message['comments'] = $data['comments']; - $sql = sprintf("UPDATE release_comments " - ."SET issynced = 1 WHERE id IN (%s)", - implode(",", $data['ids'])); + // Store Comments + while (($data = $this->unPostedComments()) !== null) { + $message['comments'] = $data['comments']; + $sql = sprintf('UPDATE release_comments ' + .'SET issynced = 1 WHERE id IN (%s)', + implode(',', $data['ids'])); - // Generate keys if one doesn't exist - if(!($this->_ssl_prvkey && $this->_ssl_pubkey)) - { - if($this->keygen(false, true) !== false) - // Post a discovery message if enabled - $this->post_discovery(); - else - return false; - } + // Generate keys if one doesn't exist + if (! ($this->_ssl_prvkey && $this->_ssl_pubkey)) { + if ($this->keygen(false, true) !== false) { + // Post a discovery message if enabled + $this->post_discovery(); + } else { + return false; + } + } - // Encode Message so it can be posted - $article = $this->encodePost($message, $reftime_local); - if($article === false){ - echo "Failed.\n"; - return false; - } - //echo "Done.\n"; + // Encode Message so it can be posted + $article = $this->encodePost($message, $reftime_local); + if ($article === false) { + echo "Failed.\n"; - // Post message - printf("Spotnab : %d posting ...\n", count($message['comments'])); - if (!$this->_postArticle($article, $retries)) - { - // Post is good; update database - $res = $this->_pdo->queryExec($sql); - echo "Failed.\n"; - return false; - } + return false; + } + //echo "Done.\n"; - // Update Database - $this->_pdo->queryExec($sql); - } + // Post message + printf("Spotnab : %d posting ...\n", count($message['comments'])); + if (! $this->_postArticle($article, $retries)) { + // Post is good; update database + $res = $this->_pdo->queryExec($sql); + echo "Failed.\n"; - // If code reached here then we're good - return true; - } + return false; + } - // *********************************************************************** - private function _postArticle ($article, $retries=3) - { - // Extract message id - if(!preg_match('/Message-ID: <(?P<id>[^>]+)>/', $article[0], $matches)){ - // we couldn't extract the message id - return false; - } + // Update Database + $this->_pdo->queryExec($sql); + } - $msg_id = $matches['id']; + // If code reached here then we're good + return true; + } - // Connect to server - if (($this->_pdo->getSetting('alternate_nntp') == 1 ? $this->_nntp->doConnect(true, true) : $this->_nntp->doConnect()) !== true) { - exit($this->_pdo->log->error("Unable to connect to usenet." . PHP_EOL)); - } - while($retries > 0) - { - try - { - $summary = $this->_nntp->selectGroup($this->_post_group); - if(NNTP::isError($summary)){ - $summary = $this->_nntpReset($this->_post_group); - $retries--; - continue; - } - // Check if server will receive an article - $_err = $this->_nntp->cmdPost(); - if (NNTP::isError($_err)) { - $summary = $this->_nntpReset($this->_post_group); - $retries--; - continue; - } + // *********************************************************************** + private function _postArticle($article, $retries = 3) + { + // Extract message id + if (! preg_match('/Message-ID: <(?P<id>[^>]+)>/', $article[0], $matches)) { + // we couldn't extract the message id + return false; + } - // Actually send the article - $_err = $this->_nntp->cmdPost2($article); + $msg_id = $matches['id']; - }catch(\Exception $e){ - // Ensure We're not connected - try{$this->_nntp->doQuit();} - catch(\Exception $e) - {/* do nothing */} + // Connect to server + if (($this->_pdo->getSetting('alternate_nntp') == 1 ? $this->_nntp->doConnect(true, true) : $this->_nntp->doConnect()) !== true) { + exit($this->_pdo->log->error('Unable to connect to usenet.'.PHP_EOL)); + } + while ($retries > 0) { + try { + $summary = $this->_nntp->selectGroup($this->_post_group); + if (NNTP::isError($summary)) { + $summary = $this->_nntpReset($this->_post_group); + $retries--; + continue; + } + // Check if server will receive an article + $_err = $this->_nntp->cmdPost(); + if (NNTP::isError($_err)) { + $summary = $this->_nntpReset($this->_post_group); + $retries--; + continue; + } - // Post failed - $retries--; - // try again - continue; - } + // Actually send the article + $_err = $this->_nntp->cmdPost2($article); + } catch (\Exception $e) { + // Ensure We're not connected + try { + $this->_nntp->doQuit(); + } catch (\Exception $e) {/* do nothing */ + } - // Now we verify the post worked okay - // The below code was commented out but not removed as it - // is good reference on how to quickly scan for an article. - // The problem with the below code is some providers were - // taking up to 20 min for the post to show... so checking - // right after posting was failing for this group. + // Post failed + $retries--; + // try again + continue; + } - // We're done - return true; - } - return false; - } + // Now we verify the post worked okay + // The below code was commented out but not removed as it + // is good reference on how to quickly scan for an article. + // The problem with the below code is some providers were + // taking up to 20 min for the post to show... so checking + // right after posting was failing for this group. - // *********************************************************************** - private function _nntpReset ($group = NULL) - { - // Reset Connection - try{$this->_nntp->doQuit();} - catch(\Exception $e) - {/* do nothing */} + // We're done + return true; + } - // Attempt to reconnect - if (($this->_pdo->getSetting('alternate_nntp') == 1 ? $this->_nntp->doConnect(true, true) : $this->_nntp->doConnect()) !== true) { - exit($this->_pdo->log->error("Unable to connect to usenet." . PHP_EOL)); - } + return false; + } - if($group !== NULL) - { - // Reselect group if specified - $summary = $this->_nntp->selectGroup($this->_post_group); - return $summary; - } - return true; - } + // *********************************************************************** + private function _nntpReset($group = null) + { + // Reset Connection + try { + $this->_nntp->doQuit(); + } catch (\Exception $e) {/* do nothing */ + } - // *********************************************************************** - public function getRandomStr($len) { - // Valid Characters - static $vc = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; + // Attempt to reconnect + if (($this->_pdo->getSetting('alternate_nntp') == 1 ? $this->_nntp->doConnect(true, true) : $this->_nntp->doConnect()) !== true) { + exit($this->_pdo->log->error('Unable to connect to usenet.'.PHP_EOL)); + } - $unique = ''; - for($i = 0; $i < $len; $i++) - $unique .= $vc[mt_rand(0, strlen($vc) - 1)]; + if ($group !== null) { + // Reselect group if specified + $summary = $this->_nntp->selectGroup($this->_post_group); - return $unique; - } + return $summary; + } - // *********************************************************************** - public function decodePost($message, $key = NULL, $decrypt = true) { + return true; + } + + // *********************************************************************** + public function getRandomStr($len) + { + // Valid Characters + static $vc = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; + + $unique = ''; + for ($i = 0; $i < $len; $i++) { + $unique .= $vc[mt_rand(0, strlen($vc) - 1)]; + } + + return $unique; + } + + // *********************************************************************** + public function decodePost($message, $key = null, $decrypt = true) + { // Decode Yenc - $message = Yenc::decode($message); + $message = Yenc::decode($message); - // Decompress Messsage - $message = @gzuncompress($message); + // Decompress Messsage + $message = @gzuncompress($message); - if ($key === NULL) - $key = $this->_ssl_pubkey; + if ($key === null) { + $key = $this->_ssl_pubkey; + } - // Decrypt Message - if($decrypt){ - $message = $this->decrypt($message, $key); - if($message === false){ - // fail - return false; - } - }else{ - // Convert from base64 - $message = base64_decode($message); - if($message === false){ - // Fail - return false; - } - } + // Decrypt Message + if ($decrypt) { + $message = $this->decrypt($message, $key); + if ($message === false) { + // fail + return false; + } + } else { + // Convert from base64 + $message = base64_decode($message); + if ($message === false) { + // Fail + return false; + } + } - $message = json_decode($message, true); - if($message === false){ - // Fail - return false; - } + $message = json_decode($message, true); + if ($message === false) { + // Fail + return false; + } - return $message; - } + return $message; + } - // *********************************************************************** - public function encodePost($message, $reftime = NULL, $debug = false, - $prvkey = NULL, $passphrase = NULL, $encrypt = true, - $msgtype = SpotNab::FETCH_COMMENT_TYPE, - $user = NULL, $email = NULL, $group = NULL) { - /* + // *********************************************************************** + public function encodePost($message, $reftime = null, $debug = false, + $prvkey = null, $passphrase = null, $encrypt = true, + $msgtype = self::FETCH_COMMENT_TYPE, + $user = null, $email = null, $group = null) + { + /* - Assembles and encodes a message ready to be posted onto - a usenet server. + Assembles and encodes a message ready to be posted onto + a usenet server. - false is returned if the function fails, + false is returned if the function fails, - If a reftime is specified, it is presumed that it will be in - an integer format and it will be localtime + If a reftime is specified, it is presumed that it will be in + an integer format and it will be localtime - If the debug is set to true, then a third part of the - article is returned containing header information that would - look as though _get_header() returned it - */ + If the debug is set to true, then a third part of the + article is returned containing header information that would + look as though _get_header() returned it + */ - // Assumed to be in Y-m-d H:i:s format or int - // convert local time into UTC - $reftime = $this->local2utc($reftime, "YmdHis"); + // Assumed to be in Y-m-d H:i:s format or int + // convert local time into UTC + $reftime = $this->local2utc($reftime, 'YmdHis'); - $msgid = sprintf('<%s.%s.%d@%s>', + $msgid = sprintf('<%s.%s.%d@%s>', $this->getRandomStr(30), $msgtype, time(), - SpotNab::SEGID_DOMAIN + self::SEGID_DOMAIN ); - if(!is_string($message)){ - // If message is not already in string format, then - // it's in it's assembled mixed array format... we - // need to convert it to json before proceeding - $message = json_encode($message, JSON_HEX_TAG|JSON_HEX_APOS| - JSON_HEX_QUOT|JSON_HEX_AMP|JSON_UNESCAPED_UNICODE); - if($message === false){ - // Fail - return false; - } - } + if (! is_string($message)) { + // If message is not already in string format, then + // it's in it's assembled mixed array format... we + // need to convert it to json before proceeding + $message = json_encode($message, JSON_HEX_TAG | JSON_HEX_APOS | + JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE); + if ($message === false) { + // Fail + return false; + } + } - // nntp posting expects an array as follows: - // array( - // [0] => 'Message Header' - // [1] => 'Message Body' - // ); + // nntp posting expects an array as follows: + // array( + // [0] => 'Message Header' + // [1] => 'Message Body' + // ); - if($encrypt){ - // Encrypt Message - $message = $this->encrypt($message, $prvkey, $passphrase); - if($message === false){ - // fail - return false; - } - }else{ - // Convert to base64 - $message = base64_encode($message); - } + if ($encrypt) { + // Encrypt Message + $message = $this->encrypt($message, $prvkey, $passphrase); + if ($message === false) { + // fail + return false; + } + } else { + // Convert to base64 + $message = base64_encode($message); + } - // Compress Messsage - $message = @gzcompress($message, 9); + // Compress Messsage + $message = @gzcompress($message, 9); - // Yenc Binary Content - $message = Yenc::encode($message, md5($message)); + // Yenc Binary Content + $message = Yenc::encode($message, md5($message)); - // - // Prepare Header - // + // + // Prepare Header + // - // Checksum id - $checksum = sha1($message); + // Checksum id + $checksum = sha1($message); - // Prepare Subject - $subject = sprintf("%s-%s", + // Prepare Subject + $subject = sprintf('%s-%s', // checksum against message transmitted $checksum, // Save UTC Time $reftime ); - if($user === NULL) - $user = trim($this->_post_user); - if($email === NULL) - $email = trim($this->_post_email); - if($group === NULL) - $group = trim($this->_post_group); + if ($user === null) { + $user = trim($this->_post_user); + } + if ($email === null) { + $email = trim($this->_post_email); + } + if ($group === null) { + $group = trim($this->_post_group); + } - $header = "Subject: " . $subject . "\r\n"; - $header .= "Newsgroups: " . $group . "\r\n"; - $header .= "Message-ID: $msgid\r\n"; - $header .= "X-Newsreader: NewzNab v 0.4.1" . "\r\n"; - $header .= "X-No-Archive: yes\r\n"; + $header = 'Subject: '.$subject."\r\n"; + $header .= 'Newsgroups: '.$group."\r\n"; + $header .= "Message-ID: $msgid\r\n"; + $header .= 'X-Newsreader: NewzNab v 0.4.1'."\r\n"; + $header .= "X-No-Archive: yes\r\n"; - $header .= "From: ".$user. " <" . $email . ">\r\n"; + $header .= 'From: '.$user.' <'.$email.">\r\n"; - // Binary Content - $header .= 'Content-Type: text/plain; charset=ISO-8859-1' . "\r\n"; - $header .= 'Content-Transfer-Encoding: 8bit' . "\r\n"; + // Binary Content + $header .= 'Content-Type: text/plain; charset=ISO-8859-1'."\r\n"; + $header .= 'Content-Transfer-Encoding: 8bit'."\r\n"; - // Assemble Article in structure NNTP expects - $article = [$header, $message]; + // Assemble Article in structure NNTP expects + $article = [$header, $message]; - if($debug){ - // Append some debug data to the article - $article[] = [ + if ($debug) { + // Append some debug data to the article + $article[] = [ 'Number' => 1234, 'Subject' => $subject, 'From' => sprintf('%s <%s>', $user, $email), @@ -2031,65 +2105,70 @@ class SpotNab { 'Bytes' => strlen($message), 'Lines' => '1', 'Epoch' => strtotime($this->utc2local($reftime)), - 'Group' => $group + 'Group' => $group, ]; - } - return $article; - } + } - // *********************************************************************** - public function unPostedComments($limit = SpotNab::POST_MAXIMUM_COMMENTS) { - /* - * This function returns a list of comments that have not been - * otherwise posted to usenet. - * - * $from and $to will configure themselves if set to NULL - * but otherwise it's expected format is string "Y-m-d H:i:s" - */ + return $article; + } - // Now we fetch for any new posts since reference point - $sql = sprintf("SELECT r.gid, rc.id, rc.text, u.username, " - ."rc.isvisible, rc.createddate, rc.host " - ."FROM release_comments rc " - ."JOIN releases r ON r.id = rc.releases_id AND rc.releases_id != 0 " - ."JOIN users u ON rc.users_id = u.id AND rc.users_id != 0 " - ."WHERE r.gid IS NOT NULL " - ."AND sourceid = 0 AND issynced = 0 " - ."LIMIT %d", $limit); + // *********************************************************************** + public function unPostedComments($limit = self::POST_MAXIMUM_COMMENTS) + { + /* + * This function returns a list of comments that have not been + * otherwise posted to usenet. + * + * $from and $to will configure themselves if set to NULL + * but otherwise it's expected format is string "Y-m-d H:i:s" + */ - $res = $this->_pdo->query($sql); - if(!$res) - return NULL; + // Now we fetch for any new posts since reference point + $sql = sprintf('SELECT r.gid, rc.id, rc.text, u.username, ' + .'rc.isvisible, rc.createddate, rc.host ' + .'FROM release_comments rc ' + .'JOIN releases r ON r.id = rc.releases_id AND rc.releases_id != 0 ' + .'JOIN users u ON rc.users_id = u.id AND rc.users_id != 0 ' + .'WHERE r.gid IS NOT NULL ' + .'AND sourceid = 0 AND issynced = 0 ' + .'LIMIT %d', $limit); - // Now we prepare a comments array to return with - $comments = []; - $ids = []; + $res = $this->_pdo->query($sql); + if (! $res) { + return null; + } - foreach($res as $comment){ - // If we don't have a gid then we can't make the post; - // the user hasn't set up there database to store the gid's - // correctly + // Now we prepare a comments array to return with + $comments = []; + $ids = []; - if(empty($comment['gid'])) - continue; + foreach ($res as $comment) { + // If we don't have a gid then we can't make the post; + // the user hasn't set up there database to store the gid's + // correctly - // Privacy options (scramble username or not) - if ($this->_post_privacy) - $username = sprintf( - "sn-%s", + if (empty($comment['gid'])) { + continue; + } + + // Privacy options (scramble username or not) + if ($this->_post_privacy) { + $username = sprintf( + 'sn-%s', substr(md5($comment['username'].$this->_pdo->getSetting('siteseed')), 0, 6) ); - else - $username = $comment['username']; + } else { + $username = $comment['username']; + } - // Hash a unique Comment id to associate with this message - $cid = md5($comment['id'].$comment['username'].$comment['createddate'].$comment['host']); + // Hash a unique Comment id to associate with this message + $cid = md5($comment['id'].$comment['username'].$comment['createddate'].$comment['host']); - // Keep list of IDs (required for cleanup) - $ids[] = $comment['id']; + // Keep list of IDs (required for cleanup) + $ids[] = $comment['id']; - // Build Comment - $comments[] = [ + // Build Comment + $comments[] = [ // Release Global id 'gid' => $comment['gid'], // Comment id @@ -2101,245 +2180,269 @@ class SpotNab { // Store visibility flag 'is_visible' => $comment['isvisible'], // Convert createddate to UTC - 'postdate_utc' => $this->local2utc($comment['createddate']) + 'postdate_utc' => $this->local2utc($comment['createddate']), ]; - } + } - // Return Results if they are present - return (count($comments)>0)? - ['comments' => $comments, 'ids' => $ids] :NULL; - } + // Return Results if they are present + return (count($comments) > 0) ? + ['comments' => $comments, 'ids' => $ids] : null; + } - // *********************************************************************** - public function utc2local($utc = NULL, $format="Y-m-d H:i:s") { - /* - * Takes a utc time as input and outputs local - * If no argument is specified then current local - * time is returned. - */ - if(is_string($utc)) { - return date($format, strtotime($utc. " UTC")); - } else if(is_int($utc)) { - return date($format, strtotime(date($format, $utc)." UTC")); - } - return date($format); - } + // *********************************************************************** + public function utc2local($utc = null, $format = 'Y-m-d H:i:s') + { + /* + * Takes a utc time as input and outputs local + * If no argument is specified then current local + * time is returned. + */ + if (is_string($utc)) { + return date($format, strtotime($utc.' UTC')); + } elseif (is_int($utc)) { + return date($format, strtotime(date($format, $utc).' UTC')); + } - // *********************************************************************** - public function local2utc($local = NULL, $format="Y-m-d H:i:s") { - /* - * Takes a local time as input and outputs UTC - * If no argument is specified then current UTC - * time is returned. - */ - if(is_string($local)) { - return gmdate($format, strtotime($local)); - } else if(is_int($local)) { - return gmdate($format, $local); - } - return gmdate($format); - } + return date($format); + } - // *********************************************************************** - private function _keygen($passphrase = NULL, $bits=1024, - $type=OPENSSL_KEYTYPE_RSA) - { - if(!function_exists('openssl_pkey_new')) { - return false; - } + // *********************************************************************** + public function local2utc($local = null, $format = 'Y-m-d H:i:s') + { + /* + * Takes a local time as input and outputs UTC + * If no argument is specified then current UTC + * time is returned. + */ + if (is_string($local)) { + return gmdate($format, strtotime($local)); + } elseif (is_int($local)) { + return gmdate($format, $local); + } - //Generate Key - $res = openssl_pkey_new( + return gmdate($format); + } + + // *********************************************************************** + private function _keygen($passphrase = null, $bits = 1024, + $type = OPENSSL_KEYTYPE_RSA) + { + if (! function_exists('openssl_pkey_new')) { + return false; + } + + //Generate Key + $res = openssl_pkey_new( [ 'private_key_bits' => $bits, 'private_key_type' => $type, - 'config' => OPENSSL_CFG_PATH + 'config' => OPENSSL_CFG_PATH, ] ); - if ($res === false) { - //print_r(openssl_error_string() ); - return false; - } + if ($res === false) { + //print_r(openssl_error_string() ); + return false; + } - // Get Private Key - openssl_pkey_export($res, $prvkey, $passphrase, + // Get Private Key + openssl_pkey_export($res, $prvkey, $passphrase, ['config' => OPENSSL_CFG_PATH] ); - // Get Public Key - $details = openssl_pkey_get_details($res); - if($details === false) { - return false; - } - $pubkey = $details['key']; + // Get Public Key + $details = openssl_pkey_get_details($res); + if ($details === false) { + return false; + } + $pubkey = $details['key']; - return [ + return [ 'pubkey' => $this->compstr($pubkey), 'prvkey' => $this->compstr($prvkey), ]; - } + } - // *********************************************************************** - public function encrypt ($source, $prvkey = NULL, $passphrase = NULL){ - // Encryption performed using private key - if($prvkey === NULL) - // Default Key if none is specified - $prvkey = $this->_ssl_prvkey; + // *********************************************************************** + public function encrypt($source, $prvkey = null, $passphrase = null) + { + // Encryption performed using private key + if ($prvkey === null) { + // Default Key if none is specified + $prvkey = $this->_ssl_prvkey; + } - if(!$prvkey) - // Still no key... - return false; + if (! $prvkey) { + // Still no key... + return false; + } - if(!function_exists('openssl_get_privatekey')) - return false; + if (! function_exists('openssl_get_privatekey')) { + return false; + } - // Load Public Key into array - $crypttext=''; - $pkey = openssl_get_privatekey($prvkey, $passphrase); - if($pkey === false) - // bad key - return false; + // Load Public Key into array + $crypttext = ''; + $pkey = openssl_get_privatekey($prvkey, $passphrase); + if ($pkey === false) { + // bad key + return false; + } - $batch = $len = strlen($source); - $ptr = 0; - $encrypted = ''; + $batch = $len = strlen($source); + $ptr = 0; + $encrypted = ''; - while($len > 0){ - // Prepare batch size - $batch = (($len - SpotNab::SSL_MAX_BUF_LEN) > 0) ? SpotNab::SSL_MAX_BUF_LEN : $len; + while ($len > 0) { + // Prepare batch size + $batch = (($len - self::SSL_MAX_BUF_LEN) > 0) ? self::SSL_MAX_BUF_LEN : $len; - $res = openssl_private_encrypt(substr($source, $ptr, $batch), $crypttext, $pkey); - if($res === false) { - // Encryption failed - openssl_free_key($pkey); - return false; - } - $encrypted .= base64_encode($crypttext) . SpotNab::SSL_BUF_DELIMITER; - $len -= $batch; - $ptr += $batch; - } - openssl_free_key($pkey); - return $encrypted; - } + $res = openssl_private_encrypt(substr($source, $ptr, $batch), $crypttext, $pkey); + if ($res === false) { + // Encryption failed + openssl_free_key($pkey); - // *********************************************************************** - public function decrypt ($source, $pubkey = NULL){ - // Decryption performed using public key - if($pubkey === NULL) - // Default Key if none is specified - $pubkey = $this->_ssl_pubkey; + return false; + } + $encrypted .= base64_encode($crypttext).self::SSL_BUF_DELIMITER; + $len -= $batch; + $ptr += $batch; + } + openssl_free_key($pkey); - if(!$pubkey) - // Still no key... - return false; + return $encrypted; + } - if(!function_exists('openssl_get_publickey')) - return false; + // *********************************************************************** + public function decrypt($source, $pubkey = null) + { + // Decryption performed using public key + if ($pubkey === null) { + // Default Key if none is specified + $pubkey = $this->_ssl_pubkey; + } - $pkey = openssl_get_publickey($pubkey); - if($pkey === false){ - // bad key - //echo openssl_error_string(); - return false; - } + if (! $pubkey) { + // Still no key... + return false; + } - $cryptlist = explode(SpotNab::SSL_BUF_DELIMITER, $source); + if (! function_exists('openssl_get_publickey')) { + return false; + } - $decrypted = ''; - foreach($cryptlist as $crypt){ - if(!strlen($crypt))break; - $_crypt = base64_decode($crypt); - if($_crypt === false){ - // Fail - return false; - } + $pkey = openssl_get_publickey($pubkey); + if ($pkey === false) { + // bad key + //echo openssl_error_string(); + return false; + } - $res = openssl_public_decrypt($_crypt, $out, $pkey, OPENSSL_PKCS1_PADDING); - if($res === false){ - // Decryption failed - //echo "DEBUG: ".openssl_error_string()."\n"; - openssl_free_key($pkey); - return false; - } - $decrypted .= $out; - } - openssl_free_key($pkey); + $cryptlist = explode(self::SSL_BUF_DELIMITER, $source); - return $decrypted; - } + $decrypted = ''; + foreach ($cryptlist as $crypt) { + if (! strlen($crypt)) { + break; + } + $_crypt = base64_decode($crypt); + if ($_crypt === false) { + // Fail + return false; + } - // *********************************************************************** - public function compstr ($str){ - /* - * Compress a string - */ - $str = @gzcompress($str); - return base64_encode($str); - } + $res = openssl_public_decrypt($_crypt, $out, $pkey, OPENSSL_PKCS1_PADDING); + if ($res === false) { + // Decryption failed + //echo "DEBUG: ".openssl_error_string()."\n"; + openssl_free_key($pkey); - // *********************************************************************** - public function decompstr ($str){ - /* - * De-compress a string - */ - $str = base64_decode($str); - return @gzuncompress($str); - } + return false; + } + $decrypted .= $out; + } + openssl_free_key($pkey); - public function getSources() - { - return $this->_pdo->query("SELECT id, lastupdate,lastbroadcast, active, description, " - ."(SELECT count(id) from release_comments where sourceid = s.id)" - ." AS comments FROM spotnabsources s"); - } + return $decrypted; + } - public function getSourceById($id) - { - $sql = sprintf("SELECT * FROM spotnabsources WHERE id = %d", $id); - return $this->_pdo->queryOneRow($sql); - } + // *********************************************************************** + public function compstr($str) + { + /* + * Compress a string + */ + $str = @gzcompress($str); - public function addSource($description,$username,$usermail,$usenetgroup,$publickey) - { - $sql = sprintf("INSERT INTO spotnabsources " - ."(description, username, useremail," - ." usenetgroup, publickey, active) " - ."VALUES (%s, %s, %s, %s, %s, 0)", + return base64_encode($str); + } + + // *********************************************************************** + public function decompstr($str) + { + /* + * De-compress a string + */ + $str = base64_decode($str); + + return @gzuncompress($str); + } + + public function getSources() + { + return $this->_pdo->query('SELECT id, lastupdate,lastbroadcast, active, description, ' + .'(SELECT count(id) from release_comments where sourceid = s.id)' + .' AS comments FROM spotnabsources s'); + } + + public function getSourceById($id) + { + $sql = sprintf('SELECT * FROM spotnabsources WHERE id = %d', $id); + + return $this->_pdo->queryOneRow($sql); + } + + public function addSource($description, $username, $usermail, $usenetgroup, $publickey) + { + $sql = sprintf('INSERT INTO spotnabsources ' + .'(description, username, useremail,' + .' usenetgroup, publickey, active) ' + .'VALUES (%s, %s, %s, %s, %s, 0)', $this->_pdo->escapeString($description), $this->_pdo->escapeString($username), $this->_pdo->escapeString($usermail), $this->_pdo->escapeString($usenetgroup), $this->_pdo->escapeString($publickey)); - return $this->_pdo->queryInsert($sql); - } - public function updateSource($id, $description,$username,$usermail,$usenetgroup,$publickey) - { - return $this->_pdo->queryExec( - sprintf("UPDATE spotnabsources SET " - ."description = %s, username = %s, useremail = %s," - ." usenetgroup = %s, publickey = %s WHERE id= %d", + return $this->_pdo->queryInsert($sql); + } + + public function updateSource($id, $description, $username, $usermail, $usenetgroup, $publickey) + { + return $this->_pdo->queryExec( + sprintf('UPDATE spotnabsources SET ' + .'description = %s, username = %s, useremail = %s,' + .' usenetgroup = %s, publickey = %s WHERE id= %d', $this->_pdo->escapeString($description), $this->_pdo->escapeString($username), $this->_pdo->escapeString($usermail), $this->_pdo->escapeString($usenetgroup), $this->_pdo->escapeString($publickey), $id)); - } + } - public function deleteSource($id) - { - return $this->_pdo->queryExec(sprintf("DELETE FROM spotnabsources WHERE id = %d", $id)); - } + public function deleteSource($id) + { + return $this->_pdo->queryExec(sprintf('DELETE FROM spotnabsources WHERE id = %d', $id)); + } - public function toggleSource($id, $active) - { - return $this->_pdo->queryExec(sprintf("update spotnabsources SET active = %d WHERE id = %d", $active, $id)); - } + public function toggleSource($id, $active) + { + return $this->_pdo->queryExec(sprintf('update spotnabsources SET active = %d WHERE id = %d', $active, $id)); + } - public function getDefaultValue($table,$field) - { - return $this->_pdo->query(sprintf("SHOW COLUMNS FROM %s WHERE field = %s", $table, $this->_pdo->escapeString($field))); - } + public function getDefaultValue($table, $field) + { + return $this->_pdo->query(sprintf('SHOW COLUMNS FROM %s WHERE field = %s', $table, $this->_pdo->escapeString($field))); + } } // Create a NNTP \Exception type so we can identify it from others -class SpotNabException extends \Exception { - +class SpotNabException extends \Exception +{ } diff --git a/nntmux/StaticObject.php b/nntmux/StaticObject.php index c4e026293..a154e1575 100755 --- a/nntmux/StaticObject.php +++ b/nntmux/StaticObject.php @@ -18,8 +18,8 @@ * @author niel * @copyright 2014 nZEDb */ -namespace nntmux; +namespace nntmux; use Closure; @@ -28,65 +28,65 @@ use Closure; */ class StaticObject { + /** + * Stores the closures that represent the method filters. They are indexed by called class. + * + * @var array Method filters, indexed by `get_called_class()`. + */ + protected static $_methodFilters = []; - /** - * Stores the closures that represent the method filters. They are indexed by called class. - * - * @var array Method filters, indexed by `get_called_class()`. - */ - protected static $_methodFilters = []; + /** + * Keeps a cached list of each class' inheritance tree. + * + * @var array + */ + protected static $_parents = []; - /** - * Keeps a cached list of each class' inheritance tree. - * - * @var array - */ - protected static $_parents = []; + /** + * Apply a closure to a method of the current static object. + * + * @see lithium\core\StaticObject::_filter() + * @see lithium\util\collection\Filters + * + * @param mixed $method The name of the method to apply the closure to. Can either be a single + * method name as a string, or an array of method names. Can also be false to remove + * all filters on the current object. + * @param Closure $filter The closure that is used to filter the method(s), can also be false + * to remove all the current filters for the given method. + * + * @return void + */ + public static function applyFilter($method, $filter = null) + { + $class = get_called_class(); + if ($method === false) { + static::$_methodFilters[$class] = []; - /** - * Apply a closure to a method of the current static object. - * - * @see lithium\core\StaticObject::_filter() - * @see lithium\util\collection\Filters - * - * @param mixed $method The name of the method to apply the closure to. Can either be a single - * method name as a string, or an array of method names. Can also be false to remove - * all filters on the current object. - * @param Closure $filter The closure that is used to filter the method(s), can also be false - * to remove all the current filters for the given method. - * - * @return void - */ - public static function applyFilter($method, $filter = null) - { - $class = get_called_class(); - if ($method === false) { - static::$_methodFilters[$class] = []; - return; - } - foreach ((array)$method as $m) { - if (!isset(static::$_methodFilters[$class][$m]) || $filter === false) { - static::$_methodFilters[$class][$m] = []; - } - if ($filter !== false) { - static::$_methodFilters[$class][$m][] = $filter; - } - } - } + return; + } + foreach ((array) $method as $m) { + if (! isset(static::$_methodFilters[$class][$m]) || $filter === false) { + static::$_methodFilters[$class][$m] = []; + } + if ($filter !== false) { + static::$_methodFilters[$class][$m][] = $filter; + } + } + } - /** - * Calls a method on this object with the given parameters. Provides an OO wrapper for - * `forward_static_call_[]`, and improves performance by using straight method calls - * in most cases. - * - * @param string $method Name of the method to call. - * @param array $params Parameter list to use when calling `$method`. - * - * @return mixed Returns the result of the method call. - */ - public static function invokeMethod($method, $params = []) - { - switch (count($params)) { + /** + * Calls a method on this object with the given parameters. Provides an OO wrapper for + * `forward_static_call_[]`, and improves performance by using straight method calls + * in most cases. + * + * @param string $method Name of the method to call. + * @param array $params Parameter list to use when calling `$method`. + * + * @return mixed Returns the result of the method call. + */ + public static function invokeMethod($method, $params = []) + { + switch (count($params)) { case 0: return static::$method(); case 1: @@ -100,36 +100,35 @@ class StaticObject case 5: return static::$method($params[0], $params[1], $params[2], $params[3], $params[4]); default: - return forward_static_call_array(array(get_called_class(), $method), $params); + return forward_static_call_array([get_called_class(), $method], $params); } - } + } - /** - * Gets and caches an array of the parent methods of a class. - * - * @return array Returns an array of parent classes for the current class. - */ - protected static function _parents() - { - $class = get_called_class(); + /** + * Gets and caches an array of the parent methods of a class. + * + * @return array Returns an array of parent classes for the current class. + */ + protected static function _parents() + { + $class = get_called_class(); - if (!isset(self::$_parents[$class])) { - self::$_parents[$class] = class_parents($class); - } - return self::$_parents[$class]; - } + if (! isset(self::$_parents[$class])) { + self::$_parents[$class] = class_parents($class); + } - /** - * Exit immediately. Primarily used for overrides during testing. - * - * @param integer|string $status integer range 0 to 254, string printed on exit - * - * @return void - */ - protected static function _stop($status = 0) - { - exit($status); - } + return self::$_parents[$class]; + } + + /** + * Exit immediately. Primarily used for overrides during testing. + * + * @param int|string $status integer range 0 to 254, string printed on exit + * + * @return void + */ + protected static function _stop($status = 0) + { + exit($status); + } } - -?> diff --git a/nntmux/Steam.php b/nntmux/Steam.php index 00b797d63..a3bcb85b0 100755 --- a/nntmux/Steam.php +++ b/nntmux/Steam.php @@ -1,203 +1,204 @@ <?php + namespace nntmux; -use App\Models\SteamApps; -use App\Models\Settings; -use b3rs3rk\steamfront\Main; use nntmux\db\DB; +use App\Models\Settings; +use App\Models\SteamApps; +use b3rs3rk\steamfront\Main; class Steam { - const STEAM_MATCH_PERCENTAGE = 90; + const STEAM_MATCH_PERCENTAGE = 90; - /** - * @var string The parsed game name from searchname - */ - public $searchTerm; + /** + * @var string The parsed game name from searchname + */ + public $searchTerm; - /** - * @var int The ID of the Steam Game matched - */ - protected $steamGameID; + /** + * @var int The ID of the Steam Game matched + */ + protected $steamGameID; - /** - * @var DB - */ - protected $pdo; + /** + * @var DB + */ + protected $pdo; - /** - * @var - */ - protected $lastUpdate; + /** + * @var + */ + protected $lastUpdate; - /** - * @var Main - */ - protected $steamFront; + /** + * @var Main + */ + protected $steamFront; - /** - * Steam constructor. - * - * @param array $options - */ - public function __construct(array $options = []) - { - $defaults = ['DB' => null]; - $options += $defaults; + /** + * Steam constructor. + * + * @param array $options + */ + public function __construct(array $options = []) + { + $defaults = ['DB' => null]; + $options += $defaults; - $this->pdo = ($options['DB'] instanceof DB ? $options['DB'] : new DB()); + $this->pdo = ($options['DB'] instanceof DB ? $options['DB'] : new DB()); - $this->steamFront = new Main( + $this->steamFront = new Main( [ 'country_code' => 'us', - 'local_lang' => 'english' + 'local_lang' => 'english', ] ); - } + } - /** - * Gets all Information for the game. - * - * @param integer $appID - * - * @return array|bool - */ - public function getAll($appID) - { - $res = $this->steamFront->getAppDetails($appID); + /** + * Gets all Information for the game. + * + * @param int $appID + * + * @return array|bool + */ + public function getAll($appID) + { + $res = $this->steamFront->getAppDetails($appID); - if ($res !== false) { - $result = [ + if ($res !== false) { + $result = [ 'title' => $res->name, 'description' => $res->description['short'], 'cover' => $res->images['header'], 'backdrop' => $res->images['background'], 'steamid' => $res->appid, - 'directurl' => Main::STEAM_STORE_ROOT . 'app/' . $res->appid, + 'directurl' => Main::STEAM_STORE_ROOT.'app/'.$res->appid, 'publisher' => $res->publishers, 'rating' => $res->metacritic['score'], 'releasedate' => $res->releasedate['date'], - 'genres' => implode(',', array_column($res->genres, 'description')) + 'genres' => implode(',', array_column($res->genres, 'description')), ]; - return $result; - } + return $result; + } - if ($res === false) { - ColorCLI::doEcho(ColorCLI::notice('Steam did not return game data')); - } + if ($res === false) { + ColorCLI::doEcho(ColorCLI::notice('Steam did not return game data')); + } - return false; - } + return false; + } - /** - * Searches Steam Apps table for best title match -- prefers 100% match but returns highest over 90% - * - * @param string $searchTerm The parsed game name from the release searchname - * - * @return false|int $bestMatch The Best match from the given search term - * @throws \Exception - */ - public function search($searchTerm) - { - $bestMatch = false; + /** + * Searches Steam Apps table for best title match -- prefers 100% match but returns highest over 90%. + * + * @param string $searchTerm The parsed game name from the release searchname + * + * @return false|int $bestMatch The Best match from the given search term + * @throws \Exception + */ + public function search($searchTerm) + { + $bestMatch = false; - if (empty($searchTerm)) { - ColorCLI::doEcho(ColorCLI::notice('Search term cannot be empty')); + if (empty($searchTerm)) { + ColorCLI::doEcho(ColorCLI::notice('Search term cannot be empty')); - return $bestMatch; - } + return $bestMatch; + } - $this->populateSteamAppsTable(); + $this->populateSteamAppsTable(); - $results = $this->pdo->queryDirect(" + $results = $this->pdo->queryDirect(" SELECT name, appid FROM steam_apps WHERE MATCH(name) AGAINST({$this->pdo->escapeString($searchTerm)}) LIMIT 20" ); - if ($results instanceof \Traversable) { - $bestMatchPct = 0; - foreach ($results as $result) { - // If we have an exact string match set best match and break out - if ($result['name'] === $searchTerm) { - $bestMatch = $result['appid']; - break; - } + if ($results instanceof \Traversable) { + $bestMatchPct = 0; + foreach ($results as $result) { + // If we have an exact string match set best match and break out + if ($result['name'] === $searchTerm) { + $bestMatch = $result['appid']; + break; + } - similar_text(strtolower($result['name']), strtolower($searchTerm), $percent); - // If similar_text reports an exact match set best match and break out - if ($percent === 100) { - $bestMatch = $result['appid']; - break; - } - if ($percent >= self::STEAM_MATCH_PERCENTAGE && $percent > $bestMatchPct) { - $bestMatch = $result['appid']; - $bestMatchPct = $percent; - } - } - } - if ($bestMatch === false) { - ColorCLI::doEcho(ColorCLI::notice('Steam search returned no valid results')); - } + similar_text(strtolower($result['name']), strtolower($searchTerm), $percent); + // If similar_text reports an exact match set best match and break out + if ($percent === 100) { + $bestMatch = $result['appid']; + break; + } + if ($percent >= self::STEAM_MATCH_PERCENTAGE && $percent > $bestMatchPct) { + $bestMatch = $result['appid']; + $bestMatchPct = $percent; + } + } + } + if ($bestMatch === false) { + ColorCLI::doEcho(ColorCLI::notice('Steam search returned no valid results')); + } - return $bestMatch; - } + return $bestMatch; + } - /** - * Downloads full Steam Store dump and imports data into local table - * - * @throws \Exception - */ - public function populateSteamAppsTable(): void - { - $lastUpdate = Settings::value('APIs.Steam.last_update'); - $this->lastUpdate = $lastUpdate > 0 ? $lastUpdate : 0; - if ((time() - (int)$this->lastUpdate) > 86400) { - // Set time we updated steam_apps table - $this->setLastUpdated(); - $fullAppArray = $this->steamFront->getFullAppList(); - $inserted = $dupe = 0; - echo ColorCLI::info('Populating steam apps table') . PHP_EOL; - foreach ($fullAppArray as $appsArray) { - foreach ($appsArray as $appArray) { - foreach ($appArray as $app) { - $dupeCheck = SteamApps::query()->where('appid', '=', $app['appid'])->value('appid'); + /** + * Downloads full Steam Store dump and imports data into local table. + * + * @throws \Exception + */ + public function populateSteamAppsTable(): void + { + $lastUpdate = Settings::value('APIs.Steam.last_update'); + $this->lastUpdate = $lastUpdate > 0 ? $lastUpdate : 0; + if ((time() - (int) $this->lastUpdate) > 86400) { + // Set time we updated steam_apps table + $this->setLastUpdated(); + $fullAppArray = $this->steamFront->getFullAppList(); + $inserted = $dupe = 0; + echo ColorCLI::info('Populating steam apps table').PHP_EOL; + foreach ($fullAppArray as $appsArray) { + foreach ($appsArray as $appArray) { + foreach ($appArray as $app) { + $dupeCheck = SteamApps::query()->where('appid', '=', $app['appid'])->value('appid'); - if ($dupeCheck === null) { - SteamApps::query()->insert(['name' => $this->pdo->escapeString($app['name']), 'appid' => $app['appid']]); - $inserted++; - if ($inserted % 500 === 0) { - echo PHP_EOL . number_format($inserted) . ' apps inserted.' . PHP_EOL; - } else { - echo '.'; - } - } else { - $dupe++; - } - } - } - } - echo PHP_EOL . 'Added ' . $inserted . ' new steam app(s), ' . $dupe . ' duplicates skipped' . PHP_EOL; - } - } + if ($dupeCheck === null) { + SteamApps::query()->insert(['name' => $this->pdo->escapeString($app['name']), 'appid' => $app['appid']]); + $inserted++; + if ($inserted % 500 === 0) { + echo PHP_EOL.number_format($inserted).' apps inserted.'.PHP_EOL; + } else { + echo '.'; + } + } else { + $dupe++; + } + } + } + } + echo PHP_EOL.'Added '.$inserted.' new steam app(s), '.$dupe.' duplicates skipped'.PHP_EOL; + } + } - /** - * Sets the database time for last full Steam update - */ - private function setLastUpdated(): void - { - Settings::query()->where( + /** + * Sets the database time for last full Steam update. + */ + private function setLastUpdated(): void + { + Settings::query()->where( [ ['section', '=', 'APIs'], ['subsection', '=', 'Steam'], - ['name', '=', 'last_update'] + ['name', '=', 'last_update'], ] )->update( [ - 'value' => time() + 'value' => time(), ] ); - } + } } diff --git a/nntmux/Tmux.php b/nntmux/Tmux.php index 44d214ae7..87b9582ca 100755 --- a/nntmux/Tmux.php +++ b/nntmux/Tmux.php @@ -1,117 +1,116 @@ <?php + namespace nntmux; +use nntmux\db\DB; use App\Extensions\util\Versions; use App\Models\Tmux as TmuxModel; -use nntmux\db\DB; /** - * Class Tmux - * - * @package nntmux + * Class Tmux. */ class Tmux { - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var - */ - public $tmux_session; + /** + * @var + */ + public $tmux_session; - /** - * Tmux constructor. - * - * @param DB|null $pdo - */ - public function __construct(DB $pdo = null) - { - $this->pdo = $pdo ?? new DB(); - } + /** + * Tmux constructor. + * + * @param DB|null $pdo + */ + public function __construct(DB $pdo = null) + { + $this->pdo = $pdo ?? new DB(); + } - /** - * @return string - */ - public function version(): string - { - return (new Versions())->getGitTagInFile(); - } + /** + * @return string + */ + public function version(): string + { + return (new Versions())->getGitTagInFile(); + } - /** - * @param $form - * - * @return \stdClass - */ - public function update($form): \stdClass - { - $tmux = $this->row2Object($form); + /** + * @param $form + * + * @return \stdClass + */ + public function update($form): \stdClass + { + $tmux = $this->row2Object($form); - $sql = $sqlKeys = []; - foreach ($form as $settingK => $settingV) { - if (is_array($settingV)) { - $settingV = implode(', ', $settingV); - } - $sql[] = sprintf('WHEN %s THEN %s', $this->pdo->escapeString($settingK), $this->pdo->escapeString($settingV)); - $sqlKeys[] = $this->pdo->escapeString($settingK); - } + $sql = $sqlKeys = []; + foreach ($form as $settingK => $settingV) { + if (is_array($settingV)) { + $settingV = implode(', ', $settingV); + } + $sql[] = sprintf('WHEN %s THEN %s', $this->pdo->escapeString($settingK), $this->pdo->escapeString($settingV)); + $sqlKeys[] = $this->pdo->escapeString($settingK); + } - $this->pdo->queryExec(sprintf('UPDATE tmux SET value = CASE setting %s END WHERE setting IN (%s)', implode(' ', $sql), implode(', ', $sqlKeys))); + $this->pdo->queryExec(sprintf('UPDATE tmux SET value = CASE setting %s END WHERE setting IN (%s)', implode(' ', $sql), implode(', ', $sqlKeys))); - return $tmux; - } + return $tmux; + } - /** - * @param string $setting - * - * @return bool|\stdClass - */ - public function get($setting = '') - { - if ($setting === '') { - $rows = TmuxModel::all(); - } else { - $rows = TmuxModel::query()->where('setting', $setting)->get(); - } + /** + * @param string $setting + * + * @return bool|\stdClass + */ + public function get($setting = '') + { + if ($setting === '') { + $rows = TmuxModel::all(); + } else { + $rows = TmuxModel::query()->where('setting', $setting)->get(); + } - if ($rows === false) { - return false; - } + if ($rows === false) { + return false; + } - return $this->rows2Object($rows); - } + return $this->rows2Object($rows); + } - /** - * @param $constants - * - * @return mixed - */ - public function getConnectionsInfo($constants) - { - $runVar['connections']['port_a'] = $runVar['connections']['host_a'] = $runVar['connections']['ip_a'] = false; - $runVar['connections']['port'] = env('NNTP_PORT'); - $runVar['connections']['host'] = env('NNTP_SERVER'); - $runVar['connections']['ip'] = gethostbyname($runVar['connections']['host']); - if ($constants['alternate_nntp'] === '1') { - $runVar['connections']['port_a'] = env('NNTP_PORT_A'); - $runVar['connections']['host_a'] = env('NNTP_SERVER_A'); - $runVar['connections']['ip_a'] = gethostbyname($runVar['connections']['host_a']); - } - return $runVar['connections']; - } + /** + * @param $constants + * + * @return mixed + */ + public function getConnectionsInfo($constants) + { + $runVar['connections']['port_a'] = $runVar['connections']['host_a'] = $runVar['connections']['ip_a'] = false; + $runVar['connections']['port'] = env('NNTP_PORT'); + $runVar['connections']['host'] = env('NNTP_SERVER'); + $runVar['connections']['ip'] = gethostbyname($runVar['connections']['host']); + if ($constants['alternate_nntp'] === '1') { + $runVar['connections']['port_a'] = env('NNTP_PORT_A'); + $runVar['connections']['host_a'] = env('NNTP_SERVER_A'); + $runVar['connections']['ip_a'] = gethostbyname($runVar['connections']['host_a']); + } - /** - * @param $which - * @param $connections - * - * @return mixed - */ - public function getUSPConnections($which, $connections) - { + return $runVar['connections']; + } - switch ($which) { + /** + * @param $which + * @param $connections + * + * @return mixed + */ + public function getUSPConnections($which, $connections) + { + switch ($which) { case 'alternate': $ip = 'ip_a'; $port = 'port_a'; @@ -123,70 +122,72 @@ class Tmux break; } - $runVar['conncounts'][$which]['active'] = $runVar['conncounts'][$which]['total'] = 0; + $runVar['conncounts'][$which]['active'] = $runVar['conncounts'][$which]['total'] = 0; - $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec("ss -n | grep " . $connections[$ip] . ":" . $connections[$port] . " | grep -c ESTAB")); - $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec("ss -n | grep -c " . $connections[$ip] . ":" . $connections[$port])); + $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec('ss -n | grep '.$connections[$ip].':'.$connections[$port].' | grep -c ESTAB')); + $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec('ss -n | grep -c '.$connections[$ip].':'.$connections[$port])); - if ($runVar['conncounts'][$which]['active'] == 0 && $runVar['conncounts'][$which]['total'] == 0) { - $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec("ss -n | grep " . $connections[$ip] . ":https | grep -c ESTAB")); - $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec("ss -n | grep -c " . $connections[$ip] . ":https")); - } - if ($runVar['conncounts'][$which]['active'] == 0 && $runVar['conncounts'][$which]['total'] == 0) { - $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec("ss -n | grep " . $connections[$port] . " | grep -c ESTAB")); - $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec("ss -n | grep -c " . $connections[$port])); - } - if ($runVar['conncounts'][$which]['active'] == 0 && $runVar['conncounts'][$which]['total'] == 0) { - $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec("ss -n | grep " . $connections[$ip] . " | grep -c ESTAB")); - $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec("ss -n | grep -c " . $connections[$ip])); - } - return ($runVar['conncounts']); - } + if ($runVar['conncounts'][$which]['active'] == 0 && $runVar['conncounts'][$which]['total'] == 0) { + $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec('ss -n | grep '.$connections[$ip].':https | grep -c ESTAB')); + $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec('ss -n | grep -c '.$connections[$ip].':https')); + } + if ($runVar['conncounts'][$which]['active'] == 0 && $runVar['conncounts'][$which]['total'] == 0) { + $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec('ss -n | grep '.$connections[$port].' | grep -c ESTAB')); + $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec('ss -n | grep -c '.$connections[$port])); + } + if ($runVar['conncounts'][$which]['active'] == 0 && $runVar['conncounts'][$which]['total'] == 0) { + $runVar['conncounts'][$which]['active'] = str_replace("\n", '', shell_exec('ss -n | grep '.$connections[$ip].' | grep -c ESTAB')); + $runVar['conncounts'][$which]['total'] = str_replace("\n", '', shell_exec('ss -n | grep -c '.$connections[$ip])); + } - /** - * @param $constants - * - * @return array - */ - public function getListOfPanes($constants): array - { - $panes = ['zero' => '', 'one' => '', 'two' => '']; - switch ($constants['sequential']) { + return $runVar['conncounts']; + } + + /** + * @param $constants + * + * @return array + */ + public function getListOfPanes($constants): array + { + $panes = ['zero' => '', 'one' => '', 'two' => '']; + switch ($constants['sequential']) { case 0: $panes_win_1 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:0 -F '#{pane_title}'`"); - $panes['zero'] = str_replace("\n", '', explode(" ", $panes_win_1)); + $panes['zero'] = str_replace("\n", '', explode(' ', $panes_win_1)); $panes_win_2 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:1 -F '#{pane_title}'`"); - $panes['one'] = str_replace("\n", '', explode(" ", $panes_win_2)); + $panes['one'] = str_replace("\n", '', explode(' ', $panes_win_2)); $panes_win_3 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:2 -F '#{pane_title}'`"); - $panes['two'] = str_replace("\n", '', explode(" ", $panes_win_3)); + $panes['two'] = str_replace("\n", '', explode(' ', $panes_win_3)); break; case 1: $panes_win_1 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:0 -F '#{pane_title}'`"); - $panes['zero'] = str_replace("\n", '', explode(" ", $panes_win_1)); + $panes['zero'] = str_replace("\n", '', explode(' ', $panes_win_1)); $panes_win_2 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:1 -F '#{pane_title}'`"); - $panes['one'] = str_replace("\n", '', explode(" ", $panes_win_2)); + $panes['one'] = str_replace("\n", '', explode(' ', $panes_win_2)); $panes_win_3 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:2 -F '#{pane_title}'`"); - $panes['two'] = str_replace("\n", '', explode(" ", $panes_win_3)); + $panes['two'] = str_replace("\n", '', explode(' ', $panes_win_3)); break; case 2: $panes_win_1 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:0 -F '#{pane_title}'`"); - $panes['zero'] = str_replace("\n", '', explode(" ", $panes_win_1)); + $panes['zero'] = str_replace("\n", '', explode(' ', $panes_win_1)); $panes_win_2 = shell_exec("echo `tmux list-panes -t {$constants['tmux_session']}:1 -F '#{pane_title}'`"); - $panes['one'] = str_replace("\n", '', explode(" ", $panes_win_2)); + $panes['one'] = str_replace("\n", '', explode(' ', $panes_win_2)); break; } - return $panes; - } - /** - * @return string - */ - public function getConstantSettings(): string - { - $tmuxstr = 'SELECT value FROM tmux WHERE setting ='; - $settstr = 'SELECT value FROM settings WHERE setting ='; + return $panes; + } - $sql = sprintf( + /** + * @return string + */ + public function getConstantSettings(): string + { + $tmuxstr = 'SELECT value FROM tmux WHERE setting ='; + $settstr = 'SELECT value FROM settings WHERE setting ='; + + $sql = sprintf( "SELECT (%1\$s 'sequential') AS sequential, (%1\$s 'tmux_session') AS tmux_session, @@ -197,18 +198,19 @@ class Tmux $tmuxstr, $settstr ); - return $sql; - } - /** - * @return string - */ - public function getMonitorSettings(): string - { - $tmuxstr = 'SELECT value FROM tmux WHERE setting ='; - $settstr = 'SELECT value FROM settings WHERE setting ='; + return $sql; + } - $sql = sprintf( + /** + * @return string + */ + public function getMonitorSettings(): string + { + $tmuxstr = 'SELECT value FROM tmux WHERE setting ='; + $settstr = 'SELECT value FROM settings WHERE setting ='; + + $sql = sprintf( "SELECT (%1\$s 'monitor_delay') AS monitor, (%1\$s 'binaries') AS binaries_run, @@ -273,215 +275,227 @@ class Tmux $tmuxstr, $settstr ); - return $sql; - } - /** - * @param $rows - * - * @return \stdClass - */ - public function rows2Object($rows): \stdClass - { - $obj = new \stdClass; - foreach ($rows as $row) { - $obj->{$row['setting']} = $row['value']; - } + return $sql; + } - $obj->{'version'} = $this->version(); - return $obj; - } + /** + * @param $rows + * + * @return \stdClass + */ + public function rows2Object($rows): \stdClass + { + $obj = new \stdClass; + foreach ($rows as $row) { + $obj->{$row['setting']} = $row['value']; + } - /** - * @param $row - * - * @return \stdClass - */ - public function row2Object($row): \stdClass - { - $obj = new \stdClass; - $rowKeys = array_keys($row); - foreach ($rowKeys as $key) { - $obj->{$key} = $row[$key]; - } - return $obj; - } + $obj->{'version'} = $this->version(); - /** - * @param $setting - * @param $value - * - * @return bool|\PDOStatement - */ - public function updateItem($setting, $value) - { - return TmuxModel::query()->where('setting', '=', $setting)->update(['value' => $value]); - } + return $obj; + } - //get microtime - /** - * @return float - */ - public function microtime_float(): float - { - [$usec, $sec] = explode(' ', microtime()); - return ((float)$usec + (float)$sec); - } + /** + * @param $row + * + * @return \stdClass + */ + public function row2Object($row): \stdClass + { + $obj = new \stdClass; + $rowKeys = array_keys($row); + foreach ($rowKeys as $key) { + $obj->{$key} = $row[$key]; + } - /** - * @param double $bytes - * - * @return string - */ - public function decodeSize($bytes): string - { - $types = ['B', 'KB', 'MB', 'GB', 'TB']; - $suffix = 'B'; - foreach ($types as $type) { - if ($bytes < 1024.0) { - $suffix = $type; - break; - } - $bytes /= 1024; - } - return (round($bytes, 2) . ' ' . $suffix); - } + return $obj; + } - /** - * @param $pane - * - * @return string - */ - public function writelog($pane): ?string - { - $path = NN_LOGS; - $getdate = gmdate('Ymd'); - $tmux = $this->get(); - $logs = $tmux->write_logs ?? 0; - if ($logs === 1) { - return "2>&1 | tee -a $path/$pane-$getdate.log"; - } - return ''; - } + /** + * @param $setting + * @param $value + * + * @return bool|\PDOStatement + */ + public function updateItem($setting, $value) + { + return TmuxModel::query()->where('setting', '=', $setting)->update(['value' => $value]); + } - /** - * @param $colors_start - * @param $colors_end - * @param $colors_exc - * - * @return int - */ - public function get_color($colors_start, $colors_end, $colors_exc): int - { - $exception = str_replace('.', '.', $colors_exc); - $exceptions = explode(',', $exception); - sort($exceptions); - $number = random_int($colors_start, $colors_end - count($exceptions)); - foreach ($exceptions as $exception) { - if ($number >= $exception) { - $number++; - } else { - break; - } - } - return $number; - } + //get microtime - // Returns random bool, weighted by $chance - /** - * @param $loop - * @param int $chance - * - * @return bool - */ - public function rand_bool($loop, $chance = 60): bool - { - $tmux = $this->get(); - $usecache = $tmux->usecache ?? 0; - if ($loop === 1 || $usecache === 0) { - return false; - } - return (random_int(1, 100) <= $chance); - } + /** + * @return float + */ + public function microtime_float(): float + { + [$usec, $sec] = explode(' ', microtime()); - /** - * @param $_time - * - * @return string - */ - public function relativeTime($_time): string - { - $d = []; - $d[0] = [1, 'sec']; - $d[1] = [60, 'min']; - $d[2] = [3600, 'hr']; - $d[3] = [86400, 'day']; - $d[4] = [31104000, 'yr']; + return (float) $usec + (float) $sec; + } - $w = []; + /** + * @param float $bytes + * + * @return string + */ + public function decodeSize($bytes): string + { + $types = ['B', 'KB', 'MB', 'GB', 'TB']; + $suffix = 'B'; + foreach ($types as $type) { + if ($bytes < 1024.0) { + $suffix = $type; + break; + } + $bytes /= 1024; + } - $return = ''; - $now = time(); - $diff = ($now - ($_time >= $now ? $_time - 1 : $_time)); - $secondsLeft = $diff; + return round($bytes, 2).' '.$suffix; + } - for ($i = 4; $i > -1; $i--) { - $w[$i] = (int)($secondsLeft / $d[$i][0]); - $secondsLeft -= ($w[$i] * $d[$i][0]); - if ($w[$i] !== 0) { - $return .= $w[$i] . ' ' . $d[$i][1] . (($w[$i] > 1) ? 's' : '') . ' '; - } - } - return $return; - } + /** + * @param $pane + * + * @return string + */ + public function writelog($pane): ?string + { + $path = NN_LOGS; + $getdate = gmdate('Ymd'); + $tmux = $this->get(); + $logs = $tmux->write_logs ?? 0; + if ($logs === 1) { + return "2>&1 | tee -a $path/$pane-$getdate.log"; + } - /** - * @param $cmd - * - * @return bool - */ - public function command_exist($cmd): bool - { - $returnVal = shell_exec("which $cmd 2>/dev/null"); - return (empty($returnVal) ? false : true); - } + return ''; + } - /** - * @param $qry - * @param $bookreqids - * @param int $request_hours - * @param string $db_name - * @param string $ppmax - * @param string $ppmin - * - * @return bool|string - * @throws \Exception - */ - public function proc_query($qry, $bookreqids, $request_hours, $db_name, $ppmax = '', $ppmin = '') - { - switch ((int)$qry) { + /** + * @param $colors_start + * @param $colors_end + * @param $colors_exc + * + * @return int + */ + public function get_color($colors_start, $colors_end, $colors_exc): int + { + $exception = str_replace('.', '.', $colors_exc); + $exceptions = explode(',', $exception); + sort($exceptions); + $number = random_int($colors_start, $colors_end - count($exceptions)); + foreach ($exceptions as $exception) { + if ($number >= $exception) { + $number++; + } else { + break; + } + } + + return $number; + } + + // Returns random bool, weighted by $chance + + /** + * @param $loop + * @param int $chance + * + * @return bool + */ + public function rand_bool($loop, $chance = 60): bool + { + $tmux = $this->get(); + $usecache = $tmux->usecache ?? 0; + if ($loop === 1 || $usecache === 0) { + return false; + } + + return random_int(1, 100) <= $chance; + } + + /** + * @param $_time + * + * @return string + */ + public function relativeTime($_time): string + { + $d = []; + $d[0] = [1, 'sec']; + $d[1] = [60, 'min']; + $d[2] = [3600, 'hr']; + $d[3] = [86400, 'day']; + $d[4] = [31104000, 'yr']; + + $w = []; + + $return = ''; + $now = time(); + $diff = ($now - ($_time >= $now ? $_time - 1 : $_time)); + $secondsLeft = $diff; + + for ($i = 4; $i > -1; $i--) { + $w[$i] = (int) ($secondsLeft / $d[$i][0]); + $secondsLeft -= ($w[$i] * $d[$i][0]); + if ($w[$i] !== 0) { + $return .= $w[$i].' '.$d[$i][1].(($w[$i] > 1) ? 's' : '').' '; + } + } + + return $return; + } + + /** + * @param $cmd + * + * @return bool + */ + public function command_exist($cmd): bool + { + $returnVal = shell_exec("which $cmd 2>/dev/null"); + + return empty($returnVal) ? false : true; + } + + /** + * @param $qry + * @param $bookreqids + * @param int $request_hours + * @param string $db_name + * @param string $ppmax + * @param string $ppmin + * + * @return bool|string + * @throws \Exception + */ + public function proc_query($qry, $bookreqids, $request_hours, $db_name, $ppmax = '', $ppmin = '') + { + switch ((int) $qry) { case 1: - return sprintf(" + return sprintf(' SELECT SUM(IF(nzbstatus = %d AND categories_id BETWEEN %d AND %d AND categories_id != %d AND videos_id = 0 AND tv_episodes_id BETWEEN -3 AND 0 AND size > 1048576,1,0)) AS processtv, - SUM(IF(nzbstatus = %1\$d AND categories_id = %d AND anidbid IS NULL,1,0)) AS processanime, - SUM(IF(nzbstatus = %1\$d AND categories_id BETWEEN %d AND %d AND imdbid IS NULL,1,0)) AS processmovies, - SUM(IF(nzbstatus = %1\$d AND categories_id IN (%d, %d, %d) AND musicinfo_id IS NULL,1,0)) AS processmusic, - SUM(IF(nzbstatus = %1\$d AND categories_id BETWEEN %d AND %d AND consoleinfo_id IS NULL,1,0)) AS processconsole, - SUM(IF(nzbstatus = %1\$d AND categories_id IN (%s) AND bookinfo_id IS NULL,1,0)) AS processbooks, - SUM(IF(nzbstatus = %1\$d AND categories_id = %d AND gamesinfo_id = 0,1,0)) AS processgames, - SUM(IF(nzbstatus = %1\$d AND categories_id BETWEEN %d AND %d AND xxxinfo_id = 0,1,0)) AS processxxx, + SUM(IF(nzbstatus = %1$d AND categories_id = %d AND anidbid IS NULL,1,0)) AS processanime, + SUM(IF(nzbstatus = %1$d AND categories_id BETWEEN %d AND %d AND imdbid IS NULL,1,0)) AS processmovies, + SUM(IF(nzbstatus = %1$d AND categories_id IN (%d, %d, %d) AND musicinfo_id IS NULL,1,0)) AS processmusic, + SUM(IF(nzbstatus = %1$d AND categories_id BETWEEN %d AND %d AND consoleinfo_id IS NULL,1,0)) AS processconsole, + SUM(IF(nzbstatus = %1$d AND categories_id IN (%s) AND bookinfo_id IS NULL,1,0)) AS processbooks, + SUM(IF(nzbstatus = %1$d AND categories_id = %d AND gamesinfo_id = 0,1,0)) AS processgames, + SUM(IF(nzbstatus = %1$d AND categories_id BETWEEN %d AND %d AND xxxinfo_id = 0,1,0)) AS processxxx, SUM(IF(1=1 %s,1,0)) AS processnfo, - SUM(IF(nzbstatus = %1\$d AND isrenamed = %d AND predb_id = 0 AND passwordstatus >= 0 AND nfostatus > %d - AND ((nfostatus = %d AND proc_nfo = %d) OR proc_files = %d OR proc_uid = %d OR proc_hash16k = %d OR proc_srr = %d OR proc_par2 = %d OR (nfostatus = %20\$d AND proc_sorter = %d) + SUM(IF(nzbstatus = %1$d AND isrenamed = %d AND predb_id = 0 AND passwordstatus >= 0 AND nfostatus > %d + AND ((nfostatus = %d AND proc_nfo = %d) OR proc_files = %d OR proc_uid = %d OR proc_hash16k = %d OR proc_srr = %d OR proc_par2 = %d OR (nfostatus = %20$d AND proc_sorter = %d) OR (ishashed = 1 AND dehashstatus BETWEEN -6 AND 0)) AND categories_id IN (%s),1,0)) AS processrenames, SUM(IF(isrenamed = %d,1,0)) AS renamed, - SUM(IF(nzbstatus = %1\$d AND nfostatus = %20\$d,1,0)) AS nfo, - SUM(IF(nzbstatus = %1\$d AND isrequestid = %d AND predb_id = 0 AND ((reqidstatus = %d) OR (reqidstatus = %d) OR (reqidstatus = %d AND adddate > NOW() - INTERVAL %s HOUR)),1,0)) AS requestid_inprogress, - SUM(IF(predb_id > 0 AND nzbstatus = %1\$d AND isrequestid = %28\$d AND reqidstatus = %d,1,0)) AS requestid_matched, + SUM(IF(nzbstatus = %1$d AND nfostatus = %20$d,1,0)) AS nfo, + SUM(IF(nzbstatus = %1$d AND isrequestid = %d AND predb_id = 0 AND ((reqidstatus = %d) OR (reqidstatus = %d) OR (reqidstatus = %d AND adddate > NOW() - INTERVAL %s HOUR)),1,0)) AS requestid_inprogress, + SUM(IF(predb_id > 0 AND nzbstatus = %1$d AND isrequestid = %28$d AND reqidstatus = %d,1,0)) AS requestid_matched, SUM(IF(predb_id > 0,1,0)) AS predb_matched, COUNT(DISTINCT(predb_id)) AS distinct_predb_matched - FROM releases r", + FROM releases r', NZB::NZB_ADDED, Category::TV_ROOT, Category::TV_OTHER, @@ -521,14 +535,15 @@ class Tmux case 2: $ppminString = $ppmaxString = ''; - if (is_numeric($ppmax) && !empty($ppmax)) { - $ppmax *= 1073741824; - $ppmaxString = "AND r.size < {$ppmax}"; + if (is_numeric($ppmax) && ! empty($ppmax)) { + $ppmax *= 1073741824; + $ppmaxString = "AND r.size < {$ppmax}"; } - if (is_numeric($ppmin) && !empty($ppmin)) { - $ppmin *= 1048576; - $ppminString = "AND r.size > {$ppmin}"; + if (is_numeric($ppmin) && ! empty($ppmin)) { + $ppmin *= 1048576; + $ppminString = "AND r.size > {$ppmin}"; } + return "SELECT (SELECT COUNT(r.id) FROM releases r LEFT JOIN categories c ON c.id = r.categories_id @@ -567,67 +582,68 @@ class Tmux default: return false; } - } + } - /** - * @return bool true if tmux is running, false otherwise. - * @throws \RuntimeException - */ - public function isRunning(): bool - { - $running = $this->get()->running; - if ($running === false) { - throw new \RuntimeException('Tmux\\\'s running flag was not found in the database.' . PHP_EOL . 'Please check the tables are correctly setup.' . PHP_EOL); - } + /** + * @return bool true if tmux is running, false otherwise. + * @throws \RuntimeException + */ + public function isRunning(): bool + { + $running = $this->get()->running; + if ($running === false) { + throw new \RuntimeException('Tmux\\\'s running flag was not found in the database.'.PHP_EOL.'Please check the tables are correctly setup.'.PHP_EOL); + } - return !((int)$running === 0); - } + return ! ((int) $running === 0); + } - /** - * Check if Tmux is running, if it is, stop it. - * - * @return bool true if scripts were running, false otherwise. - * @throws \RuntimeException - * @access public - */ - public function stopIfRunning(): bool - { - if ($this->isRunning() === true) { - TmuxModel::query()->where('setting', '=', 'running')->update(['value' => 0]); - $sleep = $this->get()->monitor_delay; - echo ColorCLI::header('Stopping tmux scripts and waiting ' . $sleep . ' seconds for all panes to shutdown'); - sleep($sleep); - return true; - } - ColorCLI::doEcho(ColorCLI::info('Tmux scripts are not running!')); - return false; - } + /** + * Check if Tmux is running, if it is, stop it. + * + * @return bool true if scripts were running, false otherwise. + * @throws \RuntimeException + */ + public function stopIfRunning(): bool + { + if ($this->isRunning() === true) { + TmuxModel::query()->where('setting', '=', 'running')->update(['value' => 0]); + $sleep = $this->get()->monitor_delay; + echo ColorCLI::header('Stopping tmux scripts and waiting '.$sleep.' seconds for all panes to shutdown'); + sleep($sleep); - /** - * @throws \RuntimeException - */ - public function startRunning() - { - if ($this->isRunning() === false) { - TmuxModel::query()->where('setting', '=', 'running')->update(['value' => 1]); - } - } + return true; + } + ColorCLI::doEcho(ColorCLI::info('Tmux scripts are not running!')); - /** - * Retrieves and returns ALL collections, binaries, parts, and missed parts table names from the Db - * - * @return bool|\PDOStatement - */ - public function cbpmTableQuery() - { - $regstr = '^(multigroup_)?(collections|binaries|parts|missed_parts)(_[0-9]+)?$'; + return false; + } - return $this->pdo->queryDirect(" + /** + * @throws \RuntimeException + */ + public function startRunning() + { + if ($this->isRunning() === false) { + TmuxModel::query()->where('setting', '=', 'running')->update(['value' => 1]); + } + } + + /** + * Retrieves and returns ALL collections, binaries, parts, and missed parts table names from the Db. + * + * @return bool|\PDOStatement + */ + public function cbpmTableQuery() + { + $regstr = '^(multigroup_)?(collections|binaries|parts|missed_parts)(_[0-9]+)?$'; + + return $this->pdo->queryDirect(" SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = (SELECT DATABASE()) AND TABLE_NAME REGEXP {$this->pdo->escapeString($regstr)} ORDER BY TABLE_NAME ASC" ); - } + } } diff --git a/nntmux/TmuxOutput.php b/nntmux/TmuxOutput.php index 8e38302e4..195390360 100755 --- a/nntmux/TmuxOutput.php +++ b/nntmux/TmuxOutput.php @@ -1,133 +1,134 @@ <?php + namespace nntmux; use nntmux\db\DB; use nntmux\utility\Utility; /** - * Tmux output functions for printing monitor data + * Tmux output functions for printing monitor data. * * Class TmuxOutput */ class TmuxOutput extends Tmux { - /** - * @var \simpleXMLElement object - */ - protected $_vers; + /** + * @var \simpleXMLElement object + */ + protected $_vers; - /** - * @var array Different colour masks settings used by Tmux display functions - */ - protected $_colourMasks; + /** + * @var array Different colour masks settings used by Tmux display functions + */ + protected $_colourMasks; - /** - * @var array The various Tmux runtime configuration variables - */ - private $runVar; + /** + * @var array The various Tmux runtime configuration variables + */ + private $runVar; - /** - * @var array of current format masks to use. - */ - private $tmpMasks; + /** + * @var array of current format masks to use. + */ + private $tmpMasks; + /** + * @param DB $pdo + */ + public function __construct(DB $pdo = null) + { + parent::__construct($pdo); + $this->_vers = Utility::getValidVersionsFile(); - /** - * @param DB $pdo - */ - public function __construct(DB $pdo = null) - { - parent::__construct($pdo); - $this->_vers = Utility::getValidVersionsFile(); + $this->_setColourMasks(); + } - $this->_setColourMasks(); - } + public function updateMonitorPane(&$runVar) + { + $this->runVar = $runVar; + $this->tmpMasks = $this->_getFormatMasks($runVar['settings']['compressed']); - public function updateMonitorPane(&$runVar) - { - $this->runVar = $runVar; - $this->tmpMasks = $this->_getFormatMasks($runVar['settings']['compressed']); + $buffer = $this->_getHeader(); - $buffer = $this->_getHeader(); + if ($runVar['settings']['monitor'] > 0) { + $buffer .= $this->_getMonitor(); + } - if ($runVar['settings']['monitor'] > 0) { - $buffer .= $this->_getMonitor(); - } + if ($runVar['settings']['show_query'] == 1) { + $buffer .= $this->_getQueries(); + } - if ($runVar['settings']['show_query'] == 1) { - $buffer .= $this->_getQueries(); - } + //begin update display with screen clear + passthru('clear'); + echo $buffer; + } - //begin update display with screen clear - passthru('clear'); - echo $buffer; - } + protected function _getBackfill() + { + $buffer = sprintf($this->tmpMasks[3], 'Groups', 'Active', 'Backfill'); + $buffer .= $this->_getSeparator(); - protected function _getBackfill() - { - $buffer = sprintf($this->tmpMasks[3], "Groups", "Active", "Backfill"); - $buffer .= $this->_getSeparator(); - - if ($this->runVar['settings']['backfilldays'] == "1") { - $buffer .= sprintf($this->tmpMasks[4], - "Activated", + if ($this->runVar['settings']['backfilldays'] == '1') { + $buffer .= sprintf($this->tmpMasks[4], + 'Activated', sprintf( - "%d(%d)", + '%d(%d)', $this->runVar['counts']['now']['active_groups'], $this->runVar['counts']['now']['all_groups'] ), sprintf( - "%d(%d)", + '%d(%d)', $this->runVar['counts']['now']['backfill_groups_days'], $this->runVar['counts']['now']['all_groups'] ) ); - } else { - $buffer .= sprintf($this->tmpMasks[4], - "Activated", + } else { + $buffer .= sprintf($this->tmpMasks[4], + 'Activated', sprintf( - "%d(%d)", + '%d(%d)', $this->runVar['counts']['now']['active_groups'], $this->runVar['counts']['now']['all_groups'] ), sprintf( - "%d(%d)", + '%d(%d)', $this->runVar['counts']['now']['backfill_groups_date'], $this->runVar['counts']['now']['all_groups'] ) ); - } + } - return $buffer; - } + return $buffer; + } - protected function _getFormatMasks($compressed) - { - $index = ($compressed == 1 ? '2.1' : '2.0'); - return [ + protected function _getFormatMasks($compressed) + { + $index = ($compressed == 1 ? '2.1' : '2.0'); + + return [ 1 => &$this->_colourMasks[1], 2 => &$this->_colourMasks[$index], 3 => &$this->_colourMasks[3], 4 => &$this->_colourMasks[4], 5 => &$this->_colourMasks[5], ]; - } + } - protected function _getHeader() - { - $buffer = ''; - $state = ($this->runVar['settings']['is_running'] == 1) ? 'Running' : 'Disabled'; - $version = $this->_vers->versions->git->tag; + protected function _getHeader() + { + $buffer = ''; + $state = ($this->runVar['settings']['is_running'] == 1) ? 'Running' : 'Disabled'; + $version = $this->_vers->versions->git->tag; - $buffer .= sprintf($this->tmpMasks[2], - "Monitor $state $version [" . $this->runVar['constants']['sqlpatch'] . "]: ", + $buffer .= sprintf($this->tmpMasks[2], + "Monitor $state $version [".$this->runVar['constants']['sqlpatch'].']: ', $this->relativeTime($this->runVar['timers']['timer1']) ); - $buffer .= sprintf($this->tmpMasks[1], - "USP Connections:", + $buffer .= sprintf($this->tmpMasks[1], + 'USP Connections:', sprintf( - "%d active (%d total) - %s:%d", + '%d active (%d total) - %s:%d', $this->runVar['conncounts']['primary']['active'], $this->runVar['conncounts']['primary']['total'], $this->runVar['connections']['host'], @@ -135,323 +136,323 @@ class TmuxOutput extends Tmux ) ); - if ($this->runVar['constants']['alternate_nntp']) { - $buffer .= sprintf($this->tmpMasks[1], - "USP Alternate:", + if ($this->runVar['constants']['alternate_nntp']) { + $buffer .= sprintf($this->tmpMasks[1], + 'USP Alternate:', sprintf( - "%d active (%d total) - %s:%d)", + '%d active (%d total) - %s:%d)', $this->runVar['conncounts']['alternate']['active'], $this->runVar['conncounts']['alternate']['total'], $this->runVar['connections']['host_a'], $this->runVar['connections']['port_a'] ) ); - } + } - $buffer .= sprintf($this->tmpMasks[1], - "Newest Release:", + $buffer .= sprintf($this->tmpMasks[1], + 'Newest Release:', $this->runVar['timers']['newOld']['newestrelname'] ); - $buffer .= sprintf($this->tmpMasks[1], - "Release Added:", + $buffer .= sprintf($this->tmpMasks[1], + 'Release Added:', sprintf( - "%s ago", + '%s ago', (isset($this->runVar['timers']['newOld']['newestrelease']) ? $this->relativeTime($this->runVar['timers']['newOld']['newestrelease']) : 0) ) ); - $buffer .= sprintf($this->tmpMasks[1], - "Predb Updated:", + $buffer .= sprintf($this->tmpMasks[1], + 'Predb Updated:', sprintf( - "%s ago", + '%s ago', (isset($this->runVar['timers']['newOld']['newestpre']) ? $this->relativeTime($this->runVar['timers']['newOld']['newestpre']) : 0) ) ); - $buffer .= sprintf($this->tmpMasks[1], + $buffer .= sprintf($this->tmpMasks[1], sprintf( - "Collection Age[%d]:", + 'Collection Age[%d]:', $this->runVar['constants']['delaytime'] ), sprintf( - "%s ago", + '%s ago', (isset($this->runVar['timers']['newOld']['oldestcollection']) ? $this->relativeTime($this->runVar['timers']['newOld']['oldestcollection']) : 0) ) ); - $buffer .= sprintf($this->tmpMasks[1], - "Parts in Repair:", + $buffer .= sprintf($this->tmpMasks[1], + 'Parts in Repair:', number_format($this->runVar['counts']['now']['missed_parts_table']) ); - if (($this->runVar['settings']['post'] == "1" || $this->runVar['settings']['post'] == "3") && $this->runVar['constants']['sequential'] != 2) { - $buffer .= sprintf($this->tmpMasks[1], - "Postprocess:", - "stale for " . $this->relativeTime($this->runVar['timers']['timer3']) + if (($this->runVar['settings']['post'] == '1' || $this->runVar['settings']['post'] == '3') && $this->runVar['constants']['sequential'] != 2) { + $buffer .= sprintf($this->tmpMasks[1], + 'Postprocess:', + 'stale for '.$this->relativeTime($this->runVar['timers']['timer3']) ); - } + } - return $buffer . PHP_EOL; - } + return $buffer.PHP_EOL; + } - protected function _getMonitor() - { - $buffer = $this->_getTableCounts(); - $buffer .= $this->_getPaths(); + protected function _getMonitor() + { + $buffer = $this->_getTableCounts(); + $buffer .= $this->_getPaths(); - $buffer .= sprintf($this->tmpMasks[3], "PP Lists", "Unmatched", "Matched"); - $buffer .= $this->_getSeparator(); + $buffer .= sprintf($this->tmpMasks[3], 'PP Lists', 'Unmatched', 'Matched'); + $buffer .= $this->_getSeparator(); - $buffer .= sprintf($this->tmpMasks[4], - "Nfo", + $buffer .= sprintf($this->tmpMasks[4], + 'Nfo', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['processnfo']), $this->runVar['counts']['diff']['processnfo'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['nfo']), $this->runVar['counts']['percent']['nfo'] ) ); - $buffer .= sprintf($this->tmpMasks[4], - "PreDB", + $buffer .= sprintf($this->tmpMasks[4], + 'PreDB', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['predb'] - $this->runVar['counts']['now']['distinct_predb_matched']), $this->runVar['counts']['diff']['distinct_predb_matched'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['predb_matched']), $this->runVar['counts']['percent']['predb_matched'] ) ); - $buffer .= sprintf($this->tmpMasks[4], - "RequestID", + $buffer .= sprintf($this->tmpMasks[4], + 'RequestID', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['requestid_inprogress']), $this->runVar['counts']['diff']['requestid_inprogress'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['requestid_matched']), $this->runVar['counts']['percent']['requestid_matched'] ) ); - $buffer .= sprintf($this->tmpMasks[4], - "Renames", + $buffer .= sprintf($this->tmpMasks[4], + 'Renames', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['processrenames']), $this->runVar['counts']['diff']['processrenames'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['renamed']), $this->runVar['counts']['percent']['renamed'] ) ); - $buffer .= PHP_EOL; - $buffer .= sprintf($this->tmpMasks[3], "Category", "In Process", "In Database"); - $buffer .= $this->_getSeparator(); + $buffer .= PHP_EOL; + $buffer .= sprintf($this->tmpMasks[3], 'Category', 'In Process', 'In Database'); + $buffer .= $this->_getSeparator(); - $buffer .= sprintf($this->tmpMasks[4], - "Audio", + $buffer .= sprintf($this->tmpMasks[4], + 'Audio', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['processmusic']), $this->runVar['counts']['diff']['processmusic'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['audio']), $this->runVar['counts']['percent']['audio'] ) ); - $buffer .= sprintf($this->tmpMasks[4], - "Books", + $buffer .= sprintf($this->tmpMasks[4], + 'Books', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['processbooks']), $this->runVar['counts']['diff']['processbooks'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['books']), $this->runVar['counts']['percent']['books'] ) ); - $buffer .= sprintf($this->tmpMasks[4], - "Console", + $buffer .= sprintf($this->tmpMasks[4], + 'Console', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['processconsole']), $this->runVar['counts']['diff']['processconsole'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['console']), $this->runVar['counts']['percent']['console'] ) ); - $buffer .= sprintf($this->tmpMasks[4], - "Misc", + $buffer .= sprintf($this->tmpMasks[4], + 'Misc', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['work']), $this->runVar['counts']['diff']['work'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['misc']), $this->runVar['counts']['percent']['misc'] ) ); - $buffer .= sprintf($this->tmpMasks[4], - "Movie", + $buffer .= sprintf($this->tmpMasks[4], + 'Movie', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['processmovies']), $this->runVar['counts']['diff']['processmovies'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['movies']), $this->runVar['counts']['percent']['movies'] ) ); - $buffer .= sprintf($this->tmpMasks[4], - "PC", + $buffer .= sprintf($this->tmpMasks[4], + 'PC', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['processgames']), $this->runVar['counts']['diff']['processgames'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['pc']), $this->runVar['counts']['percent']['pc'] ) ); - $buffer .= sprintf($this->tmpMasks[4], - "TV", + $buffer .= sprintf($this->tmpMasks[4], + 'TV', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['processtv']), $this->runVar['counts']['diff']['processtv'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['tv']), $this->runVar['counts']['percent']['tv'] ) ); - $buffer .= sprintf($this->tmpMasks[4], - "XXX", + $buffer .= sprintf($this->tmpMasks[4], + 'XXX', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['processxxx']), $this->runVar['counts']['diff']['processxxx'] ), sprintf( - "%s(%d%%)", + '%s(%d%%)', number_format($this->runVar['counts']['now']['xxx']), $this->runVar['counts']['percent']['xxx'] ) ); - $buffer .= $this->_getSeparator(); + $buffer .= $this->_getSeparator(); - $buffer .= sprintf($this->tmpMasks[4], - "Total", + $buffer .= sprintf($this->tmpMasks[4], + 'Total', sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['total_work']), $this->runVar['counts']['diff']['total_work'] ), sprintf( - "%s(%s)", + '%s(%s)', number_format($this->runVar['counts']['now']['releases']), $this->runVar['counts']['diff']['releases'] ) ); - $buffer .= PHP_EOL; + $buffer .= PHP_EOL; - $buffer .= $this->_getBackfill(); + $buffer .= $this->_getBackfill(); - return $buffer; - } + return $buffer; + } - protected function _getPaths() - { - $buffer = ''; + protected function _getPaths() + { + $buffer = ''; - // assign timers from tmux table - $monitor_path = $this->runVar['settings']['monitor_path']; - $monitor_path_a = $this->runVar['settings']['monitor_path_a']; - $monitor_path_b = $this->runVar['settings']['monitor_path_b']; + // assign timers from tmux table + $monitor_path = $this->runVar['settings']['monitor_path']; + $monitor_path_a = $this->runVar['settings']['monitor_path_a']; + $monitor_path_b = $this->runVar['settings']['monitor_path_b']; - if (((isset($monitor_path)) && (file_exists($monitor_path))) + if (((isset($monitor_path)) && (file_exists($monitor_path))) || ((isset($monitor_path_a)) && (file_exists($monitor_path_a))) || ((isset($monitor_path_b)) && (file_exists($monitor_path_b)))) { + $buffer .= "\n"; + $buffer .= sprintf($this->tmpMasks[3], 'File System', 'Used', 'Free'); + $buffer .= $this->_getSeparator(); - $buffer .= "\n"; - $buffer .= sprintf($this->tmpMasks[3], "File System", "Used", "Free"); - $buffer .= $this->_getSeparator(); + if (isset($monitor_path) && $monitor_path != '' && file_exists($monitor_path)) { + $disk_use = $this->decodeSize(disk_total_space($monitor_path) - disk_free_space($monitor_path)); + $disk_free = $this->decodeSize(disk_free_space($monitor_path)); + if (basename($monitor_path) == '') { + $show = '/'; + } else { + $show = basename($monitor_path); + } + $buffer .= sprintf($this->tmpMasks[4], $show, $disk_use, $disk_free); + } - if (isset($monitor_path) && $monitor_path != "" && file_exists($monitor_path)) { - $disk_use = $this->decodeSize(disk_total_space($monitor_path) - disk_free_space($monitor_path)); - $disk_free = $this->decodeSize(disk_free_space($monitor_path)); - if (basename($monitor_path) == "") { - $show = "/"; - } else { - $show = basename($monitor_path); - } - $buffer .= sprintf($this->tmpMasks[4], $show, $disk_use, $disk_free); - } + if (isset($monitor_path_a) && $monitor_path_a != '' && file_exists($monitor_path_a)) { + $disk_use = $this->decodeSize(disk_total_space($monitor_path_a) - disk_free_space($monitor_path_a)); + $disk_free = $this->decodeSize(disk_free_space($monitor_path_a)); + if (basename($monitor_path_a) == '') { + $show = '/'; + } else { + $show = basename($monitor_path_a); + } + $buffer .= sprintf($this->tmpMasks[4], $show, $disk_use, $disk_free); + } - if (isset($monitor_path_a) && $monitor_path_a != "" && file_exists($monitor_path_a)) { - $disk_use = $this->decodeSize(disk_total_space($monitor_path_a) - disk_free_space($monitor_path_a)); - $disk_free = $this->decodeSize(disk_free_space($monitor_path_a)); - if (basename($monitor_path_a) == "") { - $show = "/"; - } else { - $show = basename($monitor_path_a); - } - $buffer .= sprintf($this->tmpMasks[4], $show, $disk_use, $disk_free); - } + if (isset($monitor_path_b) && $monitor_path_b != '' && file_exists($monitor_path_b)) { + $disk_use = $this->decodeSize(disk_total_space($monitor_path_b) - disk_free_space($monitor_path_b)); + $disk_free = $this->decodeSize(disk_free_space($monitor_path_b)); + if (basename($monitor_path_b) == '') { + $show = '/'; + } else { + $show = basename($monitor_path_b); + } + $buffer .= sprintf($this->tmpMasks[4], $show, $disk_use, $disk_free); + } + } - if (isset($monitor_path_b) && $monitor_path_b != "" && file_exists($monitor_path_b)) { - $disk_use = $this->decodeSize(disk_total_space($monitor_path_b) - disk_free_space($monitor_path_b)); - $disk_free = $this->decodeSize(disk_free_space($monitor_path_b)); - if (basename($monitor_path_b) == "") { - $show = "/"; - } else { - $show = basename($monitor_path_b); - } - $buffer .= sprintf($this->tmpMasks[4], $show, $disk_use, $disk_free); - } - } - return $buffer . PHP_EOL; - } + return $buffer.PHP_EOL; + } - protected function _getQueries() - { - $buffer = PHP_EOL; - $buffer .= sprintf($this->tmpMasks[3], "Query Block", "Time", "Cumulative"); - $buffer .= $this->_getSeparator(); - $buffer .= sprintf($this->tmpMasks[4], - "Combined", + protected function _getQueries() + { + $buffer = PHP_EOL; + $buffer .= sprintf($this->tmpMasks[3], 'Query Block', 'Time', 'Cumulative'); + $buffer .= $this->_getSeparator(); + $buffer .= sprintf($this->tmpMasks[4], + 'Combined', sprintf( - "%d %d %d %d %d %d %d", + '%d %d %d %d %d %d %d', $this->runVar['timers']['query']['tmux_time'], $this->runVar['timers']['query']['split_time'], $this->runVar['timers']['query']['init_time'], @@ -461,7 +462,7 @@ class TmuxOutput extends Tmux $this->runVar['timers']['query']['tpg_time'] ), sprintf( - "%d %d %d %d %d %d %d", + '%d %d %d %d %d %d %d', $this->runVar['timers']['query']['tmux_time'], $this->runVar['timers']['query']['split1_time'], $this->runVar['timers']['query']['init1_time'], @@ -472,51 +473,50 @@ class TmuxOutput extends Tmux ) ); - $pieces = explode(" ", $this->pdo->getAttribute(\PDO::ATTR_SERVER_INFO)); - $buffer .= ColorCLI::primaryOver("\nThreads = ") . - ColorCLI::headerOver($pieces[4]) . - ColorCLI::primaryOver(', Opens = ') . - ColorCLI::headerOver($pieces[14]) . - ColorCLI::primaryOver(', Tables = ') . - ColorCLI::headerOver($pieces[22]) . - ColorCLI::primaryOver(', Slow = ') . - ColorCLI::headerOver($pieces[11]) . - ColorCLI::primaryOver(', QPS = ') . - ColorCLI::header($pieces[28]) - ; + $pieces = explode(' ', $this->pdo->getAttribute(\PDO::ATTR_SERVER_INFO)); + $buffer .= ColorCLI::primaryOver("\nThreads = "). + ColorCLI::headerOver($pieces[4]). + ColorCLI::primaryOver(', Opens = '). + ColorCLI::headerOver($pieces[14]). + ColorCLI::primaryOver(', Tables = '). + ColorCLI::headerOver($pieces[22]). + ColorCLI::primaryOver(', Slow = '). + ColorCLI::headerOver($pieces[11]). + ColorCLI::primaryOver(', QPS = '). + ColorCLI::header($pieces[28]); - return $buffer; - } + return $buffer; + } - protected function _getSeparator() - { - return sprintf($this->tmpMasks[3], - "======================================", - "=========================", - "======================================" + protected function _getSeparator() + { + return sprintf($this->tmpMasks[3], + '======================================', + '=========================', + '======================================' ); - } + } - protected function _getTableCounts() - { - $buffer = sprintf($this->tmpMasks[3], "Collections", "Binaries", "Parts"); - $buffer .= $this->_getSeparator(); - $buffer .= sprintf($this->tmpMasks[5], + protected function _getTableCounts() + { + $buffer = sprintf($this->tmpMasks[3], 'Collections', 'Binaries', 'Parts'); + $buffer .= $this->_getSeparator(); + $buffer .= sprintf($this->tmpMasks[5], number_format($this->runVar['counts']['now']['collections_table']), number_format($this->runVar['counts']['now']['binaries_table']), number_format($this->runVar['counts']['now']['parts_table']) ); - return $buffer; - } + return $buffer; + } - protected function _setColourMasks() - { - $this->_colourMasks[1] = ColorCLI::headerOver("%-18s") . " " . ColorCLI::tmuxOrange("%-48.48s"); - $this->_colourMasks['2.0'] = ColorCLI::alternateOver("%-20s") . " " . ColorCLI::tmuxOrange("%-33.33s"); - $this->_colourMasks['2.1'] = ColorCLI::headerOver("%-20s") . " " . ColorCLI::tmuxOrange("%-33.33s"); - $this->_colourMasks[3] = ColorCLI::header("%-16.16s %25.25s %25.25s"); - $this->_colourMasks[4] = ColorCLI::primaryOver("%-16.16s") . " " . ColorCLI::tmuxOrange("%25.25s %25.25s"); - $this->_colourMasks[5] = ColorCLI::tmuxOrange("%-16.16s %25.25s %25.25s"); - } + protected function _setColourMasks() + { + $this->_colourMasks[1] = ColorCLI::headerOver('%-18s').' '.ColorCLI::tmuxOrange('%-48.48s'); + $this->_colourMasks['2.0'] = ColorCLI::alternateOver('%-20s').' '.ColorCLI::tmuxOrange('%-33.33s'); + $this->_colourMasks['2.1'] = ColorCLI::headerOver('%-20s').' '.ColorCLI::tmuxOrange('%-33.33s'); + $this->_colourMasks[3] = ColorCLI::header('%-16.16s %25.25s %25.25s'); + $this->_colourMasks[4] = ColorCLI::primaryOver('%-16.16s').' '.ColorCLI::tmuxOrange('%25.25s %25.25s'); + $this->_colourMasks[5] = ColorCLI::tmuxOrange('%-16.16s %25.25s %25.25s'); + } } diff --git a/nntmux/TmuxRun.php b/nntmux/TmuxRun.php index c5bc2733b..ac5364237 100755 --- a/nntmux/TmuxRun.php +++ b/nntmux/TmuxRun.php @@ -1,45 +1,45 @@ <?php + namespace nntmux; -use App\Models\Settings; use nntmux\db\DB; +use App\Models\Settings; /** - * Tmux pane shell exec functions for pane respawning + * Tmux pane shell exec functions for pane respawning. * * Class TmuxRun */ class TmuxRun extends Tmux { - protected $_dateFormat; + protected $_dateFormat; - /** - * @param \nntmux\db\DB $pdo - * - * @throws \Exception - */ - public function __construct(DB $pdo = null) - { - parent::__construct($pdo); - $dateFormat = Settings::value( + /** + * @param \nntmux\db\DB $pdo + * + * @throws \Exception + */ + public function __construct(DB $pdo = null) + { + parent::__construct($pdo); + $dateFormat = Settings::value( [ 'section' => 'shell', 'subsection' => 'date', - 'name' => 'format' + 'name' => 'format', ]); - $this->_dateFormat = $dateFormat ?? '%Y-%m-%d %T'; + $this->_dateFormat = $dateFormat ?? '%Y-%m-%d %T'; + } - } + // main switch for running tmux panes - // main switch for running tmux panes - - /** - * @param $cmdParam - * @param $runVar - */ - public function runPane($cmdParam, &$runVar) - { - switch ((int) $runVar['constants']['sequential']) { + /** + * @param $cmdParam + * @param $runVar + */ + public function runPane($cmdParam, &$runVar) + { + switch ((int) $runVar['constants']['sequential']) { case 0: switch ((string) $cmdParam) { case 'amazon': @@ -146,14 +146,14 @@ class TmuxRun extends Tmux } break; } - } + } - /** - * @param $runVar - */ - protected function _runDehash(&$runVar) - { - switch ($runVar['settings']['dehash']) { + /** + * @param $runVar + */ + protected function _runDehash(&$runVar) + { + switch ($runVar['settings']['dehash']) { case 1: $log = $this->writelog($runVar['panes']['one'][3]); shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:1.3 ' \ @@ -183,50 +183,50 @@ class TmuxRun extends Tmux $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.3 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][3]} has been disabled/terminated by Decrypt Hashes\"'"); } - } + } - /** - * @param $runVar - */ - protected function _runFixReleaseNames(&$runVar) - { - if ((int)$runVar['settings']['fix_names'] === 1) { - if ($runVar['counts']['now']['processrenames'] > 0) { - $log = $this->writelog($runVar['panes']['one'][0]); - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:1.0 ' \ + /** + * @param $runVar + */ + protected function _runFixReleaseNames(&$runVar) + { + if ((int) $runVar['settings']['fix_names'] === 1) { + if ($runVar['counts']['now']['processrenames'] > 0) { + $log = $this->writelog($runVar['panes']['one'][0]); + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:1.0 ' \ {$runVar['commands']['_php']} {$runVar['paths']['misc']}update/nix/multiprocessing/fixrelnames.php standard $log; \ {$runVar['commands']['_php']} {$runVar['paths']['misc']}update/nix/multiprocessing/fixrelnames.php predbft $log; date +\"{$this->_dateFormat}\"; \ {$runVar['commands']['_sleep']} {$runVar['settings']['fix_timer']}' 2>&1 1> /dev/null" ); - } else { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.0 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][0]} has been disabled/terminated by no Fix Release Names to process\"'"); - } - } else { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.0 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][0]} has been disabled/terminated by Fix Release Names\"'"); - } - } + } else { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.0 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][0]} has been disabled/terminated by no Fix Release Names to process\"'"); + } + } else { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.0 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][0]} has been disabled/terminated by Fix Release Names\"'"); + } + } - /** - * @param $runVar - */ - protected function _runAmazon(&$runVar) - { - switch (true) { - case (int)$runVar['settings']['post_amazon'] === 1 && + /** + * @param $runVar + */ + protected function _runAmazon(&$runVar) + { + switch (true) { + case (int) $runVar['settings']['post_amazon'] === 1 && ( - (int)$runVar['counts']['now']['processmusic'] > 0 || - (int)$runVar['counts']['now']['processbooks'] > 0 || - (int)$runVar['counts']['now']['processconsole'] > 0 || - (int)$runVar['counts']['now']['processgames'] > 0 || - (int)$runVar['counts']['now']['processxxx'] > 0 + (int) $runVar['counts']['now']['processmusic'] > 0 || + (int) $runVar['counts']['now']['processbooks'] > 0 || + (int) $runVar['counts']['now']['processconsole'] > 0 || + (int) $runVar['counts']['now']['processgames'] > 0 || + (int) $runVar['counts']['now']['processxxx'] > 0 ) && ( - (int)$runVar['settings']['processbooks'] === 1 || - (int)$runVar['settings']['processmusic'] === 1 || - (int)$runVar['settings']['processgames'] === 1 || - (int)$runVar['settings']['processxxx'] === 1 + (int) $runVar['settings']['processbooks'] === 1 || + (int) $runVar['settings']['processmusic'] === 1 || + (int) $runVar['settings']['processgames'] === 1 || + (int) $runVar['settings']['processxxx'] === 1 ): $log = $this->writelog($runVar['panes']['two'][2]); @@ -234,16 +234,16 @@ class TmuxRun extends Tmux {$runVar['commands']['_phpn']} {$runVar['paths']['misc']}update/postprocess.php amazon true $log; date +\"{$this->_dateFormat}\"; {$runVar['commands']['_sleep']} {$runVar['settings']['post_timer_amazon']}' 2>&1 1> /dev/null" ); break; - case (int)$runVar['settings']['post_amazon'] === 1 && (int)$runVar['settings']['processbooks'] === 0 - && (int)$runVar['settings']['processmusic'] === 0 && (int)$runVar['settings']['processgames'] === 0 - && (int)$runVar['settings']['processxxx'] === 0: + case (int) $runVar['settings']['post_amazon'] === 1 && (int) $runVar['settings']['processbooks'] === 0 + && (int) $runVar['settings']['processmusic'] === 0 && (int) $runVar['settings']['processgames'] === 0 + && (int) $runVar['settings']['processxxx'] === 0: $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.2 \ 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][2]} has been disabled/terminated in Admin Disable Music/Books/Console/XXX\"'"); break; - case (int)$runVar['settings']['post_amazon'] === 1 && (int)$runVar['counts']['now']['processmusic'] === 0 && - (int)$runVar['counts']['now']['processbooks'] === 0 && (int)$runVar['counts']['now']['processconsole'] === 0 && (int)$runVar['counts']['now']['processgames'] === 0 && (int)$runVar['counts']['now']['processxxx'] === 0: + case (int) $runVar['settings']['post_amazon'] === 1 && (int) $runVar['counts']['now']['processmusic'] === 0 && + (int) $runVar['counts']['now']['processbooks'] === 0 && (int) $runVar['counts']['now']['processconsole'] === 0 && (int) $runVar['counts']['now']['processgames'] === 0 && (int) $runVar['counts']['now']['processxxx'] === 0: $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.2 \ 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][2]} has been disabled/terminated by No Music/Books/Console/Games/XXX to process\"'"); @@ -253,21 +253,21 @@ class TmuxRun extends Tmux shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.2 \ 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][2]} has been disabled/terminated by Postprocess Amazon\"'"); } - } + } - /** - * @param $runVar - */ - protected function _runAmazonFull(&$runVar) - { - switch (true) { - case ((int)$runVar['settings']['post_amazon'] === 1) && (((int)$runVar['counts']['now']['processmusic'] > 0) - || ((int)$runVar['counts']['now']['processbooks'] > 0) || ((int)$runVar['counts']['now']['processconsole'] > 0) - || ((int)$runVar['counts']['now']['processgames'] > 0) || ((int)$runVar['counts']['now']['processxxx'] > 0)) - && (((int)$runVar['settings']['processbooks'] !== 0) || ((int)$runVar['settings']['processconsole'] !== 0) - || ((int)$runVar['settings']['processmusic'] !== 0) || - ((int)$runVar['settings']['processgames'] !== 0) - || ((int)$runVar['settings']['processxxx'] !== 0)): + /** + * @param $runVar + */ + protected function _runAmazonFull(&$runVar) + { + switch (true) { + case ((int) $runVar['settings']['post_amazon'] === 1) && (((int) $runVar['counts']['now']['processmusic'] > 0) + || ((int) $runVar['counts']['now']['processbooks'] > 0) || ((int) $runVar['counts']['now']['processconsole'] > 0) + || ((int) $runVar['counts']['now']['processgames'] > 0) || ((int) $runVar['counts']['now']['processxxx'] > 0)) + && (((int) $runVar['settings']['processbooks'] !== 0) || ((int) $runVar['settings']['processconsole'] !== 0) + || ((int) $runVar['settings']['processmusic'] !== 0) || + ((int) $runVar['settings']['processgames'] !== 0) + || ((int) $runVar['settings']['processxxx'] !== 0)): $log = $this->writelog($runVar['panes']['one'][1]); shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:1.1 ' \ @@ -275,18 +275,18 @@ class TmuxRun extends Tmux date +\"{$this->_dateFormat}\"; {$runVar['commands']['_sleep']} {$runVar['settings']['post_timer_amazon']}' 2>&1 1> /dev/null" ); break; - case ((int)$runVar['settings']['post_amazon'] === 1) && ((int)$runVar['settings']['processbooks'] === 0) - && ((int)$runVar['counts']['now']['processconsole'] === 0) && ((int)$runVar['settings']['processmusic'] === 0) - && ((int)$runVar['settings']['processgames'] === 0): + case ((int) $runVar['settings']['post_amazon'] === 1) && ((int) $runVar['settings']['processbooks'] === 0) + && ((int) $runVar['counts']['now']['processconsole'] === 0) && ((int) $runVar['settings']['processmusic'] === 0) + && ((int) $runVar['settings']['processgames'] === 0): $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.1 \ 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][1]} has been disabled/terminated in Admin Disable Music/Books/Console/XXX\"'" ); break; - case ((int)$runVar['settings']['post_amazon'] === 1) && ((int)$runVar['counts']['now']['processmusic'] === 0) - && ((int)$runVar['counts']['now']['processbooks'] === 0) && ((int)$runVar['counts']['now']['processconsole'] === 0) - && ((int)$runVar['counts']['now']['processgames'] === 0) && ((int)$runVar['counts']['now']['processxxx'] === 0): + case ((int) $runVar['settings']['post_amazon'] === 1) && ((int) $runVar['counts']['now']['processmusic'] === 0) + && ((int) $runVar['counts']['now']['processbooks'] === 0) && ((int) $runVar['counts']['now']['processconsole'] === 0) + && ((int) $runVar['counts']['now']['processgames'] === 0) && ((int) $runVar['counts']['now']['processxxx'] === 0): $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.1 \ @@ -299,12 +299,12 @@ class TmuxRun extends Tmux 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][1]} has been disabled/terminated by Postprocess Amazon\"'" ); } - } + } - protected function _runNonAmazon(&$runVar) - { - switch (true) { - case (int)$runVar['settings']['post_non'] !== 0 && ((int)$runVar['counts']['now']['processmovies'] > 0 || (int)$runVar['counts']['now']['processtv'] > 0 || $runVar['counts']['now']['processanime'] > 0): + protected function _runNonAmazon(&$runVar) + { + switch (true) { + case (int) $runVar['settings']['post_non'] !== 0 && ((int) $runVar['counts']['now']['processmovies'] > 0 || (int) $runVar['counts']['now']['processtv'] > 0 || $runVar['counts']['now']['processanime'] > 0): $log = $this->writelog($runVar['panes']['two'][1]); shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:2.1 ' \ {$runVar['commands']['_php']} {$runVar['paths']['misc']}update/nix/multiprocessing/postprocess.php tv $log; \ @@ -314,7 +314,7 @@ class TmuxRun extends Tmux date +\"{$this->_dateFormat}\"; {$runVar['commands']['_sleep']} {$runVar['settings']['post_timer_non']}' 2>&1 1> /dev/null" ); break; - case (int)$runVar['settings']['post_non'] !== 0 && (int)$runVar['counts']['now']['processmovies'] === 0 && (int)$runVar['counts']['now']['processtv'] === 0 && (int)$runVar['counts']['now']['processanime'] === 0: + case (int) $runVar['settings']['post_non'] !== 0 && (int) $runVar['counts']['now']['processmovies'] === 0 && (int) $runVar['counts']['now']['processtv'] === 0 && (int) $runVar['counts']['now']['processanime'] === 0: $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.1 \ 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][1]} has been disabled/terminated by No Movies/TV/Anime to process\"'"); @@ -324,77 +324,77 @@ class TmuxRun extends Tmux shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.1 \ 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][1]} has been disabled/terminated by Postprocess Non-Amazon\"'"); } - } + } - /** - * @param $runVar - */ - protected function _runNonUpdateBinaries(&$runVar) - { - //run update_binaries - //$color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - if (((int)$runVar['settings']['binaries_run'] !== 0) && ($runVar['killswitch']['pp'] === false)) { - $log = $this->writelog($runVar['panes']['zero'][2]); - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 ' \ + /** + * @param $runVar + */ + protected function _runNonUpdateBinaries(&$runVar) + { + //run update_binaries + //$color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + if (((int) $runVar['settings']['binaries_run'] !== 0) && ($runVar['killswitch']['pp'] === false)) { + $log = $this->writelog($runVar['panes']['zero'][2]); + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 ' \ {$runVar['scripts']['binaries']} $log; date +\"{$this->_dateFormat}\"; {$runVar['commands']['_sleep']} {$runVar['settings']['bins_timer']}' 2>&1 1> /dev/null" ); - } else if ($runVar['killswitch']['pp'] === true) { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.2 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][2]} has been disabled/terminated by Exceeding Limits\"'"); - } else { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.2 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][2]} has been disabled/terminated by Binaries\"'"); - } - } + } elseif ($runVar['killswitch']['pp'] === true) { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.2 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][2]} has been disabled/terminated by Exceeding Limits\"'"); + } else { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.2 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][2]} has been disabled/terminated by Binaries\"'"); + } + } - /** - * @param $runVar - */ - protected function _runNonBackfill(&$runVar) - { - //run backfill - $backsleep = ((int)$runVar['settings']['progressive'] === 1 && floor($runVar['counts']['now']['collections_table'] / 500) > $runVar['settings']['back_timer'] + /** + * @param $runVar + */ + protected function _runNonBackfill(&$runVar) + { + //run backfill + $backsleep = ((int) $runVar['settings']['progressive'] === 1 && floor($runVar['counts']['now']['collections_table'] / 500) > $runVar['settings']['back_timer'] ? floor($runVar['counts']['now']['collections_table'] / 500) : $runVar['settings']['back_timer'] ); - if (((int)$runVar['settings']['backfill'] !== 0) && ($runVar['killswitch']['coll'] === false) && ($runVar['killswitch']['pp'] === false)) { - $log = $this->writelog($runVar['panes']['zero'][3]); - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.3 ' \ + if (((int) $runVar['settings']['backfill'] !== 0) && ($runVar['killswitch']['coll'] === false) && ($runVar['killswitch']['pp'] === false)) { + $log = $this->writelog($runVar['panes']['zero'][3]); + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.3 ' \ {$runVar['scripts']['backfill']} $log; date +\"{$this->_dateFormat}\"; {$runVar['commands']['_sleep']} $backsleep' 2>&1 1> /dev/null" ); - } else if (($runVar['killswitch']['coll'] === true) || ($runVar['killswitch']['pp'] === true)) { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.3 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][3]} has been disabled/terminated by Exceeding Limits\"'"); - } else { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.3 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][3]} has been disabled/terminated by Backfill\"'"); - } - } + } elseif (($runVar['killswitch']['coll'] === true) || ($runVar['killswitch']['pp'] === true)) { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.3 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][3]} has been disabled/terminated by Exceeding Limits\"'"); + } else { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.3 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][3]} has been disabled/terminated by Backfill\"'"); + } + } - /** - * @param $runVar - */ - protected function _runNonUpdateReleases(&$runVar) - { - //run update_releases - if ((int)$runVar['settings']['releases_run'] !== 0) { - $log = $this->writelog($runVar['panes']['zero'][4]); - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.4 ' \ + /** + * @param $runVar + */ + protected function _runNonUpdateReleases(&$runVar) + { + //run update_releases + if ((int) $runVar['settings']['releases_run'] !== 0) { + $log = $this->writelog($runVar['panes']['zero'][4]); + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.4 ' \ {$runVar['scripts']['releases']} $log; date +\"{$this->_dateFormat}\"; {$runVar['commands']['_sleep']} {$runVar['settings']['rel_timer']}' 2>&1 1> /dev/null" ); - } else { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.4 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][4]} has been disabled/terminated by Releases\"'"); - } - } + } else { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.4 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][4]} has been disabled/terminated by Releases\"'"); + } + } - /** - * @param $runVar - */ - protected function _runNZBImport(&$runVar) - { - switch ($runVar['settings']['import']) { + /** + * @param $runVar + */ + protected function _runNZBImport(&$runVar) + { + switch ($runVar['settings']['import']) { case 1: $useFilenames = 'false'; break; @@ -405,31 +405,29 @@ class TmuxRun extends Tmux $useFilenames = 'false'; } - if (((int)$runVar['settings']['import'] !== 0) && ($runVar['killswitch']['pp'] === false)) { - $log = $this->writelog($runVar['panes']['zero'][1]); - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.1 ' \ + if (((int) $runVar['settings']['import'] !== 0) && ($runVar['killswitch']['pp'] === false)) { + $log = $this->writelog($runVar['panes']['zero'][1]); + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.1 ' \ {$runVar['commands']['_phpn']} {$runVar['paths']['misc']}update/nix/multiprocessing/import.php {$runVar['settings']['nzbs']} {$runVar['settings']['nzbthreads']} true true {$useFilenames} {$runVar['settings']['import_count']} $log; \ date +\"{$this->_dateFormat}\"; {$runVar['commands']['_sleep']} {$runVar['settings']['import_timer']}' 2>&1 1> /dev/null" ); + } elseif ($runVar['killswitch']['pp'] === true) { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.1 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][1]} has been disabled/terminated by Exceeding Limits\"'"); + } else { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.1 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][1]} has been disabled/terminated by Import\"'"); + } + } - } else if ($runVar['killswitch']['pp'] === true) { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.1 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][1]} has been disabled/terminated by Exceeding Limits\"'"); - - } else { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.1 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][1]} has been disabled/terminated by Import\"'"); - } - } - - /** - * @param $runVar - */ - protected function _runPPAdditional(&$runVar) - { - //run postprocess_releases additional - switch (true) { - case ((int)$runVar['settings']['post'] === 1) && ((int)$runVar['counts']['now']['work'] > 0): + /** + * @param $runVar + */ + protected function _runPPAdditional(&$runVar) + { + //run postprocess_releases additional + switch (true) { + case ((int) $runVar['settings']['post'] === 1) && ((int) $runVar['counts']['now']['work'] > 0): $log = $this->writelog($runVar['panes']['two'][0]); $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:2.0 'echo \"\033[38;5;${color}m\"; \ @@ -437,14 +435,14 @@ class TmuxRun extends Tmux ); $runVar['timers']['timer3'] = time(); break; - case ((int)$runVar['settings']['post'] === 2) && ((int)$runVar['counts']['now']['processnfo'] > 0): + case ((int) $runVar['settings']['post'] === 2) && ((int) $runVar['counts']['now']['processnfo'] > 0): $log = $this->writelog($runVar['panes']['two'][0]); shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:2.0 ' \ {$runVar['commands']['_php']} {$runVar['paths']['misc']}update/nix/multiprocessing/postprocess.php nfo $log; date +\"{$this->_dateFormat}\"; {$runVar['commands']['_sleep']} {$runVar['settings']['post_timer']}' 2>&1 1> /dev/null" ); $runVar['timers']['timer3'] = time(); break; - case ((int)$runVar['settings']['post'] === 3) && (((int)$runVar['counts']['now']['processnfo'] > 0) || ((int)$runVar['counts']['now']['work'] > 0)): + case ((int) $runVar['settings']['post'] === 3) && (((int) $runVar['counts']['now']['processnfo'] > 0) || ((int) $runVar['counts']['now']['work'] > 0)): //run postprocess_releases additional $log = $this->writelog($runVar['panes']['two'][0]); shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:2.0 ' \ @@ -454,7 +452,7 @@ class TmuxRun extends Tmux ); $runVar['timers']['timer3'] = time(); break; - case ((int)$runVar['settings']['post'] !== 0) && ((int)$runVar['counts']['now']['processnfo'] === 0) && ((int)$runVar['counts']['now']['work'] === 0): + case ((int) $runVar['settings']['post'] !== 0) && ((int) $runVar['counts']['now']['processnfo'] === 0) && ((int) $runVar['counts']['now']['work'] === 0): $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.0 \ 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][0]} has been disabled/terminated by No Misc/Nfo to process\"'"); @@ -463,14 +461,14 @@ class TmuxRun extends Tmux $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.0 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][0]} has been disabled/terminated by Postprocess Additional\"'"); } - } + } - /** - * @param $runVar - */ - protected function _runRemoveCrap(&$runVar) - { - switch ($runVar['settings']['fix_crap_opt']) { + /** + * @param $runVar + */ + protected function _runRemoveCrap(&$runVar) + { + switch ($runVar['settings']['fix_crap_opt']) { // Do all types up to 2 hours. case 'All': @@ -491,32 +489,32 @@ class TmuxRun extends Tmux if ($runVar['modsettings']['fc']['max'] > 0) { // If this is the first run, do a full run, else run on last 2 hours of releases. - $runVar['modsettings']['fc']['time'] = '4'; - if (($runVar['counts']['iterations'] == 1) || $runVar['modsettings']['fc']['firstrun']) { - $runVar['modsettings']['fc']['time'] = 'full'; - } + $runVar['modsettings']['fc']['time'] = '4'; + if (($runVar['counts']['iterations'] == 1) || $runVar['modsettings']['fc']['firstrun']) { + $runVar['modsettings']['fc']['time'] = 'full'; + } - //Check to see if the pane is dead, if so respawn it. - if (shell_exec("tmux list-panes -t{$runVar['constants']['tmux_session']}:1 | grep ^1 | grep -c dead") == 1) { + //Check to see if the pane is dead, if so respawn it. + if (shell_exec("tmux list-panes -t{$runVar['constants']['tmux_session']}:1 | grep ^1 | grep -c dead") == 1) { // Run remove crap releases. - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:1.1 ' \ + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:1.1 ' \ echo \"Running removeCrapReleases for {$runVar['modsettings']['fix_crap'][$runVar['modsettings']['fc']['num']]}\"; \ {$runVar['commands']['_phpn']} {$runVar['paths']['misc']}testing/Releases/removeCrapReleases.php true \ {$runVar['modsettings']['fc']['time']} {$runVar['modsettings']['fix_crap'][$runVar['modsettings']['fc']['num']]} $log; \ date +\"{$this->_dateFormat}\"; {$runVar['commands']['_sleep']} {$runVar['settings']['crap_timer']}' 2>&1 1> /dev/null" ); - // Increment so we know which type to run next. - $runVar['modsettings']['fc']['num']++; - } + // Increment so we know which type to run next. + $runVar['modsettings']['fc']['num']++; + } - // If we reached the end, reset the type. - if ((int)$runVar['modsettings']['fc']['num'] === (int)$runVar['modsettings']['fc']['max']) { - $runVar['modsettings']['fc']['num'] = 0; - // And say we are not on the first run, so we run 2 hours the next times. - $runVar['modsettings']['fc']['firstrun'] = false; - } + // If we reached the end, reset the type. + if ((int) $runVar['modsettings']['fc']['num'] === (int) $runVar['modsettings']['fc']['max']) { + $runVar['modsettings']['fc']['num'] = 0; + // And say we are not on the first run, so we run 2 hours the next times. + $runVar['modsettings']['fc']['firstrun'] = false; + } } break; case 'Disabled': @@ -524,54 +522,53 @@ class TmuxRun extends Tmux $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.1 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][1]} has been disabled/terminated by Remove Crap Releases\"'"); } - } + } - /** - * @param $runVar - */ - protected function _runUpdateTv(&$runVar) - { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.2 \ + /** + * @param $runVar + */ + protected function _runUpdateTv(&$runVar) + { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.2 \ 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][2]} has been disabled/terminated by Update TV/Theater\"'"); - } + } - /** - * @param $runVar - */ - protected function _runUpdateTvFull(&$runVar) - { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.0 \ + /** + * @param $runVar + */ + protected function _runUpdateTvFull(&$runVar) + { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.0 \ 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][0]} has been disabled/terminated by Update TV/Theater\"'"); - } + } - /** - * @param $runVar - */ - protected function _runMainNon(&$runVar) - { - $this->_runNonUpdateBinaries($runVar); - $this->_runNonUpdateReleases($runVar); - $this->_runNonBackfill($runVar); - } + /** + * @param $runVar + */ + protected function _runMainNon(&$runVar) + { + $this->_runNonUpdateBinaries($runVar); + $this->_runNonUpdateReleases($runVar); + $this->_runNonBackfill($runVar); + } - /** - * @param $runVar - */ - protected function _runMainBasic(&$runVar) - { - $log = $this->writelog($runVar['panes']['zero'][2]); - if (($runVar['killswitch']['pp'] === false) && (time() - $runVar['timers']['timer5'] <= 4800)) { - - $date = 'date +"%Y-%m-%d %T";'; - $sleep = sprintf( + /** + * @param $runVar + */ + protected function _runMainBasic(&$runVar) + { + $log = $this->writelog($runVar['panes']['zero'][2]); + if (($runVar['killswitch']['pp'] === false) && (time() - $runVar['timers']['timer5'] <= 4800)) { + $date = 'date +"%Y-%m-%d %T";'; + $sleep = sprintf( '%s %s;', $runVar['commands']['_sleep'], $runVar['settings']['seq_timer'] ); - switch ($runVar['settings']['binaries_run']) { + switch ($runVar['settings']['binaries_run']) { case 0: $binaries = 'echo "\nbinaries has been disabled/terminated by Binaries"'; break; @@ -587,7 +584,7 @@ class TmuxRun extends Tmux $binaries = ''; } - switch ($runVar['settings']['backfill']) { + switch ($runVar['settings']['backfill']) { case 0: $backfill = 'echo "backfill is disabled in settings";'; break; @@ -618,7 +615,7 @@ class TmuxRun extends Tmux $backfill = ''; } - switch ($runVar['settings']['releases_run']) { + switch ($runVar['settings']['releases_run']) { case 0: $releases = 'echo PHP_EOL . "releases have been disabled/terminated by Releases"'; break; @@ -633,129 +630,126 @@ class TmuxRun extends Tmux $releases = ''; } - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 '$binaries $backfill $releases $date $sleep' 2>&1 1> /dev/null"); - - } else if (($runVar['killswitch']['pp'] === false) && (time() - $runVar['timers']['timer5'] >= 4800)) { - //run backfill all once and resets the timer - if ((int)$runVar['settings']['backfill'] !== 0) { - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 ' \ + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 '$binaries $backfill $releases $date $sleep' 2>&1 1> /dev/null"); + } elseif (($runVar['killswitch']['pp'] === false) && (time() - $runVar['timers']['timer5'] >= 4800)) { + //run backfill all once and resets the timer + if ((int) $runVar['settings']['backfill'] !== 0) { + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 ' \ {$runVar['commands']['_php']} {$runVar['paths']['misc']}update/nix/multiprocessing/backfill.php $log; \ date +\"{$this->_dateFormat}\"; {$runVar['commands']['_sleep']} {$runVar['settings']['seq_timer']}' 2>&1 1> /dev/null" ); - $runVar['timers']['timer5'] = time(); - } else { - $runVar['timers']['timer5'] = time(); - } - - } else if (($runVar['killswitch']['pp'] === true) && (int)$runVar['settings']['releases_run'] !== 0) { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 'echo \"\033[38;5;${color}m\"; \ + $runVar['timers']['timer5'] = time(); + } else { + $runVar['timers']['timer5'] = time(); + } + } elseif (($runVar['killswitch']['pp'] === true) && (int) $runVar['settings']['releases_run'] !== 0) { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 'echo \"\033[38;5;${color}m\"; \ echo \"\nbinaries and backfill has been disabled/terminated by Exceeding Limits\"; \ {$runVar['scripts']['releases']} $log; date +\"{$this->_dateFormat}\"; echo \"\nbinaries and backfill has been disabled/terminated by Exceeding Limits\"; \ {$runVar['commands']['_sleep']} {$runVar['settings']['seq_timer']}' 2>&1 1> /dev/null" ); + } elseif ($runVar['killswitch']['pp'] === true) { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][2]} has been disabled/terminated by Exceeding Limits\"'"); + } + } - } else if ($runVar['killswitch']['pp'] === true) { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][2]} has been disabled/terminated by Exceeding Limits\"'"); - } - } - - /** - * @param $runVar - */ - protected function _runMainFull(&$runVar) - { - $log = $this->writelog($runVar['panes']['zero'][2]); - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 ' \ + /** + * @param $runVar + */ + protected function _runMainFull(&$runVar) + { + $log = $this->writelog($runVar['panes']['zero'][2]); + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:0.2 ' \ {$runVar['paths']['misc']}update/nix/screen/sequential/user_threaded.sh true $log; date +\"{$this->_dateFormat}\"' 2>&1 1> /dev/null" ); - } + } - /** - * @param $runVar - */ - protected function _notRunningNon(&$runVar) - { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - for ($g = 1; $g <= 4; $g++) { - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][$g]} has been disabled/terminated by Running\"'"); - } - for ($g = 0; $g <= 3; $g++) { - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][$g]} has been disabled/terminated by Running\"'"); - } - for ($g = 0; $g <= 2; $g++) { - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][$g]} has been disabled/terminated by Running\"'"); - } - } + /** + * @param $runVar + */ + protected function _notRunningNon(&$runVar) + { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + for ($g = 1; $g <= 4; $g++) { + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][$g]} has been disabled/terminated by Running\"'"); + } + for ($g = 0; $g <= 3; $g++) { + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][$g]} has been disabled/terminated by Running\"'"); + } + for ($g = 0; $g <= 2; $g++) { + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][$g]} has been disabled/terminated by Running\"'"); + } + } - /** - * @param $runVar - */ - protected function _notRunningBasic(&$runVar) - { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - for ($g = 1; $g <= 2; $g++) { - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][$g]} has been disabled/terminated by Running\"'"); - } - for ($g = 0; $g <= 3; $g++) { - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][$g]} has been disabled/terminated by Running\"'"); - } - for ($g = 0; $g <= 2; $g++) { - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][$g]} has been disabled/terminated by Running\"'"); - } - } + /** + * @param $runVar + */ + protected function _notRunningBasic(&$runVar) + { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + for ($g = 1; $g <= 2; $g++) { + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][$g]} has been disabled/terminated by Running\"'"); + } + for ($g = 0; $g <= 3; $g++) { + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][$g]} has been disabled/terminated by Running\"'"); + } + for ($g = 0; $g <= 2; $g++) { + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:2.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['two'][$g]} has been disabled/terminated by Running\"'"); + } + } - /** - * @param $runVar - */ - protected function _notRunningFull(&$runVar) - { - $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); - for ($g = 1; $g <= 2; $g++) { - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][$g]} has been disabled/terminated by Running\"'"); - } - for ($g = 0; $g <= 1; $g++) { - shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][$g]} has been disabled/terminated by Running\"'"); - } - } + /** + * @param $runVar + */ + protected function _notRunningFull(&$runVar) + { + $color = $this->get_color($runVar['settings']['colors_start'], $runVar['settings']['colors_end'], $runVar['settings']['colors_exc']); + for ($g = 1; $g <= 2; $g++) { + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:0.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['zero'][$g]} has been disabled/terminated by Running\"'"); + } + for ($g = 0; $g <= 1; $g++) { + shell_exec("tmux respawnp -k -t{$runVar['constants']['tmux_session']}:1.$g 'echo \"\033[38;5;${color}m\n{$runVar['panes']['one'][$g]} has been disabled/terminated by Running\"'"); + } + } - /** - * @param $pane - * @param $runVar - */ - protected function _runIRCScraper($pane, &$runVar) - { - if ((int)$runVar['constants']['run_ircscraper'] === 1) { - //Check to see if the pane is dead, if so respawn it. - if (shell_exec("tmux list-panes -t{$runVar['constants']['tmux_session']}:${pane} | grep ^0 | grep -c dead") == 1) { - shell_exec( + /** + * @param $pane + * @param $runVar + */ + protected function _runIRCScraper($pane, &$runVar) + { + if ((int) $runVar['constants']['run_ircscraper'] === 1) { + //Check to see if the pane is dead, if so respawn it. + if (shell_exec("tmux list-panes -t{$runVar['constants']['tmux_session']}:${pane} | grep ^0 | grep -c dead") == 1) { + shell_exec( "tmux respawnp -t{$runVar['constants']['tmux_session']}:${pane}.0 ' \ {$runVar['commands']['_phpn']} {$runVar['paths']['scraper']} true'" ); - } - } else { - shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:${pane}.0 'echo \"\nIRCScraper has been disabled/terminated by IRCSCraper\"'"); - } - } + } + } else { + shell_exec("tmux respawnp -t{$runVar['constants']['tmux_session']}:${pane}.0 'echo \"\nIRCScraper has been disabled/terminated by IRCSCraper\"'"); + } + } - /** - * @param $pane - * @param $runVar - */ - protected function _runSharing($pane, &$runVar) - { - $sharing = $this->pdo->queryOneRow('SELECT enabled, posting, fetching FROM sharing'); + /** + * @param $pane + * @param $runVar + */ + protected function _runSharing($pane, &$runVar) + { + $sharing = $this->pdo->queryOneRow('SELECT enabled, posting, fetching FROM sharing'); - if ((int)$runVar['settings']['run_sharing'] === 1 && (int)$sharing['enabled'] === 1 && ((int)$sharing['posting'] === 1 || (int)$sharing['fetching'] === 1)) { - if (shell_exec("tmux list-panes -t{$runVar['constants']['tmux_session']}:${pane} | grep ^0 | grep -c dead") == 1) { - shell_exec( + if ((int) $runVar['settings']['run_sharing'] === 1 && (int) $sharing['enabled'] === 1 && ((int) $sharing['posting'] === 1 || (int) $sharing['fetching'] === 1)) { + if (shell_exec("tmux list-panes -t{$runVar['constants']['tmux_session']}:${pane} | grep ^0 | grep -c dead") == 1) { + shell_exec( "tmux respawnp -t{$runVar['constants']['tmux_session']}:${pane}.0 ' \ {$runVar['commands']['_php']} {$runVar['paths']['misc']}/update/postprocess.php spotnab true; \ {$runVar['commands']['_php']} {$runVar['paths']['misc']}/update/postprocess.php sharing true; \ {$runVar['commands']['_sleep']} {$runVar['settings']['sharing_timer']}' 2>&1 1> /dev/null" ); - } - } - } + } + } + } } diff --git a/nntmux/UserMovies.php b/nntmux/UserMovies.php index c0c33ff50..3d8e0e337 100755 --- a/nntmux/UserMovies.php +++ b/nntmux/UserMovies.php @@ -1,148 +1,149 @@ <?php + namespace nntmux; use nntmux\db\DB; /** - * Class UserMovies + * Class UserMovies. */ class UserMovies { - /** - * @var \nntmux\db\Settings - */ - public $pdo; + /** + * @var \nntmux\db\Settings + */ + public $pdo; - /** - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + } - /** - * Add movie for a user - * - * @param $uid - * @param $imdbid - * @param array $catID - * - * @return bool|int - */ - public function addMovie($uid, $imdbid, $catID = []) - { - return $this->pdo->queryInsert( + /** + * Add movie for a user. + * + * @param $uid + * @param $imdbid + * @param array $catID + * + * @return bool|int + */ + public function addMovie($uid, $imdbid, $catID = []) + { + return $this->pdo->queryInsert( sprintf( - "INSERT INTO user_movies (users_id, imdbid, categories, createddate) - VALUES (%d, %d, %s, now())", + 'INSERT INTO user_movies (users_id, imdbid, categories, createddate) + VALUES (%d, %d, %s, now())', $uid, $imdbid, - (!empty($catID) ? $this->pdo->escapeString(implode('|', $catID)) : "NULL") + (! empty($catID) ? $this->pdo->escapeString(implode('|', $catID)) : 'NULL') ) ); - } + } - /** - * Get movies for a user - * - * @param $uid - * - * @return array - */ - public function getMovies($uid) - { - return $this->pdo->query( + /** + * Get movies for a user. + * + * @param $uid + * + * @return array + */ + public function getMovies($uid) + { + return $this->pdo->query( sprintf( - "SELECT um.*, mi.year, mi.plot, mi.cover, mi.title + 'SELECT um.*, mi.year, mi.plot, mi.cover, mi.title FROM user_movies um LEFT OUTER JOIN movieinfo mi ON mi.imdbid = um.imdbid WHERE users_id = %d - ORDER BY mi.title ASC", + ORDER BY mi.title ASC', $uid ) ); - } + } - /** - * Delete movie for a user - * - * @param $uid - * @param $imdbid - * - * @return bool|\PDOStatement - */ - public function delMovie($uid, $imdbid) - { - return $this->pdo->queryExec(sprintf( - "DELETE FROM user_movies + /** + * Delete movie for a user. + * + * @param $uid + * @param $imdbid + * + * @return bool|\PDOStatement + */ + public function delMovie($uid, $imdbid) + { + return $this->pdo->queryExec(sprintf( + 'DELETE FROM user_movies WHERE users_id = %d - AND imdbid = %d ", + AND imdbid = %d ', $uid, $imdbid ) ); - } + } - /** - * Get movie for a user - * - * @param $uid - * @param $imdbid - * - * @return array|bool - */ - public function getMovie($uid, $imdbid) - { - return $this->pdo->queryOneRow(sprintf( - "SELECT um.*, mi.title + /** + * Get movie for a user. + * + * @param $uid + * @param $imdbid + * + * @return array|bool + */ + public function getMovie($uid, $imdbid) + { + return $this->pdo->queryOneRow(sprintf( + 'SELECT um.*, mi.title FROM user_movies um LEFT OUTER JOIN movieinfo mi ON mi.imdbid = um.imdbid WHERE um.users_id = %d - AND um.imdbid = %d ", + AND um.imdbid = %d ', $uid, $imdbid ) ); - } + } - /** - * @param $uid - */ - public function delMovieForUser($uid) - { - $this->pdo->queryExec(sprintf( - "DELETE FROM user_movies - WHERE users_id = %d", + /** + * @param $uid + */ + public function delMovieForUser($uid) + { + $this->pdo->queryExec(sprintf( + 'DELETE FROM user_movies + WHERE users_id = %d', $uid ) ); - } + } - /** - * Update movie for a user - * - * @param $uid - * @param $imdbid - * @param array $catID - */ - public function updateMovie($uid, $imdbid, $catID = []) - { - $this->pdo->queryExec( + /** + * Update movie for a user. + * + * @param $uid + * @param $imdbid + * @param array $catID + */ + public function updateMovie($uid, $imdbid, $catID = []) + { + $this->pdo->queryExec( sprintf( - "UPDATE user_movies + 'UPDATE user_movies SET categories = %s WHERE users_id = %d - AND imdbid = %d", - (!empty($catID) ? $this->pdo->escapeString(implode('|', $catID)) : "NULL"), + AND imdbid = %d', + (! empty($catID) ? $this->pdo->escapeString(implode('|', $catID)) : 'NULL'), $uid, $imdbid ) ); - } + } } diff --git a/nntmux/UserSeries.php b/nntmux/UserSeries.php index 08669dd8a..c707506a4 100755 --- a/nntmux/UserSeries.php +++ b/nntmux/UserSeries.php @@ -1,161 +1,162 @@ <?php + namespace nntmux; use nntmux\db\DB; /** - * Class UserSeries + * Class UserSeries. * * Sets and Gets data from and to the DB "user_series" table and the "my shows" web-page. */ class UserSeries { - /** - * @var \nntmux\db\Settings - */ - public $pdo; + /** + * @var \nntmux\db\Settings + */ + public $pdo; - /** - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - } + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + } - /** - * When a user wants to add a show to "my shows" insert it into the user series table. - * - * @param int $uID ID of user. - * @param int $videoId Video ID of tv show. - * @param array $catID List of category ID's - * - * @return bool|int - */ - public function addShow($uID, $videoId, $catID = []) - { - return $this->pdo->queryInsert( + /** + * When a user wants to add a show to "my shows" insert it into the user series table. + * + * @param int $uID ID of user. + * @param int $videoId Video ID of tv show. + * @param array $catID List of category ID's + * + * @return bool|int + */ + public function addShow($uID, $videoId, $catID = []) + { + return $this->pdo->queryInsert( sprintf( - "INSERT INTO user_series (users_id, videos_id, categories, createddate) VALUES (%d, %d, %s, NOW())", + 'INSERT INTO user_series (users_id, videos_id, categories, createddate) VALUES (%d, %d, %s, NOW())', $uID, $videoId, - (!empty($catID) ? $this->pdo->escapeString(implode('|', $catID)) : "NULL") + (! empty($catID) ? $this->pdo->escapeString(implode('|', $catID)) : 'NULL') ) ); - } + } - /** - * Get all the user's "my shows". - * - * @param int $uID ID of user. - * - * @return array - */ - public function getShows($uID) - { - return $this->pdo->query( - sprintf(" + /** + * Get all the user's "my shows". + * + * @param int $uID ID of user. + * + * @return array + */ + public function getShows($uID) + { + return $this->pdo->query( + sprintf(' SELECT us.*, v.title FROM user_series us INNER JOIN videos v ON v.id = us.videos_id WHERE users_id = %d - ORDER BY v.title ASC", + ORDER BY v.title ASC', $uID ) ); - } + } - /** - * Delete a tv show from the user's "my shows". - * - * @param int $uID ID of user. - * @param int $videoId ID of tv show. - */ - public function delShow($uID, $videoId) - { - $this->pdo->queryExec( + /** + * Delete a tv show from the user's "my shows". + * + * @param int $uID ID of user. + * @param int $videoId ID of tv show. + */ + public function delShow($uID, $videoId) + { + $this->pdo->queryExec( sprintf( - "DELETE FROM user_series WHERE users_id = %d AND videos_id = %d", + 'DELETE FROM user_series WHERE users_id = %d AND videos_id = %d', $uID, $videoId ) ); - } + } - /** - * Get tv show information for a user. - * - * @param int $uID ID of the user. - * @param int $videoId ID of the TV show. - * - * @return array|bool - */ - public function getShow($uID, $videoId) - { - return $this->pdo->queryOneRow( - sprintf(" + /** + * Get tv show information for a user. + * + * @param int $uID ID of the user. + * @param int $videoId ID of the TV show. + * + * @return array|bool + */ + public function getShow($uID, $videoId) + { + return $this->pdo->queryOneRow( + sprintf(' SELECT us.*, v.title FROM user_series us LEFT OUTER JOIN videos v ON v.id = us.videos_id WHERE us.users_id = %d - AND us.videos_id = %d", + AND us.videos_id = %d', $uID, $videoId ) ); - } + } - /** - * Delete all shows from the user's "my shows". - * - * @param int $uID ID of the user. - */ - public function delShowForUser($uID) - { - $this->pdo->queryExec( + /** + * Delete all shows from the user's "my shows". + * + * @param int $uID ID of the user. + */ + public function delShowForUser($uID) + { + $this->pdo->queryExec( sprintf( - "DELETE FROM user_series WHERE users_id = %d", + 'DELETE FROM user_series WHERE users_id = %d', $uID ) ); - } + } - /** - * Delete TV shows from all user's "my shows" that match a TV id. - * - * @param int $videoId The ID of the TV show. - */ - public function delShowForSeries($videoId) - { - $this->pdo->queryExec( + /** + * Delete TV shows from all user's "my shows" that match a TV id. + * + * @param int $videoId The ID of the TV show. + */ + public function delShowForSeries($videoId) + { + $this->pdo->queryExec( sprintf( - "DELETE FROM user_series WHERE videos_id = %d", + 'DELETE FROM user_series WHERE videos_id = %d', $videoId ) ); - } + } - /** - * Update a TV show category ID for a user's "my show" TV show. - * - * @param int $uID ID of the user. - * @param int $videoId ID of the TV show. - * @param array $catID List of category ID's. - */ - public function updateShow($uID, $videoId, $catID = []) - { - $this->pdo->queryExec( + /** + * Update a TV show category ID for a user's "my show" TV show. + * + * @param int $uID ID of the user. + * @param int $videoId ID of the TV show. + * @param array $catID List of category ID's. + */ + public function updateShow($uID, $videoId, $catID = []) + { + $this->pdo->queryExec( sprintf( - "UPDATE user_series SET categories = %s WHERE users_id = %d AND videos_id = %d", - (!empty($catID) ? $this->pdo->escapeString(implode('|', $catID)) : "NULL"), + 'UPDATE user_series SET categories = %s WHERE users_id = %d AND videos_id = %d', + (! empty($catID) ? $this->pdo->escapeString(implode('|', $catID)) : 'NULL'), $uID, $videoId ) ); - } + } } diff --git a/nntmux/Users.php b/nntmux/Users.php index 42fbaa771..f1b1fb482 100755 --- a/nntmux/Users.php +++ b/nntmux/Users.php @@ -1,197 +1,199 @@ <?php + namespace nntmux; +use nntmux\db\DB; +use App\Models\User; use App\Models\Settings; -use App\Models\UserRequest; use App\Models\UserRole; +use App\Models\UserRequest; +use nntmux\utility\Utility; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Password; -use nntmux\db\DB; -use nntmux\utility\Utility; -use App\Models\User; class Users { - const ERR_SIGNUP_BADUNAME = -1; - const ERR_SIGNUP_BADPASS = -2; - const ERR_SIGNUP_BADEMAIL = -3; - const ERR_SIGNUP_UNAMEINUSE = -4; - const ERR_SIGNUP_EMAILINUSE = -5; - const ERR_SIGNUP_BADINVITECODE = -6; - const ERR_SIGNUP_BADCAPTCHA = -7; - const SUCCESS = 1; + const ERR_SIGNUP_BADUNAME = -1; + const ERR_SIGNUP_BADPASS = -2; + const ERR_SIGNUP_BADEMAIL = -3; + const ERR_SIGNUP_UNAMEINUSE = -4; + const ERR_SIGNUP_EMAILINUSE = -5; + const ERR_SIGNUP_BADINVITECODE = -6; + const ERR_SIGNUP_BADCAPTCHA = -7; + const SUCCESS = 1; - const ROLE_GUEST = 0; - const ROLE_USER = 1; - const ROLE_ADMIN = 2; - const ROLE_DISABLED = 3; - const ROLE_MODERATOR = 4; + const ROLE_GUEST = 0; + const ROLE_USER = 1; + const ROLE_ADMIN = 2; + const ROLE_DISABLED = 3; + const ROLE_MODERATOR = 4; - const DEFAULT_INVITES = 1; - const DEFAULT_INVITE_EXPIRY_DAYS = 7; + const DEFAULT_INVITES = 1; + const DEFAULT_INVITE_EXPIRY_DAYS = 7; - const SALTLEN = 4; - const SHA1LEN = 40; + const SALTLEN = 4; + const SHA1LEN = 40; - /** - * @var int - */ - public $password_hash_cost; + /** + * @var int + */ + public $password_hash_cost; - /** - * Users SELECT queue type. - */ - const QUEUE_NONE = 0; - const QUEUE_SABNZBD = 1; - const QUEUE_NZBGET = 2; + /** + * Users SELECT queue type. + */ + const QUEUE_NONE = 0; + const QUEUE_SABNZBD = 1; + const QUEUE_NZBGET = 2; - /** - * @var DB - */ - private $pdo; + /** + * @var DB + */ + private $pdo; - /** - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = $options['Settings'] instanceof DB ? $options['Settings'] : new DB(); + $this->pdo = $options['Settings'] instanceof DB ? $options['Settings'] : new DB(); - $this->password_hash_cost = defined('NN_PASSWORD_HASH_COST') ? NN_PASSWORD_HASH_COST : 11; - } + $this->password_hash_cost = defined('NN_PASSWORD_HASH_COST') ? NN_PASSWORD_HASH_COST : 11; + } - /** - * Verify a password against a hash. - * - * Automatically update the hash if it needs to be. - * - * @param string $password Password to check against hash. - * @param string|bool $hash Hash to check against password. - * @param int $userID ID of the user. - * - * @return bool - */ - public function checkPassword($password, $hash, $userID = -1): bool - { - if (Hash::check($password, $hash) === false) { - return false; - } + /** + * Verify a password against a hash. + * + * Automatically update the hash if it needs to be. + * + * @param string $password Password to check against hash. + * @param string|bool $hash Hash to check against password. + * @param int $userID ID of the user. + * + * @return bool + */ + public function checkPassword($password, $hash, $userID = -1): bool + { + if (Hash::check($password, $hash) === false) { + return false; + } - // Update the hash if it needs to be. - if (is_numeric($userID) && $userID > 0 && Hash::needsRehash($hash)) { - $hash = $this->hashPassword($password); + // Update the hash if it needs to be. + if (is_numeric($userID) && $userID > 0 && Hash::needsRehash($hash)) { + $hash = $this->hashPassword($password); - if ($hash !== false) { - User::query()->where('id', $userID)->update(['password' => $hash]); - } - } - return true; - } + if ($hash !== false) { + User::query()->where('id', $userID)->update(['password' => $hash]); + } + } + return true; + } - /** - * @return array - */ - public function get(): array - { - return User::all()->all(); - } + /** + * @return array + */ + public function get(): array + { + return User::all()->all(); + } - /** - * Get the users selected theme. - * - * @param string|int $userID The id of the user. - * - * @return array|bool The users selected theme. - */ - public function getStyle($userID) - { - $row = User::query()->where('id', $userID)->value('style'); - return $row ?? 'None'; - } + /** + * Get the users selected theme. + * + * @param string|int $userID The id of the user. + * + * @return array|bool The users selected theme. + */ + public function getStyle($userID) + { + $row = User::query()->where('id', $userID)->value('style'); - /** - * @param $id - */ - public function delete($id): void - { - $this->delCartForUser($id); - $this->delUserCategoryExclusions($id); - $this->delDownloadRequests($id); - $this->delApiRequests($id); + return $row ?? 'None'; + } - $rc = new ReleaseComments(); - $rc->deleteCommentsForUser($id); + /** + * @param $id + */ + public function delete($id): void + { + $this->delCartForUser($id); + $this->delUserCategoryExclusions($id); + $this->delDownloadRequests($id); + $this->delApiRequests($id); - $um = new UserMovies(); - $um->delMovieForUser($id); + $rc = new ReleaseComments(); + $rc->deleteCommentsForUser($id); - $us = new UserSeries(); - $us->delShowForUser($id); + $um = new UserMovies(); + $um->delMovieForUser($id); - $forum = new Forum(); - $forum->deleteUser($id); + $us = new UserSeries(); + $us->delShowForUser($id); - User::query()->where('id', $id)->delete(); - } + $forum = new Forum(); + $forum->deleteUser($id); - /** - * @param $uid - */ - public function delCartForUser($uid): void - { - $this->pdo->queryExec(sprintf('DELETE FROM users_releases WHERE users_id = %d', $uid)); - } + User::query()->where('id', $id)->delete(); + } - /** - * @param $uid - */ - public function delUserCategoryExclusions($uid): void - { - $this->pdo->queryExec(sprintf('DELETE FROM user_excluded_categories WHERE users_id = %d', $uid)); - } + /** + * @param $uid + */ + public function delCartForUser($uid): void + { + $this->pdo->queryExec(sprintf('DELETE FROM users_releases WHERE users_id = %d', $uid)); + } - /** - * @param $userID - */ - public function delDownloadRequests($userID): void - { - $this->pdo->queryExec(sprintf('DELETE FROM user_downloads WHERE users_id = %d', $userID)); - } + /** + * @param $uid + */ + public function delUserCategoryExclusions($uid): void + { + $this->pdo->queryExec(sprintf('DELETE FROM user_excluded_categories WHERE users_id = %d', $uid)); + } - /** - * @param $userID - */ - public function delApiRequests($userID): void - { - UserRequest::query()->where('users_id', $userID)->delete(); - } + /** + * @param $userID + */ + public function delDownloadRequests($userID): void + { + $this->pdo->queryExec(sprintf('DELETE FROM user_downloads WHERE users_id = %d', $userID)); + } - /** - * Get all users / extra data from other tables. - * - * @param $start - * @param $offset - * @param $orderBy - * @param string $userName - * @param string $email - * @param string $host - * @param string $role - * @param bool $apiRequests - * - * @return array - * @throws \Exception - */ - public function getRange($start, $offset, $orderBy, $userName = '', $email = '', $host = '', $role = '', $apiRequests = false): array - { - if ($apiRequests) { - $this->clearApiRequests(false); - $query = " + /** + * @param $userID + */ + public function delApiRequests($userID): void + { + UserRequest::query()->where('users_id', $userID)->delete(); + } + + /** + * Get all users / extra data from other tables. + * + * @param $start + * @param $offset + * @param $orderBy + * @param string $userName + * @param string $email + * @param string $host + * @param string $role + * @param bool $apiRequests + * + * @return array + * @throws \Exception + */ + public function getRange($start, $offset, $orderBy, $userName = '', $email = '', $host = '', $role = '', $apiRequests = false): array + { + if ($apiRequests) { + $this->clearApiRequests(false); + $query = " SELECT users.*, user_roles.name AS rolename, COUNT(user_requests.id) AS apirequests FROM users INNER JOIN user_roles ON user_roles.id = users.role @@ -199,44 +201,42 @@ class Users WHERE users.id != 0 %s %s %s %s AND email != 'sharing@nZEDb.com' GROUP BY users.id - ORDER BY %s %s %s" - ; - } else { - $query = ' + ORDER BY %s %s %s"; + } else { + $query = ' SELECT users.*, user_roles.name AS rolename FROM users INNER JOIN user_roles ON user_roles.id = users.role WHERE 1=1 %s %s %s %s - ORDER BY %s %s %s' - ; - } + ORDER BY %s %s %s'; + } - $order = $this->getBrowseOrder($orderBy); + $order = $this->getBrowseOrder($orderBy); - return $this->pdo->query( + return $this->pdo->query( sprintf( $query, - ($userName !== '' ? ('AND users.username ' . $this->pdo->likeString($userName)) : ''), - ($email !== '' ? ('AND users.email ' . $this->pdo->likeString($email)) : ''), - ($host !== '' ? ('AND users.host ' . $this->pdo->likeString($host)) : ''), - ($role !== '' ? ('AND users.role = ' . $role) : ''), + ($userName !== '' ? ('AND users.username '.$this->pdo->likeString($userName)) : ''), + ($email !== '' ? ('AND users.email '.$this->pdo->likeString($email)) : ''), + ($host !== '' ? ('AND users.host '.$this->pdo->likeString($host)) : ''), + ($role !== '' ? ('AND users.role = '.$role) : ''), $order[0], $order[1], - ($start === false ? '' : ('LIMIT ' . $offset . ' OFFSET ' . $start)) + ($start === false ? '' : ('LIMIT '.$offset.' OFFSET '.$start)) ) ); - } + } - /** - * @param string $orderBy - * - * @return array - */ - public function getBrowseOrder($orderBy): array - { - $order = ($orderBy === '' ? 'username_desc' : $orderBy); - $orderArr = explode('_', $order); - switch ($orderArr[0]) { + /** + * @param string $orderBy + * + * @return array + */ + public function getBrowseOrder($orderBy): array + { + $order = ($orderBy === '' ? 'username_desc' : $orderBy); + $orderArr = explode('_', $order); + switch ($orderArr[0]) { case 'username': $orderField = 'username'; break; @@ -271,81 +271,82 @@ class Users $orderField = 'username'; break; } - $orderSort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc'; - return [$orderField, $orderSort]; - } + $orderSort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc'; - /** - * @param string|int $role - * - * @return mixed - */ - public function getCount($role = '') - { - $res = $this->pdo->queryOneRow(sprintf("SELECT COUNT(id) as num FROM users WHERE email != 'sharing@nZEDb.com' %s", $role !== '' ? sprintf('AND role = %d', $role) : '')); + return [$orderField, $orderSort]; + } - return $res['num']; - } + /** + * @param string|int $role + * + * @return mixed + */ + public function getCount($role = '') + { + $res = $this->pdo->queryOneRow(sprintf("SELECT COUNT(id) as num FROM users WHERE email != 'sharing@nZEDb.com' %s", $role !== '' ? sprintf('AND role = %d', $role) : '')); - /** - * @param $id - * @param $userName - * @param $email - * @param $grabs - * @param $role - * @param $notes - * @param $invites - * @param $movieview - * @param $musicview - * @param $gameview - * @param $xxxview - * @param $consoleview - * @param $bookview - * @param string $queueType - * @param string $nzbgetURL - * @param string $nzbgetUsername - * @param string $nzbgetPassword - * @param string $saburl - * @param string $sabapikey - * @param string $sabpriority - * @param string $sabapikeytype - * @param bool $nzbvortexServerUrl - * @param bool $nzbvortexApiKey - * @param bool $cp_url - * @param bool $cp_api - * @param string $style - * - * @return int - * @throws \Illuminate\Database\Eloquent\ModelNotFoundException - */ - public function update($id, $userName, $email, $grabs, $role, $notes, $invites, $movieview, $musicview, $gameview, $xxxview, $consoleview, $bookview, $queueType = '', $nzbgetURL = '', $nzbgetUsername = '', $nzbgetPassword = '', $saburl = '', $sabapikey = '', $sabpriority = '', $sabapikeytype = '', $nzbvortexServerUrl = false, $nzbvortexApiKey = false, $cp_url = false, $cp_api = false, $style = 'None'): int - { - $userName = trim($userName); - $email = trim($email); + return $res['num']; + } - if (!$this->isValidUsername($userName)) { - return self::ERR_SIGNUP_BADUNAME; - } + /** + * @param $id + * @param $userName + * @param $email + * @param $grabs + * @param $role + * @param $notes + * @param $invites + * @param $movieview + * @param $musicview + * @param $gameview + * @param $xxxview + * @param $consoleview + * @param $bookview + * @param string $queueType + * @param string $nzbgetURL + * @param string $nzbgetUsername + * @param string $nzbgetPassword + * @param string $saburl + * @param string $sabapikey + * @param string $sabpriority + * @param string $sabapikeytype + * @param bool $nzbvortexServerUrl + * @param bool $nzbvortexApiKey + * @param bool $cp_url + * @param bool $cp_api + * @param string $style + * + * @return int + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function update($id, $userName, $email, $grabs, $role, $notes, $invites, $movieview, $musicview, $gameview, $xxxview, $consoleview, $bookview, $queueType = '', $nzbgetURL = '', $nzbgetUsername = '', $nzbgetPassword = '', $saburl = '', $sabapikey = '', $sabpriority = '', $sabapikeytype = '', $nzbvortexServerUrl = false, $nzbvortexApiKey = false, $cp_url = false, $cp_api = false, $style = 'None'): int + { + $userName = trim($userName); + $email = trim($email); - if (!$this->isValidEmail($email)) { - return self::ERR_SIGNUP_BADEMAIL; - } + if (! $this->isValidUsername($userName)) { + return self::ERR_SIGNUP_BADUNAME; + } - $res = $this->getByUsername($userName); - if ($res) { - if ((int)$res['id'] !== (int)$id) { - return self::ERR_SIGNUP_UNAMEINUSE; - } - } + if (! $this->isValidEmail($email)) { + return self::ERR_SIGNUP_BADEMAIL; + } - $res = $this->getByEmail($email); - if ($res) { - if ((int)$res['id'] !== (int)$id) { - return self::ERR_SIGNUP_EMAILINUSE; - } - } + $res = $this->getByUsername($userName); + if ($res) { + if ((int) $res['id'] !== (int) $id) { + return self::ERR_SIGNUP_UNAMEINUSE; + } + } - $sql = [ + $res = $this->getByEmail($email); + if ($res) { + if ((int) $res['id'] !== (int) $id) { + return self::ERR_SIGNUP_EMAILINUSE; + } + } + + $sql = [ 'username' => $userName, 'email' => $email, 'grabs' => $grabs, @@ -370,804 +371,800 @@ class Users 'nzbvortex_server_url' => $nzbvortexServerUrl, 'nzbvortex_api_key' => $nzbvortexApiKey, 'cp_url' => $cp_url, - 'cp_api' => $cp_api + 'cp_api' => $cp_api, ]; - User::query()->where('id', $id)->update($sql); + User::query()->where('id', $id)->update($sql); - return self::SUCCESS; - } + return self::SUCCESS; + } - /** - * @param string $userName - * - * @return int - */ - public function isValidUsername(string $userName): int - { - return preg_match('/^[a-z][a-z0-9_]{2,}$/i', $userName); - } + /** + * @param string $userName + * + * @return int + */ + public function isValidUsername(string $userName): int + { + return preg_match('/^[a-z][a-z0-9_]{2,}$/i', $userName); + } - /** - * When a user is registering or updating their profile, check if the email is valid. - * - * @param string $email - * - * @return bool - */ - public function isValidEmail(string $email): bool - { - return (bool)preg_match('/^([\w\+-]+)(\.[\w\+-]+)*@([a-z0-9-]+\.)+[a-z]{2,6}$/i', $email); - } + /** + * When a user is registering or updating their profile, check if the email is valid. + * + * @param string $email + * + * @return bool + */ + public function isValidEmail(string $email): bool + { + return (bool) preg_match('/^([\w\+-]+)(\.[\w\+-]+)*@([a-z0-9-]+\.)+[a-z]{2,6}$/i', $email); + } - /** - * @param string $userName - * - * @return array|bool - */ - public function getByUsername(string $userName) - { - return $this->pdo->queryOneRow(sprintf('SELECT users.*, user_roles.name as rolename, user_roles.apirequests, user_roles.downloadrequests FROM users INNER JOIN user_roles on user_roles.id = users.role WHERE username = %s', $this->pdo->escapeString($userName))); - } + /** + * @param string $userName + * + * @return array|bool + */ + public function getByUsername(string $userName) + { + return $this->pdo->queryOneRow(sprintf('SELECT users.*, user_roles.name as rolename, user_roles.apirequests, user_roles.downloadrequests FROM users INNER JOIN user_roles on user_roles.id = users.role WHERE username = %s', $this->pdo->escapeString($userName))); + } - /** - * @param string $email - * - * @return \Illuminate\Database\Eloquent\Model|static - * @throws \Illuminate\Database\Eloquent\ModelNotFoundException - */ - public function getByEmail(string $email) - { - return User::query()->where('email', '=', $email)->first(); - } + /** + * @param string $email + * + * @return \Illuminate\Database\Eloquent\Model|static + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function getByEmail(string $email) + { + return User::query()->where('email', '=', $email)->first(); + } - /** - * @param int $uid - * @param int $role - * - * @return int - */ - public function updateUserRole(int $uid, int $role): int - { - User::query()->where('id', $uid)->update(['role' => $role]); + /** + * @param int $uid + * @param int $role + * + * @return int + */ + public function updateUserRole(int $uid, int $role): int + { + User::query()->where('id', $uid)->update(['role' => $role]); - return self::SUCCESS; - } + return self::SUCCESS; + } - /** - * @param $uid - * @param $date - * - * @return int - */ - public function updateUserRoleChangeDate($uid, $date): int - { - User::query()->where('id', $uid)->update(['rolechangedate' => $date]); + /** + * @param $uid + * @param $date + * + * @return int + */ + public function updateUserRoleChangeDate($uid, $date): int + { + User::query()->where('id', $uid)->update(['rolechangedate' => $date]); - return self::SUCCESS; - } + return self::SUCCESS; + } - /** - * @param $msgsubject - * @param $msgbody - * - * @return int - * @throws \Exception - */ - public function updateExpiredRoles($msgsubject, $msgbody): int - { - $data = User::query()->whereDate('rolechangedate', '<', (new \DateTime())->format('Y-m-d H:i:s'))->select(['id', 'email'])->get(); + /** + * @param $msgsubject + * @param $msgbody + * + * @return int + * @throws \Exception + */ + public function updateExpiredRoles($msgsubject, $msgbody): int + { + $data = User::query()->whereDate('rolechangedate', '<', (new \DateTime())->format('Y-m-d H:i:s'))->select(['id', 'email'])->get(); - foreach ($data as $u) { - Utility::sendEmail($u['email'], $msgsubject, $msgbody, Settings::value('site.main.email')); - User::query()->where('id', $u['id'])->update(['role' => self::ROLE_USER, 'rolechangedate' => null]); - } + foreach ($data as $u) { + Utility::sendEmail($u['email'], $msgsubject, $msgbody, Settings::value('site.main.email')); + User::query()->where('id', $u['id'])->update(['role' => self::ROLE_USER, 'rolechangedate' => null]); + } - return self::SUCCESS; - } + return self::SUCCESS; + } - /** - * @param $uid - * - * @return int - */ - public function updateRssKey($uid): int - { - User::query()->where('id', $uid)->update(['rsstoken' => md5(Password::getRepository()->createNewToken())]); + /** + * @param $uid + * + * @return int + */ + public function updateRssKey($uid): int + { + User::query()->where('id', $uid)->update(['rsstoken' => md5(Password::getRepository()->createNewToken())]); - return self::SUCCESS; - } + return self::SUCCESS; + } - /** - * @param $id - * @param $guid - * - * @return int - */ - public function updatePassResetGuid($id, $guid): int - { - User::query()->where('id', $id)->update(['resetguid' => $guid]); + /** + * @param $id + * @param $guid + * + * @return int + */ + public function updatePassResetGuid($id, $guid): int + { + User::query()->where('id', $id)->update(['resetguid' => $guid]); - return self::SUCCESS; - } + return self::SUCCESS; + } - /** - * @param int $id - * @param string $password - * - * @return int - */ - public function updatePassword(int $id, string $password): int - { - User::query()->where('id', $id)->update(['password' => $this->hashPassword($password), 'userseed' => md5(Utility::generateUuid())]); + /** + * @param int $id + * @param string $password + * + * @return int + */ + public function updatePassword(int $id, string $password): int + { + User::query()->where('id', $id)->update(['password' => $this->hashPassword($password), 'userseed' => md5(Utility::generateUuid())]); - return self::SUCCESS; - } + return self::SUCCESS; + } - /** - * Hash a password using crypt. - * - * @param string $password - * - * @return string|bool - */ - public function hashPassword($password) - { - return Hash::make($password); - } + /** + * Hash a password using crypt. + * + * @param string $password + * + * @return string|bool + */ + public function hashPassword($password) + { + return Hash::make($password); + } - /** - * @param string $string - * - * @return string - */ - public static function hashSHA1(string $string): string - { - return sha1($string); - } + /** + * @param string $string + * + * @return string + */ + public static function hashSHA1(string $string): string + { + return sha1($string); + } - /** - * @param $guid - * - * @return \Illuminate\Database\Eloquent\Model|static - * @throws \Illuminate\Database\Eloquent\ModelNotFoundException - */ - public function getByPassResetGuid(string $guid) - { - return User::query()->where('resetguid', $guid)->first(); - } + /** + * @param $guid + * + * @return \Illuminate\Database\Eloquent\Model|static + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function getByPassResetGuid(string $guid) + { + return User::query()->where('resetguid', $guid)->first(); + } - /** - * @param $id - * @param int $num - */ - public function incrementGrabs(int $id, $num = 1): void - { - User::query()->where('id', $id)->increment('grabs', $num); - } + /** + * @param $id + * @param int $num + */ + public function incrementGrabs(int $id, $num = 1): void + { + User::query()->where('id', $id)->increment('grabs', $num); + } - /** - * Check if the user is in the database, and if their API key is good, return user data if so. - * - * @param int $userID ID of the user. - * @param string $rssToken API key. - * - * @return bool|array - */ - public function getByIdAndRssToken($userID, $rssToken) - { - $user = $this->getById($userID); - if ($user === false) { - return false; - } + /** + * Check if the user is in the database, and if their API key is good, return user data if so. + * + * @param int $userID ID of the user. + * @param string $rssToken API key. + * + * @return bool|array + */ + public function getByIdAndRssToken($userID, $rssToken) + { + $user = $this->getById($userID); + if ($user === false) { + return false; + } - return ($user['rsstoken'] !== $rssToken ? false : $user); - } + return $user['rsstoken'] !== $rssToken ? false : $user; + } - /** - * @param $id - * - * @return array|bool - */ - public function getById($id) - { + /** + * @param $id + * + * @return array|bool + */ + public function getById($id) + { + $sql = sprintf('SELECT users.*, user_roles.name as rolename, user_roles.hideads, user_roles.canpreview, user_roles.apirequests, user_roles.downloadrequests, NOW() as now FROM users INNER JOIN user_roles on user_roles.id = users.role WHERE users.id = %d', $id); - $sql = sprintf('SELECT users.*, user_roles.name as rolename, user_roles.hideads, user_roles.canpreview, user_roles.apirequests, user_roles.downloadrequests, NOW() as now FROM users INNER JOIN user_roles on user_roles.id = users.role WHERE users.id = %d', $id); + $result = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - $result = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); + if (empty($result)) { + return false; + } - if (empty($result)) { - return false; - } + return $result[0]; + } - return $result[0]; - } + /** + * @param string $rssToken + * + * @return array|bool + */ + public function getByRssToken(string $rssToken) + { + return $this->pdo->queryOneRow(sprintf('SELECT users.*, user_roles.apirequests, user_roles.downloadrequests, NOW() as now FROM users INNER JOIN user_roles on user_roles.id = users.role WHERE users.rsstoken = %s', $this->pdo->escapeString($rssToken))); + } - /** - * @param string $rssToken - * - * @return array|bool - */ - public function getByRssToken(string $rssToken) - { - return $this->pdo->queryOneRow(sprintf('SELECT users.*, user_roles.apirequests, user_roles.downloadrequests, NOW() as now FROM users INNER JOIN user_roles on user_roles.id = users.role WHERE users.rsstoken = %s', $this->pdo->escapeString($rssToken))); - } + /** + * @return array + */ + public function getBrowseOrdering(): array + { + return ['username_asc', 'username_desc', 'email_asc', 'email_desc', 'host_asc', 'host_desc', 'createddate_asc', 'createddate_desc', 'lastlogin_asc', 'lastlogin_desc', 'apiaccess_asc', 'apiaccess_desc', 'apirequests_asc', 'apirequests_desc', 'grabs_asc', 'grabs_desc', 'role_asc', 'role_desc', 'rolechangedate_asc', 'rolechangedate_desc']; + } - /** - * @return array - */ - public function getBrowseOrdering(): array - { - return ['username_asc', 'username_desc', 'email_asc', 'email_desc', 'host_asc', 'host_desc', 'createddate_asc', 'createddate_desc', 'lastlogin_asc', 'lastlogin_desc', 'apiaccess_asc', 'apiaccess_desc', 'apirequests_asc', 'apirequests_desc', 'grabs_asc', 'grabs_desc', 'role_asc', 'role_desc', 'rolechangedate_asc', 'rolechangedate_desc']; - } + /** + * @param $username + * + * @return bool + */ + public function isDisabled($username): bool + { + return $this->roleCheck(self::ROLE_DISABLED, $username); + } - /** - * @param $username - * - * @return bool - */ - public function isDisabled($username): bool - { - return $this->roleCheck(self::ROLE_DISABLED, $username); - } + /** + * @param $url + * + * @return bool + */ + public function isValidUrl($url): bool + { + return (! preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) ? false : true; + } - /** - * @param $url - * - * @return bool - */ - public function isValidUrl($url): bool - { - return (!preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) ? false : true; - } + /** + * Create a random username. + * + * @param string $email + * + * @return string + */ + public function generateUsername($email): string + { + $string = ''; + if (preg_match('/[A-Za-z0-9]+/', $email, $matches)) { + $string = $matches[0]; + } - /** - * Create a random username. - * - * @param string $email - * - * @return string - */ - public function generateUsername($email): string - { - $string = ''; - if (preg_match('/[A-Za-z0-9]+/', $email, $matches)) { - $string = $matches[0]; - } + return 'u'.substr(md5(uniqid('', true)), 0, 7).$string; + } - return 'u' . substr(md5(uniqid('', true)), 0, 7) . $string; - } + /** + * @return string + */ + public function generatePassword(): string + { + return str_random(8); + } - /** - * @return string - */ - public function generatePassword(): string - { - return str_random(8); - } + /** + * Register a new user. + * + * @param $userName + * @param $password + * @param $email + * @param $host + * @param int $role + * @param $notes + * @param int $invites + * @param string $inviteCode + * @param bool $forceInviteMode + * + * @return bool|int + * @throws \Exception + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + public function signup($userName, $password, $email, $host, $role = self::ROLE_USER, $notes, $invites = self::DEFAULT_INVITES, $inviteCode = '', $forceInviteMode = false) + { + $userName = trim($userName); + $password = trim($password); + $email = trim($email); - /** - * Register a new user. - * - * @param $userName - * @param $password - * @param $email - * @param $host - * @param int $role - * @param $notes - * @param int $invites - * @param string $inviteCode - * @param bool $forceInviteMode - * - * @return bool|int - * @throws \Exception - * @throws \Illuminate\Database\Eloquent\ModelNotFoundException - */ - public function signup($userName, $password, $email, $host, $role = self::ROLE_USER, $notes, $invites = self::DEFAULT_INVITES, $inviteCode = '', $forceInviteMode = false) - { + if (! $this->isValidUsername($userName)) { + return self::ERR_SIGNUP_BADUNAME; + } - $userName = trim($userName); - $password = trim($password); - $email = trim($email); + if (! $this->isValidPassword($password)) { + return self::ERR_SIGNUP_BADPASS; + } - if (!$this->isValidUsername($userName)) { - return self::ERR_SIGNUP_BADUNAME; - } + if (! $this->isValidEmail($email)) { + return self::ERR_SIGNUP_BADEMAIL; + } - if (!$this->isValidPassword($password)) { - return self::ERR_SIGNUP_BADPASS; - } + $res = $this->getByUsername($userName); + if ($res) { + return self::ERR_SIGNUP_UNAMEINUSE; + } - if (!$this->isValidEmail($email)) { - return self::ERR_SIGNUP_BADEMAIL; - } + $res = $this->getByEmail($email); + if ($res) { + return self::ERR_SIGNUP_EMAILINUSE; + } - $res = $this->getByUsername($userName); - if ($res) { - return self::ERR_SIGNUP_UNAMEINUSE; - } + // Make sure this is the last check, as if a further validation check failed, the invite would still have been used up. + $invitedBy = 0; + if (! $forceInviteMode && (int) Settings::value('..registerstatus') === Settings::REGISTER_STATUS_INVITE) { + if ($inviteCode === '') { + return self::ERR_SIGNUP_BADINVITECODE; + } - $res = $this->getByEmail($email); - if ($res) { - return self::ERR_SIGNUP_EMAILINUSE; - } + $invitedBy = $this->checkAndUseInvite($inviteCode); + if ($invitedBy < 0) { + return self::ERR_SIGNUP_BADINVITECODE; + } + } - // Make sure this is the last check, as if a further validation check failed, the invite would still have been used up. - $invitedBy = 0; - if (!$forceInviteMode && (int)Settings::value('..registerstatus') === Settings::REGISTER_STATUS_INVITE) { - if ($inviteCode === '') { - return self::ERR_SIGNUP_BADINVITECODE; - } + return $this->add($userName, $password, $email, $role, $notes, $host, $invites, $invitedBy); + } - $invitedBy = $this->checkAndUseInvite($inviteCode); - if ($invitedBy < 0) { - return self::ERR_SIGNUP_BADINVITECODE; - } - } + /** + * @param $password + * + * @return bool + */ + public function isValidPassword(string $password): bool + { + return strlen($password) > 5; + } - return $this->add($userName, $password, $email, $role, $notes, $host, $invites, $invitedBy); - } + /** + * If a invite is used, decrement the person who invited's invite count. + * + * @param int $inviteCode + * + * @return int + */ + public function checkAndUseInvite($inviteCode): int + { + $invite = $this->getInvite($inviteCode); + if (! $invite) { + return -1; + } - /** - * @param $password - * - * @return bool - */ - public function isValidPassword(string $password): bool - { - return (strlen($password) > 5); - } + User::query()->where('id', $invite['users_id'])->decrement('invites'); + $this->deleteInvite($inviteCode); - /** - * If a invite is used, decrement the person who invited's invite count. - * - * @param int $inviteCode - * - * @return int - */ - public function checkAndUseInvite($inviteCode): int - { - $invite = $this->getInvite($inviteCode); - if (!$invite) { - return -1; - } + return $invite['users_id']; + } - User::query()->where('id', $invite['users_id'])->decrement('invites'); - $this->deleteInvite($inviteCode); - return $invite['users_id']; - } + /** + * @param $inviteToken + * + * @return array|bool + */ + public function getInvite($inviteToken) + { + // + // Tidy any old invites sent greater than DEFAULT_INVITE_EXPIRY_DAYS days ago. + // + $this->pdo->queryExec(sprintf('DELETE FROM invitations WHERE createddate < now() - INTERVAL %d DAY', self::DEFAULT_INVITE_EXPIRY_DAYS)); - /** - * @param $inviteToken - * - * @return array|bool - */ - public function getInvite($inviteToken) - { - // - // Tidy any old invites sent greater than DEFAULT_INVITE_EXPIRY_DAYS days ago. - // - $this->pdo->queryExec(sprintf('DELETE FROM invitations WHERE createddate < now() - INTERVAL %d DAY', self::DEFAULT_INVITE_EXPIRY_DAYS)); - - return $this->pdo->queryOneRow( + return $this->pdo->queryOneRow( sprintf( 'SELECT * FROM invitations WHERE guid = %s', $this->pdo->escapeString($inviteToken) ) ); - } + } - /** - * @param $inviteToken - */ - public function deleteInvite(string $inviteToken): void - { + /** + * @param $inviteToken + */ + public function deleteInvite(string $inviteToken): void + { + $this->pdo->queryExec(sprintf('DELETE FROM invitations WHERE guid = %s', $this->pdo->escapeString($inviteToken))); + } - $this->pdo->queryExec(sprintf('DELETE FROM invitations WHERE guid = %s', $this->pdo->escapeString($inviteToken))); - } + /** + * Add a new user. + * + * @param $userName + * @param $password + * @param $email + * @param $role + * @param $notes + * @param $host + * @param int $invites + * @param int $invitedBy + * + * @return bool|int + */ + public function add($userName, $password, $email, $role, $notes, $host, $invites = self::DEFAULT_INVITES, $invitedBy = 0) + { + $password = $this->hashPassword($password); + if (! $password) { + return false; + } - - /** - * Add a new user - * - * @param $userName - * @param $password - * @param $email - * @param $role - * @param $notes - * @param $host - * @param int $invites - * @param int $invitedBy - * - * @return bool|int - */ - public function add($userName, $password, $email, $role, $notes, $host, $invites = self::DEFAULT_INVITES, $invitedBy = 0) - { - - $password = $this->hashPassword($password); - if (!$password) { - return false; - } - return User::query()->insertGetId( + return User::query()->insertGetId( [ 'username' => $userName, 'password' => $password, 'email' => $email, 'role' => $role, 'createddate' => new \DateTime('NOW'), - 'host' => (int)Settings::value('..storeuserips') === 1 ? $host : '', + 'host' => (int) Settings::value('..storeuserips') === 1 ? $host : '', 'rsstoken' => md5(Password::getRepository()->createNewToken()), 'invites' => $invites, - 'invitedby' => (int)$invitedBy === 0 ? 'NULL' : $invitedBy, + 'invitedby' => (int) $invitedBy === 0 ? 'NULL' : $invitedBy, 'userseed' => md5(Utility::generateUuid()), - 'notes' => $notes + 'notes' => $notes, ] ); - } + } - /** - * Verify if the user is logged in. - * - * @return bool - * @throws \Exception - */ - public function isLoggedIn(): bool - { - if (isset($_SESSION['uid'])) { - return true; - } - if (isset($_COOKIE['uid'], $_COOKIE['idh'])) { - $u = $this->getById($_COOKIE['uid']); + /** + * Verify if the user is logged in. + * + * @return bool + * @throws \Exception + */ + public function isLoggedIn(): bool + { + if (isset($_SESSION['uid'])) { + return true; + } + if (isset($_COOKIE['uid'], $_COOKIE['idh'])) { + $u = $this->getById($_COOKIE['uid']); - if ((int)$u['role'] !== self::ROLE_DISABLED && $_COOKIE['idh'] === self::hashSHA1($u['userseed'] . $_COOKIE['uid'])) { - $this->login($_COOKIE['uid'], $_SERVER['REMOTE_ADDR']); - } - } - return isset($_SESSION['uid']); - } + if ((int) $u['role'] !== self::ROLE_DISABLED && $_COOKIE['idh'] === self::hashSHA1($u['userseed'].$_COOKIE['uid'])) { + $this->login($_COOKIE['uid'], $_SERVER['REMOTE_ADDR']); + } + } - /** - * Log in a user. - * - * @param int $userID ID of the user. - * @param string $host - * @param bool $remember Save the user in cookies to keep them logged in. - * - * @throws \Exception - */ - public function login($userID, $host = '', $remember = false): void - { - $_SESSION['uid'] = $userID; + return isset($_SESSION['uid']); + } - if ((int)Settings::value('..storeuserips') !== 1) { - $host = ''; - } + /** + * Log in a user. + * + * @param int $userID ID of the user. + * @param string $host + * @param bool $remember Save the user in cookies to keep them logged in. + * + * @throws \Exception + */ + public function login($userID, $host = '', $remember = false): void + { + $_SESSION['uid'] = $userID; - $this->updateSiteAccessed($userID, $host); + if ((int) Settings::value('..storeuserips') !== 1) { + $host = ''; + } - if ($remember === true) { - $this->setCookies($userID); - } - } + $this->updateSiteAccessed($userID, $host); - /** - * When a user logs in, update the last time they logged in. - * - * @param int $userID ID of the user. - * @param string $host - */ - public function updateSiteAccessed($userID, $host = ''): void - { - $this->pdo->queryExec( + if ($remember === true) { + $this->setCookies($userID); + } + } + + /** + * When a user logs in, update the last time they logged in. + * + * @param int $userID ID of the user. + * @param string $host + */ + public function updateSiteAccessed($userID, $host = ''): void + { + $this->pdo->queryExec( sprintf( 'UPDATE users SET lastlogin = NOW() %s WHERE id = %d', - ($host === '' ? '' : (', host = ' . $this->pdo->escapeString($host))), + ($host === '' ? '' : (', host = '.$this->pdo->escapeString($host))), $userID ) ); - } + } - /** - * Set up cookies for a user. - * - * @param int $userID - */ - public function setCookies($userID): void - { - $user = $this->getById($userID); - $secure_cookie = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? '1' : '0'); - setcookie('uid', $userID, time() + 2592000, '/', null, $secure_cookie, true); - setcookie('idh', self::hashSHA1($user['userseed'] . $userID), time() + 2592000, '/', null, $secure_cookie, true); } + /** + * Set up cookies for a user. + * + * @param int $userID + */ + public function setCookies($userID): void + { + $user = $this->getById($userID); + $secure_cookie = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? '1' : '0'); + setcookie('uid', $userID, time() + 2592000, '/', null, $secure_cookie, true); + setcookie('idh', self::hashSHA1($user['userseed'].$userID), time() + 2592000, '/', null, $secure_cookie, true); + } - /** - * Return the User ID of the user. - * - * @return int - */ - public function currentUserId(): int - { - return $_SESSION['uid'] ?? -1; - } + /** + * Return the User ID of the user. + * + * @return int + */ + public function currentUserId(): int + { + return $_SESSION['uid'] ?? -1; + } - /** - * Logout the user, destroying his cookies and session. - */ - public function logout(): void - { - session_unset(); - session_destroy(); - $secure_cookie = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? '1' : '0'); - setcookie('uid', null, -1, '/', null, $secure_cookie, true); - setcookie('idh', null, -1, '/', null, $secure_cookie, true); - } + /** + * Logout the user, destroying his cookies and session. + */ + public function logout(): void + { + session_unset(); + session_destroy(); + $secure_cookie = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? '1' : '0'); + setcookie('uid', null, -1, '/', null, $secure_cookie, true); + setcookie('idh', null, -1, '/', null, $secure_cookie, true); + } - /** - * @param $uid - */ - public function updateApiAccessed($uid): void - { + /** + * @param $uid + */ + public function updateApiAccessed($uid): void + { + User::query()->where('id', $uid)->update(['apiaccess' => date('Y-m-d h:m:s')]); + } - User::query()->where('id', $uid)->update(['apiaccess' => date('Y-m-d h:m:s')]); - } + /** + * @param $uid + * @param $releaseid + * + * @return false|int|string + */ + public function addCart($uid, $releaseid) + { + $sql = sprintf('INSERT INTO users_releases (users_id, releases_id, createddate) VALUES (%d, %d, now())', $uid, $releaseid); - /** - * @param $uid - * @param $releaseid - * - * @return false|int|string - */ - public function addCart($uid, $releaseid) - { + return $this->pdo->queryInsert($sql); + } - $sql = sprintf('INSERT INTO users_releases (users_id, releases_id, createddate) VALUES (%d, %d, now())', $uid, $releaseid); + /** + * @param $uid + * @param int|string $releaseId + * + * @return array + */ + public function getCart($uid, $releaseId = ''): array + { + if ($releaseId !== '') { + $releaseId = ' AND releases.id = '.$releaseId; + } - return $this->pdo->queryInsert($sql); - } + return $this->pdo->query(sprintf('SELECT users_releases.*, releases.searchname,releases.guid FROM users_releases INNER JOIN releases on releases.id = users_releases.releases_id WHERE users_id = %d %s', $uid, $releaseId)); + } - /** - * @param $uid - * @param int|string $releaseId - * - * @return array - */ - public function getCart($uid, $releaseId = ''): array - { + /** + * @param array $guids + * @param $userID + * + * @return bool + */ + public function delCartByGuid($guids, $userID): bool + { + if (! is_array($guids)) { + return false; + } - if ($releaseId !== '') { - $releaseId = ' AND releases.id = ' . $releaseId; - } + $del = []; + foreach ($guids as $guid) { + $rel = $this->pdo->queryOneRow(sprintf('SELECT id FROM releases WHERE guid = %s', $this->pdo->escapeString($guid))); + if ($rel) { + $del[] = $rel['id']; + } + } - return $this->pdo->query(sprintf('SELECT users_releases.*, releases.searchname,releases.guid FROM users_releases INNER JOIN releases on releases.id = users_releases.releases_id WHERE users_id = %d %s', $uid, $releaseId)); - } - - /** - * @param array $guids - * @param $userID - * - * @return bool - */ - public function delCartByGuid($guids, $userID): bool - { - if (!is_array($guids)) { - return false; - } - - $del = []; - foreach ($guids as $guid) { - $rel = $this->pdo->queryOneRow(sprintf('SELECT id FROM releases WHERE guid = %s', $this->pdo->escapeString($guid))); - if ($rel) { - $del[] = $rel['id']; - } - } - - return (bool)$this->pdo->queryExec( + return (bool) $this->pdo->queryExec( sprintf( 'DELETE FROM users_releases WHERE releases_id IN (%s) AND users_id = %d', implode(',', $del), $userID ) ); - } + } - /** - * @param $guid - * @param $uid - */ - public function delCartByUserAndRelease($guid, $uid): void - { - $rel = $this->pdo->queryOneRow(sprintf('SELECT id FROM releases WHERE guid = %s', $this->pdo->escapeString($guid))); - if ($rel) { - $this->pdo->queryExec(sprintf('DELETE FROM users_releases WHERE users_id = %d AND releases_id = %d', $uid, $rel['id'])); - } - } + /** + * @param $guid + * @param $uid + */ + public function delCartByUserAndRelease($guid, $uid): void + { + $rel = $this->pdo->queryOneRow(sprintf('SELECT id FROM releases WHERE guid = %s', $this->pdo->escapeString($guid))); + if ($rel) { + $this->pdo->queryExec(sprintf('DELETE FROM users_releases WHERE users_id = %d AND releases_id = %d', $uid, $rel['id'])); + } + } - /** - * @param $rid - */ - public function delCartForRelease($rid): void - { - $this->pdo->queryExec(sprintf('DELETE FROM users_releases WHERE releases_id = %d', $rid)); - } + /** + * @param $rid + */ + public function delCartForRelease($rid): void + { + $this->pdo->queryExec(sprintf('DELETE FROM users_releases WHERE releases_id = %d', $rid)); + } + /** + * @param $uid + * @param array $catids + */ + public function addCategoryExclusions($uid, array $catids): void + { + $this->delUserCategoryExclusions($uid); + if (count($catids) > 0) { + foreach ($catids as $catid) { + $this->pdo->queryInsert(sprintf('INSERT INTO user_excluded_categories (users_id, categories_id, createddate) VALUES (%d, %d, now())', $uid, $catid)); + } + } + } - /** - * @param $uid - * @param array $catids - */ - public function addCategoryExclusions($uid, array $catids): void - { - $this->delUserCategoryExclusions($uid); - if (count($catids) > 0) { - foreach ($catids as $catid) { - $this->pdo->queryInsert(sprintf('INSERT INTO user_excluded_categories (users_id, categories_id, createddate) VALUES (%d, %d, now())', $uid, $catid)); - } - } - } + /** + * @param $role + * + * @return array + */ + public function getRoleCategoryExclusion($role): array + { + $ret = []; + $categories = $this->pdo->query(sprintf('SELECT categories_id FROM role_excluded_categories WHERE role = %d', $role)); + foreach ($categories as $category) { + $ret[] = $category['categories_id']; + } - /** - * @param $role - * - * @return array - */ - public function getRoleCategoryExclusion($role): array - { - $ret = []; - $categories = $this->pdo->query(sprintf('SELECT categories_id FROM role_excluded_categories WHERE role = %d', $role)); - foreach ($categories as $category) { - $ret[] = $category['categories_id']; - } + return $ret; + } - return $ret; - } + /** + * @param $role + * @param $catids + */ + public function addRoleCategoryExclusions($role, array $catids): void + { + $this->delRoleCategoryExclusions($role); + if (count($catids) > 0) { + foreach ($catids as $catid) { + $this->pdo->queryInsert(sprintf('INSERT INTO role_excluded_categories (role, categories_id, createddate) VALUES (%d, %d, now())', $role, $catid)); + } + } + } - /** - * @param $role - * @param $catids - */ - public function addRoleCategoryExclusions($role, array $catids): void - { - $this->delRoleCategoryExclusions($role); - if (count($catids) > 0) { - foreach ($catids as $catid) { - $this->pdo->queryInsert(sprintf('INSERT INTO role_excluded_categories (role, categories_id, createddate) VALUES (%d, %d, now())', $role, $catid)); - } - } - } + /** + * @param $role + */ + public function delRoleCategoryExclusions($role): void + { + $this->pdo->queryExec(sprintf('DELETE FROM role_excluded_categories WHERE role = %d', $role)); + } - /** - * @param $role - */ - public function delRoleCategoryExclusions($role): void - { - $this->pdo->queryExec(sprintf('DELETE FROM role_excluded_categories WHERE role = %d', $role)); - } + /** + * Get the list of categories the user has excluded. + * + * @param int $userID ID of the user. + * + * @return array + */ + public function getCategoryExclusion($userID): array + { + $ret = []; + $categories = $this->pdo->query(sprintf('SELECT categories_id FROM user_excluded_categories WHERE users_id = %d', $userID)); + foreach ($categories as $category) { + $ret[] = $category['categories_id']; + } - /** - * Get the list of categories the user has excluded. - * - * @param int $userID ID of the user. - * - * @return array - */ - public function getCategoryExclusion($userID): array - { - $ret = []; - $categories = $this->pdo->query(sprintf('SELECT categories_id FROM user_excluded_categories WHERE users_id = %d', $userID)); - foreach ($categories as $category) { - $ret[] = $category['categories_id']; - } + return $ret; + } - return $ret; - } + /** + * Get list of category names excluded by the user. + * + * @param int $userID ID of the user. + * + * @return array + */ + public function getCategoryExclusionNames($userID): array + { + $data = $this->getCategoryExclusion($userID); + $category = new Category(['Settings' => $this->pdo]); + $categories = $category->getByIds($data); + $ret = []; + if ($categories !== false) { + foreach ($categories as $cat) { + $ret[] = $cat['title']; + } + } - /** - * Get list of category names excluded by the user. - * - * @param int $userID ID of the user. - * - * @return array - */ - public function getCategoryExclusionNames($userID): array - { - $data = $this->getCategoryExclusion($userID); - $category = new Category(['Settings' => $this->pdo]); - $categories = $category->getByIds($data); - $ret = []; - if ($categories !== false) { - foreach ($categories as $cat) { - $ret[] = $cat['title']; - } - } - return $ret; - } + return $ret; + } - /** - * @param $uid - * @param $catid - */ - public function delCategoryExclusion($uid, $catid): void - { - $this->pdo->queryExec(sprintf('DELETE FROM user_excluded_categories WHERE users_id = %d AND categories_id = %d', $uid, $catid)); - } + /** + * @param $uid + * @param $catid + */ + public function delCategoryExclusion($uid, $catid): void + { + $this->pdo->queryExec(sprintf('DELETE FROM user_excluded_categories WHERE users_id = %d AND categories_id = %d', $uid, $catid)); + } - /** - * @param $sitetitle - * @param $siteemail - * @param $serverurl - * @param $uid - * @param $emailto - * - * @return string - * @throws \Exception - */ - public function sendInvite($sitetitle, $siteemail, $serverurl, $uid, $emailto): string - { - $sender = $this->getById($uid); - $token = self::hashSHA1(uniqid('', true)); - $subject = $sitetitle . ' Invitation'; - $url = $serverurl . 'register?invitecode=' . $token; - $contents = $sender['username'] . ' has sent an invite to join ' . $sitetitle . ' to this email address. To accept the invitation click the following link. ' . $url; + /** + * @param $sitetitle + * @param $siteemail + * @param $serverurl + * @param $uid + * @param $emailto + * + * @return string + * @throws \Exception + */ + public function sendInvite($sitetitle, $siteemail, $serverurl, $uid, $emailto): string + { + $sender = $this->getById($uid); + $token = self::hashSHA1(uniqid('', true)); + $subject = $sitetitle.' Invitation'; + $url = $serverurl.'register?invitecode='.$token; + $contents = $sender['username'].' has sent an invite to join '.$sitetitle.' to this email address. To accept the invitation click the following link. '.$url; - Utility::sendEmail($emailto, $subject, $contents, $siteemail); - $this->addInvite($uid, $token); + Utility::sendEmail($emailto, $subject, $contents, $siteemail); + $this->addInvite($uid, $token); - return $url; - } + return $url; + } - /** - * @param $uid - * @param $inviteToken - */ - public function addInvite(int $uid, string $inviteToken): void - { - $this->pdo->queryInsert(sprintf('INSERT INTO invitations (guid, users_id, createddate) VALUES (%s, %d, now())', $this->pdo->escapeString($inviteToken), $uid)); - } + /** + * @param $uid + * @param $inviteToken + */ + public function addInvite(int $uid, string $inviteToken): void + { + $this->pdo->queryInsert(sprintf('INSERT INTO invitations (guid, users_id, createddate) VALUES (%s, %d, now())', $this->pdo->escapeString($inviteToken), $uid)); + } - /** - * @return array - */ - public function getTopGrabbers(): array - { - return $this->pdo->query('SELECT id, username, SUM(grabs) as grabs FROM users + /** + * @return array + */ + public function getTopGrabbers(): array + { + return $this->pdo->query('SELECT id, username, SUM(grabs) as grabs FROM users GROUP BY id, username HAVING SUM(grabs) > 0 ORDER BY grabs DESC LIMIT 10' ); - } + } - /** - * Get list of user signups by month. - * - * @return array - */ - public function getUsersByMonth(): array - { - return $this->pdo->query(" + /** + * Get list of user signups by month. + * + * @return array + */ + public function getUsersByMonth(): array + { + return $this->pdo->query(" SELECT DATE_FORMAT(createddate, '%M %Y') AS mth, COUNT(id) AS num FROM users WHERE createddate IS NOT NULL AND createddate != '0000-00-00 00:00:00' GROUP BY mth ORDER BY createddate DESC" ); - } + } - /** - * @return array - * @throws \Exception - */ - public function getUsersByHostHash(): array - { - $ipsql = "('-1')"; + /** + * @return array + * @throws \Exception + */ + public function getUsersByHostHash(): array + { + $ipsql = "('-1')"; - if (Settings::value('..userhostexclusion') !== '') { - $ipsql = ''; - $ips = explode(',', Settings::value('..userhostexclusion')); - foreach ($ips as $ip) { - $ipsql .= $this->pdo->escapeString($this->getHostHash($ip, Settings::value('..siteseed'))) . ','; - } - $ipsql = "(" . $ipsql . " '-1')"; - } + if (Settings::value('..userhostexclusion') !== '') { + $ipsql = ''; + $ips = explode(',', Settings::value('..userhostexclusion')); + foreach ($ips as $ip) { + $ipsql .= $this->pdo->escapeString($this->getHostHash($ip, Settings::value('..siteseed'))).','; + } + $ipsql = '('.$ipsql." '-1')"; + } - $sql = sprintf("SELECT hosthash, group_concat(users_id) AS user_string, group_concat(username) AS user_names + $sql = sprintf("SELECT hosthash, group_concat(users_id) AS user_string, group_concat(username) AS user_names FROM ( SELECT hosthash, users_id, username FROM user_downloads LEFT OUTER JOIN users ON users.id = user_downloads.users_id WHERE hosthash IS NOT NULL AND hosthash NOT IN %s GROUP BY hosthash, users_id @@ -1180,43 +1177,43 @@ class Users limit 10", $ipsql, $ipsql ); - return $this->pdo->query($sql); - } + return $this->pdo->query($sql); + } - /** - * @param $host - * @param string|null $siteseed - * - * @return string - * @throws \Exception - */ - public function getHostHash($host, string $siteseed = ''): string - { - if ($siteseed === '') { - $siteseed = Settings::value('..siteseed'); - } + /** + * @param $host + * @param string|null $siteseed + * + * @return string + * @throws \Exception + */ + public function getHostHash($host, string $siteseed = ''): string + { + if ($siteseed === '') { + $siteseed = Settings::value('..siteseed'); + } - return self::hashSHA1($siteseed . $host . $siteseed); - } + return self::hashSHA1($siteseed.$host.$siteseed); + } - /** - * @return array - */ - public function getUsersByRole(): array - { - return $this->pdo->query('SELECT ur.name, COUNT(u.id) as num FROM users u + /** + * @return array + */ + public function getUsersByRole(): array + { + return $this->pdo->query('SELECT ur.name, COUNT(u.id) as num FROM users u INNER JOIN user_roles ur ON ur.id = u.role GROUP BY ur.name ORDER BY COUNT(u.id) DESC' ); - } + } - /** - * @return array - */ - public function getLoginCountsByMonth(): array - { - return $this->pdo->query("SELECT 'Login' as type, + /** + * @return array + */ + public function getLoginCountsByMonth(): array + { + return $this->pdo->query("SELECT 'Login' as type, sum(case when lastlogin > curdate() - INTERVAL 1 DAY then 1 else 0 end) as 1day, sum(case when lastlogin > curdate() - INTERVAL 7 DAY AND lastlogin < curdate() - INTERVAL 1 DAY then 1 else 0 end) as 7day, sum(case when lastlogin > curdate() - INTERVAL 1 MONTH AND lastlogin < curdate() - INTERVAL 7 DAY then 1 else 0 end) as 1month, @@ -1234,68 +1231,69 @@ class Users sum(case when apiaccess < curdate() - INTERVAL 6 MONTH then 1 else 0 end) as 12month FROM users" ); - } + } - /** - * @return array - */ - public function getRoles(): array - { - return UserRole::all()->toArray(); - } + /** + * @return array + */ + public function getRoles(): array + { + return UserRole::all()->toArray(); + } - /** - * @param $id - * - * @return \Illuminate\Database\Eloquent\Model|null|static - */ - public function getRoleById($id) - { - return UserRole::query()->where('id', $id)->first(); - } + /** + * @param $id + * + * @return \Illuminate\Database\Eloquent\Model|null|static + */ + public function getRoleById($id) + { + return UserRole::query()->where('id', $id)->first(); + } - /** - * @param $name - * @param $apirequests - * @param $downloadrequests - * @param $defaultinvites - * @param $canpreview - * @param $hideads - * - * @return false|int|string - */ - public function addRole($name, $apirequests, $downloadrequests, $defaultinvites, $canpreview, $hideads) - { - return UserRole::query()->insertGetId( + /** + * @param $name + * @param $apirequests + * @param $downloadrequests + * @param $defaultinvites + * @param $canpreview + * @param $hideads + * + * @return false|int|string + */ + public function addRole($name, $apirequests, $downloadrequests, $defaultinvites, $canpreview, $hideads) + { + return UserRole::query()->insertGetId( [ 'name' => $name, 'apirequests' => $apirequests, 'downloadrequests' => $downloadrequests, 'defaultinvites' => $defaultinvites, 'canpreview' => $canpreview, - 'hideads' => $hideads + 'hideads' => $hideads, ] ); - } + } - /** - * @param $id - * @param $name - * @param $apirequests - * @param $downloadrequests - * @param $defaultinvites - * @param $isdefault - * @param $canpreview - * @param $hideads - * - * @return int - */ - public function updateRole($id, $name, $apirequests, $downloadrequests, $defaultinvites, $isdefault, $canpreview, $hideads) - { - if ((int)$isdefault === 1) { - UserRole::query()->update(['isdefault' => 0]); - } - return UserRole::query()->where('id', $id)->update( + /** + * @param $id + * @param $name + * @param $apirequests + * @param $downloadrequests + * @param $defaultinvites + * @param $isdefault + * @param $canpreview + * @param $hideads + * + * @return int + */ + public function updateRole($id, $name, $apirequests, $downloadrequests, $defaultinvites, $isdefault, $canpreview, $hideads) + { + if ((int) $isdefault === 1) { + UserRole::query()->update(['isdefault' => 0]); + } + + return UserRole::query()->where('id', $id)->update( [ 'name' => $name, 'apirequests' => $apirequests, @@ -1303,140 +1301,141 @@ class Users 'defaultinvites' => $defaultinvites, 'isdefault' => $isdefault, 'canpreview' => $canpreview, - 'hideads' => $hideads + 'hideads' => $hideads, ] ); - } + } - /** - * @param $id - * - * @return bool|\PDOStatement - */ - public function deleteRole($id) - { - $res = $this->pdo->query(sprintf('SELECT id FROM users WHERE role = %d', $id)); - if (count($res) > 0) { - $userids = []; - foreach ($res as $user) { - $userids[] = $user['id']; - } - $defaultrole = $this->getDefaultRole(); - $this->pdo->queryExec(sprintf('UPDATE users SET role = %d WHERE id IN (%s)', $defaultrole['id'], implode(',', $userids))); - } + /** + * @param $id + * + * @return bool|\PDOStatement + */ + public function deleteRole($id) + { + $res = $this->pdo->query(sprintf('SELECT id FROM users WHERE role = %d', $id)); + if (count($res) > 0) { + $userids = []; + foreach ($res as $user) { + $userids[] = $user['id']; + } + $defaultrole = $this->getDefaultRole(); + $this->pdo->queryExec(sprintf('UPDATE users SET role = %d WHERE id IN (%s)', $defaultrole['id'], implode(',', $userids))); + } - return UserRole::query()->where('id', $id)->delete(); - } + return UserRole::query()->where('id', $id)->delete(); + } - /** - * @return \Illuminate\Database\Eloquent\Model|null|static - */ - public function getDefaultRole() - { - return UserRole::query()->where('isdefault', '=', 1)->first(); - } + /** + * @return \Illuminate\Database\Eloquent\Model|null|static + */ + public function getDefaultRole() + { + return UserRole::query()->where('isdefault', '=', 1)->first(); + } - /** - * Get the quantity of API requests in the last day for the users_id. - * - * @param int $userID - * - * @return int - * @throws \Exception - */ - public function getApiRequests($userID): int - { - // Clear old requests. - $this->clearApiRequests($userID); - $requests = UserRequest::query()->where('users_id', $userID)->count('id'); - return (!$requests ? 0 : $requests); - } + /** + * Get the quantity of API requests in the last day for the users_id. + * + * @param int $userID + * + * @return int + * @throws \Exception + */ + public function getApiRequests($userID): int + { + // Clear old requests. + $this->clearApiRequests($userID); + $requests = UserRequest::query()->where('users_id', $userID)->count('id'); - /** - * If a user accesses the API, log it. - * - * @param int $userID ID of the user. - * @param string $request The API request. - * - */ - public function addApiRequest($userID, $request): void - { - UserRequest::query()->insert(['users_id' => $userID, 'request' => $request, 'timestamp'=> new \DateTime('NOW')]); - } + return ! $requests ? 0 : $requests; + } - /** - * Delete api requests older than a day. - * - * @param int|bool $userID - * int The users ID. - * bool false do all user ID's.. - * - * @return void - * @throws \Exception - */ - protected function clearApiRequests($userID): void - { - if ($userID === false) { - UserRequest::query()->where('timestamp', '<', date_sub(new \DateTime('NOW'), new \DateInterval('P1D')))->delete(); - } else { - UserRequest::query()->where('users_id', $userID)->where('timestamp', '<', date_sub(new \DateTime('NOW'), new \DateInterval('P1D')))->delete(); - } - } + /** + * If a user accesses the API, log it. + * + * @param int $userID ID of the user. + * @param string $request The API request. + */ + public function addApiRequest($userID, $request): void + { + UserRequest::query()->insert(['users_id' => $userID, 'request' => $request, 'timestamp'=> new \DateTime('NOW')]); + } - /** - * deletes old rows FROM the userrequest and user_downloads tables. - * if site->userdownloadpurgedays SET to 0 then all release history is removed but - * the download/request rows must remain for at least one day to allow the role based - * limits to apply. - * - * @param int $days - * - * @throws \Exception - */ - public function pruneRequestHistory($days = 0): void - { - if ($days === 0) { - $days = 1; - $this->pdo->queryExec('UPDATE user_downloads SET releases_id = null'); - } + /** + * Delete api requests older than a day. + * + * @param int|bool $userID + * int The users ID. + * bool false do all user ID's.. + * + * @return void + * @throws \Exception + */ + protected function clearApiRequests($userID): void + { + if ($userID === false) { + UserRequest::query()->where('timestamp', '<', date_sub(new \DateTime('NOW'), new \DateInterval('P1D')))->delete(); + } else { + UserRequest::query()->where('users_id', $userID)->where('timestamp', '<', date_sub(new \DateTime('NOW'), new \DateInterval('P1D')))->delete(); + } + } - UserRequest::query()->where('timestamp', '<', date_sub(new \DateTime('NOW'), new \DateInterval('P' . $days . 'D')))->delete(); - $this->pdo->queryExec(sprintf('DELETE FROM user_downloads WHERE timestamp < DATE_SUB(NOW(), INTERVAL %d DAY)', $days)); - } + /** + * deletes old rows FROM the userrequest and user_downloads tables. + * if site->userdownloadpurgedays SET to 0 then all release history is removed but + * the download/request rows must remain for at least one day to allow the role based + * limits to apply. + * + * @param int $days + * + * @throws \Exception + */ + public function pruneRequestHistory($days = 0): void + { + if ($days === 0) { + $days = 1; + $this->pdo->queryExec('UPDATE user_downloads SET releases_id = null'); + } - /** - * Get the COUNT of how many NZB's the user has downloaded in the past day. - * - * @param int $userID - * - * @return int - */ - public function getDownloadRequests($userID): int - { - // Clear old requests. - $this->pdo->queryExec( + UserRequest::query()->where('timestamp', '<', date_sub(new \DateTime('NOW'), new \DateInterval('P'.$days.'D')))->delete(); + $this->pdo->queryExec(sprintf('DELETE FROM user_downloads WHERE timestamp < DATE_SUB(NOW(), INTERVAL %d DAY)', $days)); + } + + /** + * Get the COUNT of how many NZB's the user has downloaded in the past day. + * + * @param int $userID + * + * @return int + */ + public function getDownloadRequests($userID): int + { + // Clear old requests. + $this->pdo->queryExec( sprintf( 'DELETE FROM user_downloads WHERE users_id = %d AND timestamp < DATE_SUB(NOW(), INTERVAL 1 DAY)', $userID ) ); - $value = $this->pdo->queryOneRow( + $value = $this->pdo->queryOneRow( sprintf( 'SELECT COUNT(id) AS num FROM user_downloads WHERE users_id = %d AND timestamp > DATE_SUB(NOW(), INTERVAL 1 DAY)', $userID ) ); - return ($value === false ? 0 : (int) $value['num']); - } - /** - * @param $userID - * - * @return array - */ - public function getDownloadRequestsForUser($userID): array - { - return $this->pdo->query(sprintf('SELECT u.*, r.guid, r.searchname FROM user_downloads u + return $value === false ? 0 : (int) $value['num']; + } + + /** + * @param $userID + * + * @return array + */ + public function getDownloadRequestsForUser($userID): array + { + return $this->pdo->query(sprintf('SELECT u.*, r.guid, r.searchname FROM user_downloads u LEFT OUTER JOIN releases r ON r.id = u.releases_id WHERE u.users_id = %d ORDER BY u.timestamp @@ -1444,87 +1443,86 @@ class Users $userID ) ); - } + } - /** - * If a user downloads a NZB, log it. - * - * @param int $userID id of the user. - * - * @param $releaseID - * - * @return bool|int - */ - public function addDownloadRequest($userID, $releaseID) - { - return $this->pdo->queryInsert( + /** + * If a user downloads a NZB, log it. + * + * @param int $userID id of the user. + * + * @param $releaseID + * + * @return bool|int + */ + public function addDownloadRequest($userID, $releaseID) + { + return $this->pdo->queryInsert( sprintf( 'INSERT INTO user_downloads (users_id, releases_id, timestamp) VALUES (%d, %d, NOW())', $userID, $releaseID ) ); - } + } - /** - * @param $releaseID - * - * @return false|int|string - */ - public function delDownloadRequestsForRelease(int $releaseID) - { - return $this->pdo->queryInsert(sprintf('DELETE FROM user_downloads WHERE releases_id = %d', $releaseID)); - } + /** + * @param $releaseID + * + * @return false|int|string + */ + public function delDownloadRequestsForRelease(int $releaseID) + { + return $this->pdo->queryInsert(sprintf('DELETE FROM user_downloads WHERE releases_id = %d', $releaseID)); + } - /** - * Checks if a user is a specific role. - * - * @notes Uses type of $user to denote identifier. if string: username, if int: users_id - * @param int $roleID - * @param string|int $user - * @return bool - */ - public function roleCheck($roleID, $user): bool - { + /** + * Checks if a user is a specific role. + * + * @notes Uses type of $user to denote identifier. if string: username, if int: users_id + * @param int $roleID + * @param string|int $user + * @return bool + */ + public function roleCheck($roleID, $user): bool + { + if (is_string($user) && strlen($user) > 0) { + $user = $this->pdo->escapeString($user); + $querySuffix = "username = $user"; + } elseif (is_int($user) && $user >= 0) { + $querySuffix = "id = $user"; + } else { + return false; + } - if (is_string($user) && strlen($user) > 0) { - $user = $this->pdo->escapeString($user); - $querySuffix = "username = $user"; - } elseif (is_int($user) && $user >= 0) { - $querySuffix = "id = $user"; - } else { - return false; - } - - $result = $this->pdo->queryOneRow( + $result = $this->pdo->queryOneRow( sprintf( 'SELECT role FROM users WHERE %s', $querySuffix ) ); - return $result['role'] === $roleID; - } + return $result['role'] === $roleID; + } - /** - * Wrapper for roleCheck specifically for Admins. - * - * @param int $userID - * @return bool - */ - public function isAdmin($userID): bool - { - return $this->roleCheck(self::ROLE_ADMIN, (int)$userID); - } + /** + * Wrapper for roleCheck specifically for Admins. + * + * @param int $userID + * @return bool + */ + public function isAdmin($userID): bool + { + return $this->roleCheck(self::ROLE_ADMIN, (int) $userID); + } - /** - * Wrapper for roleCheck specifically for Moderators. - * - * @param int $userId - * @return bool - */ - public function isModerator($userId): bool - { - return $this->roleCheck(self::ROLE_MODERATOR, (int)$userId); - } + /** + * Wrapper for roleCheck specifically for Moderators. + * + * @param int $userId + * @return bool + */ + public function isModerator($userId): bool + { + return $this->roleCheck(self::ROLE_MODERATOR, (int) $userId); + } } diff --git a/nntmux/Videos.php b/nntmux/Videos.php index dc6aee126..dc5db395b 100755 --- a/nntmux/Videos.php +++ b/nntmux/Videos.php @@ -1,136 +1,136 @@ <?php + namespace nntmux; use nntmux\db\DB; -use nntmux\Category; /** - * Class Videos -- functions for site interaction - * - * @package nntmux + * Class Videos -- functions for site interaction. */ -Class Videos +class Videos { - /** - * @param array $options - */ - public function __construct(array $options = []) { - $defaults = [ + /** + * @param array $options + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Logger' => null, 'Settings' => null, ]; - $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->catWhere = "r.categories_id BETWEEN " . Category::TV_ROOT . " AND " . Category::TV_OTHER; - } + $options += $defaults; + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->catWhere = 'r.categories_id BETWEEN '.Category::TV_ROOT.' AND '.Category::TV_OTHER; + } - /** - * Get info from tables for the provided ID. - * - * @param $id - * - * @return array - */ - public function getByVideoID($id) - { - return $this->pdo->queryOneRow( - sprintf(" + /** + * Get info from tables for the provided ID. + * + * @param $id + * + * @return array + */ + public function getByVideoID($id) + { + return $this->pdo->queryOneRow( + sprintf(' SELECT v.*, tvi.summary, tvi.publisher, tvi.image FROM videos v INNER JOIN tv_info tvi ON v.id = tvi.videos_id - WHERE id = %d", + WHERE id = %d', $id ) ); - } + } - /** - * Retrieves a range of all shows for the show-edit admin list - * - * @param $start - * @param $num - * @param string $showname - * - * @return array - */ - public function getRange($start, $num, $showname = "") - { - if ($start === false) { - $limit = ""; - } else { - $limit = "LIMIT " . $num . " OFFSET " . $start; - } + /** + * Retrieves a range of all shows for the show-edit admin list. + * + * @param $start + * @param $num + * @param string $showname + * + * @return array + */ + public function getRange($start, $num, $showname = '') + { + if ($start === false) { + $limit = ''; + } else { + $limit = 'LIMIT '.$num.' OFFSET '.$start; + } - $rsql = ''; - if ($showname != "") { - $rsql .= sprintf("AND v.title LIKE %s ", $this->pdo->escapeString("%" . $showname . "%")); - } + $rsql = ''; + if ($showname != '') { + $rsql .= sprintf('AND v.title LIKE %s ', $this->pdo->escapeString('%'.$showname.'%')); + } - return $this->pdo->query( - sprintf(" + return $this->pdo->query( + sprintf(' SELECT v.*, tvi.summary, tvi.publisher, tvi.image FROM videos v INNER JOIN tv_info tvi ON v.id = tvi.videos_id WHERE 1=1 %s - ORDER BY v.id ASC %s", + ORDER BY v.id ASC %s', $rsql, $limit ) ); - } + } - /** - * Returns a count of all shows -- usually used by pager - * - * @param string $showname - * - * @return mixed - */ - public function getCount($showname = "") - { - $rsql = ''; - if ($showname != "") { - $rsql .= sprintf("AND v.title LIKE %s ", $this->pdo->escapeString("%" . $showname . "%")); - } - $res = $this->pdo->queryOneRow( - sprintf(" + /** + * Returns a count of all shows -- usually used by pager. + * + * @param string $showname + * + * @return mixed + */ + public function getCount($showname = '') + { + $rsql = ''; + if ($showname != '') { + $rsql .= sprintf('AND v.title LIKE %s ', $this->pdo->escapeString('%'.$showname.'%')); + } + $res = $this->pdo->queryOneRow( + sprintf(' SELECT COUNT(v.id) AS num FROM videos v INNER JOIN tv_info tvi ON v.id = tvi.videos_id - WHERE 1=1 %s", + WHERE 1=1 %s', $rsql ) ); - return $res["num"]; - } - /** - * Retrieves and returns a list of shows with eligible releases - * - * @param $uid - * @param string $letter - * @param string $showname - * - * @return array - */ - public function getSeriesList($uid, $letter = "", $showname = "") - { - $rsql = ''; - if ($letter != "") { - if ($letter == '0-9') { - $letter = '[0-9]'; - } + return $res['num']; + } - $rsql .= sprintf("AND v.title REGEXP %s", $this->pdo->escapeString('^' . $letter)); - } - $tsql = ''; - if ($showname != '') { - $tsql .= sprintf("AND v.title LIKE %s", $this->pdo->escapeString("%" . $showname . "%")); - } + /** + * Retrieves and returns a list of shows with eligible releases. + * + * @param $uid + * @param string $letter + * @param string $showname + * + * @return array + */ + public function getSeriesList($uid, $letter = '', $showname = '') + { + $rsql = ''; + if ($letter != '') { + if ($letter == '0-9') { + $letter = '[0-9]'; + } - $qry = sprintf(" + $rsql .= sprintf('AND v.title REGEXP %s', $this->pdo->escapeString('^'.$letter)); + } + $tsql = ''; + if ($showname != '') { + $tsql .= sprintf('AND v.title LIKE %s', $this->pdo->escapeString('%'.$showname.'%')); + } + + $qry = sprintf(' SELECT v.* FROM (SELECT v.*, tve.firstaired AS prevdate, tve.title AS previnfo, @@ -147,14 +147,15 @@ Class Videos STRAIGHT_JOIN releases r ON r.videos_id = v.id WHERE %s GROUP BY v.id - ORDER BY v.title ASC", + ORDER BY v.title ASC', $uid, $rsql, $tsql, $this->catWhere ); - $sql = $this->pdo->query($qry); - return $sql; - } + $sql = $this->pdo->query($qry); + + return $sql; + } } diff --git a/nntmux/XXX.php b/nntmux/XXX.php index 61d060f9f..6b9421e5c 100755 --- a/nntmux/XXX.php +++ b/nntmux/XXX.php @@ -2,157 +2,156 @@ namespace nntmux; -use App\Models\Settings; use nntmux\db\DB; -use nntmux\processing\adult\AEBN; -use nntmux\processing\adult\ADM; +use App\Models\Settings; use nntmux\processing\adult\ADE; -use nntmux\processing\adult\Hotmovies; +use nntmux\processing\adult\ADM; +use nntmux\processing\adult\AEBN; use nntmux\processing\adult\Popporn; - +use nntmux\processing\adult\Hotmovies; /** - * Class XXX + * Class XXX. */ class XXX { - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * What scraper class did we use -- used for template and trailer information - * - * @var string - */ - protected $whichclass = ''; + /** + * What scraper class did we use -- used for template and trailer information. + * + * @var string + */ + protected $whichclass = ''; - /** - * Current title being passed through various sites/api's. - * - * @var string - */ - protected $currentTitle = ''; + /** + * Current title being passed through various sites/api's. + * + * @var string + */ + protected $currentTitle = ''; - /** - * @var Logger - */ - protected $debugging; + /** + * @var Logger + */ + protected $debugging; - /** - * @var bool - */ - protected $debug; + /** + * @var bool + */ + protected $debug; - /** - * @var bool - */ - protected $echooutput; + /** + * @var bool + */ + protected $echooutput; - /** - * @var string - */ - protected $imgSavePath; + /** + * @var string + */ + protected $imgSavePath; - /** - * @var ReleaseImage - */ - protected $releaseImage; + /** + * @var ReleaseImage + */ + protected $releaseImage; - protected $currentRelID; + protected $currentRelID; - protected $movieqty; + protected $movieqty; - /** - * @var string - */ - protected $showPasswords; + /** + * @var string + */ + protected $showPasswords; - protected $cookie; + protected $cookie; - /** - * @var array|bool|int|string - */ - public $catWhere; + /** + * @var array|bool|int|string + */ + public $catWhere; - /** - * @param array $options Echo to cli / Class instances. - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Echo to cli / Class instances. + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'ReleaseImage' => null, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->releaseImage = ($options['ReleaseImage'] instanceof ReleaseImage ? $options['ReleaseImage'] : new ReleaseImage($this->pdo)); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->releaseImage = ($options['ReleaseImage'] instanceof ReleaseImage ? $options['ReleaseImage'] : new ReleaseImage($this->pdo)); - $this->movieqty = (Settings::value('..maxxxxprocessed') !== '') ? Settings::value('..maxxxxprocessed') : 100; - $this->showPasswords = Releases::showPasswords(); - $this->debug = NN_DEBUG; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->imgSavePath = NN_COVERS . 'xxx' . DS; - $this->cookie = NN_TMP . 'xxx.cookie'; - $this->catWhere = 'AND categories_id IN (' . - Category::XXX_DVD . ', ' . - Category::XXX_WMV . ', ' . - Category::XXX_XVID . ', ' . - Category::XXX_X264 . ', ' . - Category::XXX_SD . ', ' . - Category::XXX_CLIPHD . ', ' . - Category::XXX_CLIPSD . ', ' . - Category::XXX_WEBDL . ') '; + $this->movieqty = (Settings::value('..maxxxxprocessed') !== '') ? Settings::value('..maxxxxprocessed') : 100; + $this->showPasswords = Releases::showPasswords(); + $this->debug = NN_DEBUG; + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + $this->imgSavePath = NN_COVERS.'xxx'.DS; + $this->cookie = NN_TMP.'xxx.cookie'; + $this->catWhere = 'AND categories_id IN ('. + Category::XXX_DVD.', '. + Category::XXX_WMV.', '. + Category::XXX_XVID.', '. + Category::XXX_X264.', '. + Category::XXX_SD.', '. + Category::XXX_CLIPHD.', '. + Category::XXX_CLIPSD.', '. + Category::XXX_WEBDL.') '; - if (NN_DEBUG || NN_LOGGING) { - $this->debug = true; - try { - $this->debugging = new Logger(); - } catch (LoggerException $error) { - $this->debug = false; - } - } - } + if (NN_DEBUG || NN_LOGGING) { + $this->debug = true; + try { + $this->debugging = new Logger(); + } catch (LoggerException $error) { + $this->debug = false; + } + } + } - /** - * Get info for a xxx id. - * - * @param int $xxxid - * - * @return array|bool - */ - public function getXXXInfo($xxxid) - { - return $this->pdo->queryOneRow(sprintf('SELECT *, UNCOMPRESS(plot) AS plot FROM xxxinfo WHERE id = %d', $xxxid)); - } + /** + * Get info for a xxx id. + * + * @param int $xxxid + * + * @return array|bool + */ + public function getXXXInfo($xxxid) + { + return $this->pdo->queryOneRow(sprintf('SELECT *, UNCOMPRESS(plot) AS plot FROM xxxinfo WHERE id = %d', $xxxid)); + } - /** - * Get movie releases with covers for xxx browse page. - * - * @param $cat - * @param $start - * @param $num - * @param $orderBy - * @param $maxAge - * @param array $excludedCats - * - * @return array - */ - public function getXXXRange($cat, $start, $num, $orderBy, $maxAge = -1, array $excludedCats = []): array - { - $catsrch = ''; - if (count($cat) > 0 && $cat[0] !== -1) { - $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); - } + /** + * Get movie releases with covers for xxx browse page. + * + * @param $cat + * @param $start + * @param $num + * @param $orderBy + * @param $maxAge + * @param array $excludedCats + * + * @return array + */ + public function getXXXRange($cat, $start, $num, $orderBy, $maxAge = -1, array $excludedCats = []): array + { + $catsrch = ''; + if (count($cat) > 0 && $cat[0] !== -1) { + $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); + } - $order = $this->getXXXOrder($orderBy); + $order = $this->getXXXOrder($orderBy); - $xxxmovies = $this->pdo->queryCalc( + $xxxmovies = $this->pdo->queryCalc( sprintf(" SELECT SQL_CALC_FOUND_ROWS xxx.id, @@ -169,26 +168,26 @@ class XXX $this->getBrowseBy(), $catsrch, ($maxAge > 0 - ? 'AND r.postdate > NOW() - INTERVAL ' . $maxAge . 'DAY ' + ? 'AND r.postdate > NOW() - INTERVAL '.$maxAge.'DAY ' : '' ), - (count($excludedCats) > 0 ? ' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')' : ''), + (count($excludedCats) > 0 ? ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')' : ''), $order[0], $order[1], - ($start === false ? '' : ' LIMIT ' . $num . ' OFFSET ' . $start) + ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start) ), true, NN_CACHE_EXPIRY_MEDIUM ); - $xxxIDs = $releaseIDs = false; + $xxxIDs = $releaseIDs = false; - if (is_array($xxxmovies['result'])) { - foreach ($xxxmovies['result'] AS $xxx => $id) { - $xxxIDs[] = $id['id']; - $releaseIDs[] = $id['grp_release_id']; - } - } + if (is_array($xxxmovies['result'])) { + foreach ($xxxmovies['result'] as $xxx => $id) { + $xxxIDs[] = $id['id']; + $releaseIDs[] = $id['grp_release_id']; + } + } - $sql = sprintf(" + $sql = sprintf(" SELECT GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id, GROUP_CONCAT(r.rarinnerfilecount ORDER BY r.postdate DESC SEPARATOR ',') AS grp_rarinnerfilecount, @@ -227,32 +226,32 @@ class XXX $this->getBrowseBy(), $catsrch, ($maxAge > 0 - ? 'AND r.postdate > NOW() - INTERVAL ' . $maxAge . 'DAY ' + ? 'AND r.postdate > NOW() - INTERVAL '.$maxAge.'DAY ' : '' ), - (count($excludedCats) > 0 ? ' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')' : ''), + (count($excludedCats) > 0 ? ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')' : ''), $order[0], $order[1] ); - $return = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); - if (!empty($return)) { - $return[0]['_totalcount'] = $xxxmovies['total'] ?? 0; - } + $return = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM); + if (! empty($return)) { + $return[0]['_totalcount'] = $xxxmovies['total'] ?? 0; + } - return $return; - } + return $return; + } - /** - * Get the order type the user requested on the movies page. - * - * @param $orderBy - * - * @return array - */ - protected function getXXXOrder($orderBy): array - { - $orderArr = explode('_', (($orderBy === '') ? 'MAX(r.postdate)' : $orderBy)); - switch ($orderArr[0]) { + /** + * Get the order type the user requested on the movies page. + * + * @param $orderBy + * + * @return array + */ + protected function getXXXOrder($orderBy): array + { + $orderArr = explode('_', (($orderBy === '') ? 'MAX(r.postdate)' : $orderBy)); + switch ($orderArr[0]) { case 'title': $orderField = 'xxx.title'; break; @@ -262,104 +261,102 @@ class XXX break; } - return [$orderField, isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1]) ? $orderArr[1] : 'desc']; - } + return [$orderField, isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1]) ? $orderArr[1] : 'desc']; + } - /** - * Order types for xxx page. - * - * @return array - */ - public function getXXXOrdering(): array - { - return ['title_asc', 'title_desc', 'name_asc', 'name_desc', 'size_asc', 'size_desc', 'posted_asc', 'posted_desc', 'cat_asc', 'cat_desc']; - } + /** + * Order types for xxx page. + * + * @return array + */ + public function getXXXOrdering(): array + { + return ['title_asc', 'title_desc', 'name_asc', 'name_desc', 'size_asc', 'size_desc', 'posted_asc', 'posted_desc', 'cat_asc', 'cat_desc']; + } - /** - * @return string - */ - protected function getBrowseBy(): string - { - $browseBy = ' '; - $browseByArr = ['title', 'director', 'actors', 'genre', 'id']; - foreach ($browseByArr as $bb) { - if (isset($_REQUEST[$bb]) && !empty($_REQUEST[$bb])) { - $bbv = stripslashes($_REQUEST[$bb]); - if ($bb === 'genre') { - $bbv = $this->getGenreID($bbv); - } - if ($bb === 'id') { - $browseBy .= 'AND xxx.' . $bb . '=' . $bbv; - } else { - $browseBy .= 'AND xxx.' . $bb . ' ' . $this->pdo->likeString($bbv, true, true); - } - } - } + /** + * @return string + */ + protected function getBrowseBy(): string + { + $browseBy = ' '; + $browseByArr = ['title', 'director', 'actors', 'genre', 'id']; + foreach ($browseByArr as $bb) { + if (isset($_REQUEST[$bb]) && ! empty($_REQUEST[$bb])) { + $bbv = stripslashes($_REQUEST[$bb]); + if ($bb === 'genre') { + $bbv = $this->getGenreID($bbv); + } + if ($bb === 'id') { + $browseBy .= 'AND xxx.'.$bb.'='.$bbv; + } else { + $browseBy .= 'AND xxx.'.$bb.' '.$this->pdo->likeString($bbv, true, true); + } + } + } - return $browseBy; - } + return $browseBy; + } - /** - * Create click-able links to actors/genres/directors/etc.. - * - * @param $data - * @param $field - * - * @return string - */ - public function makeFieldLinks($data, $field): string - { - if (empty($data[$field])) { - return ''; - } + /** + * Create click-able links to actors/genres/directors/etc.. + * + * @param $data + * @param $field + * + * @return string + */ + public function makeFieldLinks($data, $field): string + { + if (empty($data[$field])) { + return ''; + } - $tmpArr = explode(',', $data[$field]); - $newArr = []; - $i = 0; - foreach ($tmpArr as $ta) { - if (trim($ta) === '') { - continue; - } - if ($field === 'genre') { - $ta = $this->getGenres(true, $ta); - $ta = $ta['title']; - } - if ($i > 7) { - break; - } //only use first 8 - $newArr[] = '<a href="' . WWW_TOP . '/xxx?' . $field . '=' . urlencode($ta) . '" title="' . $ta . '">' . $ta . '</a>'; - $i++; - } + $tmpArr = explode(',', $data[$field]); + $newArr = []; + $i = 0; + foreach ($tmpArr as $ta) { + if (trim($ta) === '') { + continue; + } + if ($field === 'genre') { + $ta = $this->getGenres(true, $ta); + $ta = $ta['title']; + } + if ($i > 7) { + break; + } //only use first 8 + $newArr[] = '<a href="'.WWW_TOP.'/xxx?'.$field.'='.urlencode($ta).'" title="'.$ta.'">'.$ta.'</a>'; + $i++; + } - return implode(', ', $newArr); - } + return implode(', ', $newArr); + } - /** - * Update XXX Information from getXXXCovers.php in misc/testing/PostProc - * - * @param string $id - * @param string $title - * @param string $tagLine - * @param string $plot - * @param string $genre - * @param string $director - * @param string $actors - * @param string $extras - * @param string $productInfo - * @param string $trailers - * @param string $directUrl - * @param string $classUsed - * @param string $cover - * @param string $backdrop - */ - public function update( + /** + * Update XXX Information from getXXXCovers.php in misc/testing/PostProc. + * + * @param string $id + * @param string $title + * @param string $tagLine + * @param string $plot + * @param string $genre + * @param string $director + * @param string $actors + * @param string $extras + * @param string $productInfo + * @param string $trailers + * @param string $directUrl + * @param string $classUsed + * @param string $cover + * @param string $backdrop + */ + public function update( $id = '', $title = '', $tagLine = '', $plot = '', $genre = '', $director = '', $actors = '', $extras = '', $productInfo = '', $trailers = '', $directUrl = '', $classUsed = '', $cover = '', $backdrop = '' - ): void - { - if (!empty($id)) { - - $this->pdo->queryExec( + ): void { + if (! empty($id)) { + $this->pdo->queryExec( sprintf('UPDATE xxxinfo SET title = %s, tagline = %s, plot = COMPRESS(%s), genre = %s, director = %s, actors = %s, extras = %s, productinfo = %s, trailers = %s, directurl = %s, classused = %s, cover = %d, backdrop = %d, updateddate = NOW() @@ -380,197 +377,195 @@ class XXX $id ) ); - } - } + } + } - /** - * Get all genres for search-filter.tpl - * - * @param bool $activeOnly - * - * @return array|null - */ - public function getAllGenres($activeOnly = false) - { - $ret = null; + /** + * Get all genres for search-filter.tpl. + * + * @param bool $activeOnly + * + * @return array|null + */ + public function getAllGenres($activeOnly = false) + { + $ret = null; - if ($activeOnly) { - $res = $this->pdo->query('SELECT title FROM genres WHERE disabled = 0 AND type = ' . - Category::XXX_ROOT . ' ORDER BY title' + if ($activeOnly) { + $res = $this->pdo->query('SELECT title FROM genres WHERE disabled = 0 AND type = '. + Category::XXX_ROOT.' ORDER BY title' ); - } else { - $res = $this->pdo->query('SELECT title FROM genres WHERE disabled = 1 AND type = ' . - Category::XXX_ROOT . ' ORDER BY title' + } else { + $res = $this->pdo->query('SELECT title FROM genres WHERE disabled = 1 AND type = '. + Category::XXX_ROOT.' ORDER BY title' ); - } + } - foreach ($res as $arr => $value) { - $ret[] = $value['title']; - } + foreach ($res as $arr => $value) { + $ret[] = $value['title']; + } - return $ret; - } + return $ret; + } - /** - * Get Genres for activeonly and/or an ID - * - * @param bool $activeOnly - * @param null|string $gid - * - * @return array|bool - */ - public function getGenres($activeOnly = false, $gid = null) - { - if ($gid !== null) { - $gid = ' AND id = ' . $this->pdo->escapeString($gid) . ' ORDER BY title'; - } else { - $gid = ' ORDER BY title'; - } + /** + * Get Genres for activeonly and/or an ID. + * + * @param bool $activeOnly + * @param null|string $gid + * + * @return array|bool + */ + public function getGenres($activeOnly = false, $gid = null) + { + if ($gid !== null) { + $gid = ' AND id = '.$this->pdo->escapeString($gid).' ORDER BY title'; + } else { + $gid = ' ORDER BY title'; + } - if ($activeOnly) { - return $this->pdo->queryOneRow('SELECT title FROM genres WHERE disabled = 0 AND type = ' . Category::XXX_ROOT . $gid); - } + if ($activeOnly) { + return $this->pdo->queryOneRow('SELECT title FROM genres WHERE disabled = 0 AND type = '.Category::XXX_ROOT.$gid); + } - return $this->pdo->queryOneRow('SELECT title FROM genres WHERE disabled = 1 AND type = ' . Category::XXX_ROOT . $gid); - } + return $this->pdo->queryOneRow('SELECT title FROM genres WHERE disabled = 1 AND type = '.Category::XXX_ROOT.$gid); + } - /** - * Get Genre id's Of the title - * - * @param $arr - Array or String - * - * @return string - If array .. 1,2,3,4 if string .. 1 - */ - protected function getGenreID($arr): string - { - $ret = null; + /** + * Get Genre id's Of the title. + * + * @param $arr - Array or String + * + * @return string - If array .. 1,2,3,4 if string .. 1 + */ + protected function getGenreID($arr): string + { + $ret = null; - if (!is_array($arr)) { - $res = $this->pdo->queryOneRow('SELECT id FROM genres WHERE title = ' . $this->pdo->escapeString($arr)); - if ($res !== false) { - return $res['id']; - } - } + if (! is_array($arr)) { + $res = $this->pdo->queryOneRow('SELECT id FROM genres WHERE title = '.$this->pdo->escapeString($arr)); + if ($res !== false) { + return $res['id']; + } + } - foreach ($arr as $key => $value) { - $res = $this->pdo->queryOneRow('SELECT id FROM genres WHERE title = ' . $this->pdo->escapeString($value)); - if ($res !== false) { - $ret .= ',' . $res['id']; - } else { - $ret .= ',' . $this->insertGenre($value); - } - } + foreach ($arr as $key => $value) { + $res = $this->pdo->queryOneRow('SELECT id FROM genres WHERE title = '.$this->pdo->escapeString($value)); + if ($res !== false) { + $ret .= ','.$res['id']; + } else { + $ret .= ','.$this->insertGenre($value); + } + } - $ret = ltrim($ret, ','); + $ret = ltrim($ret, ','); - return $ret; - } + return $ret; + } - /** - * Inserts Genre and returns last affected row (Genre ID) - * - * @param $genre - * - * @return bool - */ - private function insertGenre($genre): bool - { - $res = ''; - if ($genre !== null) { - $res = $this->pdo->queryInsert(sprintf('INSERT INTO genres (title, type, disabled) VALUES (%s ,%d ,%d)', $this->pdo->escapeString($genre), Category::XXX_ROOT, 0)); - } + /** + * Inserts Genre and returns last affected row (Genre ID). + * + * @param $genre + * + * @return bool + */ + private function insertGenre($genre): bool + { + $res = ''; + if ($genre !== null) { + $res = $this->pdo->queryInsert(sprintf('INSERT INTO genres (title, type, disabled) VALUES (%s ,%d ,%d)', $this->pdo->escapeString($genre), Category::XXX_ROOT, 0)); + } - return $res; - } + return $res; + } - /** - * Inserts Trailer Code by Class - * - * @param $whichclass - * @param $res - * - * @return string - */ - public function insertSwf($whichclass, $res): string - { - $ret = ''; - if ($whichclass === 'ade') { - if (!empty($res)) { - $trailers = unserialize($res, 'ade'); - $ret .= "<object width='360' height='240' type='application/x-shockwave-flash' id='EmpireFlashPlayer' name='EmpireFlashPlayer' data='" . $trailers['url'] . "'>"; - $ret .= "<param name='flashvars' value= 'streamID=" . $trailers['streamid'] . "&autoPlay=false&BaseStreamingUrl=" . $trailers['baseurl'] . "'>"; - $ret .= "</object>"; + /** + * Inserts Trailer Code by Class. + * + * @param $whichclass + * @param $res + * + * @return string + */ + public function insertSwf($whichclass, $res): string + { + $ret = ''; + if ($whichclass === 'ade') { + if (! empty($res)) { + $trailers = unserialize($res, 'ade'); + $ret .= "<object width='360' height='240' type='application/x-shockwave-flash' id='EmpireFlashPlayer' name='EmpireFlashPlayer' data='".$trailers['url']."'>"; + $ret .= "<param name='flashvars' value= 'streamID=".$trailers['streamid'].'&autoPlay=false&BaseStreamingUrl='.$trailers['baseurl']."'>"; + $ret .= '</object>'; - return $ret; - } - } - if ($whichclass === 'pop') { - if (!empty($res)) { - $trailers = unserialize($res, 'pop'); - $ret .= "<embed id='trailer' width='480' height='360'"; - $ret .= "flashvars='" . $trailers['flashvars'] . "' allowfullscreen='true' allowscriptaccess='always' quality='high' name='trailer' style='undefined'"; - $ret .= "src='" . $trailers['baseurl'] . "' type='application/x-shockwave-flash'>"; + return $ret; + } + } + if ($whichclass === 'pop') { + if (! empty($res)) { + $trailers = unserialize($res, 'pop'); + $ret .= "<embed id='trailer' width='480' height='360'"; + $ret .= "flashvars='".$trailers['flashvars']."' allowfullscreen='true' allowscriptaccess='always' quality='high' name='trailer' style='undefined'"; + $ret .= "src='".$trailers['baseurl']."' type='application/x-shockwave-flash'>"; - return $ret; - } - } + return $ret; + } + } - return $ret; - } + return $ret; + } - /** - * @param $movie - * - * @return false|int|string - * @throws \Exception - */ - public function updateXXXInfo($movie) - { - $cover = $backdrop = 0; - $xxxID = -2; - $this->whichclass = 'aebn'; - $mov = new AEBN(); - $mov->cookie = $this->cookie; - ColorCLI::doEcho(ColorCLI::info('Checking AEBN for movie info')); - $res = $mov->processSite($movie); + /** + * @param $movie + * + * @return false|int|string + * @throws \Exception + */ + public function updateXXXInfo($movie) + { + $cover = $backdrop = 0; + $xxxID = -2; + $this->whichclass = 'aebn'; + $mov = new AEBN(); + $mov->cookie = $this->cookie; + ColorCLI::doEcho(ColorCLI::info('Checking AEBN for movie info')); + $res = $mov->processSite($movie); - if ($res === false) { - $this->whichclass = 'pop'; - $mov = new Popporn(); - $mov->cookie = $this->cookie; - ColorCLI::doEcho(ColorCLI::info('Checking PopPorn for movie info')); - $res = $mov->processSite($movie); - } + if ($res === false) { + $this->whichclass = 'pop'; + $mov = new Popporn(); + $mov->cookie = $this->cookie; + ColorCLI::doEcho(ColorCLI::info('Checking PopPorn for movie info')); + $res = $mov->processSite($movie); + } - if ($res === false) { - $this->whichclass = 'adm'; - $mov = new ADM(); - $mov->cookie = $this->cookie; - ColorCLI::doEcho(ColorCLI::info('Checking ADM for movie info')); - $res = $mov->processSite($movie); - } + if ($res === false) { + $this->whichclass = 'adm'; + $mov = new ADM(); + $mov->cookie = $this->cookie; + ColorCLI::doEcho(ColorCLI::info('Checking ADM for movie info')); + $res = $mov->processSite($movie); + } - if ($res === false) { - $this->whichclass = 'ade'; - $mov = new ADE(); - ColorCLI::doEcho(ColorCLI::info('Checking ADE for movie info')); - $res = $mov->processSite($movie); - } + if ($res === false) { + $this->whichclass = 'ade'; + $mov = new ADE(); + ColorCLI::doEcho(ColorCLI::info('Checking ADE for movie info')); + $res = $mov->processSite($movie); + } - if ($res === false) { - $this->whichclass = 'hotm'; - $mov = new Hotmovies(); - $mov->cookie = $this->cookie; - ColorCLI::doEcho(ColorCLI::info('Checking HotMovies for movie info')); - $res = $mov->processSite($movie); - } + if ($res === false) { + $this->whichclass = 'hotm'; + $mov = new Hotmovies(); + $mov->cookie = $this->cookie; + ColorCLI::doEcho(ColorCLI::info('Checking HotMovies for movie info')); + $res = $mov->processSite($movie); + } - - // If a result is true getAll information. - if ($res) { - if ($this->echooutput) { - - switch ($this->whichclass) { + // If a result is true getAll information. + if ($res) { + if ($this->echooutput) { + switch ($this->whichclass) { case 'aebn': $fromstr = 'Adult Entertainment Broadcast Network'; break; @@ -589,56 +584,55 @@ class XXX default: $fromstr = ''; } - ColorCLI::doEcho(ColorCLI::primary('Fetching XXX info from: ' . $fromstr)); - } - $res = $mov->getAll(); - } else { - // Nothing was found, go ahead and set to -2 - return -2; - } + ColorCLI::doEcho(ColorCLI::primary('Fetching XXX info from: '.$fromstr)); + } + $res = $mov->getAll(); + } else { + // Nothing was found, go ahead and set to -2 + return -2; + } - $res['cast'] = !empty($res['cast']) ? implode(',', $res['cast']) : ''; - $res['genres'] = !empty($res['genres']) ? $this->getGenreID($res['genres']) : ''; + $res['cast'] = ! empty($res['cast']) ? implode(',', $res['cast']) : ''; + $res['genres'] = ! empty($res['genres']) ? $this->getGenreID($res['genres']) : ''; - $mov = [ - 'trailers' => !empty($res['trailers']) ? serialize($res['trailers']) : '', - 'extras' => !empty($res['extras']) ? serialize($res['extras']) : '', - 'productinfo' => !empty($res['productinfo']) ? serialize($res['productinfo']) : '', - 'backdrop' => !empty($res['backcover']) ? $res['backcover'] : 0, - 'cover' => !empty($res['boxcover']) ? $res['boxcover'] : 0, - 'title' => !empty($res['title']) ? html_entity_decode($res['title'], ENT_QUOTES, 'UTF-8') : '', - 'plot' => !empty($res['synopsis']) ? html_entity_decode($res['synopsis'], ENT_QUOTES, 'UTF-8') : '', - 'tagline' => !empty($res['tagline']) ? html_entity_decode($res['tagline'], ENT_QUOTES, 'UTF-8') : '', - 'genre' => !empty($res['genres']) ? html_entity_decode($res['genres'], ENT_QUOTES, 'UTF-8') : '', - 'director' => !empty($res['director']) ? html_entity_decode($res['director'], ENT_QUOTES, 'UTF-8') : '', - 'actors' => !empty($res['cast']) ? html_entity_decode($res['cast'], ENT_QUOTES, 'UTF-8') : '', - 'directurl' => !empty($res['directurl']) ? html_entity_decode($res['directurl'], ENT_QUOTES, 'UTF-8') : '', - 'classused' => $this->whichclass + $mov = [ + 'trailers' => ! empty($res['trailers']) ? serialize($res['trailers']) : '', + 'extras' => ! empty($res['extras']) ? serialize($res['extras']) : '', + 'productinfo' => ! empty($res['productinfo']) ? serialize($res['productinfo']) : '', + 'backdrop' => ! empty($res['backcover']) ? $res['backcover'] : 0, + 'cover' => ! empty($res['boxcover']) ? $res['boxcover'] : 0, + 'title' => ! empty($res['title']) ? html_entity_decode($res['title'], ENT_QUOTES, 'UTF-8') : '', + 'plot' => ! empty($res['synopsis']) ? html_entity_decode($res['synopsis'], ENT_QUOTES, 'UTF-8') : '', + 'tagline' => ! empty($res['tagline']) ? html_entity_decode($res['tagline'], ENT_QUOTES, 'UTF-8') : '', + 'genre' => ! empty($res['genres']) ? html_entity_decode($res['genres'], ENT_QUOTES, 'UTF-8') : '', + 'director' => ! empty($res['director']) ? html_entity_decode($res['director'], ENT_QUOTES, 'UTF-8') : '', + 'actors' => ! empty($res['cast']) ? html_entity_decode($res['cast'], ENT_QUOTES, 'UTF-8') : '', + 'directurl' => ! empty($res['directurl']) ? html_entity_decode($res['directurl'], ENT_QUOTES, 'UTF-8') : '', + 'classused' => $this->whichclass, ]; - $check = $this->pdo->queryOneRow(sprintf('SELECT id FROM xxxinfo WHERE title = %s', $this->pdo->escapeString($mov['title']))); + $check = $this->pdo->queryOneRow(sprintf('SELECT id FROM xxxinfo WHERE title = %s', $this->pdo->escapeString($mov['title']))); - if ($check !== false && $check['id'] > 0) { + if ($check !== false && $check['id'] > 0) { + $xxxID = $check['id']; - $xxxID = $check['id']; + // Update BoxCover. + if (! empty($mov['cover'])) { + $cover = $this->releaseImage->saveImage($xxxID.'-cover', $mov['cover'], $this->imgSavePath); + } - // Update BoxCover. - if (!empty($mov['cover'])) { - $cover = $this->releaseImage->saveImage($xxxID . '-cover', $mov['cover'], $this->imgSavePath); - } + // BackCover. + if (! empty($mov['backdrop'])) { + $backdrop = $this->releaseImage->saveImage($xxxID.'-backdrop', $mov['backdrop'], $this->imgSavePath, 1920, 1024); + } - // BackCover. - if (!empty($mov['backdrop'])) { - $backdrop = $this->releaseImage->saveImage($xxxID . '-backdrop', $mov['backdrop'], $this->imgSavePath, 1920, 1024); - } + // Update Current XXX Information + $this->update($check['id'], $mov['title'], $mov['tagline'], $mov['plot'], $mov['genre'], $mov['director'], $mov['actors'], $mov['extras'], $mov['productinfo'], $mov['trailers'], $mov['directurl'], $mov['classused'], $cover, $backdrop); + } - // Update Current XXX Information - $this->update($check['id'], $mov['title'], $mov['tagline'], $mov['plot'], $mov['genre'], $mov['director'], $mov['actors'], $mov['extras'], $mov['productinfo'], $mov['trailers'], $mov['directurl'], $mov['classused'], $cover, $backdrop); - } - - // Insert New XXX Information - if ($check === false) { - $xxxID = $this->pdo->queryInsert( + // Insert New XXX Information + if ($check === false) { + $xxxID = $this->pdo->queryInsert( sprintf(' INSERT INTO xxxinfo (title, tagline, plot, genre, director, actors, extras, productinfo, trailers, directurl, classused, createddate, updateddate) @@ -657,36 +651,36 @@ class XXX $this->pdo->escapeString($mov['classused']) ) ); - // Update BoxCover. - if (!empty($mov['cover'])) { - $cover = $this->releaseImage->saveImage($xxxID . '-cover', $mov['cover'], $this->imgSavePath); - } + // Update BoxCover. + if (! empty($mov['cover'])) { + $cover = $this->releaseImage->saveImage($xxxID.'-cover', $mov['cover'], $this->imgSavePath); + } - // BackCover. - if (!empty($mov['backdrop'])) { - $backdrop = $this->releaseImage->saveImage($xxxID . '-backdrop', $mov['backdrop'], $this->imgSavePath, 1920, 1024); - } + // BackCover. + if (! empty($mov['backdrop'])) { + $backdrop = $this->releaseImage->saveImage($xxxID.'-backdrop', $mov['backdrop'], $this->imgSavePath, 1920, 1024); + } - $this->pdo->queryExec(sprintf('UPDATE xxxinfo SET cover = %d, backdrop = %d WHERE id = %d', $cover, $backdrop, $xxxID)); - } + $this->pdo->queryExec(sprintf('UPDATE xxxinfo SET cover = %d, backdrop = %d WHERE id = %d', $cover, $backdrop, $xxxID)); + } - if ($this->echooutput) { - ColorCLI::doEcho( - ColorCLI::headerOver(($xxxID !== false ? 'Added/updated XXX movie: ' . ColorCLI::primary($mov['title']) : 'Nothing to update for XXX movie: ' . ColorCLI::primary($mov['title']))) + if ($this->echooutput) { + ColorCLI::doEcho( + ColorCLI::headerOver(($xxxID !== false ? 'Added/updated XXX movie: '.ColorCLI::primary($mov['title']) : 'Nothing to update for XXX movie: '.ColorCLI::primary($mov['title']))) ); - } + } - return $xxxID; - } + return $xxxID; + } - /** - * Process XXX releases where xxxinfo is 0 - * - * @throws \Exception - */ - public function processXXXReleases(): void - { - $res = $this->pdo->query(sprintf(' + /** + * Process XXX releases where xxxinfo is 0. + * + * @throws \Exception + */ + public function processXXXReleases(): void + { + $res = $this->pdo->query(sprintf(' SELECT r.searchname, r.id FROM releases r WHERE r.nzbstatus = 1 @@ -697,97 +691,95 @@ class XXX $this->movieqty ) ); - $movieCount = count($res); + $movieCount = count($res); - if ($movieCount > 0) { + if ($movieCount > 0) { + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::header('Processing '.$movieCount.' XXX releases.')); + } - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::header('Processing ' . $movieCount . ' XXX releases.')); - } + // Loop over releases. + foreach ($res as $arr) { + $idcheck = -2; - // Loop over releases. - foreach ($res as $arr) { + // Try to get a name. + if ($this->parseXXXSearchName($arr['searchname']) !== false) { + $check = $this->checkXXXInfoExists($this->currentTitle); + if ($check === false) { + $this->currentRelID = $arr['id']; + if ($this->debug && $this->echooutput) { + ColorCLI::doEcho('DB name: '.$arr['searchname'], true); + } + if ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::primaryOver('Looking up: ').ColorCLI::headerOver($this->currentTitle), true); + } - $idcheck = -2; + ColorCLI::doEcho(ColorCLI::info('Local match not found, checking web!'), true); + $idcheck = $this->updateXXXInfo($this->currentTitle); + } else { + ColorCLI::doEcho(ColorCLI::info('Local match found for XXX Movie: '.ColorCLI::headerOver($this->currentTitle)), true); + $idcheck = (int) $check['id']; + } + } else { + ColorCLI::doEcho('.', true); + } + $this->pdo->queryExec(sprintf('UPDATE releases SET xxxinfo_id = %d WHERE id = %d %s', $idcheck, $arr['id'], $this->catWhere)); + } + } elseif ($this->echooutput) { + ColorCLI::doEcho(ColorCLI::header('No xxx releases to process.')); + } + } - // Try to get a name. - if ($this->parseXXXSearchName($arr['searchname']) !== false) { - $check = $this->checkXXXInfoExists($this->currentTitle); - if ($check === false) { - $this->currentRelID = $arr['id']; - if ($this->debug && $this->echooutput) { - ColorCLI::doEcho('DB name: ' . $arr['searchname'], true); - } - if ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::primaryOver('Looking up: ') . ColorCLI::headerOver($this ->currentTitle), true); - } + /** + * Checks xxxinfo to make sure releases exist. + * + * @param $releaseName + * + * @return array|bool + */ + protected function checkXXXInfoExists($releaseName) + { + return $this->pdo->queryOneRow(sprintf('SELECT id, title FROM xxxinfo WHERE title %s', $this->pdo->likeString($releaseName, false, true))); + } - ColorCLI::doEcho(ColorCLI::info('Local match not found, checking web!'), true); - $idcheck = $this->updateXXXInfo($this->currentTitle); - } else { - ColorCLI::doEcho(ColorCLI::info('Local match found for XXX Movie: ' . ColorCLI::headerOver($this->currentTitle)), true); - $idcheck = (int)$check['id']; - } - } else { - ColorCLI::doEcho('.', true); - } - $this->pdo->queryExec(sprintf('UPDATE releases SET xxxinfo_id = %d WHERE id = %d %s', $idcheck, $arr['id'], $this->catWhere)); - } - } elseif ($this->echooutput) { - ColorCLI::doEcho(ColorCLI::header('No xxx releases to process.')); - } - } + /** + * Cleans up a searchname to make it easier to scrape. + * + * @param string $releaseName + * + * @return bool + */ + protected function parseXXXSearchName($releaseName): bool + { + $name = ''; + $followingList = '[^\w]((2160|1080|480|720)(p|i)|AC3D|Directors([^\w]CUT)?|DD5\.1|(DVD|BD|BR)(Rip)?|BluRay|divx|HDTV|iNTERNAL|LiMiTED|(Real\.)?Proper|RE(pack|Rip)|Sub\.?(fix|pack)|Unrated|WEB-DL|(x|H)[-._ ]?264|xvid|[Dd][Ii][Ss][Cc](\d+|\s*\d+|\.\d+)|XXX|BTS|DirFix|Trailer|WEBRiP|NFO|(19|20)\d\d)[^\w]'; - /** - * Checks xxxinfo to make sure releases exist - * - * @param $releaseName - * - * @return array|bool - */ - protected function checkXXXInfoExists($releaseName) - { - return $this->pdo->queryOneRow(sprintf('SELECT id, title FROM xxxinfo WHERE title %s', $this->pdo->likeString($releaseName, false, true))); - } + if (preg_match('/([^\w]{2,})?(?P<name>[\w .-]+?)'.$followingList.'/i', $releaseName, $matches)) { + $name = $matches['name']; + } - /** - * Cleans up a searchname to make it easier to scrape. - * - * @param string $releaseName - * - * @return bool - */ - protected function parseXXXSearchName($releaseName): bool - { - $name = ''; - $followingList = '[^\w]((2160|1080|480|720)(p|i)|AC3D|Directors([^\w]CUT)?|DD5\.1|(DVD|BD|BR)(Rip)?|BluRay|divx|HDTV|iNTERNAL|LiMiTED|(Real\.)?Proper|RE(pack|Rip)|Sub\.?(fix|pack)|Unrated|WEB-DL|(x|H)[-._ ]?264|xvid|[Dd][Ii][Ss][Cc](\d+|\s*\d+|\.\d+)|XXX|BTS|DirFix|Trailer|WEBRiP|NFO|(19|20)\d\d)[^\w]'; - - if (preg_match('/([^\w]{2,})?(?P<name>[\w .-]+?)' . $followingList . '/i', $releaseName, $matches)) { - $name = $matches['name']; - } - - // Check if we got something. - if ($name !== '') { + // Check if we got something. + if ($name !== '') { // If we still have any of the words in $followingList, remove them. - $name = preg_replace('/' . $followingList . '/i', ' ', $name); - // Remove periods, underscored, anything between parenthesis. - $name = preg_replace('/\(.*?\)|[-._]/i', ' ', $name); - // Finally remove multiple spaces and trim leading spaces. - $name = trim(preg_replace('/\s{2,}/', ' ', $name)); - // Remove Private Movies {d} from name better matching. - $name = trim(preg_replace('/^Private\s(Specials|Blockbusters|Blockbuster|Sports|Gold|Lesbian|Movies|Classics|Castings|Fetish|Stars|Pictures|XXX|Private|Black\sLabel|Black)\s\d+/i', '', $name)); - // Remove Foreign Words at the end of the name. - $name = trim(preg_replace('/(brazilian|chinese|croatian|danish|deutsch|dutch|estonian|flemish|finnish|french|german|greek|hebrew|icelandic|italian|latin|nordic|norwegian|polish|portuguese|japenese|japanese|russian|serbian|slovenian|spanish|spanisch|swedish|thai|turkish)$/i', '', $name)); + $name = preg_replace('/'.$followingList.'/i', ' ', $name); + // Remove periods, underscored, anything between parenthesis. + $name = preg_replace('/\(.*?\)|[-._]/i', ' ', $name); + // Finally remove multiple spaces and trim leading spaces. + $name = trim(preg_replace('/\s{2,}/', ' ', $name)); + // Remove Private Movies {d} from name better matching. + $name = trim(preg_replace('/^Private\s(Specials|Blockbusters|Blockbuster|Sports|Gold|Lesbian|Movies|Classics|Castings|Fetish|Stars|Pictures|XXX|Private|Black\sLabel|Black)\s\d+/i', '', $name)); + // Remove Foreign Words at the end of the name. + $name = trim(preg_replace('/(brazilian|chinese|croatian|danish|deutsch|dutch|estonian|flemish|finnish|french|german|greek|hebrew|icelandic|italian|latin|nordic|norwegian|polish|portuguese|japenese|japanese|russian|serbian|slovenian|spanish|spanisch|swedish|thai|turkish)$/i', '', $name)); - // Check if the name is long enough and not just numbers and not file (d) of (d) and does not contain Episodes and any dated 00.00.00 which are site rips.. - if (strlen($name) > 5 && !preg_match('/^\d+$/', $name) && !preg_match('/( File \d+ of \d+|\d+.\d+.\d+)/', $name) && !preg_match('/(E\d+)/', $name) && !preg_match('/\d\d\.\d\d.\d\d/', $name)) { - $this->currentTitle = $name; + // Check if the name is long enough and not just numbers and not file (d) of (d) and does not contain Episodes and any dated 00.00.00 which are site rips.. + if (strlen($name) > 5 && ! preg_match('/^\d+$/', $name) && ! preg_match('/( File \d+ of \d+|\d+.\d+.\d+)/', $name) && ! preg_match('/(E\d+)/', $name) && ! preg_match('/\d\d\.\d\d.\d\d/', $name)) { + $this->currentTitle = $name; - return true; - } - } + return true; + } + } - return false; - } + return false; + } } diff --git a/nntmux/bootstrap.php b/nntmux/bootstrap.php index f87b14ce5..a0e672d45 100755 --- a/nntmux/bootstrap.php +++ b/nntmux/bootstrap.php @@ -18,17 +18,13 @@ * @author niel * @copyright 2016 nZEDb */ -require_once NN_ROOT . 'vendor/autoload.php'; +require_once NN_ROOT.'vendor/autoload.php'; -use nntmux\config\Configure; use nntmux\utility\Utility; +use nntmux\config\Configure; - -if (!defined('HAS_WHICH')) { - define('HAS_WHICH', Utility::hasWhich() ? true : false); +if (! defined('HAS_WHICH')) { + define('HAS_WHICH', Utility::hasWhich() ? true : false); } - new Configure('indexer'); - -?> diff --git a/nntmux/build/ComposerScripts.php b/nntmux/build/ComposerScripts.php index 50578f2a0..dc61b7795 100644 --- a/nntmux/build/ComposerScripts.php +++ b/nntmux/build/ComposerScripts.php @@ -10,12 +10,13 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link <http://www.gnu.org/licenses/>. * @author niel * @copyright 2017 nZEDb */ + namespace nntmux\build; use Composer\Script\Event; @@ -23,59 +24,57 @@ use Illuminate\Foundation\Application; class ComposerScripts { - public static function postInstallCmd() - { - $last = $output = $return = null; - if ((int)getenv('COMPOSER_DEV_MODE') === 1) { - echo 'Updating git hooks... '; - $last = exec('build/git-hooks/addHooks.sh', $output, $return); - if ($return > 0) { - echo PHP_EOL; - exit($last); - } - echo 'done' . PHP_EOL; - } - } + public static function postInstallCmd() + { + $last = $output = $return = null; + if ((int) getenv('COMPOSER_DEV_MODE') === 1) { + echo 'Updating git hooks... '; + $last = exec('build/git-hooks/addHooks.sh', $output, $return); + if ($return > 0) { + echo PHP_EOL; + exit($last); + } + echo 'done'.PHP_EOL; + } + } - /** - * Handle the post-install Composer event. - * - * @param \Composer\Script\Event $event - * @return void - */ - public static function postInstall(Event $event) - { - require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php'; + /** + * Handle the post-install Composer event. + * + * @param \Composer\Script\Event $event + * @return void + */ + public static function postInstall(Event $event) + { + require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php'; - static::clearCompiled(); - } + static::clearCompiled(); + } - /** - * Handle the post-update Composer event. - * - * @param \Composer\Script\Event $event - * @return void - */ - public static function postUpdate(Event $event) - { - require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php'; + /** + * Handle the post-update Composer event. + * + * @param \Composer\Script\Event $event + * @return void + */ + public static function postUpdate(Event $event) + { + require_once $event->getComposer()->getConfig()->get('vendor-dir').'/autoload.php'; - static::clearCompiled(); - } + static::clearCompiled(); + } - /** - * Clear the cached Laravel bootstrapping files. - * - * @return void - */ - protected static function clearCompiled() - { - $nntmux = new Application(getcwd()); + /** + * Clear the cached Laravel bootstrapping files. + * + * @return void + */ + protected static function clearCompiled() + { + $nntmux = new Application(getcwd()); - if (file_exists($servicesPath = $nntmux->getCachedServicesPath())) { - @unlink($servicesPath); - } - } + if (file_exists($servicesPath = $nntmux->getCachedServicesPath())) { + @unlink($servicesPath); + } + } } - -?> diff --git a/nntmux/config/Configure.php b/nntmux/config/Configure.php index 6decf7509..d7eddae36 100755 --- a/nntmux/config/Configure.php +++ b/nntmux/config/Configure.php @@ -18,140 +18,138 @@ * @author niel * @copyright 2015 NN */ + namespace nntmux\config; class Configure { - private static $environments = [ + private static $environments = [ 'indexer' => [ '.env' => true, - 'settings' => false + 'settings' => false, ], 'install' => [ '.env' => true, - 'settings' => false + 'settings' => false, ], 'smarty' => [ '.env' => true, - 'settings' => false + 'settings' => false, ], ]; - /** - * Configure constructor. - * - * @param string $environment - */ - public function __construct($environment = 'indexer') - { - try { - $this->loadEnvironment($environment); - } catch (\RuntimeException $e) { - echo $e->getMessage(); - } - } + /** + * Configure constructor. + * + * @param string $environment + */ + public function __construct($environment = 'indexer') + { + try { + $this->loadEnvironment($environment); + } catch (\RuntimeException $e) { + echo $e->getMessage(); + } + } - /** - * @param $environment - * @throws \RuntimeException - */ - private function loadEnvironment($environment) - { - if (array_key_exists($environment, Configure::$environments)) { - foreach (Configure::$environments[$environment] as $config => $throwException) { - $this->loadSettings($config, $throwException); - } - } else { - throw new \RuntimeException('Unknown environment passed to Configure class!'); - } - } + /** + * @param $environment + * @throws \RuntimeException + */ + private function loadEnvironment($environment) + { + if (array_key_exists($environment, self::$environments)) { + foreach (self::$environments[$environment] as $config => $throwException) { + $this->loadSettings($config, $throwException); + } + } else { + throw new \RuntimeException('Unknown environment passed to Configure class!'); + } + } - /** - * @param $filename - * @param bool $throwException - * @throws \RuntimeException - */ - public function loadSettings($filename, $throwException = true) - { - - if ($filename === '.env') { - $file = NN_ROOT . '.env'; - } else { - $file = NN_CONFIGS . $filename . '.php'; - } - if (!file_exists($file) && $throwException) { - $errorCode = (int)($filename === '.env'); - throw new \RuntimeException( + /** + * @param $filename + * @param bool $throwException + * @throws \RuntimeException + */ + public function loadSettings($filename, $throwException = true) + { + if ($filename === '.env') { + $file = NN_ROOT.'.env'; + } else { + $file = NN_CONFIGS.$filename.'.php'; + } + if (! file_exists($file) && $throwException) { + $errorCode = (int) ($filename === '.env'); + throw new \RuntimeException( "Unable to load configuration file '$file'. Make sure it has been created and contains correct settings.", $errorCode ); - } - if ($file !== NN_ROOT . '.env' && file_exists($file)) { - require_once $file; - } + } + if ($file !== NN_ROOT.'.env' && file_exists($file)) { + require_once $file; + } - - switch ($filename) { + switch ($filename) { case '.env': $this->defaultSSL(); break; case 'settings': - $settings_file = NN_CONFIGS . 'settings.php'; + $settings_file = NN_CONFIGS.'settings.php'; if (is_file($settings_file)) { - require_once $settings_file; - if (PHP_SAPI === 'cli') { - $current_settings_file_version = 4; // Update this when updating settings.example.php - if (!defined('NN_SETTINGS_FILE_VERSION') || + require_once $settings_file; + if (PHP_SAPI === 'cli') { + $current_settings_file_version = 4; // Update this when updating settings.example.php + if (! defined('NN_SETTINGS_FILE_VERSION') || NN_SETTINGS_FILE_VERSION != $current_settings_file_version ) { - echo("\033[0;31mNotice: Your $settings_file file is either out of date or you have not updated" . - " NN_SETTINGS_FILE_VERSION to $current_settings_file_version in that file.\033[0m" . - PHP_EOL - ); - } - unset($current_settings_file_version); - } - } else if (!defined('ITEMS_PER_PAGE')) { - define('ITEMS_PER_PAGE', '50'); - define('ITEMS_PER_COVER_PAGE', '20'); - define('NN_ECHOCLI', true); - define('NN_DEBUG', false); - define('NN_LOGGING', false); - define('NN_LOGINFO', false); - define('NN_LOGNOTICE', false); - define('NN_LOGWARNING', false); - 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'); + echo "\033[0;31mNotice: Your $settings_file file is either out of date or you have not updated". + " NN_SETTINGS_FILE_VERSION to $current_settings_file_version in that file.\033[0m". + PHP_EOL; + } + unset($current_settings_file_version); + } + } elseif (! defined('ITEMS_PER_PAGE')) { + define('ITEMS_PER_PAGE', '50'); + define('ITEMS_PER_COVER_PAGE', '20'); + define('NN_ECHOCLI', true); + define('NN_DEBUG', false); + define('NN_LOGGING', false); + define('NN_LOGINFO', false); + define('NN_LOGNOTICE', false); + define('NN_LOGWARNING', false); + 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'); } unset($settings_file); break; } - } + } - private function defaultSSL() - { - // Check if they updated config.php for the openssl changes. Only check 1 to save speed. - if (!defined('NN_SSL_VERIFY_PEER')) { - define('NN_SSL_CAFILE', ''); - define('NN_SSL_CAPATH', ''); - define('NN_SSL_VERIFY_PEER', '0'); - define('NN_SSL_VERIFY_HOST', '0'); - define('NN_SSL_ALLOW_SELF_SIGNED', '1'); - } - } + private function defaultSSL() + { + // Check if they updated config.php for the openssl changes. Only check 1 to save speed. + if (! defined('NN_SSL_VERIFY_PEER')) { + define('NN_SSL_CAFILE', ''); + define('NN_SSL_CAPATH', ''); + define('NN_SSL_VERIFY_PEER', '0'); + define('NN_SSL_VERIFY_HOST', '0'); + define('NN_SSL_ALLOW_SELF_SIGNED', '1'); + } + } } diff --git a/nntmux/config/ircscraper_settings_example.php b/nntmux/config/ircscraper_settings_example.php index 9a6664d4a..94cae853f 100755 --- a/nntmux/config/ircscraper_settings_example.php +++ b/nntmux/config/ircscraper_settings_example.php @@ -71,12 +71,12 @@ define('SCRAPE_IRC_TITLE_IGNORE', ''); **********************************************************************************************************************/ define('SCRAPE_IRC_CHANNELS', serialize( - array( + [ //'#Channel' => 'Password', '#PreNNTmux' => null, '#nZEDbPRE' => null, - '#nZEDbPRE2' => null - ) + '#nZEDbPRE2' => null, + ] ) ); @@ -106,7 +106,7 @@ define('SCRAPE_IRC_SOURCE_IGNORE', '#pre@corrupt' => false, '#scnzb' => false, '#tvnzb' => false, - 'srrdb' => false + 'srrdb' => false, ] ) ); diff --git a/nntmux/config/openssl.example.php b/nntmux/config/openssl.example.php index faeb2d22c..d2e2e4f1b 100755 --- a/nntmux/config/openssl.example.php +++ b/nntmux/config/openssl.example.php @@ -18,11 +18,8 @@ * @author niel * @copyright 2015 NN */ - define('NN_SSL_ALLOW_SELF_SIGNED', '1'); define('NN_SSL_CAFILE', ''); define('NN_SSL_CAPATH', ''); define('NN_SSL_VERIFY_HOST', '0'); define('NN_SSL_VERIFY_PEER', '0'); - -?> diff --git a/nntmux/config/settings.example.php b/nntmux/config/settings.example.php index f98ff1e5d..001b84f7d 100755 --- a/nntmux/config/settings.example.php +++ b/nntmux/config/settings.example.php @@ -1,4 +1,5 @@ <?php + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////// Copy this file to settings.php and edit the options. ////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -11,7 +12,7 @@ use nntmux\utility\Utility; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////// MISC ////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/** +/* * When we update settings.example.php, we will raise this version, you will get a message saying your settings.php * is out of date, you will need to update it and change the version number. * @@ -24,21 +25,21 @@ define('NN_SETTINGS_FILE_VERSION', 4); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// Web Settings ////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/** +/* * How many releases to show per page in list view. * * @default '50' */ define('ITEMS_PER_PAGE', '50'); -/** +/* * How many releases to show per page in cover view. * * @default '20' */ define('ITEMS_PER_COVER_PAGE', '20'); -/** +/* * How many releases maximum to display in total on browse/search/etc. * If you have ITEMS_PER_PAGE set to 50, and NN_MAX_PAGER_RESULTS set to 125000, you would get a maximum of * 2,500 pages of results in searches/browse. @@ -50,14 +51,14 @@ define('ITEMS_PER_COVER_PAGE', '20'); */ define('NN_MAX_PAGER_RESULTS', '125000'); -/** +/* * If the PRE API page (preinfo) is open to the public or only accessible by registered / api users. * * @default false */ define('NN_PREINFO_OPEN', false); -/** +/* * Whether to check if a person is trying to send too many requests in a given amount of time, * lock out the person of the site for a amount of time. * @@ -65,14 +66,14 @@ define('NN_PREINFO_OPEN', false); */ define('NN_FLOOD_CHECK', false); -/** +/* * How many seconds should the person be locked out of the site. * * @default 5 */ define('NN_FLOOD_WAIT_TIME', 5); -/** +/* * How many requests in a second can a person send to the site max before being locked out for * NN_FLOOD_WAIT_TIME seconds. * @@ -80,7 +81,7 @@ define('NN_FLOOD_WAIT_TIME', 5); */ define('NN_FLOOD_MAX_REQUESTS_PER_SECOND', 5); -/** +/* * The higher this number, the more secure the password algorithm for the website will be, at the cost * of server resources. * To find a good number for your server, run the misc/testing/Various/find_password_hash_cost.php script. @@ -90,7 +91,7 @@ define('NN_FLOOD_MAX_REQUESTS_PER_SECOND', 5); */ define('NN_PASSWORD_HASH_COST', 11); -/** +/* * The type of search system to use on the site. * * 0 = The default system, which uses fulltext indexing (very fast but search results can be unexpected). @@ -105,7 +106,7 @@ define('NN_RELEASE_SEARCH_TYPE', 0); /////////////////////////////////////////////// Sphinx Settings //////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/** +/* * This is the hostname to use when connecting to the SphinxQL server, * * @note Using localhost / 127.0.0.1 has caused me issues and only 0 worked on my local server. @@ -114,14 +115,14 @@ define('NN_RELEASE_SEARCH_TYPE', 0); */ define('NN_SPHINXQL_HOST_NAME', '0'); -/** +/* * This is the port to the SphinxQL server. * * @default 9306 */ define('NN_SPHINXQL_PORT', 9306); -/** +/* * This is the (optional) location to the SphinxQL server socket file, if you set the "listen" setting to a sock file. * * @default '' @@ -131,21 +132,21 @@ define('NN_SPHINXQL_SOCK_FILE', ''); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// CLI Settings ////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/** +/* * Display text to console(terminal) output. * * @default true */ define('NN_ECHOCLI', true); -/** +/* * Rename releases using PAR2 files (if they match on PRE titles)? * * @default true */ define('NN_RENAME_PAR2', true); -/** +/* * Rename music releases using media info from the MP3/FLAC/etc tags (names are created using info found in the tags)? * * @default true @@ -155,7 +156,7 @@ define('NN_RENAME_MUSIC_MEDIAINFO', true); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////// Cache Settings ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/** +/* * Type of cache server(s) to use: * 0 - disabled ; No cache server(s) will be used. * 1 - memcached ; Memcached server(s) will be used for caching. @@ -172,7 +173,7 @@ define('NN_RENAME_MUSIC_MEDIAINFO', true); */ define('NN_CACHE_TYPE', 0); -/** +/* * List of redis or memcached servers to connect to. Separate them by comma. * Host: (string) Address for the cache server. '127.0.0.1' for a local server. * Port: (integer) Default for memcached is 11211, Default for redis is 6379 @@ -186,12 +187,12 @@ define('NN_CACHE_HOSTS', serialize( 'Server1' => [ 'host' => '127.0.0.1', 'port' => 11211, - 'weight' => 0 + 'weight' => 0, ], ] )); -/** +/* * Optional path to unix socket file, leave '' if to not use. * If using a unix socket file, the server list is overridden. * This should be faster than using the host/port if your cache server is local. @@ -203,14 +204,14 @@ define('NN_CACHE_HOSTS', serialize( */ define('NN_CACHE_SOCKET_FILE', ''); -/** +/* * Timeout for connecting to cache server(s). * * @default 10 */ define('NN_CACHE_TIMEOUT', 10); -/** +/* * Memcached allows to compress the data, saving RAM at the expense of CPU time. * * @note Does nothing on redis. @@ -218,7 +219,7 @@ define('NN_CACHE_TIMEOUT', 10); */ define('NN_CACHE_COMPRESSION', false); -/** +/* * Serialization is a way of converting data in PHP into strings of text which can be stored on the cache server. * * 0 - Use the PHP serializer. Recommended for most people. @@ -236,7 +237,7 @@ define('NN_CACHE_COMPRESSION', false); */ define('NN_CACHE_SERIALIZER', 0); -/** +/* * Amount of time in seconds to expire data from the cache server. * The developers of NN decide what should be set as short/medium/long, depending on the type of data. * @@ -249,21 +250,21 @@ define('NN_CACHE_EXPIRY_LONG', 900); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// Log Settings ////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/** +/* * Display debug messages on console or web page. * * @default false */ define('NN_DEBUG', false); -/** +/* * Log debug messages to newznab/resources/debug.log * * @default false */ define('NN_LOGGING', false); -/** +/* * var_dump missing autoloader files. * * @note Dev setting. @@ -271,21 +272,21 @@ define('NN_LOGGING', false); */ define('NN_LOGAUTOLOADER', false); -/** +/* * How many log files to keep in the log folder. * * @default 20 */ define('NN_LOGGING_MAX_LOGS', 20); -/** +/* * How large can the log files be in MegaBytes before we create a new one? The old files are compressed. * * @default 30 */ define('NN_LOGGING_MAX_SIZE', 30); -/** +/* * The folder to put the log files in. Put quotes, example : '/var/log/NN/' * The default is in the NN root folder /resources/logs/ * @@ -294,7 +295,7 @@ define('NN_LOGGING_MAX_SIZE', 30); */ define('NN_LOGGING_LOG_FOLDER', NN_LOGS); -/** +/* * The name of the log file. * Must be alphanumeric (a-z 0-9) and contain no file extensions. * @@ -302,28 +303,28 @@ define('NN_LOGGING_LOG_FOLDER', NN_LOGS); */ define('NN_LOGGING_LOG_NAME', 'nntmux'); -/** +/* * Display memory usage in log file and debug message output? * * @default true */ define('NN_LOGGING_LOG_MEMORY_USAGE', true); -/** +/* * Display CPU load in log file and debug message output? * * @default true */ define('NN_LOGGING_LOG_CPU_LOAD', true); -/** +/* * Display running time in log file and debug message output? * * @default true */ define('NN_LOGGING_LOG_RUNNING_TIME', true); -/** +/* * Display resource usage in log file and debug message output? * * @default false @@ -334,42 +335,42 @@ define('NN_LOGGING_LOG_RESOURCE_USAGE', false); * The following options require either NN_DEBUG OR NN_LOGGING to be true: * *********************************************************************************/ -/** +/* * Log and/or echo debug Info messages. * * @default false */ define('NN_LOGINFO', false); -/** +/* * Log and/or echo debug Notice messages. * * @default false */ define('NN_LOGNOTICE', false); -/** +/* * Log and/or echo debug Warning messages. * * @default false */ define('NN_LOGWARNING', false); -/** +/* * Log and/or echo debug Error messages. * * @default false */ define('NN_LOGERROR', false); -/** +/* * Log and/or echo debug Fatal messages. * * @default false */ define('NN_LOGFATAL', false); -/** +/* * Log and/or echo debug failed SQL queries. * * @default false @@ -379,7 +380,7 @@ define('NN_LOGQUERIES', false); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// SQL Settings ////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/** +/* * Strip white space (space, carriage return, new line, tab, etc) from queries before sending to MySQL. * This is useful if you use the MySQL slow query log. * @@ -388,7 +389,7 @@ define('NN_LOGQUERIES', false); */ define('NN_QUERY_STRIP_WHITESPACE', false); -/** +/* * Use transactions when doing certain SQL jobs. * This has advantages and disadvantages. * If there's a problem during a transaction, MySQL can revert the row inserts which is beneficial. @@ -399,7 +400,7 @@ define('NN_QUERY_STRIP_WHITESPACE', false); */ define('NN_USE_SQL_TRANSACTIONS', true); -/** +/* * Allows the use of LOW_PRIORITY in certain DELETE queries. * This prevents table locks by deleting only when no SELECT queries are active on the table. * This works on MyISAM/ARIA, not INNODB. @@ -411,7 +412,7 @@ define('NN_USE_SQL_TRANSACTIONS', true); */ define('NN_SQL_DELETE_LOW_PRIORITY', false); -/** +/* * Allows the use QUICK in certain DELETE queries. * This makes DELETE queries faster on MyISAM/ARIA tables by not merging index leaves. * Only supported on MyISAM/ARIA @@ -426,13 +427,13 @@ define('NN_SQL_DELETE_QUICK', false); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////// PHPMailer Settings ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/** +/* * Simple constant to let us know this file is included and we should use PHPMailer library. * Uncomment the line below after setting the other constants. */ define('PHPMAILER_ENABLED', false); -/** +/* * Global "From" Address. * This address will be set as the From: address on every email sent by NN. * @@ -442,7 +443,7 @@ define('PHPMAILER_ENABLED', false); */ define('PHPMAILER_FROM_EMAIL', ''); -/** +/* * Global "From" Name. * Along with the email above, this will display as the name. * @@ -452,7 +453,7 @@ define('PHPMAILER_FROM_EMAIL', ''); */ define('PHPMAILER_FROM_NAME', ''); -/** +/* * Global "Reply-to" Address. * This address will be set as the Reply-to: address on every email sent by NN. * @@ -462,7 +463,7 @@ define('PHPMAILER_FROM_NAME', ''); */ define('PHPMAILER_REPLYTO', ''); -/** +/* * Always BCC. * This email address will be blind carbon copied on every email sent from this site. * @@ -471,7 +472,7 @@ define('PHPMAILER_REPLYTO', ''); */ define('PHPMAILER_BCC', ''); -/** +/* * Should we use a SMTP server to send mail? * If false, it will use your default settings from php.ini. * @@ -484,7 +485,7 @@ define('PHPMAILER_USE_SMTP', false); * The following options require PHPMAILER_USE_SMTP to be true: * *********************************************************************************/ -/** +/* * This is the hostname to use if connecting to a SMTP server. * * @note You can specify main and backup hosts, delimit with a semicolon. (i.e. 'main.host.com;backup.host.com') @@ -492,7 +493,7 @@ define('PHPMAILER_USE_SMTP', false); */ define('PHPMAILER_SMTP_HOST', ''); -/** +/* * TLS & SSL Support for your SMTP server. * * @note Possible values: false, 'tls', 'ssl' @@ -500,7 +501,7 @@ define('PHPMAILER_SMTP_HOST', ''); */ define('PHPMAILER_SMTP_SECURE', 'tls'); -/** +/* * SMTP Port * * @note Usually this is 25, 465, or 587 @@ -508,7 +509,7 @@ define('PHPMAILER_SMTP_SECURE', 'tls'); */ define('PHPMAILER_SMTP_PORT', 587); -/** +/* * Does your SMTP host require authentication? * * @note Be sure to set credentials below if changing to true. @@ -520,14 +521,14 @@ define('PHPMAILER_SMTP_AUTH', false); * The following options require both PHPMAILER_USE_SMTP & PHPMAILER_SMTP_AUTH to be true: * *********************************************************************************/ -/** +/* * SMTP username for authentication. * * @default '' */ define('PHPMAILER_SMTP_USER', ''); -/** +/* * SMTP password for authentication. * * @default '' @@ -539,173 +540,173 @@ define('PHPMAILER_SMTP_PASSWORD', ''); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (Utility::isCLI()) { - /** + /* * Your server's local timezone. * @note Uncomment to enable. * @see https://secure.php.net/manual/en/timezones.php * @version 4 */ - //ini_set('date.timezone', 'America/New_York'); + //ini_set('date.timezone', 'America/New_York'); - /** - * Maximum amount of memory a PHP script can consume before being terminated. - * @note Uncomment to enable. - * @default '1024M' - * @version 4 - */ - //ini_set('memory_limit', '1024M'); + /* + * Maximum amount of memory a PHP script can consume before being terminated. + * @note Uncomment to enable. + * @default '1024M' + * @version 4 + */ + //ini_set('memory_limit', '1024M'); - /** - * Show PHP errors on CLI output. - * @note Set to '1' for development. - * @default '0' - * @version 4 - */ - ini_set('display_errors', '0'); + /* + * Show PHP errors on CLI output. + * @note Set to '1' for development. + * @default '0' + * @version 4 + */ + ini_set('display_errors', '0'); - /** - * Show startup errors on CLI output. - * @note Set to '1' for development/debugging. - * @default '0' - * @version 4 - */ - ini_set('display_startup_errors', '0'); + /* + * Show startup errors on CLI output. + * @note Set to '1' for development/debugging. + * @default '0' + * @version 4 + */ + ini_set('display_startup_errors', '0'); - /** - * Type of errors to display. - * @note For development/debugging set to E_ALL - * @default E_ALL & ~E_DEPRECATED & ~E_STRICT - * @see https://secure.php.net/manual/en/errorfunc.constants.php - * @version 4 - */ - ini_set('error_reporting', E_ALL); + /* + * Type of errors to display. + * @note For development/debugging set to E_ALL + * @default E_ALL & ~E_DEPRECATED & ~E_STRICT + * @see https://secure.php.net/manual/en/errorfunc.constants.php + * @version 4 + */ + ini_set('error_reporting', E_ALL); - /** - * Turn off HTML tags in error messages. - * @default '1' - * @version 4 - */ - ini_set('html_errors', '1'); + /* + * Turn off HTML tags in error messages. + * @default '1' + * @version 4 + */ + ini_set('html_errors', '1'); - /** - * Set the location to log PHP errors. - * @default NN_LOGS . 'php_errors.log' - * @note To log to syslog, put in 'syslog' - * @version 4 - */ - ini_set('error_log', NN_LOGS . 'php_errors_cli.log'); + /* + * Set the location to log PHP errors. + * @default NN_LOGS . 'php_errors.log' + * @note To log to syslog, put in 'syslog' + * @version 4 + */ + ini_set('error_log', NN_LOGS.'php_errors_cli.log'); - /** - * Log errors to error_log? - * @default '1' - * @version 4 - */ - ini_set('log_errors', '1'); + /* + * Log errors to error_log? + * @default '1' + * @version 4 + */ + ini_set('log_errors', '1'); - /** - * Max line length for a error. - * @default 1024 - * @version 4 - */ - ini_set('log_errors_max_len', '1024'); + /* + * Max line length for a error. + * @default 1024 + * @version 4 + */ + ini_set('log_errors_max_len', '1024'); - /** - * Store the last PHP error in $php_errormsg - * @default '0' - * @note This is a development/debugging option. - * @version 4 - */ - ini_set('track_errors', '0'); + /* + * Store the last PHP error in $php_errormsg + * @default '0' + * @note This is a development/debugging option. + * @version 4 + */ + ini_set('track_errors', '0'); -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////// PHP Web Settings /////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } else { - /** + /* * Your server's local timezone. * @note Uncomment to enable. * @see https://secure.php.net/manual/en/timezones.php * @version 4 */ - //ini_set('date.timezone', 'America/New_York'); + //ini_set('date.timezone', 'America/New_York'); - /** - * Maximum amount of seconds a script can run before being terminated. - * @default '120' - * @version 4 - */ - ini_set('max_execution_time', '120'); + /* + * Maximum amount of seconds a script can run before being terminated. + * @default '120' + * @version 4 + */ + ini_set('max_execution_time', '120'); - /** - * Maximum amount of memory a PHP script can consume before being terminated. - * @note Uncomment to enable. - * @default '1024M' - * @version 4 - */ - //ini_set('memory_limit', '1024M'); + /* + * Maximum amount of memory a PHP script can consume before being terminated. + * @note Uncomment to enable. + * @default '1024M' + * @version 4 + */ + //ini_set('memory_limit', '1024M'); - /** - * Show PHP errors on web browser. - * @note Set to '1' for development. - * @default '0' - * @version 4 - */ - ini_set('display_errors', '0'); + /* + * Show PHP errors on web browser. + * @note Set to '1' for development. + * @default '0' + * @version 4 + */ + ini_set('display_errors', '0'); - /** - * Show startup errors on web browser. - * @note Set to '1' for development/debugging. - * @default '0' - * @version 4 - */ - ini_set('display_startup_errors', '0'); + /* + * Show startup errors on web browser. + * @note Set to '1' for development/debugging. + * @default '0' + * @version 4 + */ + ini_set('display_startup_errors', '0'); - /** - * Type of errors to display. - * @note For development/debugging set to E_ALL - * @default E_ALL & ~E_DEPRECATED & ~E_STRICT - * @see https://secure.php.net/manual/en/errorfunc.constants.php - * @version 4 - */ - ini_set('error_reporting', E_ALL); + /* + * Type of errors to display. + * @note For development/debugging set to E_ALL + * @default E_ALL & ~E_DEPRECATED & ~E_STRICT + * @see https://secure.php.net/manual/en/errorfunc.constants.php + * @version 4 + */ + ini_set('error_reporting', E_ALL); - /** - * Turn off HTML tags in error messages. - * @default '1' - * @version 4 - */ - ini_set('html_errors', '1'); + /* + * Turn off HTML tags in error messages. + * @default '1' + * @version 4 + */ + ini_set('html_errors', '1'); - /** - * Set the location to log PHP errors. - * @default NN_LOGS . 'php_errors.log' - * @note To log to syslog, put in 'syslog' - * @version 4 - */ - ini_set('error_log', NN_LOGS . 'php_errors_web.log'); + /* + * Set the location to log PHP errors. + * @default NN_LOGS . 'php_errors.log' + * @note To log to syslog, put in 'syslog' + * @version 4 + */ + ini_set('error_log', NN_LOGS.'php_errors_web.log'); - /** - * Log errors to error_log? - * @default '1' - * @version 4 - */ - ini_set('log_errors', '1'); + /* + * Log errors to error_log? + * @default '1' + * @version 4 + */ + ini_set('log_errors', '1'); - /** - * Max line length for a error. - * @default 1024 - * @version 4 - */ - ini_set('log_errors_max_len', '1024'); + /* + * Max line length for a error. + * @default 1024 + * @version 4 + */ + ini_set('log_errors_max_len', '1024'); - /** - * Store the last PHP error in $php_errormsg - * @default '0' - * @note This is a development/debugging option. - * @version 4 - */ - ini_set('track_errors', '0'); + /* + * Store the last PHP error in $php_errormsg + * @default '0' + * @note This is a development/debugging option. + * @version 4 + */ + ini_set('track_errors', '0'); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -713,45 +714,45 @@ if (Utility::isCLI()) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (extension_loaded('xdebug')) { - /** + /* * Display colors on xdebug CLI output? * 0 - off, 1 - on only if on a TTY with ansi support, 2 - on regardless of TTY or ansi support. * @default 0 * @version 4 */ - ini_set('xdebug.cli_color', '0'); + ini_set('xdebug.cli_color', '0'); - /** - * Replace PHP's var_dump with xdebug's own? - * @default '1' - * @version 4 - */ - ini_set('xdebug.overload_var_dump', '1'); + /* + * Replace PHP's var_dump with xdebug's own? + * @default '1' + * @version 4 + */ + ini_set('xdebug.overload_var_dump', '1'); - /** - * How many items in a array or object to display on var_dump. - * @note Set to '-1' for no limit. - * @default '128' - * @version 4 - */ - ini_set('xdebug.var_display_max_children', '128'); + /* + * How many items in a array or object to display on var_dump. + * @note Set to '-1' for no limit. + * @default '128' + * @version 4 + */ + ini_set('xdebug.var_display_max_children', '128'); - /** - * Maximum string length on var_dump. (anything over is truncated) - * @note Set to '-1' for no limit. - * @default '512' - * @version 4 - */ - ini_set('xdebug.var_display_max_data', '512'); + /* + * Maximum string length on var_dump. (anything over is truncated) + * @note Set to '-1' for no limit. + * @default '512' + * @version 4 + */ + ini_set('xdebug.var_display_max_data', '512'); - /** - * How many nested arrays / objects deep to display on var_dump. - * @note Set to '-1' for no limit. - * @note Maximum value is '1023' - * @default '3' - * @version 4 - */ - ini_set('xdebug.var_display_max_depth', '3'); + /* + * How many nested arrays / objects deep to display on var_dump. + * @note Set to '-1' for no limit. + * @note Maximum value is '1023' + * @default '3' + * @version 4 + */ + ini_set('xdebug.var_display_max_depth', '3'); } /*********************************************************************************************************************** diff --git a/nntmux/constants.php b/nntmux/constants.php index 256b27652..bb25352e3 100755 --- a/nntmux/constants.php +++ b/nntmux/constants.php @@ -1,4 +1,5 @@ <?php + // YOU SHOULD NOT EDIT ANYTHING IN THIS FILE, COPY .../nzedb/config/settings.example.php TO .../nzedb/config/settings.php AND EDIT THAT FILE! define('NN_MINIMUM_PHP_VERSION', '7.1.0'); @@ -8,63 +9,63 @@ define('NN_MINIMUM_MARIA_VERSION', '10.1'); define('DS', DIRECTORY_SEPARATOR); // These are file path constants -define('NN_ROOT', realpath(dirname(__DIR__)) . DS); +define('NN_ROOT', realpath(dirname(__DIR__)).DS); // Used to refer to the main lib class files. -define('NN_LIB', NN_ROOT . 'nntmux' . DS); +define('NN_LIB', NN_ROOT.'nntmux'.DS); define('NN_CORE', NN_LIB); -define('NN_CONFIGS', NN_CORE . 'config' . DS); +define('NN_CONFIGS', NN_CORE.'config'.DS); // Used to refer to the third party library files. -define('NN_LIBS', NN_ROOT . 'libs' . DS); +define('NN_LIBS', NN_ROOT.'libs'.DS); // Used to refer to the /misc class files. -define('NN_MISC', NN_ROOT . 'misc' . DS); +define('NN_MISC', NN_ROOT.'misc'.DS); // /misc/update/ -define('NN_UPDATE', NN_MISC . 'update' . DS); +define('NN_UPDATE', NN_MISC.'update'.DS); // /misc/update/nix/ -define('NN_NIX', NN_UPDATE . 'nix' . DS); +define('NN_NIX', NN_UPDATE.'nix'.DS); // /misc/update/nix/multiprocessing -define('NN_MULTI', NN_UPDATE . 'nix' . DS. 'multiprocessing' . DS); +define('NN_MULTI', NN_UPDATE.'nix'.DS.'multiprocessing'.DS); // /misc/update/nix/tmux/ -define('NN_TMUX', NN_UPDATE . 'nix' . DS . 'tmux'. DS); +define('NN_TMUX', NN_UPDATE.'nix'.DS.'tmux'.DS); // /misc/update/nix/multiprocessing/ -define('NN_MULTIPROCESSING', NN_NIX . 'multiprocessing' . DS); +define('NN_MULTIPROCESSING', NN_NIX.'multiprocessing'.DS); // Refers to the web root for the Smarty lib -define('NN_WWW', NN_ROOT . 'public' . DS); +define('NN_WWW', NN_ROOT.'public'.DS); // Used to refer to the resources folder -define('NN_RES', NN_ROOT . 'resources' . DS); +define('NN_RES', NN_ROOT.'resources'.DS); // Used to refer to the covers folder -define('NN_COVERS', NN_RES . 'covers' . DS); +define('NN_COVERS', NN_RES.'covers'.DS); // Smarty's cache. -define('NN_SMARTY_CACHE', NN_RES . 'smarty' . DS . 'cache/'); +define('NN_SMARTY_CACHE', NN_RES.'smarty'.DS.'cache/'); // Smarty's configuration files. -define('NN_SMARTY_CONFIGS', NN_RES .'smarty' . DS . 'configs/'); +define('NN_SMARTY_CONFIGS', NN_RES.'smarty'.DS.'configs/'); // Smarty's compiled template cache. -define('NN_SMARTY_TEMPLATES', NN_RES . 'smarty' . DS . 'templates_c/'); +define('NN_SMARTY_TEMPLATES', NN_RES.'smarty'.DS.'templates_c/'); // Used to refer to the tmp folder -define('NN_TMP', NN_RES . 'tmp' . DS); +define('NN_TMP', NN_RES.'tmp'.DS); // Full path is fs to the themes folder -define('NN_THEMES', NN_WWW . 'themes' . DS); +define('NN_THEMES', NN_WWW.'themes'.DS); // Shared theme items (pictures, scripts). -define('NN_THEMES_SHARED', NN_THEMES . 'shared' . DS); +define('NN_THEMES_SHARED', NN_THEMES.'shared'.DS); // Path where log files are stored. -define('NN_LOGS', NN_RES . 'logs' . DS); +define('NN_LOGS', NN_RES.'logs'.DS); -define('NN_VERSIONS', NN_ROOT . 'build' . DS . 'nntmux.xml'); +define('NN_VERSIONS', NN_ROOT.'build'.DS.'nntmux.xml'); diff --git a/nntmux/db/DB.php b/nntmux/db/DB.php index 2284bf772..87c4782d1 100755 --- a/nntmux/db/DB.php +++ b/nntmux/db/DB.php @@ -1,16 +1,16 @@ <?php + namespace nntmux\db; -use App\Models\Settings; -use nntmux\ColorCLI; -use nntmux\ConsoleTools; use nntmux\Logger; +use nntmux\ColorCLI; +use Ramsey\Uuid\Uuid; +use App\Models\Settings; +use nntmux\ConsoleTools; +use nntmux\libraries\Cache; use nntmux\LoggerException; use nntmux\utility\Utility; -use nntmux\libraries\Cache; use nntmux\libraries\CacheException; -use Ramsey\Uuid\Uuid; - /** * Class for handling connection to MySQL database using PDO. @@ -24,92 +24,92 @@ use Ramsey\Uuid\Uuid; */ class DB extends \PDO { - /** - * @var bool Is this a Command Line Interface instance. - * - * This needs to be revisited when moving to li3. Web pages do not need this class so it shouldn't be included by default. - */ - public $cli; + /** + * @var bool Is this a Command Line Interface instance. + * + * This needs to be revisited when moving to li3. Web pages do not need this class so it shouldn't be included by default. + */ + public $cli; - /** - * @var object Instance of \nntmux\ConsoleTools class. - */ - public $ct; + /** + * @var object Instance of \nntmux\ConsoleTools class. + */ + public $ct; - /** - * @var \nntmux\ColorCLI Instance variable for logging object. Currently only ColorCLI supported, - * but expanding for full logging with agnostic API planned. - */ - public $log; + /** + * @var \nntmux\ColorCLI Instance variable for logging object. Currently only ColorCLI supported, + * but expanding for full logging with agnostic API planned. + */ + public $log; - /** - * @note Setting this static causes issues when creating multiple instances of this class with different - * MySQL servers, the next instances re-uses the server of the first instance. - * @var \PDO Instance of PDO class. - */ - public $pdo = null; + /** + * @note Setting this static causes issues when creating multiple instances of this class with different + * MySQL servers, the next instances re-uses the server of the first instance. + * @var \PDO Instance of PDO class. + */ + public $pdo = null; - /** - * @var bool - */ - protected $_debug; + /** + * @var bool + */ + protected $_debug; - /** - * @var object Class instance debugging. - */ - private $debugging; + /** + * @var object Class instance debugging. + */ + private $debugging; - /** - * @var string Lower-cased name of DBMS in use. - */ - private $dbSystem; + /** + * @var string Lower-cased name of DBMS in use. + */ + private $dbSystem; - /** - * @var string Version of the Db server. - */ - private $dbVersion; + /** + * @var string Version of the Db server. + */ + private $dbVersion; - /** - * @var string Stored copy of the dsn used to connect. - */ - private $dsn; + /** + * @var string Stored copy of the dsn used to connect. + */ + private $dsn; - /** - * @var array Options passed into the constructor or defaulted. - */ - private $opts; + /** + * @var array Options passed into the constructor or defaulted. + */ + private $opts; - /** - * @var null|\nntmux\libraries\Cache - */ - private $cacheServer = null; + /** + * @var null|\nntmux\libraries\Cache + */ + private $cacheServer = null; - /** - * @var bool Should we cache the results of the query method? - */ - private $cacheEnabled = false; + /** + * @var bool Should we cache the results of the query method? + */ + private $cacheEnabled = false; - /** - * @var string MySQL LOW_PRIORITY DELETE option. - */ - private $DELETE_LOW_PRIORITY = ''; + /** + * @var string MySQL LOW_PRIORITY DELETE option. + */ + private $DELETE_LOW_PRIORITY = ''; - /** - * @var string MYSQL QUICK DELETE option. - */ - private $DELETE_QUICK = ''; + /** + * @var string MYSQL QUICK DELETE option. + */ + private $DELETE_QUICK = ''; - /** - * Constructor. Sets up all necessary properties. Instantiates a PDO object - * if needed, otherwise returns the current one. - * - * @param array $options - */ - public function __construct(array $options = []) - { - $this->cli = Utility::isCLI(); + /** + * Constructor. Sets up all necessary properties. Instantiates a PDO object + * if needed, otherwise returns the current one. + * + * @param array $options + */ + public function __construct(array $options = []) + { + $this->cli = Utility::isCLI(); - $defaults = [ + $defaults = [ 'checkVersion' => false, 'createDb' => false, // create dbname if it does not exist? 'ct' => new ConsoleTools(), @@ -118,992 +118,993 @@ class DB extends \PDO 'dbpass' => env('DB_PASSWORD', 'nntmux'), 'dbport' => env('DB_PORT', '3306'), 'dbsock' => env('DB_SOCKET'), - 'dbtype' => env('DB_SYSTEM','mysql'), + 'dbtype' => env('DB_SYSTEM', 'mysql'), 'dbuser' => env('DB_USER', 'nntmux'), 'log' => new ColorCLI(), 'persist' => false, ]; - $options += $defaults; + $options += $defaults; - if (!$this->cli) { - $options['log'] = null; - } - $this->opts = $options; + if (! $this->cli) { + $options['log'] = null; + } + $this->opts = $options; - if (!empty($this->opts['dbtype'])) { - $this->dbSystem = strtolower($this->opts['dbtype']); - } + if (! empty($this->opts['dbtype'])) { + $this->dbSystem = strtolower($this->opts['dbtype']); + } - if (!($this->pdo instanceof \PDO)) { - $this->initialiseDatabase(); - } + if (! ($this->pdo instanceof \PDO)) { + $this->initialiseDatabase(); + } - $this->cacheEnabled = (defined('NN_CACHE_TYPE') && (NN_CACHE_TYPE > 0) ? true : false); + $this->cacheEnabled = (defined('NN_CACHE_TYPE') && (NN_CACHE_TYPE > 0) ? true : false); - if ($this->cacheEnabled) { - try { - $this->cacheServer = new Cache(); - } catch (CacheException $error) { - $this->cacheEnabled = false; - $this->echoError($error->getMessage(), '__construct', 4); - } - } + if ($this->cacheEnabled) { + try { + $this->cacheServer = new Cache(); + } catch (CacheException $error) { + $this->cacheEnabled = false; + $this->echoError($error->getMessage(), '__construct', 4); + } + } - $this->ct = $this->opts['ct']; - $this->log = $this->opts['log']; + $this->ct = $this->opts['ct']; + $this->log = $this->opts['log']; - $this->_debug = (NN_DEBUG || NN_LOGGING); - if ($this->_debug) { - try { - $this->debugging = new Logger(['ColorCLI' => $this->log]); - } catch (LoggerException $error) { - $this->_debug = false; - } - } + $this->_debug = (NN_DEBUG || NN_LOGGING); + if ($this->_debug) { + try { + $this->debugging = new Logger(['ColorCLI' => $this->log]); + } catch (LoggerException $error) { + $this->_debug = false; + } + } + if ($this->opts['checkVersion']) { + $this->fetchDbVersion(); + } - if ($this->opts['checkVersion']) { - $this->fetchDbVersion(); - } + if (defined('NN_SQL_DELETE_LOW_PRIORITY') && NN_SQL_DELETE_LOW_PRIORITY) { + $this->DELETE_LOW_PRIORITY = ' LOW_PRIORITY '; + } - if (defined('NN_SQL_DELETE_LOW_PRIORITY') && NN_SQL_DELETE_LOW_PRIORITY) { - $this->DELETE_LOW_PRIORITY = ' LOW_PRIORITY '; - } + if (defined('NN_SQL_DELETE_QUICK') && NN_SQL_DELETE_QUICK) { + $this->DELETE_QUICK = ' QUICK '; + } - if (defined('NN_SQL_DELETE_QUICK') && NN_SQL_DELETE_QUICK) { - $this->DELETE_QUICK = ' QUICK '; - } + return $this->pdo; + } - return $this->pdo; - } + public function __destruct() + { + $this->pdo = null; + } - public function __destruct() - { - $this->pdo = null; - } + public function __get($name) + { + $result = $this->queryOneRow("SELECT value FROM settings WHERE setting = '$name' LIMIT 1"); - public function __get($name) - { - $result = $this->queryOneRow("SELECT value FROM settings WHERE setting = '$name' LIMIT 1"); + return is_array($result) ? $result['value'] : $result; + } - return is_array($result) ? $result['value'] : $result; - } + public function checkDbExists($name = null) + { + if (empty($name)) { + $name = $this->opts['dbname']; + } - public function checkDbExists($name = null) - { - if (empty($name)) { - $name = $this->opts['dbname']; - } + $found = false; + $tables = self::getTableList(); + foreach ($tables as $table) { + if ($table['Database'] == $name) { + $found = true; + break; + } + } - $found = false; - $tables = self::getTableList(); - foreach ($tables as $table) { - if ($table['Database'] == $name) { - $found = true; - break; - } - } - return $found; - } + return $found; + } - /** - * Looks up info for index on table. - * - * @param $table string Table to look at. - * @param $index string Index to check. - * - * @return bool|array False on failure, associative array of SHOW data. - */ - public function checkIndex($table, $index) - { - $result = $this->pdo->query( + /** + * Looks up info for index on table. + * + * @param $table string Table to look at. + * @param $index string Index to check. + * + * @return bool|array False on failure, associative array of SHOW data. + */ + public function checkIndex($table, $index) + { + $result = $this->pdo->query( sprintf( "SHOW INDEX FROM %s WHERE key_name = '%s'", trim($table), trim($index) ) ); - if ($result === false) { - return false; - } + if ($result === false) { + return false; + } - return $result->fetch(\PDO::FETCH_ASSOC); - } + return $result->fetch(\PDO::FETCH_ASSOC); + } - public function checkColumnIndex($table, $column) - { - $result = $this->pdo->query( + public function checkColumnIndex($table, $column) + { + $result = $this->pdo->query( sprintf( "SHOW INDEXES IN %s WHERE non_unique = 0 AND column_name = '%s'", trim($table), trim($column) ) ); - if ($result === false) { - return false; - } + if ($result === false) { + return false; + } - return $result->fetchAll(\PDO::FETCH_ASSOC); - } + return $result->fetchAll(\PDO::FETCH_ASSOC); + } - public function debugDisable() - { - unset($this->debugging); - $this->_debug = false; - } + public function debugDisable() + { + unset($this->debugging); + $this->_debug = false; + } - public function debugEnable() - { - $this->_debug = true; - try { - $this->debugging = new Logger(['ColorCLI' => $this->log]); - } catch (LoggerException $error) { - $this->_debug = false; - } - } + public function debugEnable() + { + $this->_debug = true; + try { + $this->debugging = new Logger(['ColorCLI' => $this->log]); + } catch (LoggerException $error) { + $this->_debug = false; + } + } - public function getSetting($name) - { - $result = $this->queryOneRow("SELECT value FROM settings WHERE setting = '$name' LIMIT 1"); - return is_array($result) ? $result['value'] : $result; - } + public function getSetting($name) + { + $result = $this->queryOneRow("SELECT value FROM settings WHERE setting = '$name' LIMIT 1"); - /** - * Return a tree-like array of all or selected settings. - * - * @param array $options Options array for Settings::find() i.e. ['conditions' => ...]. - * @param bool $excludeUnsectioned If rows with empty 'section' field should be excluded. - * Note this doesn't prevent empty 'subsection' fields. - * - * @return array - * @throws \RuntimeException - */ - public function getSettingsAsTree($excludeUnsectioned = true) - { - $where = $excludeUnsectioned ? "WHERE section != ''" : ''; + return is_array($result) ? $result['value'] : $result; + } - $sql = sprintf("SELECT section, subsection, name, value, hint FROM settings %s ORDER BY section, subsection, name", + /** + * Return a tree-like array of all or selected settings. + * + * @param array $options Options array for Settings::find() i.e. ['conditions' => ...]. + * @param bool $excludeUnsectioned If rows with empty 'section' field should be excluded. + * Note this doesn't prevent empty 'subsection' fields. + * + * @return array + * @throws \RuntimeException + */ + public function getSettingsAsTree($excludeUnsectioned = true) + { + $where = $excludeUnsectioned ? "WHERE section != ''" : ''; + + $sql = sprintf('SELECT section, subsection, name, value, hint FROM settings %s ORDER BY section, subsection, name', $where); - $results = $this->queryArray($sql); + $results = $this->queryArray($sql); - $tree = []; - if (is_array($results)) { - foreach ($results as $result) { - if (!empty($result['section']) || !$excludeUnsectioned) { - $tree[$result['section']][$result['subsection']][$result['name']] = + $tree = []; + if (is_array($results)) { + foreach ($results as $result) { + if (! empty($result['section']) || ! $excludeUnsectioned) { + $tree[$result['section']][$result['subsection']][$result['name']] = ['value' => $result['value'], 'hint' => $result['hint']]; - } - } - } else { - echo "NO results!!\n"; - } + } + } + } else { + echo "NO results!!\n"; + } - return $tree; - } + return $tree; + } - public function getTableList() - { - $query = ($this->opts['dbtype'] === 'mysql' ? 'SHOW DATABASES' : 'SELECT datname AS Database FROM pg_database'); - $result = $this->pdo->query($query); - return $result->fetchAll(\PDO::FETCH_ASSOC); - } + public function getTableList() + { + $query = ($this->opts['dbtype'] === 'mysql' ? 'SHOW DATABASES' : 'SELECT datname AS Database FROM pg_database'); + $result = $this->pdo->query($query); - /** - * Attempts to determine if the Db is on the local machine. - * - * If the method returns true, then the Db is definitely on the local machine. However, - * returning false only indicates that it could not positively be determined to be local - so - * assume remote. - * - * @return bool Whether the Db is definitely on the local machine. - */ - public function isLocalDb() - { - $local = false; - if (!empty($this->opts['dbsock']) || $this->opts['dbhost'] == 'localhost') { - $local = true; - } else { - preg_match_all('/inet' . '6?' . ' addr: ?([^ ]+)/', `ifconfig`, $ips); + return $result->fetchAll(\PDO::FETCH_ASSOC); + } - // Check for dotted quad - if exists compare against local IP number(s) - if (preg_match('#^\d+\.\d+\.\d+\.\d+$#', $this->opts['dbhost'])) { - if (in_array($this->opts['dbhost'], $ips[1])) { - $local = true; - } - } - } - return $local; - } + /** + * Attempts to determine if the Db is on the local machine. + * + * If the method returns true, then the Db is definitely on the local machine. However, + * returning false only indicates that it could not positively be determined to be local - so + * assume remote. + * + * @return bool Whether the Db is definitely on the local machine. + */ + public function isLocalDb() + { + $local = false; + if (! empty($this->opts['dbsock']) || $this->opts['dbhost'] == 'localhost') { + $local = true; + } else { + preg_match_all('/inet'.'6?'.' addr: ?([^ ]+)/', `ifconfig`, $ips); - /** - * Init PDO instance. - */ - private function initialiseDatabase() - { + // Check for dotted quad - if exists compare against local IP number(s) + if (preg_match('#^\d+\.\d+\.\d+\.\d+$#', $this->opts['dbhost'])) { + if (in_array($this->opts['dbhost'], $ips[1])) { + $local = true; + } + } + } - if (!empty($this->opts['dbsock'])) { - $dsn = $this->dbSystem . ':unix_socket=' . $this->opts['dbsock']; - } else { - $dsn = $this->dbSystem . ':host=' . $this->opts['dbhost']; - if (!empty($this->opts['dbport'])) { - $dsn .= ';port=' . $this->opts['dbport']; - } - } - $dsn .= ';charset=utf8'; + return $local; + } - $options = [ + /** + * Init PDO instance. + */ + private function initialiseDatabase() + { + if (! empty($this->opts['dbsock'])) { + $dsn = $this->dbSystem.':unix_socket='.$this->opts['dbsock']; + } else { + $dsn = $this->dbSystem.':host='.$this->opts['dbhost']; + if (! empty($this->opts['dbport'])) { + $dsn .= ';port='.$this->opts['dbport']; + } + } + $dsn .= ';charset=utf8'; + + $options = [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_TIMEOUT => 180, \PDO::ATTR_PERSISTENT => $this->opts['persist'], - \PDO::MYSQL_ATTR_LOCAL_INFILE => true + \PDO::MYSQL_ATTR_LOCAL_INFILE => true, ]; - $this->dsn = $dsn; - // removed try/catch to let the instantiating code handle the problem (Install for - // instance can output a message that connecting failed. - $this->pdo = new \PDO($dsn, $this->opts['dbuser'], $this->opts['dbpass'], $options); + $this->dsn = $dsn; + // removed try/catch to let the instantiating code handle the problem (Install for + // instance can output a message that connecting failed. + $this->pdo = new \PDO($dsn, $this->opts['dbuser'], $this->opts['dbpass'], $options); - if ($this->opts['dbname'] != '') { - if ($this->opts['createDb']) { - $found = self::checkDbExists(); - if ($found) { - try { - $this->pdo->query("DROP DATABASE " . $this->opts['dbname']); - } catch (\Exception $e) { - throw new \RuntimeException("Error trying to drop your old database: '{$this->opts['dbname']}'", 2); - } - $found = self::checkDbExists(); - } + if ($this->opts['dbname'] != '') { + if ($this->opts['createDb']) { + $found = self::checkDbExists(); + if ($found) { + try { + $this->pdo->query('DROP DATABASE '.$this->opts['dbname']); + } catch (\Exception $e) { + throw new \RuntimeException("Error trying to drop your old database: '{$this->opts['dbname']}'", 2); + } + $found = self::checkDbExists(); + } - if ($found) { - var_dump(self::getTableList()); - throw new \RuntimeException("Could not drop your old database: '{$this->opts['dbname']}'", 2); - } else { - $this->pdo->query("CREATE DATABASE `{$this->opts['dbname']}` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"); + if ($found) { + var_dump(self::getTableList()); + throw new \RuntimeException("Could not drop your old database: '{$this->opts['dbname']}'", 2); + } else { + $this->pdo->query("CREATE DATABASE `{$this->opts['dbname']}` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"); - if (!self::checkDbExists()) { - throw new \RuntimeException("Could not create new database: '{$this->opts['dbname']}'", 3); - } - } - } - $this->pdo->query("USE {$this->opts['dbname']}"); - } + if (! self::checkDbExists()) { + throw new \RuntimeException("Could not create new database: '{$this->opts['dbname']}'", 3); + } + } + } + $this->pdo->query("USE {$this->opts['dbname']}"); + } - // In case PDO is not set to produce exceptions (PHP's default behaviour). - if ($this->pdo === false) { - $this->echoError( - "Unable to create connection to the Database!", + // In case PDO is not set to produce exceptions (PHP's default behaviour). + if ($this->pdo === false) { + $this->echoError( + 'Unable to create connection to the Database!', 'initialiseDatabase', 1, true ); - } + } - // For backwards compatibility, no need for a patch. - $this->pdo->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_LOWER); - $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC); - } + // For backwards compatibility, no need for a patch. + $this->pdo->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_LOWER); + $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC); + } - /** - * Echo error, optionally exit. - * - * @param string $error The error message. - * @param string $method The method where the error occured. - * @param int $severity The severity of the error. - * @param bool $exit Exit or not? - */ - protected function echoError($error, $method, $severity, $exit = false) - { - if ($this->_debug) { - $this->debugging->log(__CLASS__, $method, $error, $severity); + /** + * Echo error, optionally exit. + * + * @param string $error The error message. + * @param string $method The method where the error occured. + * @param int $severity The severity of the error. + * @param bool $exit Exit or not? + */ + protected function echoError($error, $method, $severity, $exit = false) + { + if ($this->_debug) { + $this->debugging->log(__CLASS__, $method, $error, $severity); - echo( - ($this->cli ? $this->log->error($error) . PHP_EOL : '<div class="error">' . $error . '</div>') - ); - } + echo + $this->cli ? $this->log->error($error).PHP_EOL : '<div class="error">'.$error.'</div>'; + } - if ($exit) { - exit(); - } - } + if ($exit) { + exit(); + } + } - /** - * @return string mysql. - */ - public function DbSystem() - { - return $this->dbSystem; - } + /** + * @return string mysql. + */ + public function DbSystem() + { + return $this->dbSystem; + } - /** - * Returns a string, escaped with single quotes, false on failure. http://www.php.net/manual/en/pdo.quote.php - * - * @param string $str - * - * @return string - */ - public function escapeString($str) - { - if (is_null($str)) { - return 'NULL'; - } + /** + * Returns a string, escaped with single quotes, false on failure. http://www.php.net/manual/en/pdo.quote.php. + * + * @param string $str + * + * @return string + */ + public function escapeString($str) + { + if (is_null($str)) { + return 'NULL'; + } - return $this->pdo->quote($str); - } + return $this->pdo->quote($str); + } - /** - * Formats a 'like' string. ex.(LIKE '%chocolate%') - * - * @param string $str The string. - * @param bool $left Add a % to the left. - * @param bool $right Add a % to the right. - * - * @return string - */ - public function likeString($str, $left = true, $right = true) - { - return ('LIKE ' . $this->escapeString(($left ? '%' : '') . $str . ($right ? '%' : ''))); - } + /** + * Formats a 'like' string. ex.(LIKE '%chocolate%'). + * + * @param string $str The string. + * @param bool $left Add a % to the left. + * @param bool $right Add a % to the right. + * + * @return string + */ + public function likeString($str, $left = true, $right = true) + { + return 'LIKE '.$this->escapeString(($left ? '%' : '').$str.($right ? '%' : '')); + } - /** - * Verify if pdo var is instance of PDO class. - * - * @return bool - */ - public function isInitialised() - { - return ($this->pdo instanceof \PDO); - } + /** + * Verify if pdo var is instance of PDO class. + * + * @return bool + */ + public function isInitialised() + { + return $this->pdo instanceof \PDO; + } - /** - * For inserting a row. Returns last insert ID. queryExec is better if you do not need the id. - * - * @param string $query - * - * @return integer|false|string - */ - public function queryInsert($query) - { - if (!$this->parseQuery($query)) { - return false; - } + /** + * For inserting a row. Returns last insert ID. queryExec is better if you do not need the id. + * + * @param string $query + * + * @return int|false|string + */ + public function queryInsert($query) + { + if (! $this->parseQuery($query)) { + return false; + } - $i = 2; - $error = ''; - while ($i < 11) { - $result = $this->queryExecHelper($query, true); - if (is_array($result) && isset($result['deadlock'])) { - $error = $result['message']; - if ($result['deadlock'] === true) { - $this->echoError("A Deadlock or lock wait timeout has occurred, sleeping. (" . - ($i - 1) . ")", + $i = 2; + $error = ''; + while ($i < 11) { + $result = $this->queryExecHelper($query, true); + if (is_array($result) && isset($result['deadlock'])) { + $error = $result['message']; + if ($result['deadlock'] === true) { + $this->echoError('A Deadlock or lock wait timeout has occurred, sleeping. ('. + ($i - 1).')', 'queryInsert', 4); - $this->ct->showsleep($i * ($i / 2)); - $i++; - } else { - break; - } - } elseif ($result === false) { - $error = 'Unspecified error.'; - break; - } else { - return $result; - } - } - if ($this->_debug) { - $this->echoError($error, 'queryInsert', 4); - $this->debugging->log(__CLASS__, __FUNCTION__, $query, Logger::LOG_SQL); - } - return false; - } + $this->ct->showsleep($i * ($i / 2)); + $i++; + } else { + break; + } + } elseif ($result === false) { + $error = 'Unspecified error.'; + break; + } else { + return $result; + } + } + if ($this->_debug) { + $this->echoError($error, 'queryInsert', 4); + $this->debugging->log(__CLASS__, __FUNCTION__, $query, Logger::LOG_SQL); + } - /** - * Delete rows from MySQL. - * - * @param string $query - * @param bool $silent Echo or log errors? - * - * @return bool|\PDOStatement - */ - public function queryDelete($query, $silent = false) - { - // Accommodate for chained queries (SELECT 1;DELETE x FROM y) - if (preg_match('#(.*?[^a-z0-9]|^)DELETE\s+(.+?)$#is', $query, $matches)) { - $query = $matches[1] . 'DELETE ' . $this->DELETE_LOW_PRIORITY . $this->DELETE_QUICK . $matches[2]; - } - return $this->queryExec($query, $silent); - } + return false; + } - /** - * Used for deleting, updating (and inserting without needing the last insert id). - * - * @param string $query - * @param bool $silent Echo or log errors? - * - * @return bool|\PDOStatement - */ - public function queryExec($query, $silent = false) - { - if (!$this->parseQuery($query)) { - return false; - } + /** + * Delete rows from MySQL. + * + * @param string $query + * @param bool $silent Echo or log errors? + * + * @return bool|\PDOStatement + */ + public function queryDelete($query, $silent = false) + { + // Accommodate for chained queries (SELECT 1;DELETE x FROM y) + if (preg_match('#(.*?[^a-z0-9]|^)DELETE\s+(.+?)$#is', $query, $matches)) { + $query = $matches[1].'DELETE '.$this->DELETE_LOW_PRIORITY.$this->DELETE_QUICK.$matches[2]; + } - $i = 2; - $error = ''; - while ($i < 11) { - $result = $this->queryExecHelper($query); - if (is_array($result) && isset($result['deadlock'])) { - $error = $result['message']; - if ($result['deadlock'] === true) { - $this->echoError("A Deadlock or lock wait timeout has occurred, sleeping. (" . ($i - 1) . ")", 'queryExec', 4); - $this->ct->showsleep($i * ($i / 2)); - $i++; - } else { - break; - } - } elseif ($result === false) { - $error = 'Unspecified error.'; - break; - } else { - return $result; - } - } - if ($silent === false && $this->_debug) { - $this->echoError($error, 'queryExec', 4); - $this->debugging->log(__CLASS__, __FUNCTION__, $query, Logger::LOG_SQL); - } - return false; - } + return $this->queryExec($query, $silent); + } - /** - * Helper method for queryInsert and queryExec, checks for deadlocks. - * - * @param string $query - * @param bool $insert - * - * @return array|\PDOStatement - */ - protected function queryExecHelper($query, $insert = false) - { - try { - if ($insert === false) { - $run = $this->pdo->prepare($query); - $run->execute(); - return $run; - } else { - $ins = $this->pdo->prepare($query); - $ins->execute(); - return $this->pdo->lastInsertId(); - } + /** + * Used for deleting, updating (and inserting without needing the last insert id). + * + * @param string $query + * @param bool $silent Echo or log errors? + * + * @return bool|\PDOStatement + */ + public function queryExec($query, $silent = false) + { + if (! $this->parseQuery($query)) { + return false; + } - } catch (\PDOException $e) { - // Deadlock or lock wait timeout, try 10 times. - if ( + $i = 2; + $error = ''; + while ($i < 11) { + $result = $this->queryExecHelper($query); + if (is_array($result) && isset($result['deadlock'])) { + $error = $result['message']; + if ($result['deadlock'] === true) { + $this->echoError('A Deadlock or lock wait timeout has occurred, sleeping. ('.($i - 1).')', 'queryExec', 4); + $this->ct->showsleep($i * ($i / 2)); + $i++; + } else { + break; + } + } elseif ($result === false) { + $error = 'Unspecified error.'; + break; + } else { + return $result; + } + } + if ($silent === false && $this->_debug) { + $this->echoError($error, 'queryExec', 4); + $this->debugging->log(__CLASS__, __FUNCTION__, $query, Logger::LOG_SQL); + } + + return false; + } + + /** + * Helper method for queryInsert and queryExec, checks for deadlocks. + * + * @param string $query + * @param bool $insert + * + * @return array|\PDOStatement + */ + protected function queryExecHelper($query, $insert = false) + { + try { + if ($insert === false) { + $run = $this->pdo->prepare($query); + $run->execute(); + + return $run; + } else { + $ins = $this->pdo->prepare($query); + $ins->execute(); + + return $this->pdo->lastInsertId(); + } + } catch (\PDOException $e) { + // Deadlock or lock wait timeout, try 10 times. + if ( $e->errorInfo[1] == 1213 || $e->errorInfo[0] == 40001 || $e->errorInfo[1] == 1205 || $e->getMessage() == 'SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction' ) { - return ['deadlock' => true, 'message' => $e->getMessage()]; - } + return ['deadlock' => true, 'message' => $e->getMessage()]; + } - // Check if we lost connection to MySQL. - else if ($this->_checkGoneAway($e->getMessage()) !== false) { + // Check if we lost connection to MySQL. + elseif ($this->_checkGoneAway($e->getMessage()) !== false) { // Reconnect to MySQL. - if ($this->_reconnect() === true) { + if ($this->_reconnect() === true) { // If we reconnected, retry the query. - return $this->queryExecHelper($query, $insert); + return $this->queryExecHelper($query, $insert); + } + } - } - } + return ['deadlock' => false, 'message' => $e->getMessage()]; + } + } - return ['deadlock' => false, 'message' => $e->getMessage()]; - } - } + /** + * Direct query. Return the affected row count. http://www.php.net/manual/en/pdo.exec.php. + * + * @note If not "consumed", causes this error: + * 'SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. + * Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, + * you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.' + * + * @param string $query + * @param bool $silent Whether to skip echoing errors to the console. + * + * @return bool|int|\PDOStatement + */ + public function exec($query, $silent = false) + { + if (! $this->parseQuery($query)) { + return false; + } - /** - * Direct query. Return the affected row count. http://www.php.net/manual/en/pdo.exec.php - * - * @note If not "consumed", causes this error: - * 'SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. - * Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, - * you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.' - * - * @param string $query - * @param bool $silent Whether to skip echoing errors to the console. - * - * @return bool|int|\PDOStatement - */ - public function exec($query, $silent = false) - { - if (!$this->parseQuery($query)) { - return false; - } - - try { - return $this->pdo->exec($query); - - } catch (\PDOException $e) { + try { + return $this->pdo->exec($query); + } catch (\PDOException $e) { // Check if we lost connection to MySQL. - if ($this->_checkGoneAway($e->getMessage()) !== false) { + if ($this->_checkGoneAway($e->getMessage()) !== false) { // Reconnect to MySQL. - if ($this->_reconnect() === true) { + if ($this->_reconnect() === true) { // If we reconnected, retry the query. - return $this->exec($query, $silent); + return $this->exec($query, $silent); + } else { + // If we are not reconnected, return false. + return false; + } + } elseif (! $silent) { + $this->echoError($e->getMessage(), 'Exec', 4, false); - } else { - // If we are not reconnected, return false. - return false; - } + if ($this->_debug) { + $this->debugging->log(__CLASS__, __FUNCTION__, $query, Logger::LOG_SQL); + } + } - } else if (!$silent) { - $this->echoError($e->getMessage(), 'Exec', 4, false); + return false; + } + } - if ($this->_debug) { - $this->debugging->log(__CLASS__, __FUNCTION__, $query, Logger::LOG_SQL); - } - } + /** + * Returns an array of result (empty array if no results or an error occurs) + * Optional: Pass true to cache the result with a cache server. + * + * @param string $query SQL to execute. + * @param bool $cache Indicates if the query result should be cached. + * @param int $cacheExpiry The time in seconds before deleting the query result from the cache server. + * + * @return array Array of results (possibly empty) on success, empty array on failure. + */ + public function query($query, $cache = false, $cacheExpiry = 600) + { + if (! $this->parseQuery($query)) { + return false; + } - return false; - } - } + if ($cache === true && $this->cacheEnabled === true) { + try { + $data = $this->cacheServer->get($this->cacheServer->createKey($query)); + if ($data !== false) { + return $data; + } + } catch (CacheException $error) { + $this->echoError($error->getMessage(), 'query', 4); + } + } - /** - * Returns an array of result (empty array if no results or an error occurs) - * Optional: Pass true to cache the result with a cache server. - * - * @param string $query SQL to execute. - * @param bool $cache Indicates if the query result should be cached. - * @param int $cacheExpiry The time in seconds before deleting the query result from the cache server. - * - * @return array Array of results (possibly empty) on success, empty array on failure. - */ - public function query($query, $cache = false, $cacheExpiry = 600) - { - if (!$this->parseQuery($query)) { - return false; - } + $result = $this->queryArray($query); - if ($cache === true && $this->cacheEnabled === true) { - try { - $data = $this->cacheServer->get($this->cacheServer->createKey($query)); - if ($data !== false) { - return $data; - } - } catch (CacheException $error) { - $this->echoError($error->getMessage(), 'query', 4); - } - } + if ($result !== false && $cache === true && $this->cacheEnabled === true) { + $this->cacheServer->set($this->cacheServer->createKey($query), $result, $cacheExpiry); + } - $result = $this->queryArray($query); + return ($result === false) ? [] : $result; + } - if ($result !== false && $cache === true && $this->cacheEnabled === true) { - $this->cacheServer->set($this->cacheServer->createKey($query), $result, $cacheExpiry); - } + /** + * Returns a multidimensional array of result of the query function return and the count of found rows + * Note: Query passed to this function SHOULD include SQL_CALC_FOUND_ROWS + * Optional: Pass true to cache the result with a cache server. + * + * @param string $query SQL to execute. + * @param bool $cache Indicates if the query result should be cached. + * @param int $cacheExpiry The time in seconds before deleting the query result from the cache server. + * + * @return array Array of results (possibly empty) on success, empty array on failure. + */ + public function queryCalc($query, $cache = false, $cacheExpiry = 600) + { + $data = $this->query($query, $cache, $cacheExpiry); - return ($result === false) ? [] : $result; - } + if (strpos($query, 'SQL_CALC_FOUND_ROWS') === false) { + return $data; + } - /** - * Returns a multidimensional array of result of the query function return and the count of found rows - * Note: Query passed to this function SHOULD include SQL_CALC_FOUND_ROWS - * Optional: Pass true to cache the result with a cache server. - * - * @param string $query SQL to execute. - * @param bool $cache Indicates if the query result should be cached. - * @param int $cacheExpiry The time in seconds before deleting the query result from the cache server. - * - * @return array Array of results (possibly empty) on success, empty array on failure. - */ - public function queryCalc($query, $cache = false, $cacheExpiry = 600) - { - $data = $this->query($query, $cache, $cacheExpiry); + // Remove LIMIT and OFFSET from query to allow queryCalc usage with browse + $query = preg_replace('#(\s+LIMIT\s+\d+)?\s+OFFSET\s+\d+\s*$#i', '', $query); - if (strpos($query, 'SQL_CALC_FOUND_ROWS') === false) { - return $data; - } + if ($cache === true && $this->cacheEnabled === true) { + try { + $count = $this->cacheServer->get($this->cacheServer->createKey($query.'count')); + if ($count !== false) { + return ['total' => $count, 'result' => $data]; + } + } catch (CacheException $error) { + $this->echoError($error->getMessage(), 'queryCalc', 4); + } + } - // Remove LIMIT and OFFSET from query to allow queryCalc usage with browse - $query = preg_replace('#(\s+LIMIT\s+\d+)?\s+OFFSET\s+\d+\s*$#i', '', $query); + $result = $this->queryOneRow('SELECT FOUND_ROWS() AS total'); - if ($cache === true && $this->cacheEnabled === true) { - try { - $count = $this->cacheServer->get($this->cacheServer->createKey($query . 'count')); - if ($count !== false) { - return ['total' => $count, 'result' => $data]; - } - } catch (CacheException $error) { - $this->echoError($error->getMessage(), 'queryCalc', 4); - } - } + if ($result !== false && $cache === true && $this->cacheEnabled === true) { + $this->cacheServer->set($this->cacheServer->createKey($query.'count'), $result['total'], $cacheExpiry); + } - $result = $this->queryOneRow('SELECT FOUND_ROWS() AS total'); - - if ($result !== false && $cache === true && $this->cacheEnabled === true) { - $this->cacheServer->set($this->cacheServer->createKey($query . 'count'), $result['total'], $cacheExpiry); - } - - return + return [ 'total' => ($result === false ? 0 : $result['total']), - 'result' => $data + 'result' => $data, ]; - } + } - /** - * Main method for creating results as an array. - * - * @param string $query SQL to execute. - * - * @return array|boolean Array of results on success or false on failure. - */ - public function queryArray($query) - { - $result = false; - if (!empty($query)) { - $result = $this->queryDirect($query); + /** + * Main method for creating results as an array. + * + * @param string $query SQL to execute. + * + * @return array|bool Array of results on success or false on failure. + */ + public function queryArray($query) + { + $result = false; + if (! empty($query)) { + $result = $this->queryDirect($query); - if (!empty($result)) { - $result = $result->fetchAll(); - } - } + if (! empty($result)) { + $result = $result->fetchAll(); + } + } - return $result; - } + return $result; + } - /** - * Returns all results as an associative array. - * - * Do not use this function for large dat-asets, as it can cripple the Db server and use huge - * amounts of RAM. Instead iterate through the data. - * - * @param string $query The query to execute. - * - * @return array|boolean Array of results on success, false otherwise. - */ - public function queryAssoc($query) - { - if ($query == '') { - return false; - } - $mode = $this->pdo->getAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE); - if ($mode != \PDO::FETCH_ASSOC) { - $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC); - } + /** + * Returns all results as an associative array. + * + * Do not use this function for large dat-asets, as it can cripple the Db server and use huge + * amounts of RAM. Instead iterate through the data. + * + * @param string $query The query to execute. + * + * @return array|bool Array of results on success, false otherwise. + */ + public function queryAssoc($query) + { + if ($query == '') { + return false; + } + $mode = $this->pdo->getAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE); + if ($mode != \PDO::FETCH_ASSOC) { + $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC); + } - $result = $this->queryArray($query); + $result = $this->queryArray($query); - if ($mode != \PDO::FETCH_ASSOC) { - $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, $mode); // Restore old mode - } - return $result; - } + if ($mode != \PDO::FETCH_ASSOC) { + $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, $mode); // Restore old mode + } - /** - * Query without returning an empty array like our function query(). http://php.net/manual/en/pdo.query.php - * - * @param string $query The query to run. - * @param bool $ignore Ignore errors, do not log them? - * - * @return bool|\PDOStatement - */ - public function queryDirect($query, $ignore = false) - { - if (!$this->parseQuery($query)) { - return false; - } + return $result; + } - try { - $result = $this->pdo->query($query); - } catch (\PDOException $e) { + /** + * Query without returning an empty array like our function query(). http://php.net/manual/en/pdo.query.php. + * + * @param string $query The query to run. + * @param bool $ignore Ignore errors, do not log them? + * + * @return bool|\PDOStatement + */ + public function queryDirect($query, $ignore = false) + { + if (! $this->parseQuery($query)) { + return false; + } + + try { + $result = $this->pdo->query($query); + } catch (\PDOException $e) { // Check if we lost connection to MySQL. - if ($this->_checkGoneAway($e->getMessage()) !== false) { + if ($this->_checkGoneAway($e->getMessage()) !== false) { // Reconnect to MySQL. - if ($this->_reconnect() === true) { + if ($this->_reconnect() === true) { // If we reconnected, retry the query. - $result = $this->queryDirect($query); + $result = $this->queryDirect($query); + } else { + // If we are not reconnected, return false. + $result = false; + } + } else { + if ($ignore === false) { + $this->echoError($e->getMessage(), 'queryDirect', 4, false); + if ($this->_debug) { + $this->debugging->log(__CLASS__, __FUNCTION__, $query, Logger::LOG_SQL); + } + } + $result = false; + } + } - } else { - // If we are not reconnected, return false. - $result = false; - } + return $result; + } - } else { - if ($ignore === false) { - $this->echoError($e->getMessage(), 'queryDirect', 4, false); - if ($this->_debug) { - $this->debugging->log(__CLASS__, __FUNCTION__, $query, Logger::LOG_SQL); - } - } - $result = false; - } - } - return $result; - } + /** + * Reconnect to MySQL when the connection has been lost. + * + * @see ping(), _checkGoneAway() for checking the connection. + * + * @return bool + */ + protected function _reconnect() + { + $this->initialiseDatabase(); - /** - * Reconnect to MySQL when the connection has been lost. - * - * @see ping(), _checkGoneAway() for checking the connection. - * - * @return bool - */ - protected function _reconnect() - { - $this->initialiseDatabase(); + // Check if we are really connected to MySQL. + if ($this->ping() === false) { + // If we are not reconnected, return false. + return false; + } - // Check if we are really connected to MySQL. - if ($this->ping() === false) { - // If we are not reconnected, return false. - return false; - } - return true; - } + return true; + } - /** - * Verify that we've lost a connection to MySQL. - * - * @param string $errorMessage - * - * @return bool - */ - protected function _checkGoneAway($errorMessage) - { - if (stripos($errorMessage, 'MySQL server has gone away') !== false) { - return true; - } - return false; - } + /** + * Verify that we've lost a connection to MySQL. + * + * @param string $errorMessage + * + * @return bool + */ + protected function _checkGoneAway($errorMessage) + { + if (stripos($errorMessage, 'MySQL server has gone away') !== false) { + return true; + } - /** - * Returns the first row of the query. - * - * @param string $query - * @param bool $appendLimit - * - * @return array|bool - */ - public function queryOneRow($query, $appendLimit = true) - { - // Force the query to only return 1 row, so queryArray doesn't potentially run out of memory on a large data set. - // First check if query already contains a LIMIT clause. - if (preg_match('#\s+LIMIT\s+(?P<lower>\d+)(,\s+(?P<upper>\d+))?(;)?$#i', $query, $matches)) { - if (!isset($matches['upper']) && isset($matches['lower']) && $matches['lower'] == 1) { - // good it's already correctly set. - } else { - // We have a limit, but it's not for a single row - return false; - } + return false; + } - } else if ($appendLimit) { - $query .= ' LIMIT 1'; - } + /** + * Returns the first row of the query. + * + * @param string $query + * @param bool $appendLimit + * + * @return array|bool + */ + public function queryOneRow($query, $appendLimit = true) + { + // Force the query to only return 1 row, so queryArray doesn't potentially run out of memory on a large data set. + // First check if query already contains a LIMIT clause. + if (preg_match('#\s+LIMIT\s+(?P<lower>\d+)(,\s+(?P<upper>\d+))?(;)?$#i', $query, $matches)) { + if (! isset($matches['upper']) && isset($matches['lower']) && $matches['lower'] == 1) { + // good it's already correctly set. + } else { + // We have a limit, but it's not for a single row + return false; + } + } elseif ($appendLimit) { + $query .= ' LIMIT 1'; + } - $rows = $this->query($query); - if (!$rows || count($rows) == 0) { - $rows = false; - } + $rows = $this->query($query); + if (! $rows || count($rows) == 0) { + $rows = false; + } - return is_array($rows) ? $rows[0] : $rows; - } + return is_array($rows) ? $rows[0] : $rows; + } - /** - * Optimises/repairs tables on mysql. - * - * @param bool $admin If we are on web, don't echo. - * @param string $type 'full' | '' Force optimize of all tables. - * 'space' Optimise tables with 5% or more free space. - * 'analyze' Analyze tables to rebuild statistics. - * @param bool $local Only analyze local tables. Good if running replication. - * @param array $tableList (optional) Names of tables to analyze. - * - * @return int Quantity optimized/analyzed - */ - public function optimise($admin = false, $type = '', $local = false, $tableList = []) - { - $tableAnd = ''; - if (count($tableList)) { - foreach ($tableList as $tableName) { - $tableAnd .= ($this->escapeString($tableName) . ','); - } - $tableAnd = (' AND Name IN (' . rtrim($tableAnd, ',') . ')'); - } + /** + * Optimises/repairs tables on mysql. + * + * @param bool $admin If we are on web, don't echo. + * @param string $type 'full' | '' Force optimize of all tables. + * 'space' Optimise tables with 5% or more free space. + * 'analyze' Analyze tables to rebuild statistics. + * @param bool $local Only analyze local tables. Good if running replication. + * @param array $tableList (optional) Names of tables to analyze. + * + * @return int Quantity optimized/analyzed + */ + public function optimise($admin = false, $type = '', $local = false, $tableList = []) + { + $tableAnd = ''; + if (count($tableList)) { + foreach ($tableList as $tableName) { + $tableAnd .= ($this->escapeString($tableName).','); + } + $tableAnd = (' AND Name IN ('.rtrim($tableAnd, ',').')'); + } - switch ($type) { + switch ($type) { case 'space': - $tableArray = $this->queryDirect('SHOW TABLE STATUS WHERE Data_free / Data_length > 0.005' . $tableAnd); - $myIsamTables = $this->queryDirect("SHOW TABLE STATUS WHERE ENGINE LIKE 'myisam' AND Data_free / Data_length > 0.005" . $tableAnd); + $tableArray = $this->queryDirect('SHOW TABLE STATUS WHERE Data_free / Data_length > 0.005'.$tableAnd); + $myIsamTables = $this->queryDirect("SHOW TABLE STATUS WHERE ENGINE LIKE 'myisam' AND Data_free / Data_length > 0.005".$tableAnd); break; case 'analyze': case '': case 'full': default: - $tableArray = $this->queryDirect('SHOW TABLE STATUS WHERE 1=1' . $tableAnd); - $myIsamTables = $this->queryDirect("SHOW TABLE STATUS WHERE ENGINE LIKE 'myisam'" . $tableAnd); + $tableArray = $this->queryDirect('SHOW TABLE STATUS WHERE 1=1'.$tableAnd); + $myIsamTables = $this->queryDirect("SHOW TABLE STATUS WHERE ENGINE LIKE 'myisam'".$tableAnd); break; } - $optimised = 0; - if ($tableArray instanceof \Traversable && $tableArray->rowCount()) { + $optimised = 0; + if ($tableArray instanceof \Traversable && $tableArray->rowCount()) { + $tableNames = ''; + foreach ($tableArray as $table) { + $tableNames .= $table['name'].','; + } + $tableNames = rtrim($tableNames, ','); - $tableNames = ''; - foreach ($tableArray as $table) { - $tableNames .= $table['name'] . ','; - } - $tableNames = rtrim($tableNames, ','); + $local = ($local ? 'LOCAL' : ''); + if ($type === 'analyze') { + $this->queryExec(sprintf('ANALYZE %s TABLE %s', $local, $tableNames)); + $this->logOptimize($admin, 'ANALYZE', $tableNames); + } else { + $this->queryExec(sprintf('OPTIMIZE %s TABLE %s', $local, $tableNames)); + $this->logOptimize($admin, 'OPTIMIZE', $tableNames); - $local = ($local ? 'LOCAL' : ''); - if ($type === 'analyze') { - $this->queryExec(sprintf('ANALYZE %s TABLE %s', $local, $tableNames)); - $this->logOptimize($admin, 'ANALYZE', $tableNames); - } else { + if ($myIsamTables instanceof \Traversable && $myIsamTables->rowCount()) { + $tableNames = ''; + foreach ($myIsamTables as $table) { + $tableNames .= $table['name'].','; + } + $tableNames = rtrim($tableNames, ','); + $this->queryExec(sprintf('REPAIR %s TABLE %s', $local, $tableNames)); + $this->logOptimize($admin, 'REPAIR', $tableNames); + } + $this->queryExec(sprintf('FLUSH %s TABLES', $local)); + } + $optimised = $tableArray->rowCount(); + } - $this->queryExec(sprintf('OPTIMIZE %s TABLE %s', $local, $tableNames)); - $this->logOptimize($admin, 'OPTIMIZE', $tableNames); + return $optimised; + } - if ($myIsamTables instanceof \Traversable && $myIsamTables->rowCount()) { - $tableNames = ''; - foreach ($myIsamTables as $table) { - $tableNames .= $table['name'] . ','; - } - $tableNames = rtrim($tableNames, ','); - $this->queryExec(sprintf('REPAIR %s TABLE %s', $local, $tableNames)); - $this->logOptimize($admin, 'REPAIR', $tableNames); - } - $this->queryExec(sprintf('FLUSH %s TABLES', $local)); - } - $optimised = $tableArray->rowCount(); - } + /** + * Log/echo repaired/optimized/analyzed tables. + * + * @param bool $web If we are on web, don't echo. + * @param string $type ANALYZE|OPTIMIZE|REPAIR + * @param string $tables Table names. + * + * @void + */ + private function logOptimize($web, $type, $tables) + { + $message = $type.' ('.$tables.')'; + if ($web === false) { + echo $this->log->primary($message); + } + if ($this->_debug) { + $this->debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_INFO); + } + } - return $optimised; - } + /** + * Turns off autocommit until commit() is ran. http://www.php.net/manual/en/pdo.begintransaction.php. + * + * @return bool + */ + public function beginTransaction() + { + if (NN_USE_SQL_TRANSACTIONS) { + return $this->pdo->beginTransaction(); + } - /** - * Log/echo repaired/optimized/analyzed tables. - * - * @param bool $web If we are on web, don't echo. - * @param string $type ANALYZE|OPTIMIZE|REPAIR - * @param string $tables Table names. - * - * @access private - * @void - */ - private function logOptimize($web, $type, $tables) - { - $message = $type . ' (' . $tables . ')'; - if ($web === false) { - echo $this->log->primary($message); + return true; + } - } - if ($this->_debug) { - $this->debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_INFO); - } - } + /** + * Commits a transaction. http://www.php.net/manual/en/pdo.commit.php. + * + * @return bool + */ + public function Commit() + { + if (NN_USE_SQL_TRANSACTIONS) { + return $this->pdo->commit(); + } - /** - * Turns off autocommit until commit() is ran. http://www.php.net/manual/en/pdo.begintransaction.php - * - * @return bool - */ - public function beginTransaction() - { - if (NN_USE_SQL_TRANSACTIONS) { - return $this->pdo->beginTransaction(); - } - return true; - } + return true; + } - /** - * Commits a transaction. http://www.php.net/manual/en/pdo.commit.php - * - * @return bool - */ - public function Commit() - { - if (NN_USE_SQL_TRANSACTIONS) { - return $this->pdo->commit(); - } - return true; - } + /** + * Rollback transcations. http://www.php.net/manual/en/pdo.rollback.php. + * + * @return bool + */ + public function Rollback() + { + if (NN_USE_SQL_TRANSACTIONS) { + return $this->pdo->rollBack(); + } - /** - * Rollback transcations. http://www.php.net/manual/en/pdo.rollback.php - * - * @return bool - */ - public function Rollback() - { - if (NN_USE_SQL_TRANSACTIONS) { - return $this->pdo->rollBack(); - } - return true; - } + return true; + } - public function setCovers() - { - $path = Settings::value([ + public function setCovers() + { + $path = Settings::value([ 'section' => 'site', 'subsection' => 'main', 'name' => 'coverspath', 'setting' => 'coverspath', ]); - Utility::setCoversConstant($path); - } + Utility::setCoversConstant($path); + } - public function rowToArray(array $row) - { - $this->settings[$row['setting']] = $row['value']; - } + public function rowToArray(array $row) + { + $this->settings[$row['setting']] = $row['value']; + } - public function rowsToArray(array $rows) - { - foreach ($rows as $row) { - if (is_array($row)) { - $this->rowToArray($row); - } - } + public function rowsToArray(array $rows) + { + foreach ($rows as $row) { + if (is_array($row)) { + $this->rowToArray($row); + } + } - return $this->settings; - } + return $this->settings; + } - public function settingsUpdate($form) - { - $error = $this->settingsValidate($form); + public function settingsUpdate($form) + { + $error = $this->settingsValidate($form); - if ($error === null) { - $sql = $sqlKeys = []; - foreach ($form as $settingK => $settingV) { - $sql[] = sprintf("WHEN %s THEN %s", + if ($error === null) { + $sql = $sqlKeys = []; + foreach ($form as $settingK => $settingV) { + $sql[] = sprintf('WHEN %s THEN %s', $this->escapeString($settingK), $this->escapeString($settingV)); - $sqlKeys[] = $this->escapeString($settingK); - } + $sqlKeys[] = $this->escapeString($settingK); + } - $this->queryExec( - sprintf("UPDATE settings SET value = CASE setting %s END WHERE setting IN (%s)", + $this->queryExec( + sprintf('UPDATE settings SET value = CASE setting %s END WHERE setting IN (%s)', implode(' ', $sql), implode(', ', $sqlKeys) ) ); - } else { - $form = $error; - } + } else { + $form = $error; + } - return $form; - } + return $form; + } - protected function settingsValidate(array $fields) - { - $defaults = [ + protected function settingsValidate(array $fields) + { + $defaults = [ 'checkpasswordedrar' => false, 'ffmpegpath' => '', 'mediainfopath' => '', @@ -1112,215 +1113,218 @@ class DB extends \PDO 'unrarpath' => '', 'yydecoderpath' => '', ]; - $fields += $defaults; // Make sure keys exist to avoid error notices. - ksort($fields); - // Validate settings - $fields['nzbpath'] = Utility::trailingSlash($fields['nzbpath']); - $error = null; - switch (true) { - case ($fields['mediainfopath'] != '' && !is_file($fields['mediainfopath'])): + $fields += $defaults; // Make sure keys exist to avoid error notices. + ksort($fields); + // Validate settings + $fields['nzbpath'] = Utility::trailingSlash($fields['nzbpath']); + $error = null; + switch (true) { + case $fields['mediainfopath'] != '' && ! is_file($fields['mediainfopath']): $error = Settings::ERR_BADMEDIAINFOPATH; break; - case ($fields['ffmpegpath'] != '' && !is_file($fields['ffmpegpath'])): + case $fields['ffmpegpath'] != '' && ! is_file($fields['ffmpegpath']): $error = Settings::ERR_BADFFMPEGPATH; break; - case ($fields['unrarpath'] != '' && !is_file($fields['unrarpath'])): + case $fields['unrarpath'] != '' && ! is_file($fields['unrarpath']): $error = Settings::ERR_BADUNRARPATH; break; - case (empty($fields['nzbpath'])): + case empty($fields['nzbpath']): $error = Settings::ERR_BADNZBPATH_UNSET; break; - case (!file_exists($fields['nzbpath']) || !is_dir($fields['nzbpath'])): + case ! file_exists($fields['nzbpath']) || ! is_dir($fields['nzbpath']): $error = Settings::ERR_BADNZBPATH; break; - case (!is_readable($fields['nzbpath'])): + case ! is_readable($fields['nzbpath']): $error = Settings::ERR_BADNZBPATH_UNREADABLE; break; - case ($fields['checkpasswordedrar'] == 1 && !is_file($fields['unrarpath'])): + case $fields['checkpasswordedrar'] == 1 && ! is_file($fields['unrarpath']): $error = Settings::ERR_DEEPNOUNRAR; break; - case ($fields['tmpunrarpath'] != '' && !file_exists($fields['tmpunrarpath'])): + case $fields['tmpunrarpath'] != '' && ! file_exists($fields['tmpunrarpath']): $error = Settings::ERR_BADTMPUNRARPATH; break; - case ($fields['yydecoderpath'] != '' && + case $fields['yydecoderpath'] != '' && $fields['yydecoderpath'] !== 'simple_php_yenc_decode' && - !file_exists($fields['yydecoderpath'])): + ! file_exists($fields['yydecoderpath']): $error = Settings::ERR_BAD_YYDECODER_PATH; } - return $error; - } + return $error; + } - /** - * PHP interpretation of MySQL's from_unixtime method. - * @param int $utime UnixTime - * - * @return string - */ - public function from_unixtime($utime) - { - return 'FROM_UNIXTIME(' . $utime . ')'; - } + /** + * PHP interpretation of MySQL's from_unixtime method. + * @param int $utime UnixTime + * + * @return string + */ + public function from_unixtime($utime) + { + return 'FROM_UNIXTIME('.$utime.')'; + } - /** - * PHP interpretation of mysql's unix_timestamp method. - * @param string $date - * - * @return int - */ - public function unix_timestamp($date) - { - return strtotime($date); - } + /** + * PHP interpretation of mysql's unix_timestamp method. + * @param string $date + * + * @return int + */ + public function unix_timestamp($date) + { + return strtotime($date); + } - /** - * Get a string for MySQL with a column name in between - * ie: UNIX_TIMESTAMP(column_name) AS outputName - * - * @param string $column The datetime column. - * @param string $outputName The name to store the SQL data into. (the word after AS) - * - * @return string - */ - public function unix_timestamp_column($column, $outputName = 'unix_time') - { - return ('UNIX_TIMESTAMP(' . $column . ') AS ' . $outputName); - } + /** + * Get a string for MySQL with a column name in between + * ie: UNIX_TIMESTAMP(column_name) AS outputName. + * + * @param string $column The datetime column. + * @param string $outputName The name to store the SQL data into. (the word after AS) + * + * @return string + */ + public function unix_timestamp_column($column, $outputName = 'unix_time') + { + return 'UNIX_TIMESTAMP('.$column.') AS '.$outputName; + } - /** - * @return string - */ - public function uuid() - { - return Uuid::uuid4()->toString(); - } + /** + * @return string + */ + public function uuid() + { + return Uuid::uuid4()->toString(); + } - /** - * Checks whether the connection to the server is working. Optionally restart a new connection. - * NOTE: Restart does not happen if PDO is not using exceptions (PHP's default configuration). - * In this case check the return value === false. - * - * @param boolean $restart Whether an attempt should be made to reinitialise the Db object on failure. - * - * @return boolean - */ - public function ping($restart = false) - { - try { - return (bool)$this->pdo->query('SELECT 1+1'); - } catch (\PDOException $e) { - if ($restart == true) { - $this->initialiseDatabase(); - } - return false; - } - } + /** + * Checks whether the connection to the server is working. Optionally restart a new connection. + * NOTE: Restart does not happen if PDO is not using exceptions (PHP's default configuration). + * In this case check the return value === false. + * + * @param bool $restart Whether an attempt should be made to reinitialise the Db object on failure. + * + * @return bool + */ + public function ping($restart = false) + { + try { + return (bool) $this->pdo->query('SELECT 1+1'); + } catch (\PDOException $e) { + if ($restart == true) { + $this->initialiseDatabase(); + } - /** - * Prepares a statement to be run by the Db engine. - * To run the statement use the returned $statement with ->execute(); - * - * Ideally the signature would have array before $options but that causes a strict warning. - * - * @param string $query SQL query to run, with optional place holders. - * @param array $options Driver options. - * - * @return false|\PDOstatement on success false on failure. - * - * @link http://www.php.net/pdo.prepare.php - */ - public function Prepare($query, $options = []) - { - try { - $PDOstatement = $this->pdo->prepare($query, $options); - } catch (\PDOException $e) { - if ($this->_debug) { - $this->debugging->log(__CLASS__, __FUNCTION__, $e->getMessage(), Logger::LOG_INFO); - } - echo $this->log->error("\n" . $e->getMessage()); - $PDOstatement = false; - } - return $PDOstatement; - } + return false; + } + } - /** - * Retrieve db attributes http://us3.php.net/manual/en/pdo.getattribute.php - * - * @param int $attribute - * - * @return false|mixed - */ - public function getAttribute($attribute) - { - $result = false; - if ($attribute != '') { - try { - $result = $this->pdo->getAttribute($attribute); - } catch (\PDOException $e) { - if ($this->_debug) { - $this->debugging->log(__CLASS__, __FUNCTION__, $e->getMessage(), Logger::LOG_INFO); - } - echo $this->log->error("\n" . $e->getMessage()); - $result = false; - } + /** + * Prepares a statement to be run by the Db engine. + * To run the statement use the returned $statement with ->execute();. + * + * Ideally the signature would have array before $options but that causes a strict warning. + * + * @param string $query SQL query to run, with optional place holders. + * @param array $options Driver options. + * + * @return false|\PDOstatement on success false on failure. + * + * @link http://www.php.net/pdo.prepare.php + */ + public function Prepare($query, $options = []) + { + try { + $PDOstatement = $this->pdo->prepare($query, $options); + } catch (\PDOException $e) { + if ($this->_debug) { + $this->debugging->log(__CLASS__, __FUNCTION__, $e->getMessage(), Logger::LOG_INFO); + } + echo $this->log->error("\n".$e->getMessage()); + $PDOstatement = false; + } - } - return $result; - } + return $PDOstatement; + } - /** - * Returns the stored Db version string. - * - * @return string - */ - public function getDbVersion() - { - return $this->dbVersion; - } + /** + * Retrieve db attributes http://us3.php.net/manual/en/pdo.getattribute.php. + * + * @param int $attribute + * + * @return false|mixed + */ + public function getAttribute($attribute) + { + $result = false; + if ($attribute != '') { + try { + $result = $this->pdo->getAttribute($attribute); + } catch (\PDOException $e) { + if ($this->_debug) { + $this->debugging->log(__CLASS__, __FUNCTION__, $e->getMessage(), Logger::LOG_INFO); + } + echo $this->log->error("\n".$e->getMessage()); + $result = false; + } + } - /** - * @param string $requiredVersion The minimum version to compare against - * - * @return bool|null TRUE if Db version is greater than or eaqual to $requiredVersion, - * false if not, and null if the version isn't available to check against. - */ - public function isDbVersionAtLeast($requiredVersion) - { - if (empty($this->dbVersion)) { - return null; - } - return version_compare($requiredVersion, $this->dbVersion, '<='); - } + return $result; + } - /** - * Performs the fetch from the Db server and stores the resulting Major.Minor.Version number. - */ - private function fetchDbVersion() - { - $result = $this->queryOneRow("SELECT VERSION() AS version"); - if (!empty($result)) { - $dummy = explode('-', $result['version'], 2); - $this->dbVersion = $dummy[0]; - } - } + /** + * Returns the stored Db version string. + * + * @return string + */ + public function getDbVersion() + { + return $this->dbVersion; + } - /** - * Checks if the query is empty. Cleans the query of whitespace if needed. - * - * @param string $query - * - * @return boolean - */ - private function parseQuery(&$query) - { - if (empty($query)) { - return false; - } + /** + * @param string $requiredVersion The minimum version to compare against + * + * @return bool|null TRUE if Db version is greater than or eaqual to $requiredVersion, + * false if not, and null if the version isn't available to check against. + */ + public function isDbVersionAtLeast($requiredVersion) + { + if (empty($this->dbVersion)) { + return null; + } - if (NN_QUERY_STRIP_WHITESPACE) { - $query = Utility::collapseWhiteSpace($query); - } - return true; - } + return version_compare($requiredVersion, $this->dbVersion, '<='); + } + /** + * Performs the fetch from the Db server and stores the resulting Major.Minor.Version number. + */ + private function fetchDbVersion() + { + $result = $this->queryOneRow('SELECT VERSION() AS version'); + if (! empty($result)) { + $dummy = explode('-', $result['version'], 2); + $this->dbVersion = $dummy[0]; + } + } + + /** + * Checks if the query is empty. Cleans the query of whitespace if needed. + * + * @param string $query + * + * @return bool + */ + private function parseQuery(&$query) + { + if (empty($query)) { + return false; + } + + if (NN_QUERY_STRIP_WHITESPACE) { + $query = Utility::collapseWhiteSpace($query); + } + + return true; + } } diff --git a/nntmux/db/DbUpdate.php b/nntmux/db/DbUpdate.php index c4f0a79f5..8b7d08de5 100755 --- a/nntmux/db/DbUpdate.php +++ b/nntmux/db/DbUpdate.php @@ -18,118 +18,117 @@ * @author niel * @copyright 2014 nZEDb */ + namespace nntmux\db; -use App\Models\Settings; use nntmux\ColorCLI; -use nntmux\db\DB; use nntmux\utility\Git; +use App\Models\Settings; use nntmux\utility\Utility; - class DbUpdate { - public $backedup; + public $backedup; - /** - * @var DB Instance variable for DB object. - */ - public $pdo; + /** + * @var DB Instance variable for DB object. + */ + public $pdo; - /** - * @var Git instance - */ - public $git; + /** + * @var Git instance + */ + public $git; - /** - * @var object Instance variable for logging object. Currently only ColorCLI supported, - * but expanding for full logging with agnostic API planned. - */ - public $log; + /** + * @var object Instance variable for logging object. Currently only ColorCLI supported, + * but expanding for full logging with agnostic API planned. + */ + public $log; - /** - * @var object Instance object for sites/settings class. - */ - public $settings; + /** + * @var object Instance object for sites/settings class. + */ + public $settings; - protected $_DbSystem; + protected $_DbSystem; - /** - * @var bool Has the Db been backed up? - */ - private $backedUp = false; + /** + * @var bool Has the Db been backed up? + */ + private $backedUp = false; - /** - * @var bool Should we perform a backup? - */ - private $backup; + /** + * @var bool Should we perform a backup? + */ + private $backup; - public function __construct(array $options = []) - { - $options += [ + public function __construct(array $options = []) + { + $options += [ 'backup' => true, 'db' => null, 'git' => new Git(), 'logger' => new ColorCLI(), ]; - $this->backup = $options['backup']; - $this->git = $options['git']; - $this->log = $options['logger']; - // Must be DB not Settings because the Settings table may not exist yet. - $this->pdo = (($options['db'] instanceof DB) ? $options['db'] : new DB()); - $this->_DbSystem = strtolower($this->pdo->DbSystem()); - } + $this->backup = $options['backup']; + $this->git = $options['git']; + $this->log = $options['logger']; + // Must be DB not Settings because the Settings table may not exist yet. + $this->pdo = (($options['db'] instanceof DB) ? $options['db'] : new DB()); + $this->_DbSystem = strtolower($this->pdo->DbSystem()); + } - /** - * @param array $options - */ - public function loadTables(array $options = []): void - { - $defaults = [ + /** + * @param array $options + */ + public function loadTables(array $options = []): void + { + $defaults = [ 'enclosedby' => null, 'ext' => 'tsv', 'files' => [], - 'path' => NN_RES . 'db' . DS . 'schema' . DS . 'data', - 'regex' => '#^' . Utility::PATH_REGEX . '(?P<order>\d+)-(?P<table>\w+)\.tsv$#', + 'path' => NN_RES.'db'.DS.'schema'.DS.'data', + 'regex' => '#^'.Utility::PATH_REGEX.'(?P<order>\d+)-(?P<table>\w+)\.tsv$#', ]; - $options += $defaults; + $options += $defaults; - $show = (Utility::isCLI() || NN_DEBUG); + $show = (Utility::isCLI() || NN_DEBUG); - $files = empty($options['files']) ? Utility::getDirFiles($options) : $options['files']; - natsort($files); - $local = $this->pdo->isLocalDb() ? '' : 'LOCAL '; - $enclosedby = empty($options['enclosedby']) ? '' : 'OPTIONALLY ENCLOSED BY "' . - $options['enclosedby'] . '"'; - $sql = 'LOAD DATA ' . - $local . 'INFILE "%s" IGNORE INTO TABLE `%s` FIELDS TERMINATED BY "\t" ' . $enclosedby . 'LINES TERMINATED BY "\n" IGNORE 1 LINES (%s)'; - foreach ($files as $file) { - if ($show === true) { - echo "File: $file\n"; - } + $files = empty($options['files']) ? Utility::getDirFiles($options) : $options['files']; + natsort($files); + $local = $this->pdo->isLocalDb() ? '' : 'LOCAL '; + $enclosedby = empty($options['enclosedby']) ? '' : 'OPTIONALLY ENCLOSED BY "'. + $options['enclosedby'].'"'; + $sql = 'LOAD DATA '. + $local.'INFILE "%s" IGNORE INTO TABLE `%s` FIELDS TERMINATED BY "\t" '.$enclosedby.'LINES TERMINATED BY "\n" IGNORE 1 LINES (%s)'; + foreach ($files as $file) { + if ($show === true) { + echo "File: $file\n"; + } - if (is_readable($file)) { - if (preg_match($options['regex'], $file, $matches)) { - $table = $matches['table']; - // Get the first line of the file which holds the columns used. - $handle = @fopen($file, 'rb'); - if (is_resource($handle)) { - $line = fgets($handle); - fclose($handle); - if ($line === false) { - echo "FAILED reading first line of '$file'\n"; - continue; - } - $fields = trim($line); + if (is_readable($file)) { + if (preg_match($options['regex'], $file, $matches)) { + $table = $matches['table']; + // Get the first line of the file which holds the columns used. + $handle = @fopen($file, 'rb'); + if (is_resource($handle)) { + $line = fgets($handle); + fclose($handle); + if ($line === false) { + echo "FAILED reading first line of '$file'\n"; + continue; + } + $fields = trim($line); - if ($show === true) { - ColorCLI::doEcho(ColorCLI::info('Inserting data into table: ' . $table)); - } - if (Utility::isWin()) { - $file = str_replace("\\", '\/', $file); - } - $this->pdo->exec("SET @@session.sql_mode = + if ($show === true) { + ColorCLI::doEcho(ColorCLI::info('Inserting data into table: '.$table)); + } + if (Utility::isWin()) { + $file = str_replace('\\', '\/', $file); + } + $this->pdo->exec("SET @@session.sql_mode = CASE WHEN @@session.sql_mode NOT LIKE '%NO_AUTO_VALUE_ON_ZERO%' THEN CASE WHEN LENGTH(@@session.sql_mode)>0 THEN CONCAT_WS(',',@@session.sql_mode,'NO_AUTO_VALUE_ON_ZERO') @@ -137,352 +136,351 @@ class DbUpdate END ELSE @@session.sql_mode END;"); - $this->pdo->queryExec(sprintf($sql, $file, $table, $fields)); - if ($table !== 'settings') { - $success = $this->pdo->query(sprintf('SELECT COUNT(id) AS num FROM %s', $table)); - if (empty($success[0]['num'])) { - ColorCLI::doEcho(ColorCLI::error('Failed to insert data into table: ' . $table)); - } else { - ColorCLI::doEcho(ColorCLI::notice('Successfully inserted data into ' . $table . ' table')); - } - } - } else { - exit("Failed to open file: '$file'\n"); - } - } else { - echo "Incorrectly formatted filename '$file' (should match " . - str_replace('#', '', $options['regex']) . "\n"; - } - } else { - echo $this->log->error(" Unable to read file: '$file'"); - } - } - } + $this->pdo->queryExec(sprintf($sql, $file, $table, $fields)); + if ($table !== 'settings') { + $success = $this->pdo->query(sprintf('SELECT COUNT(id) AS num FROM %s', $table)); + if (empty($success[0]['num'])) { + ColorCLI::doEcho(ColorCLI::error('Failed to insert data into table: '.$table)); + } else { + ColorCLI::doEcho(ColorCLI::notice('Successfully inserted data into '.$table.' table')); + } + } + } else { + exit("Failed to open file: '$file'\n"); + } + } else { + echo "Incorrectly formatted filename '$file' (should match ". + str_replace('#', '', $options['regex'])."\n"; + } + } else { + echo $this->log->error(" Unable to read file: '$file'"); + } + } + } - /** - * Takes new files in the correct format from the patches directory and turns them into proper patches. - * - * The files should be name as '+x~<table>.sql' where x is a number starting at 1 for your first - * patch. <table> should be the name of the primary table affected. If you have to modify more - * than one table, consider splitting into multiple patches using different patch modifier - * numbers to order them. i.e. +1~settings.sql, +2~predb.sql, etc. - * - * @param array $options - * - * @throws \Exception - */ - public function newPatches(array $options = []): void - { - $defaults = [ - 'data' => NN_RES . 'db' . DS . 'schema' . DS . 'data' . DS, + /** + * Takes new files in the correct format from the patches directory and turns them into proper patches. + * + * The files should be name as '+x~<table>.sql' where x is a number starting at 1 for your first + * patch. <table> should be the name of the primary table affected. If you have to modify more + * than one table, consider splitting into multiple patches using different patch modifier + * numbers to order them. i.e. +1~settings.sql, +2~predb.sql, etc. + * + * @param array $options + * + * @throws \Exception + */ + public function newPatches(array $options = []): void + { + $defaults = [ + 'data' => NN_RES.'db'.DS.'schema'.DS.'data'.DS, 'ext' => 'sql', - 'path' => NN_RES . 'db' . DS . 'patches' . DS . $this->_DbSystem, - 'regex' => '#^' . Utility::PATH_REGEX . '\+(?P<order>\d+)~(?P<table>\w+)\.sql$#', + 'path' => NN_RES.'db'.DS.'patches'.DS.$this->_DbSystem, + 'regex' => '#^'.Utility::PATH_REGEX.'\+(?P<order>\d+)~(?P<table>\w+)\.sql$#', 'safe' => true, ]; - $options += $defaults; + $options += $defaults; - $this->processPatches(['safe' => $options['safe']]); // Make sure we are completely up to date! + $this->processPatches(['safe' => $options['safe']]); // Make sure we are completely up to date! - echo $this->log->primaryOver('Looking for new patches...'); - $files = Utility::getDirFiles($options); + echo $this->log->primaryOver('Looking for new patches...'); + $files = Utility::getDirFiles($options); - $count = count($files); - echo $this->log->header(" $count found"); - if ($count > 0) { - echo $this->log->header('Processing...'); - natsort($files); - $local = $this->pdo->isLocalDb() ? '' : 'LOCAL '; + $count = count($files); + echo $this->log->header(" $count found"); + if ($count > 0) { + echo $this->log->header('Processing...'); + natsort($files); + $local = $this->pdo->isLocalDb() ? '' : 'LOCAL '; - foreach ($files as $file) { - if (!preg_match($options['regex'], $file, $matches)) { - $this->log->error("$file does not match the pattern {$options['regex']}\nPlease fix this before continuing"); - } else { - echo $this->log->header('Processing patch file: ' . $file); - $this->splitSQL($file, ['local' => $local, 'data' => $options['data']]); - $current = Settings::value('..sqlpatch'); - $current++; - Settings::query()->where('setting', '=', 'sqlpatch')->update(['value' => $current]); - $newName = $matches['drive'] . $matches['path'] . - str_pad($current, 4, '0', STR_PAD_LEFT) . '~' . - $matches['table'] . '.sql'; - rename($matches[0], $newName); - $this->git->add($newName); - if ($this->git->isCommited($this->git->getBranch() . ':' . str_replace(NN_ROOT, '', $matches[0]))) { - $this->git->add(" -u {$matches[0]}"); // remove old filename from the index. - } - } - } - } - } + foreach ($files as $file) { + if (! preg_match($options['regex'], $file, $matches)) { + $this->log->error("$file does not match the pattern {$options['regex']}\nPlease fix this before continuing"); + } else { + echo $this->log->header('Processing patch file: '.$file); + $this->splitSQL($file, ['local' => $local, 'data' => $options['data']]); + $current = Settings::value('..sqlpatch'); + $current++; + Settings::query()->where('setting', '=', 'sqlpatch')->update(['value' => $current]); + $newName = $matches['drive'].$matches['path']. + str_pad($current, 4, '0', STR_PAD_LEFT).'~'. + $matches['table'].'.sql'; + rename($matches[0], $newName); + $this->git->add($newName); + if ($this->git->isCommited($this->git->getBranch().':'.str_replace(NN_ROOT, '', $matches[0]))) { + $this->git->add(" -u {$matches[0]}"); // remove old filename from the index. + } + } + } + } + } - /** - * @param array $options - * - * @return int - * @throws \RuntimeException - */ - public function processPatches(array $options = []): int - { - $patched = 0; - $defaults = [ - 'data' => NN_RES . 'db' . DS . 'schema' . DS . 'data' . DS, + /** + * @param array $options + * + * @return int + * @throws \RuntimeException + */ + public function processPatches(array $options = []): int + { + $patched = 0; + $defaults = [ + 'data' => NN_RES.'db'.DS.'schema'.DS.'data'.DS, 'ext' => 'sql', - 'path' => NN_RES . 'db' . DS . 'patches' . DS . $this->_DbSystem, - 'regex' => '#^' . Utility::PATH_REGEX . '(?P<patch>\d{4})~(?P<table>\w+)\.sql$#', + 'path' => NN_RES.'db'.DS.'patches'.DS.$this->_DbSystem, + 'regex' => '#^'.Utility::PATH_REGEX.'(?P<patch>\d{4})~(?P<table>\w+)\.sql$#', 'safe' => true, ]; - $options += $defaults; + $options += $defaults; - $currentVersion = Settings::value('..sqlpatch'); - if (!is_numeric($currentVersion)) { - exit("Bad sqlpatch value: '$currentVersion'\n"); - } + $currentVersion = Settings::value('..sqlpatch'); + if (! is_numeric($currentVersion)) { + exit("Bad sqlpatch value: '$currentVersion'\n"); + } - $files = empty($options['files']) ? Utility::getDirFiles($options) : $options['files']; + $files = empty($options['files']) ? Utility::getDirFiles($options) : $options['files']; - if (count($files)) { - natsort($files); - $local = $this->pdo->isLocalDb() ? '' : 'LOCAL '; - $data = $options['data']; - echo $this->log->primary('Looking for unprocessed patches...'); - foreach ($files as $file) { - $setPatch = false; - $fp = fopen($file, 'r'); - $patch = fread($fp, filesize($file)); + if (count($files)) { + natsort($files); + $local = $this->pdo->isLocalDb() ? '' : 'LOCAL '; + $data = $options['data']; + echo $this->log->primary('Looking for unprocessed patches...'); + foreach ($files as $file) { + $setPatch = false; + $fp = fopen($file, 'r'); + $patch = fread($fp, filesize($file)); - if (preg_match($options['regex'], str_replace('\\', '/', $file), $matches)) { - $patch = (integer)$matches['patch']; - $setPatch = true; - } else if (preg_match( + if (preg_match($options['regex'], str_replace('\\', '/', $file), $matches)) { + $patch = (int) $matches['patch']; + $setPatch = true; + } elseif (preg_match( '/UPDATE `?site`? SET `?value`? = \'?(?P<patch>\d+)\'? WHERE `?setting`? = \'sqlpatch\'/i', $patch, $matches) ) { - $patch = (int)$matches['patch']; - } else { - throw new \RuntimeException('No patch information available, stopping!!'); - } - if ($patch > $currentVersion) { - echo $this->log->header('Processing patch file: ' . $file); - if (!$this->backedUp && $options['safe']) { - $this->_backupDb(); - } - $this->splitSQL($file, ['local' => $local, 'data' => $data]); - if ($setPatch) { - Settings::query()->where('setting', '=', 'sqlpatch')->update(['value' => $patch]); - } - $patched++; - } - } - } else { - exit($this->log->error("\nHave you changed the path to the patches folder, or do you have the right permissions?\n")); - } + $patch = (int) $matches['patch']; + } else { + throw new \RuntimeException('No patch information available, stopping!!'); + } + if ($patch > $currentVersion) { + echo $this->log->header('Processing patch file: '.$file); + if (! $this->backedUp && $options['safe']) { + $this->_backupDb(); + } + $this->splitSQL($file, ['local' => $local, 'data' => $data]); + if ($setPatch) { + Settings::query()->where('setting', '=', 'sqlpatch')->update(['value' => $patch]); + } + $patched++; + } + } + } else { + exit($this->log->error("\nHave you changed the path to the patches folder, or do you have the right permissions?\n")); + } - if ($patched === 0) { - echo $this->log->info("Nothing to patch, you are already on version $currentVersion"); - } - return $patched; - } + if ($patched === 0) { + echo $this->log->info("Nothing to patch, you are already on version $currentVersion"); + } - /** - * @param array $options - */ - public function processSQLFile(array $options = []): void - { - $defaults = [ - 'filepath' => NN_RES . 'db' . DS . 'schema' . DS . $this->_DbSystem . '-ddl.sql', + return $patched; + } + + /** + * @param array $options + */ + public function processSQLFile(array $options = []): void + { + $defaults = [ + 'filepath' => NN_RES.'db'.DS.'schema'.DS.$this->_DbSystem.'-ddl.sql', ]; - $options += $defaults; + $options += $defaults; - $sql = file_get_contents($options['filepath']); - $sql = str_replace(['DELIMITER $$', 'DELIMITER ;', '$$'], '', $sql); - $this->pdo->exec($sql); - } + $sql = file_get_contents($options['filepath']); + $sql = str_replace(['DELIMITER $$', 'DELIMITER ;', '$$'], '', $sql); + $this->pdo->exec($sql); + } - /** - * @param $file - * @param array $options - */ - public function splitSQL($file, array $options = []): void - { - $defaults = [ + /** + * @param $file + * @param array $options + */ + public function splitSQL($file, array $options = []): void + { + $defaults = [ 'data' => null, 'delimiter' => ';', 'local' => null, ]; - $options += $defaults; + $options += $defaults; - if (!empty($options['vars'])) { - extract($options['vars'], 'EXTR_OVERWRITE'); - } + if (! empty($options['vars'])) { + extract($options['vars'], 'EXTR_OVERWRITE'); + } - set_time_limit(0); + set_time_limit(0); - if (is_file($file)) { - $file = fopen($file, 'r, b'); + if (is_file($file)) { + $file = fopen($file, 'r, b'); - if (is_resource($file)) { - $query = []; + if (is_resource($file)) { + $query = []; - $delimiter = $options['delimiter']; - while (!feof($file)) { - $line = fgets($file); + $delimiter = $options['delimiter']; + while (! feof($file)) { + $line = fgets($file); - if ($line === false) { - continue; - } + if ($line === false) { + continue; + } - // Skip comments. - if (preg_match('!^\s*(#|--|//)\s*(.+?)\s*$!', $line, $matches)) { - echo ColorCLI::info('COMMENT: ' . $matches[2]); - continue; - } + // Skip comments. + if (preg_match('!^\s*(#|--|//)\s*(.+?)\s*$!', $line, $matches)) { + echo ColorCLI::info('COMMENT: '.$matches[2]); + continue; + } - // Check for non default delimiters ($$ for example). - if (preg_match('#^\s*DELIMITER\s+(?P<delimiter>.+)\s*$#i', $line, $matches)) { - $delimiter = $matches['delimiter']; - if (NN_DEBUG) { - echo ColorCLI::debug("DEBUG: Delimiter switched to $delimiter"); - } - if ($delimiter !== $options['delimiter']) { - continue; - } - } + // Check for non default delimiters ($$ for example). + if (preg_match('#^\s*DELIMITER\s+(?P<delimiter>.+)\s*$#i', $line, $matches)) { + $delimiter = $matches['delimiter']; + if (NN_DEBUG) { + echo ColorCLI::debug("DEBUG: Delimiter switched to $delimiter"); + } + if ($delimiter !== $options['delimiter']) { + continue; + } + } - // Check if the line has delimiter that is non default ($$ for example). - if ($delimiter !== $options['delimiter'] && preg_match('#^(.+?)' . preg_quote($delimiter) . '\s*$#', $line, $matches)) { - // Check if the line has also the default delimiter (;), remove it. - if (preg_match('#^(.+?)' . preg_quote($options['delimiter']) . '\s*$#', $matches[1], $matches2)) { - $matches[1] = $matches2[1]; - } - // Change the non default delimiter ($$) to the default one(;). - $line = $matches[1] . $options['delimiter']; - } + // Check if the line has delimiter that is non default ($$ for example). + if ($delimiter !== $options['delimiter'] && preg_match('#^(.+?)'.preg_quote($delimiter).'\s*$#', $line, $matches)) { + // Check if the line has also the default delimiter (;), remove it. + if (preg_match('#^(.+?)'.preg_quote($options['delimiter']).'\s*$#', $matches[1], $matches2)) { + $matches[1] = $matches2[1]; + } + // Change the non default delimiter ($$) to the default one(;). + $line = $matches[1].$options['delimiter']; + } - $query[] = $line; + $query[] = $line; - if (preg_match('~' . preg_quote($delimiter, '~') . '\s*$~iS', $line) === 1) { - $query = trim(implode('', $query)); - if ($options['local'] !== null) { - $query = str_replace('{:local:}', $options['local'], $query); - } - if (!empty($options['data'])) { - $query = str_replace('{:data:}', $options['data'], $query); - } + if (preg_match('~'.preg_quote($delimiter, '~').'\s*$~iS', $line) === 1) { + $query = trim(implode('', $query)); + if ($options['local'] !== null) { + $query = str_replace('{:local:}', $options['local'], $query); + } + if (! empty($options['data'])) { + $query = str_replace('{:data:}', $options['data'], $query); + } - try { - $qry = $this->pdo->Prepare($query); - $qry->execute(); - echo $this->log->alternateOver('SUCCESS: ') . $this->log->primary($query); - } catch (\PDOException $e) { - // Log the problem and the query. - file_put_contents( - NN_LOGS . 'patcherrors.log', - '[' . date('r') . '] [ERROR] [' . - trim(preg_replace('/\s+/', ' ', $e->getMessage())) . ']' . PHP_EOL . - '[' . date('r') . '] [QUERY] [' . - trim(preg_replace('/\s+/', ' ', $query)) . ']' . PHP_EOL, + try { + $qry = $this->pdo->Prepare($query); + $qry->execute(); + echo $this->log->alternateOver('SUCCESS: ').$this->log->primary($query); + } catch (\PDOException $e) { + // Log the problem and the query. + file_put_contents( + NN_LOGS.'patcherrors.log', + '['.date('r').'] [ERROR] ['. + trim(preg_replace('/\s+/', ' ', $e->getMessage())).']'.PHP_EOL. + '['.date('r').'] [QUERY] ['. + trim(preg_replace('/\s+/', ' ', $query)).']'.PHP_EOL, FILE_APPEND ); - if ( + if ( in_array($e->errorInfo[1], [1091, 1060, 1061, 1071, 1146], false) || in_array($e->errorInfo[0], [23505, 42701, 42703, '42P07', '42P16'], false) ) { - if ($e->errorInfo[1] === 1060) { - echo $this->log->warning( - "$query The column already exists - No need to worry \{" . - $e->errorInfo[1] . "}.\n" + if ($e->errorInfo[1] === 1060) { + echo $this->log->warning( + "$query The column already exists - No need to worry \{". + $e->errorInfo[1]."}.\n" ); - } else { - echo $this->log->warning( - "$query Skipped - No need to worry \{" . - $e->errorInfo[1] . "}.\n" + } else { + echo $this->log->warning( + "$query Skipped - No need to worry \{". + $e->errorInfo[1]."}.\n" ); - } - } else { - if (preg_match('/ALTER IGNORE/i', $query)) { - $this->pdo->queryExec('SET SESSION old_alter_table = 1'); - try { - $this->pdo->exec($query); - echo $this->log->alternateOver('SUCCESS: ') . $this->log->primary($query); - } catch (\PDOException $e) { - exit($this->log->error("$query Failed \{" . $e->errorInfo[1] . "}\n\t" . $e->errorInfo[2])); - } - } else { - exit($this->log->error("$query Failed \{" . $e->errorInfo[1] . "}\n\t" . $e->errorInfo[2])); - } - } - } + } + } else { + if (preg_match('/ALTER IGNORE/i', $query)) { + $this->pdo->queryExec('SET SESSION old_alter_table = 1'); + try { + $this->pdo->exec($query); + echo $this->log->alternateOver('SUCCESS: ').$this->log->primary($query); + } catch (\PDOException $e) { + exit($this->log->error("$query Failed \{".$e->errorInfo[1]."}\n\t".$e->errorInfo[2])); + } + } else { + exit($this->log->error("$query Failed \{".$e->errorInfo[1]."}\n\t".$e->errorInfo[2])); + } + } + } - while (ob_get_level() > 0) { - ob_end_flush(); - } - flush(); - } + while (ob_get_level() > 0) { + ob_end_flush(); + } + flush(); + } - if (is_string($query) === true) { - $query = []; - } - } - } - } - } + if (is_string($query) === true) { + $query = []; + } + } + } + } + } - /** - * @param array $options - */ - public function updateSchemaData(array $options = []): void - { - $changed = false; - $default = [ + /** + * @param array $options + */ + public function updateSchemaData(array $options = []): void + { + $changed = false; + $default = [ 'file' => '10-settings.tsv', - 'path' => 'resources' . DS . 'db' . DS . 'schema' . DS . 'data' . DS, + 'path' => 'resources'.DS.'db'.DS.'schema'.DS.'data'.DS, 'regex' => '#^(?P<section>.*)\t(?P<subsection>.*)\t(?P<name>.*)\t(?P<value>.*)\t(?P<hint>.*)\t(?P<setting>.*)$#', - 'value' => function(array $matches) { - return "{$matches['section']}\t{$matches['subsection']}\t{$matches['name']}\t{$matches['value']}\t{$matches['hint']}\t{$matches['setting']}"; - } // WARNING: leaving this empty will blank not remove lines. + 'value' => function (array $matches) { + return "{$matches['section']}\t{$matches['subsection']}\t{$matches['name']}\t{$matches['value']}\t{$matches['hint']}\t{$matches['setting']}"; + }, // WARNING: leaving this empty will blank not remove lines. ]; - $options += $default; + $options += $default; - $file = []; - $filespec = Utility::trailingSlash($options['path']) . $options['path']; - if (file_exists($filespec) && ($file = file($filespec, FILE_IGNORE_NEW_LINES))) { - $count = count($file); - $index = 0; - while ($index < $count) { - if (preg_match($options['regex'], $file[$index], $matches)) { - if (VERBOSE) { - echo $this->log->primary('Matched: ' . $file[$index]); - } - $index++; + $file = []; + $filespec = Utility::trailingSlash($options['path']).$options['path']; + if (file_exists($filespec) && ($file = file($filespec, FILE_IGNORE_NEW_LINES))) { + $count = count($file); + $index = 0; + while ($index < $count) { + if (preg_match($options['regex'], $file[$index], $matches)) { + if (VERBOSE) { + echo $this->log->primary('Matched: '.$file[$index]); + } + $index++; - if (is_callable($options['value'])) { - $file[$index] = $options['value']($matches); - } else { - $file[$index] = $options['value']; - } - $changed = true; - } - } - } + if (is_callable($options['value'])) { + $file[$index] = $options['value']($matches); + } else { + $file[$index] = $options['value']; + } + $changed = true; + } + } + } - if ($changed) { - if (file_put_contents($filespec, implode("\n", $file)) === false) { - echo $this->log->error('Error writing file to disc!!'); - } - } - } + if ($changed) { + if (file_put_contents($filespec, implode("\n", $file)) === false) { + echo $this->log->error('Error writing file to disc!!'); + } + } + } - protected function _backupDb(): void - { - $PHP = 'php'; + protected function _backupDb(): void + { + $PHP = 'php'; - system("$PHP " . NN_MISC . 'testing' . DS . 'DB' . DS . $this->_DbSystem . + system("$PHP ".NN_MISC.'testing'.DS.'DB'.DS.$this->_DbSystem. 'dump_tables.php db dump'); - $this->backedup = true; - } + $this->backedup = true; + } } - -?> diff --git a/nntmux/db/PreDb.php b/nntmux/db/PreDb.php index 966fbeed7..40e67c4ef 100755 --- a/nntmux/db/PreDb.php +++ b/nntmux/db/PreDb.php @@ -18,15 +18,15 @@ * @author niel * @copyright 2014 nZEDb */ -namespace nntmux\db; +namespace nntmux\db; class PreDb extends DB { - /** - * @var array Prepared Statement objects - */ - protected $ps = [ + /** + * @var array Prepared Statement objects + */ + protected $ps = [ 'AddGroups' => null, 'DeleteShort' => null, 'Export' => null, @@ -37,48 +37,48 @@ class PreDb extends DB 'UpdateGroupID' => null, ]; - public function __construct(array $options = []) - { - $defaults = []; - $options += $defaults; - parent::__construct($options); + public function __construct(array $options = []) + { + $defaults = []; + $options += $defaults; + parent::__construct($options); - $this->tableMain = 'predb'; - $this->tableTemp = 'predb_imports'; - } + $this->tableMain = 'predb'; + $this->tableTemp = 'predb_imports'; + } - public function executeAddGroups() - { - if (!isset($this->ps['AddGroups'])) { - $this->prepareSQLAddGroups(); - } + public function executeAddGroups() + { + if (! isset($this->ps['AddGroups'])) { + $this->prepareSQLAddGroups(); + } - return $this->ps['AddGroups']->execute(); - } + return $this->ps['AddGroups']->execute(); + } - public function executeDeleteShort() - { - if (!isset($this->ps['DeleteShort'])) { - $this->prepareSQLDeleteShort(); - } + public function executeDeleteShort() + { + if (! isset($this->ps['DeleteShort'])) { + $this->prepareSQLDeleteShort(); + } - return $this->ps['DeleteShort']->execute(); - } + return $this->ps['DeleteShort']->execute(); + } - /** - * @param array|null $options array of parameter. - * 'enclosedby' - string for enclosed by clause. default: empty string, - * 'fields' - string for FIELDS SEPARATED BY clause. default: '\t', - * 'limit' - string for LIMIT clause. Zero indicate no clause. Default: 0, - * 'lines' - string for LINES TERMINATED BY. Default: '\r\n' (Windows style EOLs to allow \n to be used in text), - * 'path' - path (including filename) to write data to. - * All parameter will be escaped before use. - * - * @return false|\PDOStatement - */ - public function executeExport(array $options = null) - { - $defaults = [ + /** + * @param array|null $options array of parameter. + * 'enclosedby' - string for enclosed by clause. default: empty string, + * 'fields' - string for FIELDS SEPARATED BY clause. default: '\t', + * 'limit' - string for LIMIT clause. Zero indicate no clause. Default: 0, + * 'lines' - string for LINES TERMINATED BY. Default: '\r\n' (Windows style EOLs to allow \n to be used in text), + * 'path' - path (including filename) to write data to. + * All parameter will be escaped before use. + * + * @return false|\PDOStatement + */ + public function executeExport(array $options = null) + { + $defaults = [ 'enclosedby' => '', 'fields' => '\t', 'limit' => 0, @@ -86,143 +86,144 @@ class PreDb extends DB 'local' => false, 'path' => null, ]; - $options += $defaults; + $options += $defaults; - if (empty($options['path'])) { - return null; - } else if (!is_numeric($options['limit'])) { - return null; - } + if (empty($options['path'])) { + return null; + } elseif (! is_numeric($options['limit'])) { + return null; + } - $limit = $options['limit'] > 0 ? "LIMIT {$options['limit']}" : ''; + $limit = $options['limit'] > 0 ? "LIMIT {$options['limit']}" : ''; - $enclosedby = empty($options['enclosedby']) ? '' : "ENCLOSED BY {$this->escapeString($options['enclosedby'])}"; + $enclosedby = empty($options['enclosedby']) ? '' : "ENCLOSED BY {$this->escapeString($options['enclosedby'])}"; - $sql = <<<SQL_EXPORT + $sql = <<<SQL_EXPORT SELECT title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, g.name FROM {$this->tableMain} p LEFT OUTER JOIN groups g ON p.groups_id = g.id $limit INTO OUTFILE '{$options['path']}' FIELDS TERMINATED BY '{$options['fields']}' $enclosedby LINES TERMINATED BY '{$options['lines']}'; SQL_EXPORT; - if (NN_DEBUG) { - echo "$sql\n"; - } + if (NN_DEBUG) { + echo "$sql\n"; + } - return $this->queryDirect($sql); - } + return $this->queryDirect($sql); + } - public function executeInsert() - { - if (!isset($this->ps['Insert'])) { - $this->prepareSQLInsert(); - } + public function executeInsert() + { + if (! isset($this->ps['Insert'])) { + $this->prepareSQLInsert(); + } - return $this->ps['Insert']->execute(); - } + return $this->ps['Insert']->execute(); + } - public function executeLoadData(array $options = null) - { - $defaults = [ + public function executeLoadData(array $options = null) + { + $defaults = [ 'path' => null, ]; - $options += $defaults; + $options += $defaults; - if (empty($options['path'])) { - return null; - } + if (empty($options['path'])) { + return null; + } - if (!isset($this->ps['LoadData'])) { - // TODO detect LOCAL here and pass parameter as appropriate - $this->prepareSQLLoadData($options); - } + if (! isset($this->ps['LoadData'])) { + // TODO detect LOCAL here and pass parameter as appropriate + $this->prepareSQLLoadData($options); + } - return $this->ps['LoadData']->execute([':path' => $options['path']]); - } + return $this->ps['LoadData']->execute([':path' => $options['path']]); + } - public function executeTruncate() - { - if (!isset($this->ps['Truncate'])) { - $this->prepareSQLTruncate(); - } - return $this->ps['Truncate']->execute(); - } + public function executeTruncate() + { + if (! isset($this->ps['Truncate'])) { + $this->prepareSQLTruncate(); + } - public function executeUpdateGroupID() - { - if (!isset($this->ps['UpdateGroupID'])) { - $this->prepareSQLUpdateGroupIDs(); - } + return $this->ps['Truncate']->execute(); + } - return $this->ps['UpdateGroupID']->execute(); - } + public function executeUpdateGroupID() + { + if (! isset($this->ps['UpdateGroupID'])) { + $this->prepareSQLUpdateGroupIDs(); + } - public function import($filespec, $localDB = false) - { - if (!($this->ps['AddGroups'] instanceof \PDOStatement)) { - $this->prepareImportSQL($localDB); - } + return $this->ps['UpdateGroupID']->execute(); + } - $this->ps['Truncate']->execute(); + public function import($filespec, $localDB = false) + { + if (! ($this->ps['AddGroups'] instanceof \PDOStatement)) { + $this->prepareImportSQL($localDB); + } - $this->ps['LoadData']->execute([':path' => $filespec]); + $this->ps['Truncate']->execute(); - $this->ps['DeleteShort']->execute(); + $this->ps['LoadData']->execute([':path' => $filespec]); - $this->ps['AddGroups']->execute(); + $this->ps['DeleteShort']->execute(); - $this->ps['UpdateGroupID']->execute(); + $this->ps['AddGroups']->execute(); - $this->ps['Insert']->execute(); - } + $this->ps['UpdateGroupID']->execute(); - public function progress($settings = null, array $options = []) - { - $defaults = [ - 'path' => NN_ROOT . 'cli' . DS . 'data' . DS . 'predb_progress.txt', + $this->ps['Insert']->execute(); + } + + public function progress($settings = null, array $options = []) + { + $defaults = [ + 'path' => NN_ROOT.'cli'.DS.'data'.DS.'predb_progress.txt', 'read' => true, ]; - $options += $defaults; + $options += $defaults; - if (!$options['read'] || !is_file($options['path'])) { - file_put_contents($options['path'], base64_encode(serialize($settings))); - } else { - $settings = unserialize(base64_decode(file_get_contents($options['path']))); - } + if (! $options['read'] || ! is_file($options['path'])) { + file_put_contents($options['path'], base64_encode(serialize($settings))); + } else { + $settings = unserialize(base64_decode(file_get_contents($options['path']))); + } - return $settings; - } + return $settings; + } - protected function prepareImportSQL($localDB = false, $enclosedby = '') - { - $this->prepareSQLTruncate(); + protected function prepareImportSQL($localDB = false, $enclosedby = '') + { + $this->prepareSQLTruncate(); - $this->prepareSQLLoadData(['local' => $localDB, 'enclosedby' => $enclosedby, 'optional' => true]); + $this->prepareSQLLoadData(['local' => $localDB, 'enclosedby' => $enclosedby, 'optional' => true]); - $this->prepareSQLDeleteShort(); + $this->prepareSQLDeleteShort(); - $this->prepareSQLAddGroups(); + $this->prepareSQLAddGroups(); - $this->prepareSQLUpdateGroupIDs(); + $this->prepareSQLUpdateGroupIDs(); - $this->prepareSQLInsert(); - } + $this->prepareSQLInsert(); + } - /** - * @param $sql - * @param string $index - */ - protected function prepareSQLStatement($sql, $index) - { - $this->ps[$index] = $this->prepare($sql); - } + /** + * @param $sql + * @param string $index + */ + protected function prepareSQLStatement($sql, $index) + { + $this->ps[$index] = $this->prepare($sql); + } - /** - * Add any groups that are not in our current groups table - */ - protected function prepareSQLAddGroups() - { - $sql = <<<SQL_ADD_GROUPS + /** + * Add any groups that are not in our current groups table. + */ + protected function prepareSQLAddGroups() + { + $sql = <<<'SQL_ADD_GROUPS' INSERT IGNORE INTO groups (name, description) SELECT groupname, 'Added by predb import script' FROM predb_imports AS pi LEFT JOIN groups AS g ON pi.groupname = g.name @@ -230,17 +231,17 @@ INSERT IGNORE INTO groups (name, description) GROUP BY groupname; SQL_ADD_GROUPS; - $this->prepareSQLStatement($sql, 'AddGroups'); - } + $this->prepareSQLStatement($sql, 'AddGroups'); + } - protected function prepareSQLDeleteShort() - { - $this->prepareSQLStatement('DELETE FROM predb_imports WHERE LENGTH(title) <= 8', 'DeleteShort'); - } + protected function prepareSQLDeleteShort() + { + $this->prepareSQLStatement('DELETE FROM predb_imports WHERE LENGTH(title) <= 8', 'DeleteShort'); + } - protected function prepareSQLInsert() - { - $sql = <<<SQL_INSERT + protected function prepareSQLInsert() + { + $sql = <<<SQL_INSERT INSERT INTO {$this->tableMain} (title, nfo, size, files, filename, nuked, nukereason, category, predate, SOURCE, requestid, groups_id) SELECT pi.title, pi.nfo, pi.size, pi.files, pi.filename, pi.nuked, pi.nukereason, pi.category, pi.predate, pi.source, pi.requestid, groups_id FROM predb_imports AS pi @@ -255,48 +256,48 @@ INSERT INTO {$this->tableMain} (title, nfo, size, files, filename, nuked, nukere predb.groups_id = IF(predb.groups_id = 0, pi.groups_id, predb.groups_id); SQL_INSERT; - $this->prepareSQLStatement($sql, 'Insert'); - } + $this->prepareSQLStatement($sql, 'Insert'); + } - protected function prepareSQLLoadData(array $options = []) - { - $enclosedby = ''; - $defaults = [ + protected function prepareSQLLoadData(array $options = []) + { + $enclosedby = ''; + $defaults = [ 'enclosedby' => "'", 'fields' => '\t', 'lines' => '\r\n', // Windows' style EOL to allow \n to be used in text. 'local' => false, 'optional' => true, ]; - $options += $defaults; + $options += $defaults; - $local = $options['local'] === false ? 'LOCAL' : ''; - if (!empty($options['enclosedby'])) { - $optional = $options['optional'] === true ? ' OPTIONALLY' : ''; - $enclosedby = "$optional ENCLOSED BY \"{$options['enclosedby']}\""; - } - $sql = <<<SQL_LOAD_DATA + $local = $options['local'] === false ? 'LOCAL' : ''; + if (! empty($options['enclosedby'])) { + $optional = $options['optional'] === true ? ' OPTIONALLY' : ''; + $enclosedby = "$optional ENCLOSED BY \"{$options['enclosedby']}\""; + } + $sql = <<<SQL_LOAD_DATA LOAD DATA $local INFILE :path IGNORE INTO TABLE predb_imports FIELDS TERMINATED BY '{$options['fields']}' {$enclosedby} LINES TERMINATED BY '{$options['lines']}' (title, nfo, size, files, filename, nuked, nukereason, category, predate, source, requestid, groupname); SQL_LOAD_DATA; - if (NN_DEBUG) { - echo "$sql\n"; - } + if (NN_DEBUG) { + echo "$sql\n"; + } - $this->prepareSQLStatement($sql, 'LoadData'); - } + $this->prepareSQLStatement($sql, 'LoadData'); + } - protected function prepareSQLTruncate() - { - $this->prepareSQLStatement('TRUNCATE TABLE predb_imports', 'Truncate'); - } + protected function prepareSQLTruncate() + { + $this->prepareSQLStatement('TRUNCATE TABLE predb_imports', 'Truncate'); + } - protected function prepareSQLUpdateGroupIDs() - { - $sql = "UPDATE predb_imports AS pi SET groups_id = (SELECT id FROM groups WHERE name = pi.groupname) WHERE groupname IS NOT NULL"; - $this->prepareSQLStatement($sql, 'UpdateGroupID'); - } + protected function prepareSQLUpdateGroupIDs() + { + $sql = 'UPDATE predb_imports AS pi SET groups_id = (SELECT id FROM groups WHERE name = pi.groupname) WHERE groupname IS NOT NULL'; + $this->prepareSQLStatement($sql, 'UpdateGroupID'); + } } diff --git a/nntmux/db/Settings.php b/nntmux/db/Settings.php index 8ede36387..eaec4e771 100755 --- a/nntmux/db/Settings.php +++ b/nntmux/db/Settings.php @@ -18,322 +18,325 @@ * @author niel * @copyright 2014 nZEDb */ + namespace nntmux\db; -use App\Extensions\util\Versions; use nntmux\utility\Utility; +use App\Extensions\util\Versions; class Settings extends DB { - const REGISTER_STATUS_OPEN = 0; - const REGISTER_STATUS_INVITE = 1; - const REGISTER_STATUS_CLOSED = 2; - const REGISTER_STATUS_API_ONLY = 3; - const ERR_BADUNRARPATH = -1; - const ERR_BADFFMPEGPATH = -2; - const ERR_BADMEDIAINFOPATH = -3; - const ERR_BADNZBPATH = -4; - const ERR_DEEPNOUNRAR = -5; - const ERR_BADTMPUNRARPATH = -6; - const ERR_BADNZBPATH_UNREADABLE = -7; - const ERR_BADNZBPATH_UNSET = -8; - const ERR_BAD_COVERS_PATH = -9; - const ERR_BAD_YYDECODER_PATH = -10; + const REGISTER_STATUS_OPEN = 0; + const REGISTER_STATUS_INVITE = 1; + const REGISTER_STATUS_CLOSED = 2; + const REGISTER_STATUS_API_ONLY = 3; + const ERR_BADUNRARPATH = -1; + const ERR_BADFFMPEGPATH = -2; + const ERR_BADMEDIAINFOPATH = -3; + const ERR_BADNZBPATH = -4; + const ERR_DEEPNOUNRAR = -5; + const ERR_BADTMPUNRARPATH = -6; + const ERR_BADNZBPATH_UNREADABLE = -7; + const ERR_BADNZBPATH_UNSET = -8; + const ERR_BAD_COVERS_PATH = -9; + const ERR_BAD_YYDECODER_PATH = -10; - private $settings; + private $settings; - public function __construct(array $options = []) - { - parent::__construct($options); - $result = parent::exec("describe site", true); - $this->table = ($result === false) ? 'settings' : 'site'; - $this->setCovers(); + public function __construct(array $options = []) + { + parent::__construct($options); + $result = parent::exec('describe site', true); + $this->table = ($result === false) ? 'settings' : 'site'; + $this->setCovers(); - return $this->pdo; - } + return $this->pdo; + } - /** - * Non-existent variables are assumed to be simple Settings. - * - * @param $name - * - * @return string - */ - public function __get($name) - { - return $this->getSetting($name); - } + /** + * Non-existent variables are assumed to be simple Settings. + * + * @param $name + * + * @return string + */ + public function __get($name) + { + return $this->getSetting($name); + } - /** - * Retrieve one or all settings from the Db as a string or an array; - * - * @param array|string $options Name of setting to retrieve (null for all settings) - * or array of 'feature', 'section', 'name' of setting{s} to retrieve - * - * @return string|array|bool - */ - public function getSetting($options = []) - { - // todo: think about making this static so it can be accessed without instantiating. - if (!is_array($options)) { - $options = $this->_dottedToArray($options); - if (isset($options['setting']) && isset($this->settings[$options['setting']])) { - return $this->settings[$options['setting']]; - } - } + /** + * Retrieve one or all settings from the Db as a string or an array;. + * + * @param array|string $options Name of setting to retrieve (null for all settings) + * or array of 'feature', 'section', 'name' of setting{s} to retrieve + * + * @return string|array|bool + */ + public function getSetting($options = []) + { + // todo: think about making this static so it can be accessed without instantiating. + if (! is_array($options)) { + $options = $this->_dottedToArray($options); + if (isset($options['setting']) && isset($this->settings[$options['setting']])) { + return $this->settings[$options['setting']]; + } + } - $defaults = [ + $defaults = [ 'section' => '', 'subsection' => '', 'name' => null, ]; - $options += $defaults; + $options += $defaults; - if ($this->table == 'settings') { - $result = $this->_getFromSettings($options); - } else { - $result = $this->_getFromSites($options); - } - return $result; - } + if ($this->table == 'settings') { + $result = $this->_getFromSettings($options); + } else { + $result = $this->_getFromSites($options); + } - public function getSettingsAsTree($excludeUnsectioned = true) - { - $where = $excludeUnsectioned ? "WHERE section != ''" : ''; + return $result; + } - $sql = sprintf("SELECT section, subsection, name, value, hint FROM settings %s ORDER BY section, subsection, name", $where); - $results = $this->queryArray($sql); + public function getSettingsAsTree($excludeUnsectioned = true) + { + $where = $excludeUnsectioned ? "WHERE section != ''" : ''; - $tree = []; - if (is_array($results)) { - foreach ($results as $result) { - if (!empty($result['section']) || !$excludeUnsectioned) { - $tree[$result['section']][$result['subsection']][$result['name']] = + $sql = sprintf('SELECT section, subsection, name, value, hint FROM settings %s ORDER BY section, subsection, name', $where); + $results = $this->queryArray($sql); + + $tree = []; + if (is_array($results)) { + foreach ($results as $result) { + if (! empty($result['section']) || ! $excludeUnsectioned) { + $tree[$result['section']][$result['subsection']][$result['name']] = ['value' => $result['value'], 'hint' => $result['hint']]; - } - } - } else { - echo "NO results!!\n"; - } + } + } + } else { + echo "NO results!!\n"; + } - return $tree; - } + return $tree; + } - public function rowToArray(array $row) - { - $this->settings[$row['setting']] = $row['value']; - } + public function rowToArray(array $row) + { + $this->settings[$row['setting']] = $row['value']; + } - public function rowsToArray(array $rows) - { - foreach ($rows as $row) { - if (is_array($row)) { - $this->rowToArray($row); - } - } - return $this->settings; - } + public function rowsToArray(array $rows) + { + foreach ($rows as $row) { + if (is_array($row)) { + $this->rowToArray($row); + } + } - public function setCovers() - { - $path = $this->getSetting([ + return $this->settings; + } + + public function setCovers() + { + $path = $this->getSetting([ 'section' => 'site', 'subsection' => 'main', 'name' => 'coverspath', 'setting' => 'coverspath', ]); - Utility::setCoversConstant($path); - } + Utility::setCoversConstant($path); + } - /** - * Set a setting in the database. - * - * @param array $options Array containing the mandatory keys of 'section', 'subsection', and 'value' - * - * @return boolean true or false indicating success/failure. - */ - public function setSetting(array $options) - { - if (count($options) == 1) { - foreach ($options as $key => $value) { - $options = $this->_dottedToArray($key); - $options['value'] = $value; - } - } + /** + * Set a setting in the database. + * + * @param array $options Array containing the mandatory keys of 'section', 'subsection', and 'value' + * + * @return bool true or false indicating success/failure. + */ + public function setSetting(array $options) + { + if (count($options) == 1) { + foreach ($options as $key => $value) { + $options = $this->_dottedToArray($key); + $options['value'] = $value; + } + } - $result = false; - $defaults = [ + $result = false; + $defaults = [ 'section' => null, 'subsection' => null, 'name' => '', 'value' => null, 'setting' => null, ]; - $options += $defaults; + $options += $defaults; - $temp1 = $options['section'] . $options['subsection'] . $options['name']; - $temp2 = $options['section'] . $options['subsection'] . $options['setting']; - if (!empty($temp1) || !empty($temp2)) { - if (empty($temp1)) { - if (isset($this->settings[$options['setting']])) { - $this->settings[$options['setting']] = $options['value']; - } - $result = $this->update($options); - } else if (!empty($options['name'])) { - $where = sprintf("name = '%s'", $options['name']); - $where .= ($options['section'] === null) ? '' : sprintf(" AND section = '%s'", $options['section']); - $where .= ($options['subsection'] === null) ? '' : sprintf(" AND subsection = '%s'", $options['subsection']); + $temp1 = $options['section'].$options['subsection'].$options['name']; + $temp2 = $options['section'].$options['subsection'].$options['setting']; + if (! empty($temp1) || ! empty($temp2)) { + if (empty($temp1)) { + if (isset($this->settings[$options['setting']])) { + $this->settings[$options['setting']] = $options['value']; + } + $result = $this->update($options); + } elseif (! empty($options['name'])) { + $where = sprintf("name = '%s'", $options['name']); + $where .= ($options['section'] === null) ? '' : sprintf(" AND section = '%s'", $options['section']); + $where .= ($options['subsection'] === null) ? '' : sprintf(" AND subsection = '%s'", $options['subsection']); - $sql = sprintf("UPDATE settings SET value = '%s' WHERE %s", + $sql = sprintf("UPDATE settings SET value = '%s' WHERE %s", $options['value'], $where); - $result = $this->pdo->query($sql); - } - } + $result = $this->pdo->query($sql); + } + } - return ($result === false) ? false : true; - } + return ($result === false) ? false : true; + } - public function table() - { - return $this->table; - } + public function table() + { + return $this->table; + } - public function update($form) - { - $error = $this->_validate($form); + public function update($form) + { + $error = $this->_validate($form); - if ($error === null) { - $sql = $sqlKeys = []; - foreach ($form as $settingK => $settingV) { - $sql[] = sprintf("WHEN %s THEN %s", + if ($error === null) { + $sql = $sqlKeys = []; + foreach ($form as $settingK => $settingV) { + $sql[] = sprintf('WHEN %s THEN %s', $this->escapeString($settingK), $this->escapeString($settingV)); - $sqlKeys[] = $this->escapeString($settingK); - } + $sqlKeys[] = $this->escapeString($settingK); + } - $table = $this->table(); - $this->queryExec( + $table = $this->table(); + $this->queryExec( sprintf("UPDATE $table SET value = CASE setting %s END WHERE setting IN (%s)", implode(' ', $sql), implode(', ', $sqlKeys) ) ); - } else { - $form = $error; - } - return $form; - } + } else { + $form = $error; + } - public function version() - { - try { - $ver = (new Versions())->getGitTagInRepo(); - } catch (\Exception $e) { - $ver = '0.0.0'; - } - return $ver; - } + return $form; + } - protected function _dottedToArray($setting) - { - $result = []; - if (is_string($setting)) { - $parts = explode('.', $setting); - switch (count($parts)) { + public function version() + { + try { + $ver = (new Versions())->getGitTagInRepo(); + } catch (\Exception $e) { + $ver = '0.0.0'; + } + + return $ver; + } + + protected function _dottedToArray($setting) + { + $result = []; + if (is_string($setting)) { + $parts = explode('.', $setting); + switch (count($parts)) { case 3: list( $result['section'], $result['subsection'], - $result['name'], - ) = $parts; + $result['name']) = $parts; break; case 2: list( $result['subsection'], - $result['name'], - ) = $parts; + $result['name']) = $parts; break; case 1: list( - $result['setting'], - ) = $parts; + $result['setting']) = $parts; break; } - } else { - $result = false; - } - return $result; - } + } else { + $result = false; + } - protected function _getFromSettings($options) - { - $sql = 'SELECT value FROM settings '; - $where = $options['section'] . $options['subsection'] . $options['name']; // Can't use expression in empty() < PHP 5.5 - if (!empty($where)) { - $sql .= "WHERE section = '{$options['section']}' AND subsection = '{$options['subsection']}'"; - $sql .= empty($options['name']) ? '' : " AND name = '{$options['name']}'"; - } else { - $sql .= "WHERE setting = '{$options['setting']}'"; - } - $sql .= ' ORDER BY section, subsection, name'; - $result = $this->queryOneRow($sql); + return $result; + } - return isset($result['value']) ? $result['value'] : null; - } + protected function _getFromSettings($options) + { + $sql = 'SELECT value FROM settings '; + $where = $options['section'].$options['subsection'].$options['name']; // Can't use expression in empty() < PHP 5.5 + if (! empty($where)) { + $sql .= "WHERE section = '{$options['section']}' AND subsection = '{$options['subsection']}'"; + $sql .= empty($options['name']) ? '' : " AND name = '{$options['name']}'"; + } else { + $sql .= "WHERE setting = '{$options['setting']}'"; + } + $sql .= ' ORDER BY section, subsection, name'; + $result = $this->queryOneRow($sql); - protected function _getFromSites($options) - { - $setting = empty($options['setting']) ? $options['name'] : $options['setting']; - $sql = 'SELECT value FROM settings '; - if (!empty($setting)) { - $sql .= "WHERE setting = '$setting'"; - } + return isset($result['value']) ? $result['value'] : null; + } - $result = $this->queryOneRow($sql); + protected function _getFromSites($options) + { + $setting = empty($options['setting']) ? $options['name'] : $options['setting']; + $sql = 'SELECT value FROM settings '; + if (! empty($setting)) { + $sql .= "WHERE setting = '$setting'"; + } - return $result['value']; - } + $result = $this->queryOneRow($sql); - protected function _validate(array $fields) - { - ksort($fields); - // Validate settings - $fields['nzbpath'] = Utility::trailingSlash($fields['nzbpath']); - $error = null; - switch (true) { - case ($fields['mediainfopath'] != "" && !is_file($fields['mediainfopath'])): - $error = Settings::ERR_BADMEDIAINFOPATH; + return $result['value']; + } + + protected function _validate(array $fields) + { + ksort($fields); + // Validate settings + $fields['nzbpath'] = Utility::trailingSlash($fields['nzbpath']); + $error = null; + switch (true) { + case $fields['mediainfopath'] != '' && ! is_file($fields['mediainfopath']): + $error = self::ERR_BADMEDIAINFOPATH; break; - case ($fields['ffmpegpath'] != "" && !is_file($fields['ffmpegpath'])): - $error = Settings::ERR_BADFFMPEGPATH; + case $fields['ffmpegpath'] != '' && ! is_file($fields['ffmpegpath']): + $error = self::ERR_BADFFMPEGPATH; break; - case ($fields['unrarpath'] != "" && !is_file($fields['unrarpath'])): - $error = Settings::ERR_BADUNRARPATH; + case $fields['unrarpath'] != '' && ! is_file($fields['unrarpath']): + $error = self::ERR_BADUNRARPATH; break; - case (empty($fields['nzbpath'])): - $error = Settings::ERR_BADNZBPATH_UNSET; + case empty($fields['nzbpath']): + $error = self::ERR_BADNZBPATH_UNSET; break; - case (!file_exists($fields['nzbpath']) || !is_dir($fields['nzbpath'])): - $error = Settings::ERR_BADNZBPATH; + case ! file_exists($fields['nzbpath']) || ! is_dir($fields['nzbpath']): + $error = self::ERR_BADNZBPATH; break; - case (!is_readable($fields['nzbpath'])): - $error = Settings::ERR_BADNZBPATH_UNREADABLE; + case ! is_readable($fields['nzbpath']): + $error = self::ERR_BADNZBPATH_UNREADABLE; break; - case ($fields['checkpasswordedrar'] == 1 && !is_file($fields['unrarpath'])): - $error = Settings::ERR_DEEPNOUNRAR; + case $fields['checkpasswordedrar'] == 1 && ! is_file($fields['unrarpath']): + $error = self::ERR_DEEPNOUNRAR; break; - case ($fields['tmpunrarpath'] != "" && !file_exists($fields['tmpunrarpath'])): - $error = Settings::ERR_BADTMPUNRARPATH; + case $fields['tmpunrarpath'] != '' && ! file_exists($fields['tmpunrarpath']): + $error = self::ERR_BADTMPUNRARPATH; break; - case ($fields['yydecoderpath'] != "" && + case $fields['yydecoderpath'] != '' && $fields['yydecoderpath'] !== 'simple_php_yenc_decode' && - !file_exists($fields['yydecoderpath'])): - $error = Settings::ERR_BAD_YYDECODER_PATH; + ! file_exists($fields['yydecoderpath']): + $error = self::ERR_BAD_YYDECODER_PATH; } - return $error; - } + return $error; + } } /* @@ -341,5 +344,5 @@ class Settings extends DB * This is a temporary measure until a proper frontend for cli stuff can be implemented with li3. */ if (Utility::isCLI() && isset($argv[1])) { - echo (new DB())->getSetting($argv[1]); + echo (new DB())->getSetting($argv[1]); } diff --git a/nntmux/db/populate/AniDB.php b/nntmux/db/populate/AniDB.php index 673356b3a..7ae762490 100755 --- a/nntmux/db/populate/AniDB.php +++ b/nntmux/db/populate/AniDB.php @@ -2,100 +2,100 @@ namespace nntmux\db\populate; -use App\Models\Settings; -use nntmux\ColorCLI; -use nntmux\ReleaseImage; use nntmux\db\DB; +use nntmux\ColorCLI; +use App\Models\Settings; +use nntmux\ReleaseImage; class AniDB { - const CLIENT_VERSION = 2; + const CLIENT_VERSION = 2; - /** - * Whether or not to echo message output - * @var bool - */ - public $echooutput; + /** + * Whether or not to echo message output. + * @var bool + */ + public $echooutput; - /** - * The directory to store AniDB covers - * @var string - */ - public $imgSavePath; + /** + * The directory to store AniDB covers. + * @var string + */ + public $imgSavePath; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * The AniDB ID we are looking up - * @var bool - */ - private $anidbId; + /** + * The AniDB ID we are looking up. + * @var bool + */ + private $anidbId; - /** - * The name of the nZEDb client for AniDB lookups - * @var string - */ - private $apiKey; + /** + * The name of the nZEDb client for AniDB lookups. + * @var string + */ + private $apiKey; - /** - * Whether or not AniDB thinks our client is banned - * @var bool - */ - private $banned; + /** + * Whether or not AniDB thinks our client is banned. + * @var bool + */ + private $banned; - /** - * The last unixtime a full AniDB update was run - * @var string - */ - private $lastUpdate; + /** + * The last unixtime a full AniDB update was run. + * @var string + */ + private $lastUpdate; - /** - * The number of days between full AniDB updates - * @var string - */ - private $updateInterval; + /** + * The number of days between full AniDB updates. + * @var string + */ + private $updateInterval; - /** - * @param array $options Class instances / Echo to cli. - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances / Echo to cli. + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $anidbupdint = Settings::value('APIs.AniDB.max_update_frequency'); - $lastupdated = Settings::value('APIs.AniDB.last_full_update'); + $anidbupdint = Settings::value('APIs.AniDB.max_update_frequency'); + $lastupdated = Settings::value('APIs.AniDB.last_full_update'); - $this->imgSavePath = NN_COVERS . 'anime' . DS; - $this->apiKey = Settings::value('APIs..anidbkey'); + $this->imgSavePath = NN_COVERS.'anime'.DS; + $this->apiKey = Settings::value('APIs..anidbkey'); - $this->updateInterval = $anidbupdint ?? '7'; - $this->lastUpdate = $lastupdated ?? '0'; - $this->banned = false; - } + $this->updateInterval = $anidbupdint ?? '7'; + $this->lastUpdate = $lastupdated ?? '0'; + $this->banned = false; + } - /** - * Main switch that initiates AniDB table population - * - * @param string $type - * @param int|string $anidbId - * - * @throws \Exception - */ - public function populateTable($type = '', $anidbId = ''): void - { - switch ($type) { + /** + * Main switch that initiates AniDB table population. + * + * @param string $type + * @param int|string $anidbId + * + * @throws \Exception + */ + public function populateTable($type = '', $anidbId = ''): void + { + switch ($type) { case 'full': $this->populateMainTable(); break; @@ -103,21 +103,21 @@ class AniDB $this->populateInfoTable($anidbId); break; } - } + } - /** - * Checks for an existing anime title in anidb table - * - * @param int $id The AniDB ID to be inserted - * @param string $type The title type - * @param string $lang The title language - * @param string $title The title of the Anime - * - * @return array|bool - */ - private function checkDuplicateDbEntry($id, $type, $lang, $title) - { - return $this->pdo->queryOneRow( + /** + * Checks for an existing anime title in anidb table. + * + * @param int $id The AniDB ID to be inserted + * @param string $type The title type + * @param string $lang The title language + * @param string $title The title of the Anime + * + * @return array|bool + */ + private function checkDuplicateDbEntry($id, $type, $lang, $title) + { + return $this->pdo->queryOneRow( sprintf(' SELECT anidbid FROM anidb_titles @@ -131,159 +131,160 @@ class AniDB $this->pdo->escapeString($title) ) ); - } + } - /** - * Retrieves supplemental anime info from the AniDB API - * - * @param $anidbId - * - * @return array|bool - * @throws \Exception - */ - private function getAniDbAPI($anidbId) - { - $timestamp = Settings::value('APIs.AniDB.banned') + 90000; - if ($timestamp > time()) { - echo 'Banned from AniDB lookups until ' . date('Y-m-d H:i:s', $timestamp) . PHP_EOL; - return false; - } - $apiresponse = $this->getAniDbResponse($anidbId); + /** + * Retrieves supplemental anime info from the AniDB API. + * + * @param $anidbId + * + * @return array|bool + * @throws \Exception + */ + private function getAniDbAPI($anidbId) + { + $timestamp = Settings::value('APIs.AniDB.banned') + 90000; + if ($timestamp > time()) { + echo 'Banned from AniDB lookups until '.date('Y-m-d H:i:s', $timestamp).PHP_EOL; - $AniDBAPIArray = []; + return false; + } + $apiresponse = $this->getAniDbResponse($anidbId); - if ($apiresponse === false) { - echo 'AniDB: Error getting response.' . PHP_EOL; - } elseif (preg_match('/\<error\>Banned\<\/error\>/', $apiresponse)) { - $this->banned = true; - Settings::update( + $AniDBAPIArray = []; + + if ($apiresponse === false) { + echo 'AniDB: Error getting response.'.PHP_EOL; + } elseif (preg_match('/\<error\>Banned\<\/error\>/', $apiresponse)) { + $this->banned = true; + Settings::update( ['value' => time()], ['section' => 'APIs', 'subsection' => 'AniDB', 'name' => 'banned'] ); - } elseif (preg_match('/\<error\>Anime not found\<\/error\>/', $apiresponse)) { - echo "AniDB : Anime not yet on site. Remove until next update.\n"; - } elseif ($AniDBAPIXML = new \SimpleXMLElement($apiresponse)) { + } elseif (preg_match('/\<error\>Anime not found\<\/error\>/', $apiresponse)) { + echo "AniDB : Anime not yet on site. Remove until next update.\n"; + } elseif ($AniDBAPIXML = new \SimpleXMLElement($apiresponse)) { + $AniDBAPIArray['similar'] = $this->processAPIResponseElement($AniDBAPIXML->similaranime, 'anime', false); + $AniDBAPIArray['related'] = $this->processAPIResponseElement($AniDBAPIXML->relatedanime, 'anime', false); + $AniDBAPIArray['creators'] = $this->processAPIResponseElement($AniDBAPIXML->creators, null, false); + $AniDBAPIArray['characters'] = $this->processAPIResponseElement($AniDBAPIXML->characters, null, true); + $AniDBAPIArray['categories'] = $this->processAPIResponseElement($AniDBAPIXML->categories, null, true); - $AniDBAPIArray['similar'] = $this->processAPIResponseElement($AniDBAPIXML->similaranime, 'anime', false); - $AniDBAPIArray['related'] = $this->processAPIResponseElement($AniDBAPIXML->relatedanime, 'anime', false); - $AniDBAPIArray['creators'] = $this->processAPIResponseElement($AniDBAPIXML->creators, null, false); - $AniDBAPIArray['characters'] = $this->processAPIResponseElement($AniDBAPIXML->characters, null, true); - $AniDBAPIArray['categories'] = $this->processAPIResponseElement($AniDBAPIXML->categories, null, true); + $episodeArray = []; + if ($AniDBAPIXML->episodes && $AniDBAPIXML->episodes->episode[0]->attributes()) { + $i = 1; + foreach ($AniDBAPIXML->episodes->episode as $episode) { + $titleArray = []; - $episodeArray = []; - if ($AniDBAPIXML->episodes && $AniDBAPIXML->episodes->episode[0]->attributes()) { - $i = 1; - foreach ($AniDBAPIXML->episodes->episode as $episode) { - $titleArray = []; + $episodeArray[$i]['episode_id'] = (int) $episode->attributes()->id; + $episodeArray[$i]['episode_no'] = (int) $episode->epno; + $episodeArray[$i]['airdate'] = (string) $episode->airdate; - $episodeArray[$i]['episode_id'] = (int)$episode->attributes()->id; - $episodeArray[$i]['episode_no'] = (int)$episode->epno; - $episodeArray[$i]['airdate'] = (string)$episode->airdate; + if (! empty($episode->title)) { + foreach ($episode->title as $title) { + $xmlAttribs = $title->attributes('xml', true); + // only english, x-jat imploded episode titles for now + if (in_array($xmlAttribs->lang, ['en', 'x-jat'], false)) { + $titleArray[] = $title[0]; + } + } + } - if (!empty($episode->title)) { - foreach ($episode->title as $title) { - $xmlAttribs = $title->attributes('xml', true); - // only english, x-jat imploded episode titles for now - if (in_array($xmlAttribs->lang, ['en', 'x-jat'], false)) { - $titleArray[] = $title[0]; - } - } - } + $episodeArray[$i]['episode_title'] = empty($titleArray) ? '' : implode(', ', $titleArray); + $i++; + } + } - $episodeArray[$i]['episode_title'] = empty($titleArray) ? '' : implode(', ', $titleArray); - $i++; - } - } + //start and end date come from AniDB API as date strings -- no manipulation needed + $AniDBAPIArray['startdate'] = $AniDBAPIXML->startdate ?? '0000-00-00'; + $AniDBAPIArray['enddate'] = $AniDBAPIXML->enddate ?? '0000-00-00'; - //start and end date come from AniDB API as date strings -- no manipulation needed - $AniDBAPIArray['startdate'] = $AniDBAPIXML->startdate ?? '0000-00-00'; - $AniDBAPIArray['enddate'] = $AniDBAPIXML->enddate ?? '0000-00-00'; + if (isset($AniDBAPIXML->ratings->permanent)) { + $AniDBAPIArray['rating'] = $AniDBAPIXML->ratings->permanent; + } else { + $AniDBAPIArray['rating'] = $AniDBAPIXML->ratings->temporary ?? $AniDBAPIArray['rating'] = ''; + } - if (isset($AniDBAPIXML->ratings->permanent)) { - $AniDBAPIArray['rating'] = $AniDBAPIXML->ratings->permanent; - } else { - $AniDBAPIArray['rating'] = $AniDBAPIXML->ratings->temporary ?? $AniDBAPIArray['rating'] = ''; - } - - $AniDBAPIArray += [ - 'type' => isset($AniDBAPIXML->type[0]) ? (string)$AniDBAPIXML->type : '', - 'description' => isset($AniDBAPIXML->description) ? (string)$AniDBAPIXML->description : '', - 'picture' => isset($AniDBAPIXML->picture[0]) ? (string)$AniDBAPIXML->picture : '', + $AniDBAPIArray += [ + 'type' => isset($AniDBAPIXML->type[0]) ? (string) $AniDBAPIXML->type : '', + 'description' => isset($AniDBAPIXML->description) ? (string) $AniDBAPIXML->description : '', + 'picture' => isset($AniDBAPIXML->picture[0]) ? (string) $AniDBAPIXML->picture : '', 'epsarr' => $episodeArray, ]; - return $AniDBAPIArray; - } + return $AniDBAPIArray; + } - return false; - } + return false; + } - /** - * @param \SimpleXMLElement $element - * @param string $property - * - * @param bool $children - * - * @return string - */ - private function processAPIResponseElement(\SimpleXMLElement $element, $property = null, $children = false): string - { - $property = $property ?? 'name'; - $temp = ''; + /** + * @param \SimpleXMLElement $element + * @param string $property + * + * @param bool $children + * + * @return string + */ + private function processAPIResponseElement(\SimpleXMLElement $element, $property = null, $children = false): string + { + $property = $property ?? 'name'; + $temp = ''; - if (is_object($element) && !empty($element)) { - $result = $children === true ? $element->children() : $element; - foreach ($result as $entry) { - $temp .= (string)$entry->$property . ', '; - } - } + if (is_object($element) && ! empty($element)) { + $result = $children === true ? $element->children() : $element; + foreach ($result as $entry) { + $temp .= (string) $entry->$property.', '; + } + } - return (empty($temp) ? '' : substr($temp, 0, -2)); - } + return empty($temp) ? '' : substr($temp, 0, -2); + } - /** - * Requests and returns the API data from AniDB - * - * @return string - */ - private function getAniDbResponse($anidbId): string - { - $curlString = sprintf( + /** + * Requests and returns the API data from AniDB. + * + * @return string + */ + private function getAniDbResponse($anidbId): string + { + $curlString = sprintf( 'http://api.anidb.net:9001/httpapi?request=anime&client=%s&clientver=%d&protover=1&aid=%d', $this->apiKey, self::CLIENT_VERSION, $anidbId ); - $ch = curl_init($curlString); + $ch = curl_init($curlString); - $curlOpts = [ + $curlOpts = [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_HEADER => 0, CURLOPT_FAILONERROR => 1, - CURLOPT_ENCODING => 'gzip' + CURLOPT_ENCODING => 'gzip', ]; - curl_setopt_array($ch, $curlOpts); - $apiresponse = curl_exec($ch); - curl_close($ch); - return $apiresponse; - } + curl_setopt_array($ch, $curlOpts); + $apiresponse = curl_exec($ch); + curl_close($ch); - /** - * Inserts new anime info from AniDB to anidb table - * - * @param int $id The AniDB ID to be inserted - * @param string $type The title type - * @param string $lang The title language - * @param string $title The title of the Anime - */ - private function insertAniDb($id, $type, $lang, $title): void - { - $check = $this->checkDuplicateDbEntry($id, $type, $lang, $title); + return $apiresponse; + } - if ($check === false) { - $this->pdo->queryInsert( + /** + * Inserts new anime info from AniDB to anidb table. + * + * @param int $id The AniDB ID to be inserted + * @param string $type The title type + * @param string $lang The title language + * @param string $title The title of the Anime + */ + private function insertAniDb($id, $type, $lang, $title): void + { + $check = $this->checkDuplicateDbEntry($id, $type, $lang, $title); + + if ($check === false) { + $this->pdo->queryInsert( sprintf(' INSERT IGNORE INTO anidb_titles (anidbid, type, lang, title) @@ -294,21 +295,21 @@ class AniDB $this->pdo->escapeString($title) ) ); - } else { - echo ColorCLI::warning("Duplicate: $id"); - } - } + } else { + echo ColorCLI::warning("Duplicate: $id"); + } + } - /** - * Inserts new anime info from AniDB to anidb table - * - * @param array $AniDBInfoArray - * - * @return string - */ - private function insertAniDBInfoEps(array $AniDBInfoArray = [], $anidbId): string - { - $this->pdo->queryInsert( + /** + * Inserts new anime info from AniDB to anidb table. + * + * @param array $AniDBInfoArray + * + * @return string + */ + private function insertAniDBInfoEps(array $AniDBInfoArray = [], $anidbId): string + { + $this->pdo->queryInsert( sprintf(' INSERT INTO anidb_info ( @@ -330,23 +331,23 @@ class AniDB $this->pdo->escapeString($AniDBInfoArray['characters']) ) ); - if (!empty($AniDBInfoArray['epsarr'])) { - $this->insertAniDBEpisodes($AniDBInfoArray['epsarr'], $anidbId); - } + if (! empty($AniDBInfoArray['epsarr'])) { + $this->insertAniDBEpisodes($AniDBInfoArray['epsarr'], $anidbId); + } - return $AniDBInfoArray['picture']; - } + return $AniDBInfoArray['picture']; + } - /** - * Inserts new anime info from AniDB to anidb table - * - * @param array $episodeArr - */ - private function insertAniDBEpisodes(array $episodeArr = [], $anidbId): void - { - if (!empty($episodeArr)) { - foreach ($episodeArr as $episode) { - $this->pdo->queryInsert( + /** + * Inserts new anime info from AniDB to anidb table. + * + * @param array $episodeArr + */ + private function insertAniDBEpisodes(array $episodeArr = [], $anidbId): void + { + if (! empty($episodeArr)) { + foreach ($episodeArr as $episode) { + $this->pdo->queryInsert( sprintf(' INSERT IGNORE INTO anidb_episodes (anidbid, episodeid, episode_no, episode_title, airdate) @@ -358,48 +359,48 @@ class AniDB $this->pdo->escapeString($episode['airdate']) ) ); - } - } - } + } + } + } - /** - * Grabs AniDB Full Dump XML and inserts it into anidb table - */ - private function populateMainTable() - { - $lastUpdate = (new \DateTime)->setTimestamp($this->lastUpdate); - $current = new \DateTime(); + /** + * Grabs AniDB Full Dump XML and inserts it into anidb table. + */ + private function populateMainTable() + { + $lastUpdate = (new \DateTime)->setTimestamp($this->lastUpdate); + $current = new \DateTime(); - if ($current->diff($lastUpdate)->format('%d') > $this->updateInterval) { - if ($this->echooutput) { - echo ColorCLI::header('Updating anime titles by grabbing full data AniDB dump.'); - } + if ($current->diff($lastUpdate)->format('%d') > $this->updateInterval) { + if ($this->echooutput) { + echo ColorCLI::header('Updating anime titles by grabbing full data AniDB dump.'); + } - $animetitles = new \SimpleXMLElement('compress.zlib://http://anidb.net/api/anime-titles.xml.gz', null, true); + $animetitles = new \SimpleXMLElement('compress.zlib://http://anidb.net/api/anime-titles.xml.gz', null, true); - //Even if the update process fails, - //we must mark the last update time or risk ban - $this->setLastUpdated(); + //Even if the update process fails, + //we must mark the last update time or risk ban + $this->setLastUpdated(); - if ($animetitles instanceof \Traversable) { - $count = $animetitles->count(); - if ($this->echooutput) { - echo ColorCLI::header( - 'Total of ' . number_format($count) . ' titles to add.' . PHP_EOL + if ($animetitles instanceof \Traversable) { + $count = $animetitles->count(); + if ($this->echooutput) { + echo ColorCLI::header( + 'Total of '.number_format($count).' titles to add.'.PHP_EOL ); - } + } - foreach ($animetitles as $anime) { - echo "Remaining: $count \r"; - foreach ($anime->title as $title) { - $xmlAttribs = $title->attributes('xml', true); - $this->insertAniDb( - (string)$anime['aid'], - (string)$title['type'], - (string)$xmlAttribs->lang, - (string)$title[0] + foreach ($animetitles as $anime) { + echo "Remaining: $count \r"; + foreach ($anime->title as $title) { + $xmlAttribs = $title->attributes('xml', true); + $this->insertAniDb( + (string) $anime['aid'], + (string) $title['type'], + (string) $xmlAttribs->lang, + (string) $title[0] ); - ColorCLI::primary( + ColorCLI::primary( sprintf( 'Inserting: %d, %s, %s, %s', $anime['aid'], @@ -408,126 +409,126 @@ class AniDB $title[0] ) ); - } - $count--; - } - } else { - echo PHP_EOL . - ColorCLI::error('Error retrieving XML data from AniDB. Please try again later.') . + } + $count--; + } + } else { + echo PHP_EOL. + ColorCLI::error('Error retrieving XML data from AniDB. Please try again later.'). PHP_EOL; - } - } else { - echo PHP_EOL . ColorCLI::info( - 'AniDB has been updated within the past ' . $this->updateInterval . ' days. ' . + } + } else { + echo PHP_EOL.ColorCLI::info( + 'AniDB has been updated within the past '.$this->updateInterval.' days. '. 'Either set this value lower in Site Edit (at your own risk of being banned) or try again later.'); - } - } + } + } - /** - * Directs flow for populating the AniDB Info/Episodes table - * - * @param string $anidbId - * - * @throws \Exception - */ - private function populateInfoTable($anidbId = '') - { - if (empty($anidbId)) { - $anidbIds = $this->pdo->query(sprintf( + /** + * Directs flow for populating the AniDB Info/Episodes table. + * + * @param string $anidbId + * + * @throws \Exception + */ + private function populateInfoTable($anidbId = '') + { + if (empty($anidbId)) { + $anidbIds = $this->pdo->query(sprintf( 'SELECT DISTINCT at.anidbid FROM anidb_titles at LEFT JOIN anidb_info ai ON ai.anidbid = at.anidbid WHERE ai.updated IS NULL' ) ); - foreach ($anidbIds as $anidb) { - $AniDBAPIArray = $this->getAniDbAPI($anidb['anidbid']); + foreach ($anidbIds as $anidb) { + $AniDBAPIArray = $this->getAniDbAPI($anidb['anidbid']); - if ($this->banned === true) { - ColorCLI::doEcho( + if ($this->banned === true) { + ColorCLI::doEcho( ColorCLI::error( 'AniDB Banned, import will fail, please wait 24 hours before retrying.' ), true ); - exit; - } + exit; + } - if ($AniDBAPIArray === false && $this->echooutput) { - ColorCLI::doEcho( + if ($AniDBAPIArray === false && $this->echooutput) { + ColorCLI::doEcho( ColorCLI::info( - 'Anime ID: ' . $anidb['anidbid'] . ' not available for update yet.' + 'Anime ID: '.$anidb['anidbid'].' not available for update yet.' ), true ); - } else { - $this->updateAniChildTables($AniDBAPIArray, $anidb['anidbid']); - if (NN_DEBUG) { - ColorCLI::doEcho( + } else { + $this->updateAniChildTables($AniDBAPIArray, $anidb['anidbid']); + if (NN_DEBUG) { + ColorCLI::doEcho( ColorCLI::headerOver( - 'Added/Updated AniDB ID: ' . $anidb['anidbid'] + 'Added/Updated AniDB ID: '.$anidb['anidbid'] ), true ); - } - } - sleep(random_int(120, 240)); - } - } else { - $AniDBAPIArray = $this->getAniDbAPI($anidbId); + } + } + sleep(random_int(120, 240)); + } + } else { + $AniDBAPIArray = $this->getAniDbAPI($anidbId); - if ($this->banned === true) { - ColorCLI::doEcho( + if ($this->banned === true) { + ColorCLI::doEcho( ColorCLI::error( 'AniDB Banned, import will fail, please wait 24 hours before retrying.' ), true ); - exit; - } + exit; + } - if ($AniDBAPIArray === false && $this->echooutput) { - ColorCLI::doEcho( + if ($AniDBAPIArray === false && $this->echooutput) { + ColorCLI::doEcho( ColorCLI::info( - 'Anime ID: ' . $anidbId . ' not available for update yet.' + 'Anime ID: '.$anidbId.' not available for update yet.' ), true ); - } else { - $this->updateAniChildTables($AniDBAPIArray, $anidbId); - if (NN_DEBUG) { - ColorCLI::doEcho( + } else { + $this->updateAniChildTables($AniDBAPIArray, $anidbId); + if (NN_DEBUG) { + ColorCLI::doEcho( ColorCLI::headerOver( - 'Added/Updated AniDB ID: ' . $anidbId + 'Added/Updated AniDB ID: '.$anidbId ), true ); - } - } - } - } + } + } + } + } - /** - * Sets the database time for last full AniDB update - */ - private function setLastUpdated(): void - { - (new Settings)->update( + /** + * Sets the database time for last full AniDB update. + */ + private function setLastUpdated(): void + { + (new Settings)->update( ['value' => time()], ['section' => 'APIs', 'subsection' => 'AniDB', 'name' => 'last_full_update'] ); - } + } - /** - * Updates existing anime info in anidb info/episodes tables - * - * @param array $AniDBInfoArray - * - * @return string - */ - private function updateAniDBInfoEps(array $AniDBInfoArray = [], $anidbId): string - { - $this->pdo->queryExec( + /** + * Updates existing anime info in anidb info/episodes tables. + * + * @param array $AniDBInfoArray + * + * @return string + */ + private function updateAniDBInfoEps(array $AniDBInfoArray = [], $anidbId): string + { + $this->pdo->queryExec( sprintf(' UPDATE anidb_info SET type = %s, startdate = %s, enddate = %s, related = %s, @@ -549,22 +550,22 @@ class AniDB $anidbId ) ); - if (!empty($AniDBInfoArray['epsarr'])) { - $this->insertAniDBEpisodes($AniDBInfoArray['epsarr'], $anidbId); - } + if (! empty($AniDBInfoArray['epsarr'])) { + $this->insertAniDBEpisodes($AniDBInfoArray['epsarr'], $anidbId); + } - return $AniDBInfoArray['picture']; - } + return $AniDBInfoArray['picture']; + } - /** - * Directs flow for updating child AniDB tables - * - * @param array $AniDBInfoArray - * @param $anidbId - */ - private function updateAniChildTables(array $AniDBInfoArray = [], $anidbId): void - { - $check = $this->pdo->queryOneRow( + /** + * Directs flow for updating child AniDB tables. + * + * @param array $AniDBInfoArray + * @param $anidbId + */ + private function updateAniChildTables(array $AniDBInfoArray = [], $anidbId): void + { + $check = $this->pdo->queryOneRow( sprintf(' SELECT ai.anidbid AS info FROM anidb_info ai @@ -573,18 +574,18 @@ class AniDB ) ); - if ($check === false) { - $picture = $this->insertAniDBInfoEps($AniDBInfoArray, $anidbId); - } else { - $picture = $this->updateAniDBInfoEps($AniDBInfoArray, $anidbId); - } + if ($check === false) { + $picture = $this->insertAniDBInfoEps($AniDBInfoArray, $anidbId); + } else { + $picture = $this->updateAniDBInfoEps($AniDBInfoArray, $anidbId); + } - if (!empty($picture) && !file_exists($this->imgSavePath . $anidbId . '.jpg')) { - (new ReleaseImage($this->pdo))->saveImage( + if (! empty($picture) && ! file_exists($this->imgSavePath.$anidbId.'.jpg')) { + (new ReleaseImage($this->pdo))->saveImage( $anidbId, - 'http://img7.anidb.net/pics/anime/' . $picture, + 'http://img7.anidb.net/pics/anime/'.$picture, $this->imgSavePath ); - } - } + } + } } diff --git a/nntmux/db/populate/PopulateTitles.php b/nntmux/db/populate/PopulateTitles.php index de322e890..2bb0898f6 100755 --- a/nntmux/db/populate/PopulateTitles.php +++ b/nntmux/db/populate/PopulateTitles.php @@ -18,138 +18,144 @@ * @author niel * @copyright 2014 nZEDb */ + namespace nntmux\db\populate; -use GuzzleHttp\Client; use nntmux\db\DB; +use GuzzleHttp\Client; class PopulateTitles { - /** - * @var \nntmux\db\Settings - */ - public $pdo; + /** + * @var \nntmux\db\Settings + */ + public $pdo; - /** - * @var \SimpleXMLElement - */ - protected $dataXML; + /** + * @var \SimpleXMLElement + */ + protected $dataXML; - /** - * @var \PDOStatement - */ - protected $checkForDuplicate; + /** + * @var \PDOStatement + */ + protected $checkForDuplicate; - /** - * @var \PDOStatement - */ - protected $insertEntry; + /** + * @var \PDOStatement + */ + protected $insertEntry; - protected $mainTable; + protected $mainTable; - /** - * URL of source data. - * - * @var string - */ - protected $sourceURL; + /** + * URL of source data. + * + * @var string + */ + protected $sourceURL; - protected $tempTable; + protected $tempTable; - /** - * @var Client - */ - protected $client; + /** + * @var Client + */ + protected $client; - /** - * @param $options - */ - - public function __construct($options) - { - $defaults = [ + /** + * @param $options + */ + public function __construct($options) + { + $defaults = [ 'pdo' => null, ]; - $options += $defaults; + $options += $defaults; - $this->sourceURL = $options['data-source-url']; - $this->mainTable = $options['main-table']; - $this->tempTable = $options['main-table'] . '_tmp'; + $this->sourceURL = $options['data-source-url']; + $this->mainTable = $options['main-table']; + $this->tempTable = $options['main-table'].'_tmp'; - if (isset($options['pdo']) && $options['pdo'] instanceof DB) { - $this->pdo = $options['pdo']; - } - } + if (isset($options['pdo']) && $options['pdo'] instanceof DB) { + $this->pdo = $options['pdo']; + } + } - protected function checkForDuplicate(array $parameters) - { - if ($this->checkForDuplicate instanceof \PDOStatement) { - $this->checkForDuplicate->execute($parameters); - return $this->checkForDuplicate->fetchAll(); - } else { - throw new \RuntimeException('Duplicate check query not yet prepared!'); - } - } + protected function checkForDuplicate(array $parameters) + { + if ($this->checkForDuplicate instanceof \PDOStatement) { + $this->checkForDuplicate->execute($parameters); - protected function createTempTable() - { - // Clear the old temporary table. - $sql = "DROP TABLE IF EXISTS {$this->tempTable}"; - $result = $this->pdo()->exec($sql); + return $this->checkForDuplicate->fetchAll(); + } else { + throw new \RuntimeException('Duplicate check query not yet prepared!'); + } + } - if ($result !== false) { - $sql = "CREATE TABLE {$this->tempTable} LIKE {$this->mainTable}"; - $result = $this->pdo()->exec($sql); - } - return $result; - } + protected function createTempTable() + { + // Clear the old temporary table. + $sql = "DROP TABLE IF EXISTS {$this->tempTable}"; + $result = $this->pdo()->exec($sql); - protected function insertEntry(array $parameters) - { - if ($this->insertEntry instanceof \PDOStatement) { - $this->insertEntry->execute($parameters); - return $this->insertEntry->fetchAll(); - } else { - throw new \RuntimeException('Insertion query not yet prepared!'); - } - } + if ($result !== false) { + $sql = "CREATE TABLE {$this->tempTable} LIKE {$this->mainTable}"; + $result = $this->pdo()->exec($sql); + } - protected function loadXMLFromFile($file) - { - $useErrors = libxml_use_internal_errors(true); - $this->dataXML = simplexml_load_file($file); + return $result; + } - if (!$this->dataXML) { - foreach (libxml_get_errors() as $error) { - echo "\t", $error->message; - } - } + protected function insertEntry(array $parameters) + { + if ($this->insertEntry instanceof \PDOStatement) { + $this->insertEntry->execute($parameters); - libxml_use_internal_errors($useErrors); - return ($this->dataXML !== false); - } + return $this->insertEntry->fetchAll(); + } else { + throw new \RuntimeException('Insertion query not yet prepared!'); + } + } - protected function pdo() - { - if ($this->pdo === null) { - $this->pdo = new DB(); - } - return $this->pdo; - } + protected function loadXMLFromFile($file) + { + $useErrors = libxml_use_internal_errors(true); + $this->dataXML = simplexml_load_file($file); - /** - * @param string $pathname full path to file for saving. Will be overwritten. - * - * @return bool|int - */ - protected function saveSourceFile($pathname) - { - $client = new Client(); - $result = false; - $file = $client->get($this->sourceURL)->getBody(); - if ($file !== false) { - $result = file_put_contents($pathname, $file); - } - return $result; - } + if (! $this->dataXML) { + foreach (libxml_get_errors() as $error) { + echo "\t", $error->message; + } + } + + libxml_use_internal_errors($useErrors); + + return $this->dataXML !== false; + } + + protected function pdo() + { + if ($this->pdo === null) { + $this->pdo = new DB(); + } + + return $this->pdo; + } + + /** + * @param string $pathname full path to file for saving. Will be overwritten. + * + * @return bool|int + */ + protected function saveSourceFile($pathname) + { + $client = new Client(); + $result = false; + $file = $client->get($this->sourceURL)->getBody(); + if ($file !== false) { + $result = file_put_contents($pathname, $file); + } + + return $result; + } } diff --git a/nntmux/http/API.php b/nntmux/http/API.php index 7f63c9833..986123ca8 100755 --- a/nntmux/http/API.php +++ b/nntmux/http/API.php @@ -18,167 +18,170 @@ * @author ruhllatio * @copyright 2016 nZEDb */ + namespace nntmux\http; -use nntmux\db\DB; -use nntmux\utility\Utility; -use nntmux\Category; use nntmux\Groups; +use nntmux\Category; +use nntmux\utility\Utility; /** - * Class API - * - * @package nntmux + * Class API. */ -class API extends Capabilities { +class API extends Capabilities +{ + /** + * @var array The get request from the web server + */ + public $getRequest; - /** - * @var array $_GET The get request from the web server - */ - public $getRequest; - - /** - * @param array $options - */ - public function __construct(array $options = []) - { - parent::__construct($options); - $defaults = [ + /** + * @param array $options + */ + public function __construct(array $options = []) + { + parent::__construct($options); + $defaults = [ 'Settings' => null, 'Request' => null, ]; - $options += $defaults; + $options += $defaults; - $this->getRequest = $options['Request']; - } + $this->getRequest = $options['Request']; + } - /** - * Add language from media info XML to release search names (Used by API) - * @param array $releases - */ - public function addLanguage(&$releases) - { - if ($releases && count($releases)) { - foreach ($releases as $key => $release) { - if (isset($release['id'])) { - $language = $this->pdo->queryOneRow(" + /** + * Add language from media info XML to release search names (Used by API). + * @param array $releases + */ + public function addLanguage(&$releases) + { + if ($releases && count($releases)) { + foreach ($releases as $key => $release) { + if (isset($release['id'])) { + $language = $this->pdo->queryOneRow(" SELECT audiolanguage FROM audio_data WHERE releases_id = {$release['id']}" ); - if ($language !== false) { - $releases[$key]['searchname'] = $releases[$key]['searchname'] . ' ' . $language['audiolanguage']; - } - } - } - } - } + if ($language !== false) { + $releases[$key]['searchname'] = $releases[$key]['searchname'].' '.$language['audiolanguage']; + } + } + } + } + } - /** - * Verify maxage parameter. - * - * @return int $maxAge The maximum age of the release - */ - public function maxAge(): int - { - $maxAge = -1; - if (isset($this->getRequest['maxage'])) { - if ($this->getRequest['maxage'] === '') { - Utility::showApiError(201, 'Incorrect parameter (maxage must not be empty)'); - } elseif (!is_numeric($this->getRequest['maxage'])) { - Utility::showApiError(201, 'Incorrect parameter (maxage must be numeric)'); - } else { - $maxAge = (int)$this->getRequest['maxage']; - } - } - return $maxAge; - } + /** + * Verify maxage parameter. + * + * @return int $maxAge The maximum age of the release + */ + public function maxAge(): int + { + $maxAge = -1; + if (isset($this->getRequest['maxage'])) { + if ($this->getRequest['maxage'] === '') { + Utility::showApiError(201, 'Incorrect parameter (maxage must not be empty)'); + } elseif (! is_numeric($this->getRequest['maxage'])) { + Utility::showApiError(201, 'Incorrect parameter (maxage must be numeric)'); + } else { + $maxAge = (int) $this->getRequest['maxage']; + } + } - /** - * Verify cat parameter. - * @return array - */ - public function categoryID(): array - { - $categoryID[] = -1; - if (isset($this->getRequest['cat'])) { - $categoryIDs = urldecode($this->getRequest['cat']); - // Append Web-DL category ID if HD present for SickBeard / Sonarr compatibility. - if (strpos($categoryIDs, Category::TV_HD) !== false && + return $maxAge; + } + + /** + * Verify cat parameter. + * @return array + */ + public function categoryID(): array + { + $categoryID[] = -1; + if (isset($this->getRequest['cat'])) { + $categoryIDs = urldecode($this->getRequest['cat']); + // Append Web-DL category ID if HD present for SickBeard / Sonarr compatibility. + if (strpos($categoryIDs, Category::TV_HD) !== false && strpos($categoryIDs, Category::TV_WEBDL) === false) { - $categoryIDs .= (',' . Category::TV_WEBDL); - } - $categoryID = explode(',', $categoryIDs); - } - return $categoryID; - } + $categoryIDs .= (','.Category::TV_WEBDL); + } + $categoryID = explode(',', $categoryIDs); + } - /** - * Verify groupName parameter. - * @return mixed - */ - public function group() - { - $groupName = -1; - if (isset($this->getRequest['group'])) { - $group = (new Groups())->isValidGroup($this->getRequest['group']); - if ($group !== false) { - $groupName = $group; - } - } - return $groupName; - } + return $categoryID; + } - /** - * Verify limit parameter. - * @return int - */ - public function limit(): int - { - $limit = 100; - if (isset($this->getRequest['limit']) && is_numeric($this->getRequest['limit']) && $this->getRequest['limit'] < 100) { - $limit = (int)$this->getRequest['limit']; - } - return $limit; - } + /** + * Verify groupName parameter. + * @return mixed + */ + public function group() + { + $groupName = -1; + if (isset($this->getRequest['group'])) { + $group = (new Groups())->isValidGroup($this->getRequest['group']); + if ($group !== false) { + $groupName = $group; + } + } - /** - * Verify offset parameter. - * @return int - */ - public function offset(): int - { - $offset = 0; - if (isset($this->getRequest['offset']) && is_numeric($this->getRequest['offset'])) { - $offset = (int)$this->getRequest['offset']; - } - return $offset; - } + return $groupName; + } - /** - * Check if a parameter is empty. - * @param string $parameter - */ - public function verifyEmptyParameter($parameter) - { - if (isset($this->getRequest[$parameter]) && $this->getRequest[$parameter] === '') { - Utility::showApiError(201, 'Incorrect parameter (' . $parameter . ' must not be empty)'); - } - } + /** + * Verify limit parameter. + * @return int + */ + public function limit(): int + { + $limit = 100; + if (isset($this->getRequest['limit']) && is_numeric($this->getRequest['limit']) && $this->getRequest['limit'] < 100) { + $limit = (int) $this->getRequest['limit']; + } - /** - * Inject the coverurl - * - * @param $releases - * @param callable $getCoverURL - */ - public function addCoverURL(&$releases, callable $getCoverURL) - { - if ($releases && count($releases)) { - foreach ($releases as $key => $release) { - $coverURL = $getCoverURL($release); - $releases[$key]['coverurl'] = $coverURL; - } - } - } + return $limit; + } + + /** + * Verify offset parameter. + * @return int + */ + public function offset(): int + { + $offset = 0; + if (isset($this->getRequest['offset']) && is_numeric($this->getRequest['offset'])) { + $offset = (int) $this->getRequest['offset']; + } + + return $offset; + } + + /** + * Check if a parameter is empty. + * @param string $parameter + */ + public function verifyEmptyParameter($parameter) + { + if (isset($this->getRequest[$parameter]) && $this->getRequest[$parameter] === '') { + Utility::showApiError(201, 'Incorrect parameter ('.$parameter.' must not be empty)'); + } + } + + /** + * Inject the coverurl. + * + * @param $releases + * @param callable $getCoverURL + */ + public function addCoverURL(&$releases, callable $getCoverURL) + { + if ($releases && count($releases)) { + foreach ($releases as $key => $release) { + $coverURL = $getCoverURL($release); + $releases[$key]['coverurl'] = $coverURL; + } + } + } } diff --git a/nntmux/http/Capabilities.php b/nntmux/http/Capabilities.php index 02ed7e7d3..c826428b6 100755 --- a/nntmux/http/Capabilities.php +++ b/nntmux/http/Capabilities.php @@ -18,77 +18,75 @@ * @author ruhllatio * @copyright 2016 nZEDb */ + namespace nntmux\http; -use App\Extensions\util\Versions; -use App\Models\Settings; -use nntmux\Category; use nntmux\db\DB; +use nntmux\Category; +use App\Models\Settings; use nntmux\utility\Utility; +use App\Extensions\util\Versions; /** - * Class Output -- abstract class for printing web requests outside of Smarty - * - * @package nntmux\http + * Class Output -- abstract class for printing web requests outside of Smarty. */ abstract class Capabilities { - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; + /** + * @var string The type of Capabilities request + */ + protected $type; - /** - * @var string The type of Capabilities request - */ - protected $type; - - /** - * Construct. - * - * @param array $options Class instances. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Construct. + * + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Settings' => null, ]; - $options += $defaults; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - } + $options += $defaults; + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + } - /** - * Print XML or JSON output. - * - * @param array $data Data to print. - * @param array $params Additional request parameters - * @param bool $xml True: Print as XML False: Print as JSON. - * @param int $offset How much releases to skip - * @param string $type What type of API query to format if XML - * - * @throws \Exception - */ - public function output($data, $params, $xml = true, $offset, $type = ''): void - { - $this->type = $type; + /** + * Print XML or JSON output. + * + * @param array $data Data to print. + * @param array $params Additional request parameters + * @param bool $xml True: Print as XML False: Print as JSON. + * @param int $offset How much releases to skip + * @param string $type What type of API query to format if XML + * + * @throws \Exception + */ + public function output($data, $params, $xml = true, $offset, $type = ''): void + { + $this->type = $type; - $options = [ + $options = [ 'Parameters' => $params, 'Data' => $data, 'Server' => $this->getForMenu(), 'Offset' => $offset, - 'Type' => $type + 'Type' => $type, ]; - // Generate the XML Response - $response = (new XML_Response($options))->returnXML(); + // Generate the XML Response + $response = (new XML_Response($options))->returnXML(); - if ($xml) { - header('Content-type: text/xml'); - } else { - // JSON encode the XMLWriter response - $response = json_encode( + if ($xml) { + header('Content-type: text/xml'); + } else { + // JSON encode the XMLWriter response + $response = json_encode( // Convert SimpleXMLElement response from XMLWriter //into array with namespace preservation Utility::xmlToArray( @@ -103,36 +101,36 @@ abstract class Capabilities ['rss']['channel'], JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES ); - header('Content-type: application/json'); - } - if ($response === false) { - Utility::showApiError(201); - } else { - header('Content-Length: ' . strlen($response)); - echo $response; - } - } + header('Content-type: application/json'); + } + if ($response === false) { + Utility::showApiError(201); + } else { + header('Content-Length: '.strlen($response)); + echo $response; + } + } - /** - * Collect and return various capability information for usage in API - * - * @return array - * @throws \Exception - */ - public function getForMenu(): array - { - $serverroot = ''; - $https = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'); + /** + * Collect and return various capability information for usage in API. + * + * @return array + * @throws \Exception + */ + public function getForMenu(): array + { + $serverroot = ''; + $https = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'); - if (isset($_SERVER['SERVER_NAME'])) { - $serverroot = ( - ($https === true ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] . - (((int)$_SERVER['SERVER_PORT'] !== 80 && (int)$_SERVER['SERVER_PORT'] !== 443) ? ':' . $_SERVER['SERVER_PORT'] : '') . - WWW_TOP . '/' + if (isset($_SERVER['SERVER_NAME'])) { + $serverroot = ( + ($https === true ? 'https://' : 'http://').$_SERVER['SERVER_NAME']. + (((int) $_SERVER['SERVER_PORT'] !== 80 && (int) $_SERVER['SERVER_PORT'] !== 443) ? ':'.$_SERVER['SERVER_PORT'] : ''). + WWW_TOP.'/' ); - } + } - return [ + return [ 'server' => [ 'appversion' => (new Versions())->getGitTagInFile(), 'version' => (new Versions())->getGitTagInRepo(), @@ -141,26 +139,25 @@ abstract class Capabilities 'email' => Settings::value('site.main.email'), 'meta' => Settings::value('site.main.metakeywords'), 'url' => $serverroot, - 'image' => $serverroot . 'themes/shared/images/tmux_logo.png' + 'image' => $serverroot.'themes/shared/images/tmux_logo.png', ], 'limits' => [ 'max' => 100, - 'default' => 100 + 'default' => 100, ], 'registration' => [ 'available' => 'yes', - 'open' => (int)Settings::value('..registerstatus') === 0 ? 'yes' : 'no' + 'open' => (int) Settings::value('..registerstatus') === 0 ? 'yes' : 'no', ], 'searching' => [ 'search' => ['available' => 'yes', 'supportedParams' => 'q'], 'tv-search' => ['available' => 'yes', 'supportedParams' => 'q,vid,tvdbid,traktid,rid,tvmazeid,imdbid,tmdbid,season,ep'], 'movie-search' => ['available' => 'yes', 'supportedParams' => 'q,imdbid'], - 'audio-search' => ['available' => 'no', 'supportedParams' => ''] + 'audio-search' => ['available' => 'no', 'supportedParams' => ''], ], - 'categories' => - $this->type === 'caps' + 'categories' => $this->type === 'caps' ? (new Category(['Settings' => $this->pdo]))->getForMenu() - : null + : null, ]; - } + } } diff --git a/nntmux/http/RSS.php b/nntmux/http/RSS.php index 4706ab392..611a56d1f 100755 --- a/nntmux/http/RSS.php +++ b/nntmux/http/RSS.php @@ -2,69 +2,67 @@ namespace nntmux\http; -use nntmux\Releases; -use nntmux\Category; use nntmux\NZB; +use nntmux\Category; +use nntmux\Releases; /** - * Class RSS -- contains specific functions for RSS - * - * @package nntmux + * Class RSS -- contains specific functions for RSS. */ -Class RSS extends Capabilities +class RSS extends Capabilities { - /** Releases class - * @var Releases - */ - public $releases; + /** Releases class + * @var Releases + */ + public $releases; - /** - * @param array $options - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - parent::__construct($options); - $defaults = [ + /** + * @param array $options + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + parent::__construct($options); + $defaults = [ 'Settings' => null, - 'Releases' => null + 'Releases' => null, ]; - $options += $defaults; + $options += $defaults; - $this->releases = ($options['Releases'] instanceof Releases ? $options['Releases'] : new Releases(['Settings' => $this->pdo])); - } + $this->releases = ($options['Releases'] instanceof Releases ? $options['Releases'] : new Releases(['Settings' => $this->pdo])); + } - /** - * Get releases for RSS. - * - * @param $cat - * @param int $offset - * @param int $userID - * @param int $videosId - * @param int $aniDbID - * @param int $airDate - * - * @return array - */ - public function getRss($cat, $offset, $videosId, $aniDbID, $userID = 0, $airDate = -1): array - { - $catSearch = $cartSearch = ''; + /** + * Get releases for RSS. + * + * @param $cat + * @param int $offset + * @param int $userID + * @param int $videosId + * @param int $aniDbID + * @param int $airDate + * + * @return array + */ + public function getRss($cat, $offset, $videosId, $aniDbID, $userID = 0, $airDate = -1): array + { + $catSearch = $cartSearch = ''; - $catLimit = 'AND r.categories_id BETWEEN ' . Category::TV_ROOT . ' AND ' . Category::TV_OTHER; + $catLimit = 'AND r.categories_id BETWEEN '.Category::TV_ROOT.' AND '.Category::TV_OTHER; - if (count($cat)) { - if ((int)$cat[0] === -2) { - $cartSearch = sprintf( + if (count($cat)) { + if ((int) $cat[0] === -2) { + $cartSearch = sprintf( 'INNER JOIN users_releases ON users_releases.users_id = %d AND users_releases.releases_id = r.id', $userID ); - } else if ((int)$cat[0] !== -1) { - $catSearch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); - } - } + } elseif ((int) $cat[0] !== -1) { + $catSearch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat); + } + } - $sql = $this->pdo->query( + $sql = $this->pdo->query( sprintf( "SELECT r.*, m.cover, m.imdbid, m.rating, m.plot, m.year, m.genre, m.director, m.actors, @@ -102,25 +100,26 @@ Class RSS extends Capabilities ($videosId > 0 ? sprintf('AND r.videos_id = %d %s', $videosId, ($catSearch === '' ? $catLimit : '')) : ''), ($aniDbID > 0 ? sprintf('AND r.anidbid = %d %s', $aniDbID, ($catSearch === '' ? $catLimit : '')) : ''), ($airDate > -1 ? sprintf('AND tve.firstaired >= DATE_SUB(CURDATE(), INTERVAL %d DAY)', $airDate) : ''), - ' LIMIT 0,' . ($offset > 100 ? 100 : $offset) + ' LIMIT 0,'.($offset > 100 ? 100 : $offset) ), true, NN_CACHE_EXPIRY_MEDIUM ); - return $sql; - } - /** - * Get TV shows for RSS. - * - * @param int $limit - * @param int $userID - * @param array $excludedCats - * @param int $airDate - * - * @return array - */ - public function getShowsRss($limit, $userID = 0, array $excludedCats = [], $airDate = -1): array - { - return $this->pdo->query( + return $sql; + } + + /** + * Get TV shows for RSS. + * + * @param int $limit + * @param int $userID + * @param array $excludedCats + * @param int $airDate + * + * @return array + */ + public function getShowsRss($limit, $userID = 0, array $excludedCats = [], $airDate = -1): array + { + return $this->pdo->query( sprintf(" SELECT r.*, v.id, v.title, g.name AS group_name, CONCAT(cp.title, '-', c.title) AS category_name, @@ -150,29 +149,29 @@ Class RSS extends Capabilities ), 'videos_id' ), - (count($excludedCats) ? 'AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')' : ''), + (count($excludedCats) ? 'AND r.categories_id NOT IN ('.implode(',', $excludedCats).')' : ''), ($airDate > -1 ? sprintf('AND tve.firstaired >= DATE_SUB(CURDATE(), INTERVAL %d DAY) ', $airDate) : ''), NZB::NZB_ADDED, Category::TV_ROOT, Category::TV_OTHER, $this->releases->showPasswords, - ' LIMIT ' . ($limit > 100 ? 100 : $limit) . ' OFFSET 0' + ' LIMIT '.($limit > 100 ? 100 : $limit).' OFFSET 0' ), true, NN_CACHE_EXPIRY_MEDIUM ); - } + } - /** - * Get movies for RSS. - * - * @param int $limit - * @param int $userID - * @param array $excludedCats - * - * @return array - */ - public function getMyMoviesRss($limit, $userID = 0, array $excludedCats = []): array - { - return $this->pdo->query( + /** + * Get movies for RSS. + * + * @param int $limit + * @param int $userID + * @param array $excludedCats + * + * @return array + */ + public function getMyMoviesRss($limit, $userID = 0, array $excludedCats = []): array + { + return $this->pdo->query( sprintf(" SELECT r.*, mi.title AS releasetitle, g.name AS group_name, CONCAT(cp.title, '-', c.title) AS category_name, @@ -201,29 +200,29 @@ Class RSS extends Capabilities ), 'imdbid' ), - (count($excludedCats) ? ' AND r.categories_id NOT IN (' . implode(',', $excludedCats) . ')' : ''), + (count($excludedCats) ? ' AND r.categories_id NOT IN ('.implode(',', $excludedCats).')' : ''), NZB::NZB_ADDED, Category::MOVIE_ROOT, Category::MOVIE_OTHER, $this->releases->showPasswords, - ' LIMIT ' . ($limit > 100 ? 100 : $limit) . ' OFFSET 0' + ' LIMIT '.($limit > 100 ? 100 : $limit).' OFFSET 0' ), true, NN_CACHE_EXPIRY_MEDIUM ); - } + } - /** - * @param $column - * @param $table - * - * @param $order - * - * @return array|bool - */ - public function getFirstInstance($column, $table, $order) - { - return $this->pdo->queryOneRow( + /** + * @param $column + * @param $table + * + * @param $order + * + * @return array|bool + */ + public function getFirstInstance($column, $table, $order) + { + return $this->pdo->queryOneRow( sprintf(' SELECT %1$s FROM %2$s @@ -234,5 +233,5 @@ Class RSS extends Capabilities $order ) ); - } + } } diff --git a/nntmux/http/XML_Response.php b/nntmux/http/XML_Response.php index 72f3b076f..155249ff8 100755 --- a/nntmux/http/XML_Response.php +++ b/nntmux/http/XML_Response.php @@ -21,110 +21,107 @@ namespace nntmux\http; -use nntmux\Utility\Utility; use nntmux\Category; +use nntmux\Utility\Utility; /** - * Class XMLReturn - * - * @package nntmux + * Class XMLReturn. */ class XML_Response { + /** + * @var string The buffered cData before final write + */ + protected $cdata; - /** - * @var string The buffered cData before final write - */ - protected $cdata; + /** + * The RSS namespace used for the output. + * + * @var string + */ + protected $namespace; - /** - * The RSS namespace used for the output - * - * @var string - */ - protected $namespace; + /** + * The trailing URL parameters on the request. + * + * @var mixed + */ + protected $parameters; - /** - * The trailing URL parameters on the request - * - * @var mixed - */ - protected $parameters; + /** + * The release we are adding to the stream. + * + * @var array + */ + protected $release; - /** - * The release we are adding to the stream - * - * @var array - */ - protected $release; + /** + * The retrieved releases we are returning from the API call. + * + * @var mixed + */ + protected $releases; - /** - * The retrieved releases we are returning from the API call - * - * @var mixed - */ - protected $releases; + /** + * The various server variables and active categories. + * + * @var mixed + */ + protected $server; - /** - * The various server variables and active categories - * - * @var mixed - */ - protected $server; + /** + * The XML formatting operation we are returning. + * + * @var mixed + */ + protected $type; - /** - * The XML formatting operation we are returning - * - * @var mixed - */ - protected $type; + /** + * The XMLWriter Class. + * + * @var \XMLWriter + */ + protected $xml; - /** - * The XMLWriter Class - * - * @var \XMLWriter - */ - protected $xml; + /** + * @var mixed + */ + protected $offset; - /** - * @var mixed - */ - protected $offset; - - /** - * XMLReturn constructor. - * - * @param array $options - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * XMLReturn constructor. + * + * @param array $options + */ + public function __construct(array $options = []) + { + $defaults = [ 'Parameters' => null, 'Data' => null, 'Server' => null, 'Offset' => null, 'Type' => null, ]; - $options += $defaults; + $options += $defaults; - $this->parameters = $options['Parameters']; - $this->releases = $options['Data']; - $this->server = $options['Server']; - $this->offset = $options['Offset']; - $this->type = $options['Type']; + $this->parameters = $options['Parameters']; + $this->releases = $options['Data']; + $this->server = $options['Server']; + $this->offset = $options['Offset']; + $this->type = $options['Type']; - $this->xml = new \XMLWriter(); - $this->xml->openMemory(); - $this->xml->setIndent(true); - } + $this->xml = new \XMLWriter(); + $this->xml->openMemory(); + $this->xml->setIndent(true); + } - /** - * @return bool|string - */ - public function returnXML() - { - if ($this->xml) { - switch ($this->type) { + /** + * @return bool|string + */ + public function returnXML() + { + if ($this->xml) { + switch ($this->type) { case 'caps': return $this->returnCaps(); break; @@ -142,177 +139,173 @@ class XML_Response return $this->returnReg(); break; } - } + } - return false; - } + return false; + } - /** - * XML writes and returns the API capabilities - * - * @return string The XML Formatted string data - */ - protected function returnCaps(): string - { - $w = $this->xml; - $s = $this->server; + /** + * XML writes and returns the API capabilities. + * + * @return string The XML Formatted string data + */ + protected function returnCaps(): string + { + $w = $this->xml; + $s = $this->server; - $w->startDocument('1.0', 'UTF-8'); - $w->startElement('caps'); - $this->addNode(['name' => 'server', 'data' => $s['server']]); - $this->addNode(['name' => 'limits', 'data' => $s['limits']]); - $this->addNode(['name' => 'registration', 'data' => $s['registration']]); - $this->addNodes(['name' => 'searching', 'data' => $s['searching']]); - $this->writeCategoryListing(); - $w->endElement(); - $w->endDocument(); + $w->startDocument('1.0', 'UTF-8'); + $w->startElement('caps'); + $this->addNode(['name' => 'server', 'data' => $s['server']]); + $this->addNode(['name' => 'limits', 'data' => $s['limits']]); + $this->addNode(['name' => 'registration', 'data' => $s['registration']]); + $this->addNodes(['name' => 'searching', 'data' => $s['searching']]); + $this->writeCategoryListing(); + $w->endElement(); + $w->endDocument(); - return $w->outputMemory(); - } + return $w->outputMemory(); + } - /** - * XML writes and returns the API data - * - * @return string The XML Formatted string data - */ - protected function returnApiRss(): string - { - $w = $this->xml; - $this->xml->startDocument('1.0', 'UTF-8'); - $this->includeRssAtom(); // Open RSS + /** + * XML writes and returns the API data. + * + * @return string The XML Formatted string data + */ + protected function returnApiRss(): string + { + $w = $this->xml; + $this->xml->startDocument('1.0', 'UTF-8'); + $this->includeRssAtom(); // Open RSS $w->startElement('channel'); // Open channel $this->includeRssAtomLink(); - $this->includeMetaInfo(); - $this->includeImage(); - $this->includeTotalRows(); - $this->includeReleases(); - $w->endElement(); // End channel + $this->includeMetaInfo(); + $this->includeImage(); + $this->includeTotalRows(); + $this->includeReleases(); + $w->endElement(); // End channel $w->endElement(); // End RSS $w->endDocument(); - return $w->outputMemory(); - } + return $w->outputMemory(); + } - /** - * @return string The XML formatted registration information - */ - protected function returnReg(): string - { - $this->xml->startDocument('1.0', 'UTF-8'); - $this->xml->startElement('register'); - $this->xml->writeAttribute('username', $this->parameters['username']); - $this->xml->writeAttribute('password', $this->parameters['password']); - $this->xml->writeAttribute('apikey', $this->parameters['token']); - $this->xml->endElement(); - $this->xml->endDocument(); + /** + * @return string The XML formatted registration information + */ + protected function returnReg(): string + { + $this->xml->startDocument('1.0', 'UTF-8'); + $this->xml->startElement('register'); + $this->xml->writeAttribute('username', $this->parameters['username']); + $this->xml->writeAttribute('password', $this->parameters['password']); + $this->xml->writeAttribute('apikey', $this->parameters['token']); + $this->xml->endElement(); + $this->xml->endDocument(); - return $this->xml->outputMemory(); - } + return $this->xml->outputMemory(); + } - /** - * Starts a new element, loops through the attribute data and ends the element - * - * @param array $element An array with the name of the element and the attribute data - */ - protected function addNode($element): void - { - $this->xml->startElement($element['name']); - foreach ($element['data'] AS $attr => $val) { - $this->xml->writeAttribute($attr, $val); - } - $this->xml->endElement(); - } + /** + * Starts a new element, loops through the attribute data and ends the element. + * + * @param array $element An array with the name of the element and the attribute data + */ + protected function addNode($element): void + { + $this->xml->startElement($element['name']); + foreach ($element['data'] as $attr => $val) { + $this->xml->writeAttribute($attr, $val); + } + $this->xml->endElement(); + } - /** - * Starts a new element, loops through the attribute data and ends the element - * - * @param array $element An array with the name of the element and the attribute data - */ - protected function addNodes($element): void - { - $this->xml->startElement($element['name']); - foreach ($element['data'] AS $elem => $value) { - $subelement['name'] = $elem; - $subelement['data'] = $value; - $this->addNode($subelement); - } - $this->xml->endElement(); - } + /** + * Starts a new element, loops through the attribute data and ends the element. + * + * @param array $element An array with the name of the element and the attribute data + */ + protected function addNodes($element): void + { + $this->xml->startElement($element['name']); + foreach ($element['data'] as $elem => $value) { + $subelement['name'] = $elem; + $subelement['data'] = $value; + $this->addNode($subelement); + } + $this->xml->endElement(); + } - /** - * Adds the site category listing to the XML feed - */ - protected function writeCategoryListing(): void - { - $this->xml->startElement('categories'); - foreach ($this->server['categories'] AS $p) { - $this->xml->startElement('category'); - $this->xml->writeAttribute('id', $p['id']); - $this->xml->writeAttribute('name', html_entity_decode($p['title'])); - if ($p['description'] !== '') { - $this->xml->writeAttribute('description', html_entity_decode($p['description'])); - } - foreach ($p['subcatlist'] AS $c) { - $this->xml->startElement('subcat'); - $this->xml->writeAttribute('id', $c['id']); - $this->xml->writeAttribute('name', html_entity_decode($c['title'])); - if ($c['description'] !== '') { - $this->xml->writeAttribute('description', html_entity_decode($c['description'])); - } - $this->xml->endElement(); - } - $this->xml->endElement(); - } - } + /** + * Adds the site category listing to the XML feed. + */ + protected function writeCategoryListing(): void + { + $this->xml->startElement('categories'); + foreach ($this->server['categories'] as $p) { + $this->xml->startElement('category'); + $this->xml->writeAttribute('id', $p['id']); + $this->xml->writeAttribute('name', html_entity_decode($p['title'])); + if ($p['description'] !== '') { + $this->xml->writeAttribute('description', html_entity_decode($p['description'])); + } + foreach ($p['subcatlist'] as $c) { + $this->xml->startElement('subcat'); + $this->xml->writeAttribute('id', $c['id']); + $this->xml->writeAttribute('name', html_entity_decode($c['title'])); + if ($c['description'] !== '') { + $this->xml->writeAttribute('description', html_entity_decode($c['description'])); + } + $this->xml->endElement(); + } + $this->xml->endElement(); + } + } - /** - * Adds RSS Atom information to the XML - * - */ - protected function includeRssAtom(): void - { - switch ($this->namespace) { + /** + * Adds RSS Atom information to the XML. + */ + protected function includeRssAtom(): void + { + switch ($this->namespace) { case 'newznab': $url = 'http://www.newznab.com/DTD/2010/feeds/attributes/'; break; case 'nntmux': default: - $url = $this->server['server']['url'] . 'rss-info/'; + $url = $this->server['server']['url'].'rss-info/'; } - $this->xml->startElement('rss'); - $this->xml->writeAttribute('version', '2.0'); - $this->xml->writeAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); - $this->xml->writeAttribute("xmlns:{$this->namespace}", $url); - $this->xml->writeAttribute('encoding', 'utf-8'); - } + $this->xml->startElement('rss'); + $this->xml->writeAttribute('version', '2.0'); + $this->xml->writeAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); + $this->xml->writeAttribute("xmlns:{$this->namespace}", $url); + $this->xml->writeAttribute('encoding', 'utf-8'); + } - /** - * - */ - protected function includeRssAtomLink(): void - { - $this->xml->startElement('atom:link'); - $this->xml->startAttribute('href'); - $this->xml->text($this->server['server']['url'] . ($this->namespace === 'newznab' ? 'api' : 'rss')); - $this->xml->endAttribute(); - $this->xml->startAttribute('rel'); - $this->xml->text('self'); - $this->xml->endAttribute(); - $this->xml->startAttribute('type'); - $this->xml->text('application/rss+xml'); - $this->xml->endAttribute(); - $this->xml->endElement(); - } + protected function includeRssAtomLink(): void + { + $this->xml->startElement('atom:link'); + $this->xml->startAttribute('href'); + $this->xml->text($this->server['server']['url'].($this->namespace === 'newznab' ? 'api' : 'rss')); + $this->xml->endAttribute(); + $this->xml->startAttribute('rel'); + $this->xml->text('self'); + $this->xml->endAttribute(); + $this->xml->startAttribute('type'); + $this->xml->text('application/rss+xml'); + $this->xml->endAttribute(); + $this->xml->endElement(); + } - /** - * Writes the channel information for the feed - */ - protected function includeMetaInfo(): void - { - $server = $this->server['server']; + /** + * Writes the channel information for the feed. + */ + protected function includeMetaInfo(): void + { + $server = $this->server['server']; - switch ($this->namespace) { + switch ($this->namespace) { case 'newznab': $path = 'apihelp/'; $tag = 'API'; @@ -323,247 +316,244 @@ class XML_Response $tag = 'RSS'; } - $this->xml->writeElement('title', $server['title']); - $this->xml->writeElement('description', $server['title'] . " {$tag} Details"); - $this->xml->writeElement('link', $server['url']); - $this->xml->writeElement('language', 'en-gb'); - $this->xml->writeElement('webMaster', $server['email'] . ' ' . $server['title']); - $this->xml->writeElement('category', $server['meta']); - $this->xml->writeElement('generator', 'nntmux'); - $this->xml->writeElement('ttl', '10'); - $this->xml->writeElement('docs', $this->server['server']['url'] . $path); - } + $this->xml->writeElement('title', $server['title']); + $this->xml->writeElement('description', $server['title']." {$tag} Details"); + $this->xml->writeElement('link', $server['url']); + $this->xml->writeElement('language', 'en-gb'); + $this->xml->writeElement('webMaster', $server['email'].' '.$server['title']); + $this->xml->writeElement('category', $server['meta']); + $this->xml->writeElement('generator', 'nntmux'); + $this->xml->writeElement('ttl', '10'); + $this->xml->writeElement('docs', $this->server['server']['url'].$path); + } - /** - * Adds nntmux logo data to the XML - */ - protected function includeImage(): void - { - $this->xml->startElement('image'); - $this->xml->writeAttribute('url', $this->server['server']['url'] . 'themes/shared/images/logo.png'); - $this->xml->writeAttribute('title', $this->server['server']['title']); - $this->xml->writeAttribute('link', $this->server['server']['url']); - $this->xml->writeAttribute( + /** + * Adds nntmux logo data to the XML. + */ + protected function includeImage(): void + { + $this->xml->startElement('image'); + $this->xml->writeAttribute('url', $this->server['server']['url'].'themes/shared/images/logo.png'); + $this->xml->writeAttribute('title', $this->server['server']['title']); + $this->xml->writeAttribute('link', $this->server['server']['url']); + $this->xml->writeAttribute( 'description', - 'Visit ' . $this->server['server']['title'] . ' - ' . $this->server['server']['strapline'] + 'Visit '.$this->server['server']['title'].' - '.$this->server['server']['strapline'] ); - $this->xml->endElement(); - } + $this->xml->endElement(); + } - /** - * - */ - public function includeTotalRows(): void - { - $this->xml->startElement($this->namespace . ':response'); - $this->xml->writeAttribute('offset', $this->offset); - $this->xml->writeAttribute('total', $this->releases[0]['_totalrows'] ?? 0); - $this->xml->endElement(); - } + public function includeTotalRows(): void + { + $this->xml->startElement($this->namespace.':response'); + $this->xml->writeAttribute('offset', $this->offset); + $this->xml->writeAttribute('total', $this->releases[0]['_totalrows'] ?? 0); + $this->xml->endElement(); + } - /** - * Loop through the releases and add their info to the XML stream - */ - public function includeReleases(): void - { - if (is_array($this->releases) && !empty($this->releases)) { - foreach ($this->releases AS $this->release) { - $this->xml->startElement('item'); - $this->includeReleaseMain(); - $this->setZedAttributes(); - $this->xml->endElement(); - } - } - } + /** + * Loop through the releases and add their info to the XML stream. + */ + public function includeReleases(): void + { + if (is_array($this->releases) && ! empty($this->releases)) { + foreach ($this->releases as $this->release) { + $this->xml->startElement('item'); + $this->includeReleaseMain(); + $this->setZedAttributes(); + $this->xml->endElement(); + } + } + } - /** - * Writes the primary release information - */ - public function includeReleaseMain(): void - { - $this->xml->writeElement('title', $this->release['searchname']); - $this->xml->startElement('guid'); - $this->xml->writeAttribute('isPermaLink', 'true'); - $this->xml->text("{$this->server['server']['url']}details/{$this->release['guid']}"); - $this->xml->endElement(); - $this->xml->writeElement( + /** + * Writes the primary release information. + */ + public function includeReleaseMain(): void + { + $this->xml->writeElement('title', $this->release['searchname']); + $this->xml->startElement('guid'); + $this->xml->writeAttribute('isPermaLink', 'true'); + $this->xml->text("{$this->server['server']['url']}details/{$this->release['guid']}"); + $this->xml->endElement(); + $this->xml->writeElement( 'link', - "{$this->server['server']['url']}getnzb/{$this->release['guid']}.nzb" . - "&i={$this->parameters['uid']}" . "&r={$this->parameters['token']}" . - ((int)$this->parameters['del'] === 1 ? '&del=1' : '') + "{$this->server['server']['url']}getnzb/{$this->release['guid']}.nzb". + "&i={$this->parameters['uid']}"."&r={$this->parameters['token']}". + ((int) $this->parameters['del'] === 1 ? '&del=1' : '') ); - $this->xml->writeElement('comments', "{$this->server['server']['url']}details/{$this->release['guid']}#comments"); - $this->xml->writeElement('pubDate', date(DATE_RSS, strtotime($this->release['adddate']))); - $this->xml->writeElement('category', $this->release['category_name']); - if ($this->namespace === 'newznab') { - $this->xml->writeElement('description', $this->release['searchname']); - } else { - $this->writeRssCdata(); - } - if (!isset($this->parameters['dl']) || (isset($this->parameters['dl']) && (int)$this->parameters['dl'] === 1)) { - $this->xml->startElement('enclosure'); - $this->xml->writeAttribute( + $this->xml->writeElement('comments', "{$this->server['server']['url']}details/{$this->release['guid']}#comments"); + $this->xml->writeElement('pubDate', date(DATE_RSS, strtotime($this->release['adddate']))); + $this->xml->writeElement('category', $this->release['category_name']); + if ($this->namespace === 'newznab') { + $this->xml->writeElement('description', $this->release['searchname']); + } else { + $this->writeRssCdata(); + } + if (! isset($this->parameters['dl']) || (isset($this->parameters['dl']) && (int) $this->parameters['dl'] === 1)) { + $this->xml->startElement('enclosure'); + $this->xml->writeAttribute( 'url', - "{$this->server['server']['url']}getnzb/{$this->release['guid']}.nzb" . - "&i={$this->parameters['uid']}" . "&r={$this->parameters['token']}" . - ((int)$this->parameters['del'] === 1 ? '&del=1' : '') + "{$this->server['server']['url']}getnzb/{$this->release['guid']}.nzb". + "&i={$this->parameters['uid']}"."&r={$this->parameters['token']}". + ((int) $this->parameters['del'] === 1 ? '&del=1' : '') ); - $this->xml->writeAttribute('length', $this->release['size']); - $this->xml->writeAttribute('type', 'application/x-nzb'); - $this->xml->endElement(); - } - } + $this->xml->writeAttribute('length', $this->release['size']); + $this->xml->writeAttribute('type', 'application/x-nzb'); + $this->xml->endElement(); + } + } - /** - * Writes the Zed (newznab) specific attributes - */ - protected function setZedAttributes(): void - { - $this->writeZedAttr('category', $this->release['categories_id']); - $this->writeZedAttr('size', $this->release['size']); - if (isset($this->release['coverurl']) && !empty($this->release['coverurl'])) { - $this->writeZedAttr( + /** + * Writes the Zed (newznab) specific attributes. + */ + protected function setZedAttributes(): void + { + $this->writeZedAttr('category', $this->release['categories_id']); + $this->writeZedAttr('size', $this->release['size']); + if (isset($this->release['coverurl']) && ! empty($this->release['coverurl'])) { + $this->writeZedAttr( 'coverurl', - $this->server['server']['url'] . "covers/{$this->release['coverurl']}" + $this->server['server']['url']."covers/{$this->release['coverurl']}" ); - } + } - if ((int)$this->parameters['extended'] === 1) { - $this->writeZedAttr('files', $this->release['totalpart']); - $this->writeZedAttr('poster', $this->release['fromname']); - if (($this->release['videos_id'] > 0 || $this->release['tv_episodes_id'] > 0) && $this->namespace === 'newznab') { - $this->setTvAttr(); - } + if ((int) $this->parameters['extended'] === 1) { + $this->writeZedAttr('files', $this->release['totalpart']); + $this->writeZedAttr('poster', $this->release['fromname']); + if (($this->release['videos_id'] > 0 || $this->release['tv_episodes_id'] > 0) && $this->namespace === 'newznab') { + $this->setTvAttr(); + } - if (isset($this->release['imdbid']) && $this->release['imdbid'] > 0) { - $this->writeZedAttr('imdb', $this->release['imdbid']); - } - if (isset($this->release['anidbid']) && $this->release['anidbid'] > 0) { - $this->writeZedAttr('anidbid', $this->release['anidbid']); - } - if (isset($this->release['predb_id']) && $this->release['predb_id'] > 0) { - $this->writeZedAttr('prematch', 1); - } - if (isset($this->release['nfostatus']) && (int)$this->release['nfostatus'] === 1) { - $this->writeZedAttr( + if (isset($this->release['imdbid']) && $this->release['imdbid'] > 0) { + $this->writeZedAttr('imdb', $this->release['imdbid']); + } + if (isset($this->release['anidbid']) && $this->release['anidbid'] > 0) { + $this->writeZedAttr('anidbid', $this->release['anidbid']); + } + if (isset($this->release['predb_id']) && $this->release['predb_id'] > 0) { + $this->writeZedAttr('prematch', 1); + } + if (isset($this->release['nfostatus']) && (int) $this->release['nfostatus'] === 1) { + $this->writeZedAttr( 'info', - $this->server['server']['url'] . + $this->server['server']['url']. "api?t=info&id={$this->release['guid']}&r={$this->parameters['token']}" ); - } + } - $this->writeZedAttr('grabs', $this->release['grabs']); - $this->writeZedAttr('comments', $this->release['comments']); - $this->writeZedAttr('password', $this->release['passwordstatus']); - $this->writeZedAttr('usenetdate', date_format(date_create($this->release['postdate']), 'D, d M Y H:i:s O')); - if (!empty($this->release['group_name'])) { - $this->writeZedAttr('group', $this->release['group_name']); - } - } - } + $this->writeZedAttr('grabs', $this->release['grabs']); + $this->writeZedAttr('comments', $this->release['comments']); + $this->writeZedAttr('password', $this->release['passwordstatus']); + $this->writeZedAttr('usenetdate', date_format(date_create($this->release['postdate']), 'D, d M Y H:i:s O')); + if (! empty($this->release['group_name'])) { + $this->writeZedAttr('group', $this->release['group_name']); + } + } + } - /** - * Writes the TV Specific attributes - */ - protected function setTvAttr(): void - { - if (!empty($this->release['title'])) { - $this->writeZedAttr('title', $this->release['title']); - } - if (isset($this->release['series']) && $this->release['series'] > 0) { - $this->writeZedAttr('season', $this->release['series']); - } - if (isset($this->release['episode']) && $this->release['episode'] > 0) { - $this->writeZedAttr('episode', $this->release['episode']); - } - if (!empty($this->release['firstaired'])) { - $this->writeZedAttr('tvairdate', $this->release['firstaired']); - } - if (isset($this->release['tvdb']) && $this->release['tvdb'] > 0) { - $this->writeZedAttr('tvdbid', $this->release['tvdb']); - } - if (isset($this->release['trakt']) && $this->release['trakt'] > 0) { - $this->writeZedAttr('traktid', $this->release['trakt']); - } - if (isset($this->release['tvrage']) && $this->release['tvrage'] > 0) { - $this->writeZedAttr('tvrageid', $this->release['tvrage']); - $this->writeZedAttr('rageid', $this->release['tvrage']); - } - if (isset($this->release['tvmaze']) && $this->release['tvmaze'] > 0) { - $this->writeZedAttr('tvmazeid', $this->release['tvmaze']); - } - if (isset($this->release['imdb']) && $this->release['imdb'] > 0) { - $this->writeZedAttr('imdbid', str_pad($this->release['imdb'], 7, '0', STR_PAD_LEFT)); - } - if (isset($this->release['tmdb']) && $this->release['tmdb'] > 0) { - $this->writeZedAttr('tmdbid', $this->release['tmdb']); - } - } + /** + * Writes the TV Specific attributes. + */ + protected function setTvAttr(): void + { + if (! empty($this->release['title'])) { + $this->writeZedAttr('title', $this->release['title']); + } + if (isset($this->release['series']) && $this->release['series'] > 0) { + $this->writeZedAttr('season', $this->release['series']); + } + if (isset($this->release['episode']) && $this->release['episode'] > 0) { + $this->writeZedAttr('episode', $this->release['episode']); + } + if (! empty($this->release['firstaired'])) { + $this->writeZedAttr('tvairdate', $this->release['firstaired']); + } + if (isset($this->release['tvdb']) && $this->release['tvdb'] > 0) { + $this->writeZedAttr('tvdbid', $this->release['tvdb']); + } + if (isset($this->release['trakt']) && $this->release['trakt'] > 0) { + $this->writeZedAttr('traktid', $this->release['trakt']); + } + if (isset($this->release['tvrage']) && $this->release['tvrage'] > 0) { + $this->writeZedAttr('tvrageid', $this->release['tvrage']); + $this->writeZedAttr('rageid', $this->release['tvrage']); + } + if (isset($this->release['tvmaze']) && $this->release['tvmaze'] > 0) { + $this->writeZedAttr('tvmazeid', $this->release['tvmaze']); + } + if (isset($this->release['imdb']) && $this->release['imdb'] > 0) { + $this->writeZedAttr('imdbid', str_pad($this->release['imdb'], 7, '0', STR_PAD_LEFT)); + } + if (isset($this->release['tmdb']) && $this->release['tmdb'] > 0) { + $this->writeZedAttr('tmdbid', $this->release['tmdb']); + } + } - /** - * Writes individual zed (newznab) type attributes - * - * @param string $name The namespaced attribute name tag - * @param string $value The namespaced attribute value - */ - protected function writeZedAttr($name, $value): void - { - $this->xml->startElement($this->namespace . ':attr'); - $this->xml->writeAttribute('name', $name); - $this->xml->writeAttribute('value', $value); - $this->xml->endElement(); - } + /** + * Writes individual zed (newznab) type attributes. + * + * @param string $name The namespaced attribute name tag + * @param string $value The namespaced attribute value + */ + protected function writeZedAttr($name, $value): void + { + $this->xml->startElement($this->namespace.':attr'); + $this->xml->writeAttribute('name', $name); + $this->xml->writeAttribute('value', $value); + $this->xml->endElement(); + } - /** - * Writes the cData (HTML format) for the RSS feed - * Also calls supplementary cData writes depending upon post process - */ - protected function writeRssCdata(): void - { - $this->cdata = ''; + /** + * Writes the cData (HTML format) for the RSS feed + * Also calls supplementary cData writes depending upon post process. + */ + protected function writeRssCdata(): void + { + $this->cdata = ''; - $w = $this->xml; - $r = $this->release; - $s = $this->server; - $p = $this->parameters; + $w = $this->xml; + $r = $this->release; + $s = $this->server; + $p = $this->parameters; - $this->cdata = "\n\t<div>\n"; - switch (1) { - case !empty($r['cover']): + $this->cdata = "\n\t<div>\n"; + switch (1) { + case ! empty($r['cover']): $dir = 'movies'; $column = 'imdbid'; break; - case !empty($r['mu_cover']): + case ! empty($r['mu_cover']): $dir = 'music'; $column = 'musicinfo_id'; break; - case !empty($r['co_cover']): + case ! empty($r['co_cover']): $dir = 'console'; $column = 'consoleinfo_id'; break; - case !empty($r['bo_cover']): + case ! empty($r['bo_cover']): $dir = 'books'; $column = 'bookinfo_id'; break; } - if (isset($dir, $column)) { - $dcov = ($dir === 'movies' ? '-cover' : ''); - $this->cdata .= - "\t<img style=\"margin-left:10px;margin-bottom:10px;float:right;\" " . - "src=\"{$s['server']['url']}covers/{$dir}/{$r[$column]}{$dcov}.jpg\" " . + if (isset($dir, $column)) { + $dcov = ($dir === 'movies' ? '-cover' : ''); + $this->cdata .= + "\t<img style=\"margin-left:10px;margin-bottom:10px;float:right;\" ". + "src=\"{$s['server']['url']}covers/{$dir}/{$r[$column]}{$dcov}.jpg\" ". "width=\"120\" alt=\"{$r['searchname']}\" />\n"; - } - $size = Utility::bytesToSizeString($r['size']); - $this->cdata .= - "\t<li>ID: <a href=\"{$s['server']['url']}details/{$r['guid']}\">{$r['guid']}</a></li>\n" . - "\t<li>Name: {$r['searchname']}</li>\n" . - "\t<li>Size: {$size}</li>\n" . - "\t<li>Category: <a href=\"{$s['server']['url']}browse?t={$r['categories_id']}\">{$r['category_name']}</a></li>\n" . - "\t<li>Group: <a href=\"{$s['server']['url']}browse?g={$r['group_name']}\">{$r['group_name']}</a></li>\n" . - "\t<li>Poster: {$r['fromname']}</li>\n" . + } + $size = Utility::bytesToSizeString($r['size']); + $this->cdata .= + "\t<li>ID: <a href=\"{$s['server']['url']}details/{$r['guid']}\">{$r['guid']}</a></li>\n". + "\t<li>Name: {$r['searchname']}</li>\n". + "\t<li>Size: {$size}</li>\n". + "\t<li>Category: <a href=\"{$s['server']['url']}browse?t={$r['categories_id']}\">{$r['category_name']}</a></li>\n". + "\t<li>Group: <a href=\"{$s['server']['url']}browse?g={$r['group_name']}\">{$r['group_name']}</a></li>\n". + "\t<li>Poster: {$r['fromname']}</li>\n". "\t<li>Posted: {$r['postdate']}</li>\n"; - switch ($r['passwordstatus']) { + switch ($r['passwordstatus']) { case 0: $pstatus = 'None'; break; @@ -579,38 +569,38 @@ class XML_Response default: $pstatus = 'Unknown'; } - $this->cdata .= "\t<li>Password: {$pstatus}</li>\n"; - if ($r['nfostatus'] === 1) { - $this->cdata .= - "\t<li>Nfo: " . - "<a href=\"{$s['server']['url']}api?t=nfo&id={$r['guid']}&raw=1&i={$p['uid']}&r={$p['token']}\">" . + $this->cdata .= "\t<li>Password: {$pstatus}</li>\n"; + if ($r['nfostatus'] === 1) { + $this->cdata .= + "\t<li>Nfo: ". + "<a href=\"{$s['server']['url']}api?t=nfo&id={$r['guid']}&raw=1&i={$p['uid']}&r={$p['token']}\">". "{$r['searchname']}.nfo</a></li>\n"; - } + } - if ($r['parentid'] === Category::MOVIE_ROOT && $r['imdbid'] !== '') { - $this->writeRssMovieInfo(); - } else if ($r['parentid'] === Category::MUSIC_ROOT && $r['musicinfo_id'] > 0) { - $this->writeRssMusicInfo(); - } else if ($r['parentid'] === Category::GAME_ROOT && $r['consoleinfo_id'] > 0) { - $this->writeRssConsoleInfo(); - } - $w->startElement('description'); - $w->writeCData($this->cdata . "\t</div>"); - $w->endElement(); - } + if ($r['parentid'] === Category::MOVIE_ROOT && $r['imdbid'] !== '') { + $this->writeRssMovieInfo(); + } elseif ($r['parentid'] === Category::MUSIC_ROOT && $r['musicinfo_id'] > 0) { + $this->writeRssMusicInfo(); + } elseif ($r['parentid'] === Category::GAME_ROOT && $r['consoleinfo_id'] > 0) { + $this->writeRssConsoleInfo(); + } + $w->startElement('description'); + $w->writeCData($this->cdata."\t</div>"); + $w->endElement(); + } - /** - * Writes the Movie Info for the RSS feed cData - */ - protected function writeRssMovieInfo(): void - { - $r = $this->release; + /** + * Writes the Movie Info for the RSS feed cData. + */ + protected function writeRssMovieInfo(): void + { + $r = $this->release; - $movieCol = ['rating', 'plot', 'year', 'genre', 'director', 'actors']; + $movieCol = ['rating', 'plot', 'year', 'genre', 'director', 'actors']; - $cData = $this->buildCdata($movieCol); + $cData = $this->buildCdata($movieCol); - $this->cdata .= + $this->cdata .= "\t<li>Imdb Info: \t<ul> \t<li>IMDB Link: <a href=\"http://www.imdb.com/title/tt{$r['imdbid']}/\">{$r['searchname']}</a></li>\n @@ -618,93 +608,93 @@ class XML_Response \t</ul> \t</li> \n"; - } + } - /** - * Writes the Music Info for the RSS feed cData - */ - protected function writeRssMusicInfo(): void - { - $r = $this->release; - $tData = $cDataUrl = ''; + /** + * Writes the Music Info for the RSS feed cData. + */ + protected function writeRssMusicInfo(): void + { + $r = $this->release; + $tData = $cDataUrl = ''; - $musicCol = ['mu_artist', 'mu_genre', 'mu_publisher', 'mu_releasedate', 'mu_review']; + $musicCol = ['mu_artist', 'mu_genre', 'mu_publisher', 'mu_releasedate', 'mu_review']; - $cData = $this->buildCdata($musicCol); + $cData = $this->buildCdata($musicCol); - if ($r['mu_url'] !== '') { - $cDataUrl = "<li>Amazon: <a href=\"{$r['mu_url']}\">{$r['mu_title']}</a></li>"; - } + if ($r['mu_url'] !== '') { + $cDataUrl = "<li>Amazon: <a href=\"{$r['mu_url']}\">{$r['mu_title']}</a></li>"; + } - $this->cdata .= + $this->cdata .= "\t<li>Music Info: <ul> {$cDataUrl} {$cData} </ul> </li>\n"; - if ($r['mu_tracks'] !== '') { - $tracks = explode('|', $r['mu_tracks']); - if (count($tracks) > 0) { - foreach ($tracks AS $track) { - $track = trim($track); - $tData .= "<li>{$track}</li>"; - } - } - $this->cdata .= " + if ($r['mu_tracks'] !== '') { + $tracks = explode('|', $r['mu_tracks']); + if (count($tracks) > 0) { + foreach ($tracks as $track) { + $track = trim($track); + $tData .= "<li>{$track}</li>"; + } + } + $this->cdata .= " <li>Track Listing: <ol> {$tData} </ol> </li>\n"; - } - } + } + } - /** - * Writes the Console Info for the RSS feed cData - */ - protected function writeRssConsoleInfo(): void - { - $r = $this->release; - $gamesCol = ['co_genre', 'co_publisher', 'year', 'co_review']; + /** + * Writes the Console Info for the RSS feed cData. + */ + protected function writeRssConsoleInfo(): void + { + $r = $this->release; + $gamesCol = ['co_genre', 'co_publisher', 'year', 'co_review']; - $cData = $this->buildCdata($gamesCol); + $cData = $this->buildCdata($gamesCol); - $this->cdata .= " + $this->cdata .= " <li>Console Info: <ul> <li>Amazon: <a href=\"{$r['co_url']}\">{$r['co_title']}</a></li>\n {$cData} </ul> </li>\n"; - } + } - /** - * Accepts an array of values to loop through to build cData from the release info - * - * @param array $columns The columns in the release we need to insert - * - * @return string The HTML format cData - */ - protected function buildCdata($columns): string - { - $r = $this->release; + /** + * Accepts an array of values to loop through to build cData from the release info. + * + * @param array $columns The columns in the release we need to insert + * + * @return string The HTML format cData + */ + protected function buildCdata($columns): string + { + $r = $this->release; - $cData = ''; + $cData = ''; - foreach ($columns AS $info) { - if (!empty($r[$info])) { - if ($info === 'mu_releasedate') { - $ucInfo = 'Released'; - $rDate = date('Y-m-d', strtotime($r[$info])); - $cData .= "<li>{$ucInfo}: {$rDate}</li>\n"; - } else { - $ucInfo = ucfirst(preg_replace('/^[a-z]{2}_/i', '', $info)); - $cData .= "<li>{$ucInfo}: {$r[$info]}</li>\n"; - } - } - } + foreach ($columns as $info) { + if (! empty($r[$info])) { + if ($info === 'mu_releasedate') { + $ucInfo = 'Released'; + $rDate = date('Y-m-d', strtotime($r[$info])); + $cData .= "<li>{$ucInfo}: {$rDate}</li>\n"; + } else { + $ucInfo = ucfirst(preg_replace('/^[a-z]{2}_/i', '', $info)); + $cData .= "<li>{$ucInfo}: {$r[$info]}</li>\n"; + } + } + } - return $cData; - } + return $cData; + } } diff --git a/nntmux/libraries/Cache.php b/nntmux/libraries/Cache.php index 8ead94fdb..2c85493c2 100755 --- a/nntmux/libraries/Cache.php +++ b/nntmux/libraries/Cache.php @@ -1,78 +1,76 @@ <?php + namespace nntmux\libraries; /** - * Class Cache + * Class Cache. * * Class for connecting to a memcached or redis server to cache data. - * - * @package nntmux\libraries */ class Cache { - const SERIALIZER_PHP = 0; - const SERIALIZER_IGBINARY = 1; - const SERIALIZER_NONE = 2; + const SERIALIZER_PHP = 0; + const SERIALIZER_IGBINARY = 1; + const SERIALIZER_NONE = 2; - const TYPE_DISABLED = 0; - const TYPE_MEMCACHED = 1; - const TYPE_REDIS = 2; - const TYPE_APC = 3; + const TYPE_DISABLED = 0; + const TYPE_MEMCACHED = 1; + const TYPE_REDIS = 2; + const TYPE_APC = 3; - /** - * @var \Memcached|\Redis - */ - private $server = null; + /** + * @var \Memcached|\Redis + */ + private $server = null; - /** - * Are we connected to the cache server? - * @var bool - */ - private $connected = false; + /** + * Are we connected to the cache server? + * @var bool + */ + private $connected = false; - /** - * Optional socket file location. - * @var bool|string - */ - private $socketFile; + /** + * Optional socket file location. + * @var bool|string + */ + private $socketFile; - /** - * Store data on the cache server. - * - * @param string $key Key we can use to retrieve the data. - * @param string|array $data Data to store on the cache server. - * @param int $expiration Time before the data expires on the cache server. - * - * @return bool Success/Failure. - * @access public - */ - public function set($key, $data, $expiration) - { - if ($this->ping()) { - switch (NN_CACHE_TYPE) { + /** + * Store data on the cache server. + * + * @param string $key Key we can use to retrieve the data. + * @param string|array $data Data to store on the cache server. + * @param int $expiration Time before the data expires on the cache server. + * + * @return bool Success/Failure. + */ + public function set($key, $data, $expiration) + { + if ($this->ping()) { + switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: case self::TYPE_MEMCACHED: return $this->server->set($key, $data, $expiration); case self::TYPE_APC: return apc_add($key, $data, $expiration); } - } - return false; - } + } - /** - * Attempt to retrieve a value from the cache server, if not set it. - * - * @param string $key Key we can use to retrieve the data. - * - * @return bool|string False on failure or String, data belonging to the key. - * @access public - */ - public function get($key) - { - if ($this->ping()) { - $data = ''; - switch (NN_CACHE_TYPE) { + return false; + } + + /** + * Attempt to retrieve a value from the cache server, if not set it. + * + * @param string $key Key we can use to retrieve the data. + * + * @return bool|string False on failure or String, data belonging to the key. + */ + public function get($key) + { + if ($this->ping()) { + $data = ''; + switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: case self::TYPE_MEMCACHED: $data = $this->server->get($key); @@ -81,40 +79,42 @@ class Cache $data = apc_fetch($key); break; } - return $data; - } - return false; - } - /** - * Delete data tied to a key on the cache server. - * - * @param string $key Key we can use to retrieve the data. - * - * @return bool True if deleted, false if not. - * @access public - */ - public function delete($key) - { - if ($this->ping()) { - switch (NN_CACHE_TYPE) { + return $data; + } + + return false; + } + + /** + * Delete data tied to a key on the cache server. + * + * @param string $key Key we can use to retrieve the data. + * + * @return bool True if deleted, false if not. + */ + public function delete($key) + { + if ($this->ping()) { + switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: case self::TYPE_MEMCACHED: - return (bool)$this->server->delete($key); + return (bool) $this->server->delete($key); case self::TYPE_APC: return apc_delete($key); } - } - return false; - } + } - /** - * Flush all data from the cache server? - */ - public function flush() - { - if ($this->ping()) { - switch (NN_CACHE_TYPE) { + return false; + } + + /** + * Flush all data from the cache server? + */ + public function flush() + { + if ($this->ping()) { + switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: $this->server->flushAll(); break; @@ -122,36 +122,34 @@ class Cache $this->server->flush(); break; case self::TYPE_APC: - apc_clear_cache("user"); + apc_clear_cache('user'); apc_clear_cache(); break; } - } - } + } + } - /** - * Create a SHA1 hash from a string which can be used to store/retrieve data. - * - * @param string $string - * - * @return string SHA1 hash of the input string. - * @access public - */ - public function createKey($string) - { - return sha1($string); - } + /** + * Create a SHA1 hash from a string which can be used to store/retrieve data. + * + * @param string $string + * + * @return string SHA1 hash of the input string. + */ + public function createKey($string) + { + return sha1($string); + } - /** - * Get cache server statistics. - * - * @return array - * @access public - */ - public function serverStatistics() - { - if ($this->ping()) { - switch (NN_CACHE_TYPE) { + /** + * Get cache server statistics. + * + * @return array + */ + public function serverStatistics() + { + if ($this->ping()) { + switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: return $this->server->info(); case self::TYPE_MEMCACHED: @@ -159,57 +157,58 @@ class Cache case self::TYPE_APC: return apc_cache_info(); } - } - return []; - } + } - /** - * Verify the user's cache settings, try to connect to the cache server. - */ - public function __construct() - { - if (!defined('NN_CACHE_HOSTS')) { - throw new CacheException( + return []; + } + + /** + * Verify the user's cache settings, try to connect to the cache server. + */ + public function __construct() + { + if (! defined('NN_CACHE_HOSTS')) { + throw new CacheException( 'The NN_CACHE_HOSTS is not defined! Define it in settings.php' ); - } + } - if (!defined('NN_CACHE_TIMEOUT')) { - throw new CacheException( + if (! defined('NN_CACHE_TIMEOUT')) { + 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.' ); - } + } - $this->socketFile = false; - if (defined('NN_CACHE_SOCKET_FILE') && NN_CACHE_SOCKET_FILE != '') { - $this->socketFile = true; - } + $this->socketFile = false; + if (defined('NN_CACHE_SOCKET_FILE') && NN_CACHE_SOCKET_FILE != '') { + $this->socketFile = true; + } - $serializer = false; - if (defined('NN_CACHE_SERIALIZER')) { - $serializer = true; - } + $serializer = false; + if (defined('NN_CACHE_SERIALIZER')) { + $serializer = true; + } - switch (NN_CACHE_TYPE) { + switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: - if (!extension_loaded('redis')) { - throw new CacheException('The redis extension is not loaded!'); + if (! extension_loaded('redis')) { + throw new CacheException('The redis extension is not loaded!'); } $this->server = new \Redis(); $this->connect(); if ($serializer) { - $this->server->setOption(\Redis::OPT_SERIALIZER, $this->verifySerializer()); + $this->server->setOption(\Redis::OPT_SERIALIZER, $this->verifySerializer()); } break; case self::TYPE_MEMCACHED: - if (!extension_loaded('memcached')) { - throw new CacheException('The memcached extension is not loaded!'); + if (! extension_loaded('memcached')) { + throw new CacheException('The memcached extension is not loaded!'); } $this->server = new \Memcached(); if ($serializer) { - $this->server->setOption(\Memcached::OPT_SERIALIZER, $this->verifySerializer()); + $this->server->setOption(\Memcached::OPT_SERIALIZER, $this->verifySerializer()); } $this->server->setOption(\Memcached::OPT_COMPRESSION, (defined('NN_CACHE_COMPRESSION') ? NN_CACHE_COMPRESSION : false)); $this->connect(); @@ -217,8 +216,8 @@ class Cache case self::TYPE_APC: // Faster than checking if apcu or apc is loaded. - if (!function_exists('apc_add')) { - throw new CacheException('The APCu extension is not loaded or enabled!'); + if (! function_exists('apc_add')) { + throw new CacheException('The APCu extension is not loaded or enabled!'); } $this->connect(); break; @@ -227,14 +226,14 @@ class Cache default: break; } - } + } - /** - * Destroy the connections. - */ - public function __destruct() - { - switch (NN_CACHE_TYPE) { + /** + * Destroy the connections. + */ + public function __destruct() + { + switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: $this->server->close(); break; @@ -242,76 +241,75 @@ class Cache $this->server->quit(); break; } - } + } - /** - * Connect to the cache server(s). - * - * @throws CacheException - * @access private - */ - private function connect() - { - $this->connected = false; - switch (NN_CACHE_TYPE) { + /** + * Connect to the cache server(s). + * + * @throws CacheException + */ + private function connect() + { + $this->connected = false; + switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: if ($this->socketFile === false) { - $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!'); - } else { - $this->connected = true; - } - } + $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!'); + } else { + $this->connected = true; + } + } } else { - if ($this->server->connect(NN_CACHE_SOCKET_FILE) === false) { - throw new CacheException('Error connecting to the Redis server!'); - } else { - $this->connected = true; - } + if ($this->server->connect(NN_CACHE_SOCKET_FILE) === false) { + throw new CacheException('Error connecting to the Redis server!'); + } else { + $this->connected = true; + } } break; case self::TYPE_MEMCACHED: $params = ($this->socketFile === false ? unserialize(NN_CACHE_HOSTS) : [[NN_CACHE_SOCKET_FILE, 'port' => 0]]); if ($this->server->addServers($params) === false) { - throw new CacheException('Error connecting to the Memcached server!'); + throw new CacheException('Error connecting to the Memcached server!'); } else { - $this->connected = true; + $this->connected = true; } break; case self::TYPE_APC: $this->connected = true; break; } - } + } - /** - * Check if we are still connected to the cache server, reconnect if not. - * - * @return bool - */ - private function ping() - { - if (!$this->connected) { - return false; - } - switch (NN_CACHE_TYPE) { + /** + * Check if we are still connected to the cache server, reconnect if not. + * + * @return bool + */ + private function ping() + { + if (! $this->connected) { + return false; + } + switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: try { - return (bool)$this->server->ping(); + return (bool) $this->server->ping(); } catch (\RedisException $error) { - // nothing to see here, move along + // nothing to see here, move along } break; case self::TYPE_MEMCACHED: $versions = $this->server->getVersion(); if ($versions) { - foreach ($versions as $version) { - if ($version != "255.255.255") { - return true; - } - } + foreach ($versions as $version) { + if ($version != '255.255.255') { + return true; + } + } } break; case self::TYPE_APC: @@ -319,35 +317,36 @@ class Cache default: return false; } - $this->connect(); - return $this->connected; - } + $this->connect(); - /** - * Verify the user selected serializer, return the memcached or redis appropriate serializer option. - * - * @return int - * @throws CacheException - * @access private - */ - private function verifySerializer() - { - switch (NN_CACHE_SERIALIZER) { + return $this->connected; + } + + /** + * Verify the user selected serializer, return the memcached or redis appropriate serializer option. + * + * @return int + * @throws CacheException + */ + private function verifySerializer() + { + switch (NN_CACHE_SERIALIZER) { case self::SERIALIZER_IGBINARY: - if (!extension_loaded('igbinary')) { - throw new CacheException('Error: The igbinary extension is not loaded!'); + if (! extension_loaded('igbinary')) { + throw new CacheException('Error: The igbinary extension is not loaded!'); } switch (NN_CACHE_TYPE) { case self::TYPE_REDIS: // If this is not defined, it means phpredis was not compiled with --enable-redis-igbinary - if (!defined('\Redis::SERIALIZER_IGBINARY')) { - throw new CacheException('Error: phpredis was not compiled with igbinary support!'); + if (! defined('\Redis::SERIALIZER_IGBINARY')) { + throw new CacheException('Error: phpredis was not compiled with igbinary support!'); } + return \Redis::SERIALIZER_IGBINARY; case self::TYPE_MEMCACHED: if (\Memcached::HAVE_IGBINARY > 0) { - return \Memcached::SERIALIZER_IGBINARY; + return \Memcached::SERIALIZER_IGBINARY; } throw new CacheException('Error: You have not compiled Memcached with igbinary support!'); case self::TYPE_APC: // Ignore - set by apc.serializer setting. @@ -358,8 +357,9 @@ class Cache case self::SERIALIZER_NONE: // Only redis supports this. if (NN_CACHE_TYPE != self::TYPE_REDIS) { - throw new CacheException('Error: Disabled serialization is only available on Redis!'); + throw new CacheException('Error: Disabled serialization is only available on Redis!'); } + return \Redis::SERIALIZER_NONE; case self::SERIALIZER_PHP: @@ -373,6 +373,5 @@ class Cache return null; } } - } - + } } diff --git a/nntmux/libraries/CacheException.php b/nntmux/libraries/CacheException.php index 5ac395da3..d4cfa77be 100755 --- a/nntmux/libraries/CacheException.php +++ b/nntmux/libraries/CacheException.php @@ -18,13 +18,11 @@ * @author niel * @copyright 2015 nZEDb */ + namespace nntmux\libraries; - /** - * Class CacheException - * - * @package \nzedb\libraries + * Class CacheException. */ class CacheException extends \Exception { diff --git a/nntmux/libraries/FanartTV.php b/nntmux/libraries/FanartTV.php index 81b1d258f..a223d75d0 100644 --- a/nntmux/libraries/FanartTV.php +++ b/nntmux/libraries/FanartTV.php @@ -2,7 +2,7 @@ /** * Fanart.TV * PHP class - wrapper for Fanart.TV's API - * API Documentation - http://docs.fanarttv.apiary.io/# + * API Documentation - http://docs.fanarttv.apiary.io/#. * * @author confact <hakan@dun.se> * @author DariusIII <dkrisan@gmail.com> @@ -10,75 +10,79 @@ * @copyright 2017 NNTmux * @date 2017-04-12 * @release <0.0.2> - * */ namespace nntmux\libraries; - class FanartTV { - /** - * The constructor setting the config variables - * - * @param $apiKey - */ - public function __construct($apiKey) - { - $this->apikey = $apiKey; - $this->server = 'https://webservice.fanart.tv/v3'; - } - /** - * Getting movie pictures - * - * @param string $id - * - * @return array|bool - */ - public function getMovieFanart($id) - { - if ($this->apikey !== '') { - $fanart = $this->_call('movies/' . $id); - if (!empty($fanart)) { - return $fanart; - } - return false; - } + /** + * The constructor setting the config variables. + * + * @param $apiKey + */ + public function __construct($apiKey) + { + $this->apikey = $apiKey; + $this->server = 'https://webservice.fanart.tv/v3'; + } - return false; - } - /** - * Getting tv show pictures - * - * @param string $id - * @return array|bool - */ - public function getTVFanart($id) - { - if ($this->apikey !== '') { - $fanart = $this->_call('tv/' . $id); - if (!empty($fanart)) { - return $fanart; - } - return false; - } + /** + * Getting movie pictures. + * + * @param string $id + * + * @return array|bool + */ + public function getMovieFanart($id) + { + if ($this->apikey !== '') { + $fanart = $this->_call('movies/'.$id); + if (! empty($fanart)) { + return $fanart; + } - return false; - } - /** - * The function making all the work using curl to call - * - * @param string $path - * @return array - */ - private function _call($path) - { - $url = $this->server . '/' . $path . '?api_key=' . $this->apikey; - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - $response = curl_exec($ch); - curl_close($ch); - return json_decode($response, true); - } + return false; + } + + return false; + } + + /** + * Getting tv show pictures. + * + * @param string $id + * @return array|bool + */ + public function getTVFanart($id) + { + if ($this->apikey !== '') { + $fanart = $this->_call('tv/'.$id); + if (! empty($fanart)) { + return $fanart; + } + + return false; + } + + return false; + } + + /** + * The function making all the work using curl to call. + * + * @param string $path + * @return array + */ + private function _call($path) + { + $url = $this->server.'/'.$path.'?api_key='.$this->apikey; + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $response = curl_exec($ch); + curl_close($ch); + + return json_decode($response, true); + } } diff --git a/nntmux/libraries/Forking.php b/nntmux/libraries/Forking.php index f653929f7..d96355c9d 100755 --- a/nntmux/libraries/Forking.php +++ b/nntmux/libraries/Forking.php @@ -1,66 +1,61 @@ <?php + namespace nntmux\libraries; -use App\Models\Settings; -use nntmux\Category; -use nntmux\ColorCLI; -use nntmux\MiscSorter; -use nntmux\NameFixer; use nntmux\Nfo; -use nntmux\NNTP; use nntmux\NZB; -use nntmux\RequestID; +use nntmux\NNTP; use nntmux\db\DB; +use nntmux\ColorCLI; +use nntmux\RequestID; +use App\Models\Settings; use nntmux\processing\PostProcess; /** - * Class Forking + * Class Forking. * * This forks various newznab scripts. * * 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 nntmux\libraries */ class Forking extends \fork_daemon { - const OUTPUT_NONE = 0; // Don't display child output. + const OUTPUT_NONE = 0; // Don't display child output. const OUTPUT_REALTIME = 1; // Display child output in real time. const OUTPUT_SERIALLY = 2; // Display child output when child is done. - /** * Setup required parent / self vars. */ - public function __construct() - { - parent::__construct(); + public function __construct() + { + parent::__construct(); - $this->_colorCLI = new ColorCLI(); + $this->_colorCLI = new ColorCLI(); - $this->register_logging( + $this->register_logging( [0 => $this, 1 => 'logger'], (defined('NN_MULTIPROCESSING_LOG_TYPE') ? NN_MULTIPROCESSING_LOG_TYPE : \fork_daemon::LOG_LEVEL_INFO) ); - if (defined('NN_MULTIPROCESSING_MAX_CHILD_WORK')) { - $this->max_work_per_child_set(NN_MULTIPROCESSING_MAX_CHILD_WORK); - } else { - $this->max_work_per_child_set(1); - } + if (defined('NN_MULTIPROCESSING_MAX_CHILD_WORK')) { + $this->max_work_per_child_set(NN_MULTIPROCESSING_MAX_CHILD_WORK); + } else { + $this->max_work_per_child_set(1); + } - if (defined('NN_MULTIPROCESSING_MAX_CHILD_TIME')) { - $this->child_max_run_time_set(NN_MULTIPROCESSING_MAX_CHILD_TIME); - } else { - $this->child_max_run_time_set(1800); - } + if (defined('NN_MULTIPROCESSING_MAX_CHILD_TIME')) { + $this->child_max_run_time_set(NN_MULTIPROCESSING_MAX_CHILD_TIME); + } else { + $this->child_max_run_time_set(1800); + } - // Use a single exit method for all children, makes things easier. - $this->register_parent_child_exit([0 => $this, 1 => 'childExit']); + // Use a single exit method for all children, makes things easier. + $this->register_parent_child_exit([0 => $this, 1 => 'childExit']); - if (defined('NN_MULTIPROCESSING_CHILD_OUTPUT_TYPE')) { - switch (NN_MULTIPROCESSING_CHILD_OUTPUT_TYPE) { + if (defined('NN_MULTIPROCESSING_CHILD_OUTPUT_TYPE')) { + switch (NN_MULTIPROCESSING_CHILD_OUTPUT_TYPE) { case 0: $this->outputType = self::OUTPUT_NONE; break; @@ -73,76 +68,76 @@ class Forking extends \fork_daemon default: $this->outputType = self::OUTPUT_REALTIME; } - } else { - $this->outputType = self::OUTPUT_REALTIME; - } + } else { + $this->outputType = self::OUTPUT_REALTIME; + } - $this->dnr_path = PHP_BINARY . ' ' . NN_MULTIPROCESSING . '.do_not_run' . DS . 'switch.php "php '; - } + $this->dnr_path = PHP_BINARY.' '.NN_MULTIPROCESSING.'.do_not_run'.DS.'switch.php "php '; + } - /** - * Setup the class to work on a type of work, then process the work. - * Valid work types: - * - * @param string $type The type of multiProcessing to do : backfill, binaries, releases, postprocess - * @param array $options Array containing arguments for the type of work. - * - * @throws ForkingException - */ - public function processWorkType($type, array $options = []) - { - // Set/reset some variables. - $startTime = microtime(true); - $this->workType = $type; - $this->workTypeOptions = $options; - $this->processAdditional = $this->processNFO = $this->processTV = $this->processMovies = $this->ppRenamedOnly = false; - $this->work = []; + /** + * Setup the class to work on a type of work, then process the work. + * Valid work types:. + * + * @param string $type The type of multiProcessing to do : backfill, binaries, releases, postprocess + * @param array $options Array containing arguments for the type of work. + * + * @throws ForkingException + */ + public function processWorkType($type, array $options = []) + { + // Set/reset some variables. + $startTime = microtime(true); + $this->workType = $type; + $this->workTypeOptions = $options; + $this->processAdditional = $this->processNFO = $this->processTV = $this->processMovies = $this->ppRenamedOnly = false; + $this->work = []; - // Init Settings here, as forking causes errors when it's destroyed. - $this->pdo = new DB(); + // Init Settings here, as forking causes errors when it's destroyed. + $this->pdo = new DB(); - // Process extra work that should not be forked and done before forking. - $this->processStartWork(); + // Process extra work that should not be forked and done before forking. + $this->processStartWork(); - // Get work to fork. - $this->getWork(); + // Get work to fork. + $this->getWork(); - // Now we destroy settings, to prevent errors from forking. - unset($this->pdo); + // Now we destroy settings, to prevent errors from forking. + unset($this->pdo); - // Process the work we got. - $this->processWork(); + // Process the work we got. + $this->processWork(); - // Process extra work that should not be forked and done after. - $this->processEndWork(); + // Process extra work that should not be forked and done after. + $this->processEndWork(); - if (NN_ECHOCLI) { - ColorCLI::doEcho( + if (NN_ECHOCLI) { + ColorCLI::doEcho( ColorCLI::header( - 'Multi-processing for ' . $this->workType . ' finished in ' . (microtime(true) - $startTime) . - ' seconds at ' . date(DATE_RFC2822) . '.' . PHP_EOL + 'Multi-processing for '.$this->workType.' finished in '.(microtime(true) - $startTime). + ' seconds at '.date(DATE_RFC2822).'.'.PHP_EOL ) ); - } - } + } + } - /** - * Only post process renamed movie / tv releases? - * - * @var bool - */ - private $ppRenamedOnly; + /** + * Only post process renamed movie / tv releases? + * + * @var bool + */ + private $ppRenamedOnly; - /** - * Get work for our workers to work on, set the max child processes here. - * - * @throws \Exception - */ - private function getWork() - { - $maxProcesses = 0; + /** + * Get work for our workers to work on, set the max child processes here. + * + * @throws \Exception + */ + private function getWork() + { + $maxProcesses = 0; - switch ($this->workType) { + switch ($this->workType) { case 'backfill': $maxProcesses = $this->backfillMainMethod(); @@ -204,151 +199,150 @@ class Forking extends \fork_daemon break; } - $this->setMaxProcesses($maxProcesses); - } + $this->setMaxProcesses($maxProcesses); + } - /** - * Process work if we have any. - */ - private function processWork() - { - $this->_workCount = count($this->work); - if ($this->_workCount > 0) { - - if (NN_ECHOCLI) { - ColorCLI::doEcho( + /** + * Process work if we have any. + */ + private function processWork() + { + $this->_workCount = count($this->work); + if ($this->_workCount > 0) { + if (NN_ECHOCLI) { + ColorCLI::doEcho( ColorCLI::header( - 'Multi-processing started at ' . date(DATE_RFC2822) . ' for ' . $this->workType . ' with ' . $this->_workCount . - ' job(s) to do using a max of ' . $this->maxProcesses . ' child process(es).' + 'Multi-processing started at '.date(DATE_RFC2822).' for '.$this->workType.' with '.$this->_workCount. + ' job(s) to do using a max of '.$this->maxProcesses.' child process(es).' ) ); - } + } - $this->addwork($this->work); - $this->process_work(true); - } else { - if (NN_ECHOCLI) { - ColorCLI::doEcho( + $this->addwork($this->work); + $this->process_work(true); + } else { + if (NN_ECHOCLI) { + ColorCLI::doEcho( ColorCLI::header('No work to do!') ); - } - } - } + } + } + } - /** - * Process any work that does not need to be forked, but needs to run at the end. - */ - private function processStartWork() - { - switch ($this->workType) { + /** + * Process any work that does not need to be forked, but needs to run at the end. + */ + private function processStartWork() + { + switch ($this->workType) { case 'safe_backfill': case 'safe_binaries': $this->_executeCommand( - PHP_BINARY . ' ' . NN_NIX . 'tmux/bin/update_groups.php' + PHP_BINARY.' '.NN_NIX.'tmux/bin/update_groups.php' ); break; } - } + } - /** - * Process any work that does not need to be forked, but needs to run at the end. - */ - private function processEndWork() - { - switch ($this->workType) { + /** + * Process any work that does not need to be forked, but needs to run at the end. + */ + private function processEndWork() + { + switch ($this->workType) { case 'releases': $this->_executeCommand( - $this->dnr_path . 'releases ' . count($this->work) . '_"' + $this->dnr_path.'releases '.count($this->work).'_"' ); break; case 'update_per_group': $this->_executeCommand( - $this->dnr_path . 'releases ' . count($this->work) . '_"' + $this->dnr_path.'releases '.count($this->work).'_"' ); break; } - } + } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //////////////////////////////////////// All backFill code here //////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////// All backFill code here //////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /** - * @return int - * @throws \Exception - */ - private function backfillMainMethod() - { - $this->register_child_run([0 => $this, 1 => 'backFillChildWorker']); - // The option for backFill is for doing up to x articles. Else it's done by date. - $this->work = $this->pdo->query( + /** + * @return int + * @throws \Exception + */ + private function backfillMainMethod() + { + $this->register_child_run([0 => $this, 1 => 'backFillChildWorker']); + // The option for backFill is for doing up to x articles. Else it's done by date. + $this->work = $this->pdo->query( sprintf( 'SELECT name %s FROM groups WHERE backfill = 1', - ($this->workTypeOptions[0] === false ? '' : (', ' . $this->workTypeOptions[0] . ' AS max')) + ($this->workTypeOptions[0] === false ? '' : (', '.$this->workTypeOptions[0].' AS max')) ) ); - return (int)Settings::value('..backfillthreads'); - } + return (int) Settings::value('..backfillthreads'); + } - /** - * @param $groups - * @param string $identifier - */ - public function backFillChildWorker($groups, $identifier = '') - { - foreach ($groups as $group) { - $this->_executeCommand( - PHP_BINARY . ' ' . NN_UPDATE . 'backfill.php ' . - $group['name'] . (isset($group['max']) ? (' ' . $group['max']) : '') + /** + * @param $groups + * @param string $identifier + */ + public function backFillChildWorker($groups, $identifier = '') + { + foreach ($groups as $group) { + $this->_executeCommand( + PHP_BINARY.' '.NN_UPDATE.'backfill.php '. + $group['name'].(isset($group['max']) ? (' '.$group['max']) : '') ); - } - } + } + } - /** - * @return int - * @throws \Exception - */ - private function safeBackfillMainMethod() - { - $this->register_child_run([0 => $this, 1 => 'safeBackfillChildWorker']); + /** + * @return int + * @throws \Exception + */ + private function safeBackfillMainMethod() + { + $this->register_child_run([0 => $this, 1 => 'safeBackfillChildWorker']); - $run = $this->pdo->query("SELECT (SELECT value FROM tmux WHERE setting = 'backfill_qty') AS qty, (SELECT value FROM tmux WHERE setting = 'backfill') AS backfill, (SELECT value FROM tmux WHERE setting = 'backfill_order') AS orderby, (SELECT value FROM tmux WHERE setting = 'backfill_days') AS days, (SELECT value FROM settings WHERE setting = 'maxmssgs') AS maxmsgs"); - $threads = Settings::value('..backfillthreads'); + $run = $this->pdo->query("SELECT (SELECT value FROM tmux WHERE setting = 'backfill_qty') AS qty, (SELECT value FROM tmux WHERE setting = 'backfill') AS backfill, (SELECT value FROM tmux WHERE setting = 'backfill_order') AS orderby, (SELECT value FROM tmux WHERE setting = 'backfill_days') AS days, (SELECT value FROM settings WHERE setting = 'maxmssgs') AS maxmsgs"); + $threads = Settings::value('..backfillthreads'); - $orderby = "ORDER BY a.last_record ASC"; - switch ((int)$run[0]['orderby']) { + $orderby = 'ORDER BY a.last_record ASC'; + switch ((int) $run[0]['orderby']) { case 1: - $orderby = "ORDER BY first_record_postdate DESC"; + $orderby = 'ORDER BY first_record_postdate DESC'; break; case 2: - $orderby = "ORDER BY first_record_postdate ASC"; + $orderby = 'ORDER BY first_record_postdate ASC'; break; case 3: - $orderby = "ORDER BY name ASC"; + $orderby = 'ORDER BY name ASC'; break; case 4: - $orderby = "ORDER BY name DESC"; + $orderby = 'ORDER BY name DESC'; break; case 5: - $orderby = "ORDER BY a.last_record DESC"; + $orderby = 'ORDER BY a.last_record DESC'; break; } - $backfilldays = ''; - if ($run[0]['days'] == 1) { - $backfilldays = "backfill_target"; - } elseif ($run[0]['days'] == 2) { - $backfilldays = round(abs(strtotime(date("Y-m-d")) - strtotime(Settings::value('..safebackfilldate'))) / 86400); - } + $backfilldays = ''; + if ($run[0]['days'] == 1) { + $backfilldays = 'backfill_target'; + } elseif ($run[0]['days'] == 2) { + $backfilldays = round(abs(strtotime(date('Y-m-d')) - strtotime(Settings::value('..safebackfilldate'))) / 86400); + } - $data = $this->pdo->queryOneRow( + $data = $this->pdo->queryOneRow( sprintf( - "SELECT g.name, + 'SELECT g.name, g.first_record AS our_first, MAX(a.first_record) AS their_first, MAX(a.last_record) AS their_last @@ -359,183 +353,179 @@ class Forking extends \fork_daemon AND g.backfill = 1 AND (NOW() - INTERVAL %s DAY) < g.first_record_postdate GROUP BY a.name, a.last_record, g.name, g.first_record - %s", + %s', $backfilldays, $orderby ) ); - $count = 0; - if ($data['name']) { - $this->safeBackfillGroup = $data['name']; + $count = 0; + if ($data['name']) { + $this->safeBackfillGroup = $data['name']; - $count = ($data['our_first'] - $data['their_first']); - } + $count = ($data['our_first'] - $data['their_first']); + } - if ($count > 0) { - if ($count > ($run[0]['qty'] * $threads)) { - $geteach = ceil(($run[0]['qty'] * $threads) / $run[0]['maxmsgs']); - } else { - $geteach = $count / $run[0]['maxmsgs']; - } + if ($count > 0) { + if ($count > ($run[0]['qty'] * $threads)) { + $geteach = ceil(($run[0]['qty'] * $threads) / $run[0]['maxmsgs']); + } else { + $geteach = $count / $run[0]['maxmsgs']; + } - $queue = []; - for ($i = 0; $i <= $geteach - 1; $i++) { - $queue[$i] = sprintf("get_range backfill %s %s %s %s", $data['name'], $data['our_first'] - $i * $run[0]['maxmsgs'] - $run[0]['maxmsgs'], $data['our_first'] - $i * $run[0]['maxmsgs'] - 1, $i + 1); - } - $this->work = $queue; - } + $queue = []; + for ($i = 0; $i <= $geteach - 1; $i++) { + $queue[$i] = sprintf('get_range backfill %s %s %s %s', $data['name'], $data['our_first'] - $i * $run[0]['maxmsgs'] - $run[0]['maxmsgs'], $data['our_first'] - $i * $run[0]['maxmsgs'] - 1, $i + 1); + } + $this->work = $queue; + } - return $threads; - } + return $threads; + } - /** - * @param $ranges - * @param string $identifier - */ - public function safeBackfillChildWorker($ranges, $identifier = '') - { - foreach ($ranges as $range) { - $this->_executeCommand( - $this->dnr_path . $range . '"' + /** + * @param $ranges + * @param string $identifier + */ + public function safeBackfillChildWorker($ranges, $identifier = '') + { + foreach ($ranges as $range) { + $this->_executeCommand( + $this->dnr_path.$range.'"' ); - } + } + } - return; - } + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////// All binaries code here //////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //////////////////////////////////////// All binaries code here //////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * @return null|string - * @throws \Exception - */ - private function binariesMainMethod() - { - $this->register_child_run([0 => $this, 1 => 'binariesChildWorker']); - $this->work = $this->pdo->query( + /** + * @return null|string + * @throws \Exception + */ + private function binariesMainMethod() + { + $this->register_child_run([0 => $this, 1 => 'binariesChildWorker']); + $this->work = $this->pdo->query( sprintf( 'SELECT name, %d AS max FROM groups WHERE active = 1', $this->workTypeOptions[0] ) ); - return Settings::value('..binarythreads'); - } + return Settings::value('..binarythreads'); + } - /** - * @param $groups - * @param string $identifier - */ - public function binariesChildWorker($groups, $identifier = '') - { - foreach ($groups as $group) { - $this->_executeCommand( - PHP_BINARY . ' ' . NN_UPDATE . 'update_binaries.php ' . $group['name'] . ' ' . $group['max'] + /** + * @param $groups + * @param string $identifier + */ + public function binariesChildWorker($groups, $identifier = '') + { + foreach ($groups as $group) { + $this->_executeCommand( + PHP_BINARY.' '.NN_UPDATE.'update_binaries.php '.$group['name'].' '.$group['max'] ); - } - } + } + } - /** - * @return int - * @throws \Exception - */ - private function safeBinariesMainMethod() - { - $this->register_child_run([0 => $this, 1 => 'safeBinariesChildWorker']); + /** + * @return int + * @throws \Exception + */ + private function safeBinariesMainMethod() + { + $this->register_child_run([0 => $this, 1 => 'safeBinariesChildWorker']); - $maxheaders = Settings::value('max.headers.iteration') ?: 1000000; - $maxmssgs = Settings::value('..maxmssgs'); - $threads = Settings::value('..binarythreads'); + $maxheaders = Settings::value('max.headers.iteration') ?: 1000000; + $maxmssgs = Settings::value('..maxmssgs'); + $threads = Settings::value('..binarythreads'); - $groups = $this->pdo->query(" + $groups = $this->pdo->query(' SELECT g.name AS groupname, g.last_record AS our_last, a.last_record AS their_last FROM groups g INNER JOIN short_groups a ON g.active = 1 AND g.name = a.name - ORDER BY a.last_record DESC" + ORDER BY a.last_record DESC' ); - if ($groups) { - $i = 1; - $queue = []; - foreach ($groups as $group) { - if ($group['our_last'] == 0) { - $queue[$i] = sprintf("update_group_headers %s", $group['groupname']); - $i++; - } else { - //only process if more than 20k headers available and skip the first 20k - $count = $group['their_last'] - $group['our_last'] - 20000; - //echo "count: " . $count . "maxmsgs x2: " . ($maxmssgs * 2) . PHP_EOL; - if ($count <= $maxmssgs * 2) { - $queue[$i] = sprintf("update_group_headers %s", $group['groupname']); - $i++; - } else { - $queue[$i] = sprintf("part_repair %s", $group['groupname']); - $i++; - $geteach = floor(min($count, $maxheaders) / $maxmssgs); - $remaining = min($count, $maxheaders) - $geteach * $maxmssgs; - //echo "maxmssgs: " . $maxmssgs . " geteach: " . $geteach . " remaining: " . $remaining . PHP_EOL; - for ($j = 0; $j < $geteach; $j++) { - $queue[$i] = sprintf("get_range binaries %s %s %s %s", $group['groupname'], $group['our_last'] + $j * $maxmssgs + 1, $group['our_last'] + $j * $maxmssgs + $maxmssgs, $i); - $i++; - } - //add remainder to queue - $queue[$i] = sprintf("get_range binaries %s %s %s %s", $group['groupname'], $group['our_last'] + ($j + 1) * $maxmssgs + 1, $group['our_last'] + ($j + 1) * $maxmssgs + $remaining + 1, $i); - $i++; - } - } - } - //var_dump($queue); - $this->work = $queue; - } + if ($groups) { + $i = 1; + $queue = []; + foreach ($groups as $group) { + if ($group['our_last'] == 0) { + $queue[$i] = sprintf('update_group_headers %s', $group['groupname']); + $i++; + } else { + //only process if more than 20k headers available and skip the first 20k + $count = $group['their_last'] - $group['our_last'] - 20000; + //echo "count: " . $count . "maxmsgs x2: " . ($maxmssgs * 2) . PHP_EOL; + if ($count <= $maxmssgs * 2) { + $queue[$i] = sprintf('update_group_headers %s', $group['groupname']); + $i++; + } else { + $queue[$i] = sprintf('part_repair %s', $group['groupname']); + $i++; + $geteach = floor(min($count, $maxheaders) / $maxmssgs); + $remaining = min($count, $maxheaders) - $geteach * $maxmssgs; + //echo "maxmssgs: " . $maxmssgs . " geteach: " . $geteach . " remaining: " . $remaining . PHP_EOL; + for ($j = 0; $j < $geteach; $j++) { + $queue[$i] = sprintf('get_range binaries %s %s %s %s', $group['groupname'], $group['our_last'] + $j * $maxmssgs + 1, $group['our_last'] + $j * $maxmssgs + $maxmssgs, $i); + $i++; + } + //add remainder to queue + $queue[$i] = sprintf('get_range binaries %s %s %s %s', $group['groupname'], $group['our_last'] + ($j + 1) * $maxmssgs + 1, $group['our_last'] + ($j + 1) * $maxmssgs + $remaining + 1, $i); + $i++; + } + } + } + //var_dump($queue); + $this->work = $queue; + } - return $threads; - } + return $threads; + } - /** - * @param $ranges - * @param string $identifier - */ - public function safeBinariesChildWorker($ranges, $identifier = '') - { - foreach ($ranges as $range) { - $this->_executeCommand( - $this->dnr_path . $range . '"' + /** + * @param $ranges + * @param string $identifier + */ + public function safeBinariesChildWorker($ranges, $identifier = '') + { + foreach ($ranges as $range) { + $this->_executeCommand( + $this->dnr_path.$range.'"' ); - } + } + } - return; - } + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////// All fix release names code here /////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //////////////////////////////////// All fix release names code here /////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /** + * @return int|null|string + * @throws \Exception + */ + private function fixRelNamesMainMethod() + { + $this->register_child_run([0 => $this, 1 => 'fixRelNamesChildWorker']); - /** - * @return int|null|string - * @throws \Exception - */ - private function fixRelNamesMainMethod() - { - $this->register_child_run([0 => $this, 1 => 'fixRelNamesChildWorker']); + $threads = (int) Settings::value('..fixnamethreads'); + $maxperrun = (int) Settings::value('..fixnamesperrun'); - $threads = (int)Settings::value('..fixnamethreads'); - $maxperrun = (int)Settings::value('..fixnamesperrun'); + if ($threads > 16) { + $threads = 16; + } elseif ($threads == 0) { + $threads = 1; + } - if ($threads > 16) { - $threads = 16; - } else if ($threads == 0) { - $threads = 1; - } + $leftguids = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; - $leftguids = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; - - // Prevent PreDB FT from always running - if ($this->workTypeOptions[0] === 'predbft') { - $preCount = $this->pdo->queryOneRow( + // Prevent PreDB FT from always running + if ($this->workTypeOptions[0] === 'predbft') { + $preCount = $this->pdo->queryOneRow( sprintf(" SELECT COUNT(p.id) AS num FROM predb p @@ -545,129 +535,129 @@ class Forking extends \fork_daemon AND p.predate < (NOW() - INTERVAL 1 DAY)" ) ); - if ($preCount['num'] > 0) { - $leftguids = array_slice($leftguids, 0, (int)ceil($preCount['num'] / $maxperrun)); - } else { - $leftguids = []; - } - } + if ($preCount['num'] > 0) { + $leftguids = array_slice($leftguids, 0, (int) ceil($preCount['num'] / $maxperrun)); + } else { + $leftguids = []; + } + } - $count = 0; - $queue = []; - foreach ($leftguids as $leftguid) { - $count++; - if ($maxperrun > 0) { - $queue[$count] = sprintf('%s %s %s %s', $this->workTypeOptions[0], $leftguid, $maxperrun, $count); - } - } - $this->work = $queue; + $count = 0; + $queue = []; + foreach ($leftguids as $leftguid) { + $count++; + if ($maxperrun > 0) { + $queue[$count] = sprintf('%s %s %s %s', $this->workTypeOptions[0], $leftguid, $maxperrun, $count); + } + } + $this->work = $queue; - return $threads; - } + return $threads; + } - /** - * @param $guids - * @param string $identifier - */ - public function fixRelNamesChildWorker($guids, $identifier = '') - { - foreach ($guids as $guid) { - $this->_executeCommand( - PHP_BINARY . ' ' . NN_NIX . 'tmux/bin/groupfixrelnames.php "' . $guid . '"' . ' true' + /** + * @param $guids + * @param string $identifier + */ + public function fixRelNamesChildWorker($guids, $identifier = '') + { + foreach ($guids as $guid) { + $this->_executeCommand( + PHP_BINARY.' '.NN_NIX.'tmux/bin/groupfixrelnames.php "'.$guid.'"'.' true' ); - } - } + } + } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //////////////////////////////////////// All releases code here //////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////// All releases code here //////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /** - * @return null|string - * @throws \Exception - */ - private function releasesMainMethod() - { - $this->register_child_run([0 => $this, 1 => 'releasesChildWorker']); + /** + * @return null|string + * @throws \Exception + */ + private function releasesMainMethod() + { + $this->register_child_run([0 => $this, 1 => 'releasesChildWorker']); - $groups = $this->pdo->queryDirect('SELECT id FROM groups WHERE (active = 1 OR backfill = 1)'); + $groups = $this->pdo->queryDirect('SELECT id FROM groups WHERE (active = 1 OR backfill = 1)'); - if ($groups instanceof \Traversable) { - foreach ($groups as $group) { - try { - if ($this->pdo->queryOneRow(sprintf('SELECT id FROM collections_%d LIMIT 1', $group['id'])) !== false) { - $this->work[] = ['id' => $group['id']]; - } - } catch (\PDOException $e) { - $e->getMessage(); - } - } - } + if ($groups instanceof \Traversable) { + foreach ($groups as $group) { + try { + if ($this->pdo->queryOneRow(sprintf('SELECT id FROM collections_%d LIMIT 1', $group['id'])) !== false) { + $this->work[] = ['id' => $group['id']]; + } + } catch (\PDOException $e) { + $e->getMessage(); + } + } + } - return (int)Settings::value('..releasethreads'); - } + return (int) Settings::value('..releasethreads'); + } - /** - * @param $groups - * @param string $identifier - */ - public function releasesChildWorker($groups, $identifier = '') - { - foreach ($groups as $group) { - $this->_executeCommand($this->dnr_path . 'releases ' . $group['id'] . '"'); - } - } + /** + * @param $groups + * @param string $identifier + */ + public function releasesChildWorker($groups, $identifier = '') + { + foreach ($groups as $group) { + $this->_executeCommand($this->dnr_path.'releases '.$group['id'].'"'); + } + } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////// All post process code here ///////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////// All post process code here ///////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /** - * Only 1 exit method is used for post process, since they are all similar. - * - * @param $groups - * @param string $identifier - */ - public function postProcessChildWorker($groups, $identifier = '') - { - foreach ($groups as $group) { - $type = ''; - if ($this->processAdditional) { - $type = 'pp_additional '; - } else if ($this->processNFO) { - $type = 'pp_nfo '; - } else if ($this->processMovies) { - $type = 'pp_movie '; - } else if ($this->processTV) { - $type = 'pp_tv '; - } + /** + * Only 1 exit method is used for post process, since they are all similar. + * + * @param $groups + * @param string $identifier + */ + public function postProcessChildWorker($groups, $identifier = '') + { + foreach ($groups as $group) { + $type = ''; + if ($this->processAdditional) { + $type = 'pp_additional '; + } elseif ($this->processNFO) { + $type = 'pp_nfo '; + } elseif ($this->processMovies) { + $type = 'pp_movie '; + } elseif ($this->processTV) { + $type = 'pp_tv '; + } - if ($type !== '') { - $this->_executeCommand( - $this->dnr_path . $type . $group['id'] . (isset($group['renamed']) ? (' ' . $group['renamed']) : '') . '"' + if ($type !== '') { + $this->_executeCommand( + $this->dnr_path.$type.$group['id'].(isset($group['renamed']) ? (' '.$group['renamed']) : '').'"' ); - } - } - } + } + } + } - private $ppAddMinSize; - private $ppAddMaxSize; + private $ppAddMinSize; + private $ppAddMaxSize; - /** - * Check if we should process Additional's. - * @return bool - * @throws \Exception - */ - private function checkProcessAdditional() - { - $this->ppAddMinSize = - (Settings::value('..minsizetopostprocess') !== '') ? (int)Settings::value('..minsizetopostprocess') : 1; - $this->ppAddMinSize = ($this->ppAddMinSize > 0 ? ('AND r.size > ' . ($this->ppAddMinSize * 1048576)) : ''); - $this->ppAddMaxSize = - (Settings::value('..maxsizetopostprocess') !== '') ? (int)Settings::value('..maxsizetopostprocess') : 100; - $this->ppAddMaxSize = ($this->ppAddMaxSize > 0 ? ('AND r.size < ' . ($this->ppAddMaxSize * 1073741824)) : ''); + /** + * Check if we should process Additional's. + * @return bool + * @throws \Exception + */ + private function checkProcessAdditional() + { + $this->ppAddMinSize = + (Settings::value('..minsizetopostprocess') !== '') ? (int) Settings::value('..minsizetopostprocess') : 1; + $this->ppAddMinSize = ($this->ppAddMinSize > 0 ? ('AND r.size > '.($this->ppAddMinSize * 1048576)) : ''); + $this->ppAddMaxSize = + (Settings::value('..maxsizetopostprocess') !== '') ? (int) Settings::value('..maxsizetopostprocess') : 100; + $this->ppAddMaxSize = ($this->ppAddMaxSize > 0 ? ('AND r.size < '.($this->ppAddMaxSize * 1073741824)) : ''); - return ( + return $this->pdo->queryOneRow( sprintf(' SELECT r.id @@ -683,21 +673,20 @@ class Forking extends \fork_daemon $this->ppAddMaxSize, $this->ppAddMinSize ) - ) === false ? false : true - ); - } + ) === false ? false : true; + } - /** - * @return int|null|string - * @throws \Exception - */ - private function postProcessAddMainMethod() - { - $maxProcesses = 1; - if ($this->checkProcessAdditional() === true) { - $this->processAdditional = true; - $this->register_child_run([0 => $this, 1 => 'postProcessChildWorker']); - $this->work = $this->pdo->query( + /** + * @return int|null|string + * @throws \Exception + */ + private function postProcessAddMainMethod() + { + $maxProcesses = 1; + if ($this->checkProcessAdditional() === true) { + $this->processAdditional = true; + $this->register_child_run([0 => $this, 1 => 'postProcessChildWorker']); + $this->work = $this->pdo->query( sprintf(' SELECT leftguid AS id FROM releases r @@ -714,48 +703,47 @@ class Forking extends \fork_daemon $this->ppAddMinSize ) ); - $maxProcesses = (int)Settings::value('..postthreads'); - } + $maxProcesses = (int) Settings::value('..postthreads'); + } - return $maxProcesses; - } + return $maxProcesses; + } - private $nfoQueryString = ''; + private $nfoQueryString = ''; - /** - * Check if we should process NFO's. - * @return bool - * @throws \Exception - */ - private function checkProcessNfo() - { - if (Settings::value('..lookupnfo') == 1) { - $this->nfoQueryString = Nfo::NfoQueryString($this->pdo); + /** + * Check if we should process NFO's. + * @return bool + * @throws \Exception + */ + private function checkProcessNfo() + { + if (Settings::value('..lookupnfo') == 1) { + $this->nfoQueryString = Nfo::NfoQueryString($this->pdo); - return ( + return $this->pdo->queryOneRow( sprintf( 'SELECT r.id FROM releases r WHERE 1=1 %s LIMIT 1', $this->nfoQueryString ) - ) === false ? false : true - ); - } + ) === false ? false : true; + } - return false; - } + return false; + } - /** - * @return int|null|string - * @throws \Exception - */ - private function postProcessNfoMainMethod() - { - $maxProcesses = 1; - if ($this->checkProcessNfo() === true) { - $this->processNFO = true; - $this->register_child_run([0 => $this, 1 => 'postProcessChildWorker']); - $this->work = $this->pdo->query( + /** + * @return int|null|string + * @throws \Exception + */ + private function postProcessNfoMainMethod() + { + $maxProcesses = 1; + if ($this->checkProcessNfo() === true) { + $this->processNFO = true; + $this->register_child_run([0 => $this, 1 => 'postProcessChildWorker']); + $this->work = $this->pdo->query( sprintf(' SELECT leftguid AS id FROM releases r @@ -765,21 +753,21 @@ class Forking extends \fork_daemon $this->nfoQueryString ) ); - $maxProcesses = (int)Settings::value('..nfothreads'); - } + $maxProcesses = (int) Settings::value('..nfothreads'); + } - return $maxProcesses; - } + return $maxProcesses; + } - /** - * Check if we should process Movies. - * @return bool - * @throws \Exception - */ - private function checkProcessMovies() - { - if (Settings::value('..lookupimdb') > 0) { - return ( + /** + * Check if we should process Movies. + * @return bool + * @throws \Exception + */ + private function checkProcessMovies() + { + if (Settings::value('..lookupimdb') > 0) { + return $this->pdo->queryOneRow( sprintf(' SELECT id @@ -790,27 +778,26 @@ class Forking extends \fork_daemon %s %s LIMIT 1', NZB::NZB_ADDED, - ((int)Settings::value('..lookupimdb') === 2 ? 'AND isrenamed = 1' : ''), + ((int) Settings::value('..lookupimdb') === 2 ? 'AND isrenamed = 1' : ''), ($this->ppRenamedOnly ? 'AND isrenamed = 1' : '') ) - ) === false ? false : true - ); - } + ) === false ? false : true; + } - return false; - } + return false; + } - /** - * @return int|null|string - * @throws \Exception - */ - private function postProcessMovMainMethod() - { - $maxProcesses = 1; - if ($this->checkProcessMovies() === true) { - $this->processMovies = true; - $this->register_child_run([0 => $this, 1 => 'postProcessChildWorker']); - $this->work = $this->pdo->query( + /** + * @return int|null|string + * @throws \Exception + */ + private function postProcessMovMainMethod() + { + $maxProcesses = 1; + if ($this->checkProcessMovies() === true) { + $this->processMovies = true; + $this->register_child_run([0 => $this, 1 => 'postProcessChildWorker']); + $this->work = $this->pdo->query( sprintf(' SELECT leftguid AS id, %d AS renamed FROM releases @@ -822,25 +809,25 @@ class Forking extends \fork_daemon LIMIT 16', ($this->ppRenamedOnly ? 2 : 1), NZB::NZB_ADDED, - ((int)Settings::value('..lookupimdb') === 2 ? 'AND isrenamed = 1' : ''), + ((int) Settings::value('..lookupimdb') === 2 ? 'AND isrenamed = 1' : ''), ($this->ppRenamedOnly ? 'AND isrenamed = 1' : '') ) ); - $maxProcesses = (int)Settings::value('..postthreadsnon'); - } + $maxProcesses = (int) Settings::value('..postthreadsnon'); + } - return $maxProcesses; - } + return $maxProcesses; + } - /** - * Check if we should process TV's. - * @return bool - * @throws \Exception - */ - private function checkProcessTV() - { - if (Settings::value('..lookuptvrage') > 0) { - return ( + /** + * Check if we should process TV's. + * @return bool + * @throws \Exception + */ + private function checkProcessTV() + { + if (Settings::value('..lookuptvrage') > 0) { + return $this->pdo->queryOneRow( sprintf(' SELECT id @@ -852,27 +839,26 @@ class Forking extends \fork_daemon %s %s LIMIT 1', NZB::NZB_ADDED, - (int)Settings::value('..lookuptvrage') === 2 ? 'AND isrenamed = 1' : '', + (int) Settings::value('..lookuptvrage') === 2 ? 'AND isrenamed = 1' : '', $this->ppRenamedOnly ? 'AND isrenamed = 1' : '' ) - ) === false ? false : true - ); - } + ) === false ? false : true; + } - return false; - } + return false; + } - /** - * @return int|null|string - * @throws \Exception - */ - private function postProcessTvMainMethod() - { - $maxProcesses = 1; - if ($this->checkProcessTV() === true) { - $this->processTV = true; - $this->register_child_run([0 => $this, 1 => 'postProcessChildWorker']); - $this->work = $this->pdo->query( + /** + * @return int|null|string + * @throws \Exception + */ + private function postProcessTvMainMethod() + { + $maxProcesses = 1; + if ($this->checkProcessTV() === true) { + $this->processTV = true; + $this->register_child_run([0 => $this, 1 => 'postProcessChildWorker']); + $this->work = $this->pdo->query( sprintf(' SELECT leftguid AS id, %d AS renamed FROM releases @@ -885,64 +871,64 @@ class Forking extends \fork_daemon LIMIT 16', ($this->ppRenamedOnly ? 2 : 1), NZB::NZB_ADDED, - (int)Settings::value('..lookuptvrage') === 2 ? 'AND isrenamed = 1' : '', + (int) Settings::value('..lookuptvrage') === 2 ? 'AND isrenamed = 1' : '', ($this->ppRenamedOnly ? 'AND isrenamed = 1' : '') ) ); - $maxProcesses = (int)Settings::value('..postthreadsnon'); - } + $maxProcesses = (int) Settings::value('..postthreadsnon'); + } - return $maxProcesses; - } + return $maxProcesses; + } - /** - * Process sharing. - * @return bool - * @throws \Exception - */ - private function processSharing() - { - $sharing = $this->pdo->queryOneRow('SELECT enabled FROM sharing'); - if ($sharing !== false && $sharing['enabled'] == 1) { - $nntp = new NNTP(['Settings' => $this->pdo]); - if ((int)(Settings::value('..alternate_nntp') === 1 ? $nntp->doConnect(true, true) : $nntp->doConnect()) === true) { - (new PostProcess(['Settings' => $this->pdo, 'ColorCLI' => $this->_colorCLI]))->processSharing($nntp); - } + /** + * Process sharing. + * @return bool + * @throws \Exception + */ + private function processSharing() + { + $sharing = $this->pdo->queryOneRow('SELECT enabled FROM sharing'); + if ($sharing !== false && $sharing['enabled'] == 1) { + $nntp = new NNTP(['Settings' => $this->pdo]); + if ((int) (Settings::value('..alternate_nntp') === 1 ? $nntp->doConnect(true, true) : $nntp->doConnect()) === true) { + (new PostProcess(['Settings' => $this->pdo, 'ColorCLI' => $this->_colorCLI]))->processSharing($nntp); + } - return true; - } + return true; + } - return false; - } + return false; + } - /** - * Process all that require a single thread. - * - * @throws \Exception - */ - private function processSingle() - { - $postProcess = new PostProcess(['Settings' => $this->pdo, 'ColorCLI' => $this->_colorCLI]); - //$postProcess->processAnime(); - $postProcess->processBooks(); - $postProcess->processConsoles(); - $postProcess->processGames(); - $postProcess->processMusic(); - $postProcess->processXXX(); - } + /** + * Process all that require a single thread. + * + * @throws \Exception + */ + private function processSingle() + { + $postProcess = new PostProcess(['Settings' => $this->pdo, 'ColorCLI' => $this->_colorCLI]); + //$postProcess->processAnime(); + $postProcess->processBooks(); + $postProcess->processConsoles(); + $postProcess->processGames(); + $postProcess->processMusic(); + $postProcess->processXXX(); + } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////// All requestID code goes here //////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////// All requestID code goes here //////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /** - * @return null|string - * @throws \Exception - */ - private function requestIDMainMethod() - { - $this->register_child_run([0 => $this, 1 => 'requestIDChildWorker']); - $this->work = $this->pdo->query( + /** + * @return null|string + * @throws \Exception + */ + private function requestIDMainMethod() + { + $this->register_child_run([0 => $this, 1 => 'requestIDChildWorker']); + $this->work = $this->pdo->query( sprintf(' SELECT DISTINCT(g.id) FROM groups g @@ -957,61 +943,61 @@ class Forking extends \fork_daemon ) ); - return (int)Settings::value('..reqidthreads'); - } + return (int) Settings::value('..reqidthreads'); + } - /** - * @param $groups - * @param string $identifier - */ - public function requestIDChildWorker($groups, $identifier = '') - { - foreach ($groups as $group) { - $this->_executeCommand($this->dnr_path . 'requestid ' . $group['id'] . '"'); - } - } + /** + * @param $groups + * @param string $identifier + */ + public function requestIDChildWorker($groups, $identifier = '') + { + foreach ($groups as $group) { + $this->_executeCommand($this->dnr_path.'requestid '.$group['id'].'"'); + } + } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////// All "update_per_Group" code goes here //////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////// All "update_per_Group" code goes here //////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /** - * @return null|string - * @throws \Exception - */ - private function updatePerGroupMainMethod() - { - $this->register_child_run([0 => $this, 1 => 'updatePerGroupChildWorker']); - $this->work = $this->pdo->query('SELECT id FROM groups WHERE (active = 1 OR backfill = 1)'); + /** + * @return null|string + * @throws \Exception + */ + private function updatePerGroupMainMethod() + { + $this->register_child_run([0 => $this, 1 => 'updatePerGroupChildWorker']); + $this->work = $this->pdo->query('SELECT id FROM groups WHERE (active = 1 OR backfill = 1)'); - return (int)Settings::value('..releasethreads'); - } + return (int) Settings::value('..releasethreads'); + } - /** - * @param $groups - * @param string $identifier - */ - public function updatePerGroupChildWorker($groups, $identifier = '') - { - foreach ($groups as $group) { - $this->_executeCommand( - $this->dnr_path . 'update_per_group ' . $group['id'] . '"' + /** + * @param $groups + * @param string $identifier + */ + public function updatePerGroupChildWorker($groups, $identifier = '') + { + foreach ($groups as $group) { + $this->_executeCommand( + $this->dnr_path.'update_per_group '.$group['id'].'"' ); - } - } + } + } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //////////////////////////////////////////// Various methods /////////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////// Various methods /////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /** - * Execute a shell command, use the appropriate PHP function based on user setting. - * - * @param string $command - */ - protected function _executeCommand($command) - { - switch ($this->outputType) { + /** + * Execute a shell command, use the appropriate PHP function based on user setting. + * + * @param string $command + */ + protected function _executeCommand($command) + { + switch ($this->outputType) { case self::OUTPUT_NONE: exec($command); break; @@ -1022,148 +1008,145 @@ class Forking extends \fork_daemon echo shell_exec($command); break; } - } + } - /** - * Set the amount of max child processes. - * - * @param int $maxProcesses - */ - private function setMaxProcesses($maxProcesses) - { - // Check if override setting is on. - if (defined('NN_MULTIPROCESSING_MAX_CHILDREN_OVERRIDE') && NN_MULTIPROCESSING_MAX_CHILDREN_OVERRIDE > 0) { - $maxProcesses = NN_MULTIPROCESSING_MAX_CHILDREN_OVERRIDE; - } + /** + * Set the amount of max child processes. + * + * @param int $maxProcesses + */ + private function setMaxProcesses($maxProcesses) + { + // Check if override setting is on. + if (defined('NN_MULTIPROCESSING_MAX_CHILDREN_OVERRIDE') && NN_MULTIPROCESSING_MAX_CHILDREN_OVERRIDE > 0) { + $maxProcesses = NN_MULTIPROCESSING_MAX_CHILDREN_OVERRIDE; + } - if (is_numeric($maxProcesses) && $maxProcesses > 0) { - switch ($this->workType) { + if (is_numeric($maxProcesses) && $maxProcesses > 0) { + switch ($this->workType) { case 'postProcess_tv': case 'postProcess_mov': case 'postProcess_nfo': case 'postProcess_add': if ($maxProcesses > 16) { - $maxProcesses = 16; + $maxProcesses = 16; } } - $this->maxProcesses = (int)$maxProcesses; - $this->max_children_set($this->maxProcesses); - } else { - $this->max_children_set(1); - } - } + $this->maxProcesses = (int) $maxProcesses; + $this->max_children_set($this->maxProcesses); + } else { + $this->max_children_set(1); + } + } - /** - * Echo a message to CLI. - * - * @param string $message - */ - public function logger($message) - { - if (NN_ECHOCLI) { - echo $message . PHP_EOL; - } - } + /** + * Echo a message to CLI. + * + * @param string $message + */ + public function logger($message) + { + if (NN_ECHOCLI) { + echo $message.PHP_EOL; + } + } - /** - * This method is executed whenever a child is finished doing work. - * - * @param string $pid The PID numbers. - * @param string $identifier Optional identifier to give a PID a name. - */ - public function childExit($pid, $identifier = '') - { - if (NN_ECHOCLI) { - ColorCLI::doEcho( + /** + * This method is executed whenever a child is finished doing work. + * + * @param string $pid The PID numbers. + * @param string $identifier Optional identifier to give a PID a name. + */ + public function childExit($pid, $identifier = '') + { + if (NN_ECHOCLI) { + ColorCLI::doEcho( ColorCLI::header( - 'Process ID #' . $pid . ' has completed.' . PHP_EOL . - 'There are ' . ($this->forked_children_count - 1) . ' process(es) still active with ' . - (--$this->_workCount) . ' job(s) left in the queue.' . PHP_EOL + 'Process ID #'.$pid.' has completed.'.PHP_EOL. + 'There are '.($this->forked_children_count - 1).' process(es) still active with '. + (--$this->_workCount).' job(s) left in the queue.'.PHP_EOL ) ); - } - } + } + } - /** - * - */ - public function __destruct() - { - parent::__destruct(); - } + public function __destruct() + { + parent::__destruct(); + } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////// All class vars here ///////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////// All class vars here ///////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - /** - * @var ColorCLI - */ - public $_colorCLI; + /** + * @var ColorCLI + */ + public $_colorCLI; - /** - * @var int The type of output - */ - protected $outputType; + /** + * @var int The type of output + */ + protected $outputType; - /** - * Path to do not run folder. - * - * @var string - */ - private $dnr_path; + /** + * Path to do not run folder. + * + * @var string + */ + private $dnr_path; - /** - * Work to work on. - * - * @var array - */ - private $work = []; + /** + * Work to work on. + * + * @var array + */ + private $work = []; - /** - * How much work do we have to do? - * - * @var int - */ - public $_workCount = 0; + /** + * How much work do we have to do? + * + * @var int + */ + public $_workCount = 0; - /** - * The type of work we want to work on. - * - * @var string - */ - private $workType = ''; + /** + * The type of work we want to work on. + * + * @var string + */ + private $workType = ''; - /** - * List of passed in options for the current work type. - * - * @var array - */ - private $workTypeOptions = []; + /** + * List of passed in options for the current work type. + * + * @var array + */ + private $workTypeOptions = []; - /** - * Max amount of child processes to do work at a time. - * - * @var int - */ - private $maxProcesses = 1; + /** + * Max amount of child processes to do work at a time. + * + * @var int + */ + private $maxProcesses = 1; - /** - * Group used for safe backfill. - * - * @var string - */ - private $safeBackfillGroup = ''; + /** + * Group used for safe backfill. + * + * @var string + */ + private $safeBackfillGroup = ''; - /** - * @var \nntmux\db\Settings - */ - public $pdo; + /** + * @var \nntmux\db\Settings + */ + public $pdo; - /** - * @var bool - */ - private $processAdditional = false; // Should we process additional? + /** + * @var bool + */ + private $processAdditional = false; // Should we process additional? private $processNFO = false; // Should we process NFOs? private $processMovies = false; // Should we process Movies? private $processTV = false; // Should we process TV? diff --git a/nntmux/libraries/ForkingException.php b/nntmux/libraries/ForkingException.php index 204008a89..6ac759db4 100755 --- a/nntmux/libraries/ForkingException.php +++ b/nntmux/libraries/ForkingException.php @@ -18,8 +18,8 @@ * @author niel * @copyright 2015 nZEDb */ -namespace nntmux\libraries; +namespace nntmux\libraries; class ForkingException extends \Exception { diff --git a/nntmux/libraries/ForkingImportNZB.php b/nntmux/libraries/ForkingImportNZB.php index 7a0d68d27..aeb7d4924 100755 --- a/nntmux/libraries/ForkingImportNZB.php +++ b/nntmux/libraries/ForkingImportNZB.php @@ -1,93 +1,93 @@ <?php + namespace nntmux\libraries; use nntmux\db\DB; use nntmux\ColorCLI; - /** - * Class ForkingImportNZB + * Class ForkingImportNZB. * * Multi-processing of NZB Import. */ class ForkingImportNZB extends Forking { - /** - * @param array $options - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options + */ + public function __construct(array $options = []) + { + $defaults = [ 'settings' => new DB(), ]; - $options += $defaults; + $options += $defaults; - parent::__construct(); - $this->importPath = (PHP_BINARY . ' ' . NN_MISC . 'testing' . DS . 'nzb-import.php '); - $this->pdo = $options['settings']; - } + parent::__construct(); + $this->importPath = (PHP_BINARY.' '.NN_MISC.'testing'.DS.'nzb-import.php '); + $this->pdo = $options['settings']; + } - public function __destruct() - { - parent::__destruct(); - } + public function __destruct() + { + parent::__destruct(); + } - private $deleteComplete; - private $deleteFailed; - private $useFileName; - private $maxPerProcess; + private $deleteComplete; + private $deleteFailed; + private $useFileName; + private $maxPerProcess; - public function start($folder, $maxProcesses, $deleteComplete, $deleteFailed, $useFileName, $maxPerProcess) - { - $startTime = microtime(true); - $directories = glob($folder . '/*' , GLOB_ONLYDIR); + public function start($folder, $maxProcesses, $deleteComplete, $deleteFailed, $useFileName, $maxPerProcess) + { + $startTime = microtime(true); + $directories = glob($folder.'/*', GLOB_ONLYDIR); - $this->_workCount = count($directories); + $this->_workCount = count($directories); - if ($this->_workCount == 0) { - echo ColorCLI::error('No sub-folders were found in your specified folder (' . $folder . ').'); - exit(); - } + if ($this->_workCount == 0) { + echo ColorCLI::error('No sub-folders were found in your specified folder ('.$folder.').'); + exit(); + } - if (NN_ECHOCLI) { - echo ColorCLI::header( - 'Multi-processing started at ' . date(DATE_RFC2822) . ' with ' . $this->_workCount . - ' job(s) to do using a max of ' . $maxProcesses . ' child process(es).' + if (NN_ECHOCLI) { + echo ColorCLI::header( + 'Multi-processing started at '.date(DATE_RFC2822).' with '.$this->_workCount. + ' job(s) to do using a max of '.$maxProcesses.' child process(es).' ); - } + } - $this->deleteComplete = $deleteComplete; - $this->deleteFailed = $deleteFailed; - $this->useFileName = $useFileName; - $this->maxPerProcess = $maxPerProcess; + $this->deleteComplete = $deleteComplete; + $this->deleteFailed = $deleteFailed; + $this->useFileName = $useFileName; + $this->maxPerProcess = $maxPerProcess; - $this->max_children_set($maxProcesses); - $this->register_child_run([0 => $this, 1 => 'importChildWorker']); - $this->child_max_run_time_set(86400); - $this->addwork($directories); - $this->process_work(true); + $this->max_children_set($maxProcesses); + $this->register_child_run([0 => $this, 1 => 'importChildWorker']); + $this->child_max_run_time_set(86400); + $this->addwork($directories); + $this->process_work(true); - if (NN_ECHOCLI) { - ColorCLI::doEcho( + if (NN_ECHOCLI) { + ColorCLI::doEcho( ColorCLI::header( - 'Multi-processing for import finished in ' . (microtime(true) - $startTime) . - ' seconds at ' . date(DATE_RFC2822) . '.' . PHP_EOL + 'Multi-processing for import finished in '.(microtime(true) - $startTime). + ' seconds at '.date(DATE_RFC2822).'.'.PHP_EOL ) ); - } - } + } + } - public function importChildWorker($directories, $identifier = '') - { - foreach ($directories as $directory) { - $this->_executeCommand( - $this->importPath . '"' . - $directory . '" ' . - $this->deleteComplete . ' ' . - $this->deleteFailed . ' ' . - $this->useFileName . ' ' . + public function importChildWorker($directories, $identifier = '') + { + foreach ($directories as $directory) { + $this->_executeCommand( + $this->importPath.'"'. + $directory.'" '. + $this->deleteComplete.' '. + $this->deleteFailed.' '. + $this->useFileName.' '. $this->maxPerProcess ); - } - } + } + } } diff --git a/nntmux/libraries/TraktAPI.php b/nntmux/libraries/TraktAPI.php index cead9447f..6045204b6 100755 --- a/nntmux/libraries/TraktAPI.php +++ b/nntmux/libraries/TraktAPI.php @@ -1,77 +1,75 @@ <?php + namespace nntmux\libraries; +use nntmux\db\DB; +use nntmux\ColorCLI; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; -use nntmux\ColorCLI; -use nntmux\db\DB; /** * Class TraktAPI * Retrive info from the Trakt API. */ -Class TraktAPI { +class TraktAPI +{ + const API_URL = 'https://api.trakt.tv/'; - const API_URL = 'https://api.trakt.tv/'; + /** + * @var array List of site IDs that trakt,tv supports. Only trakt is guaranteed to exist. + */ + private $types = ['imdb', 'tmdb', 'trakt', 'tvdb', 'tvrage']; - /** - * @var array List of site IDs that trakt,tv supports. Only trakt is guaranteed to exist. - */ - private $types = ['imdb', 'tmdb', 'trakt', 'tvdb', 'tvrage']; + /** + * List of headers to send to Trakt.tv when making a request. + * + * @see http://docs.trakt.apiary.io/#introduction/required-headers + * @var array + */ + private $requestHeaders; - /** - * List of headers to send to Trakt.tv when making a request. - * - * @see http://docs.trakt.apiary.io/#introduction/required-headers - * @var array - */ - private $requestHeaders; + /** + * @var Client + */ + protected $client; - /** - * @var Client - */ - protected $client; + /** + * @var DB + */ + protected $pdo; - /** - * @var DB - */ - protected $pdo; + /** + * Construct. Assign passed request headers. Headers should be complete with API key. + * + * + * @param $headers + */ + public function __construct($headers) + { + if (empty($headers)) { + // Can't work without headers. + exit; + } + $this->requestHeaders = $headers; - /** - * Construct. Assign passed request headers. Headers should be complete with API key. - * - * @access public - * - * @param $headers - */ - public function __construct($headers) - { - if (empty($headers)) { - // Can't work without headers. - exit; - } - $this->requestHeaders = $headers; + $this->client = new Client(); + $this->pdo = new DB(); + } - $this->client = new Client(); - $this->pdo = new DB(); - } - - /** - * Fetches summary from trakt.tv for the TV show using the trakt ID/season/episode. - * - * @param int $id - * @param string $season - * @param string $ep - * @param string $type - * - * @return array|bool - * @see http://docs.trakt.apiary.io/#reference/episodes/summary/get-a-single-episode-for-a-show - * - * @access public - */ - public function episodeSummary($id, $season = '', $ep = '', $type = 'min') - { - switch($type) { + /** + * Fetches summary from trakt.tv for the TV show using the trakt ID/season/episode. + * + * @param int $id + * @param string $season + * @param string $ep + * @param string $type + * + * @return array|bool + * @see http://docs.trakt.apiary.io/#reference/episodes/summary/get-a-single-episode-for-a-show + */ + public function episodeSummary($id, $season = '', $ep = '', $type = 'min') + { + switch ($type) { case 'aliases': case 'full': case 'images': @@ -83,135 +81,130 @@ Class TraktAPI { $extended = 'min'; } - $url = self::API_URL . "shows/{$id}/seasons/{$season}/episodes/{$ep}"; + $url = self::API_URL."shows/{$id}/seasons/{$season}/episodes/{$ep}"; - $array = $this->getJsonArray($url, $extended); - if (!is_array($array)) { - return false; - } - return $array; - } + $array = $this->getJsonArray($url, $extended); + if (! is_array($array)) { + return false; + } - /** - * Fetches weekend box office data from trakt.tv, updated every monday. - * - * @return array|bool - * @see http://docs.trakt.apiary.io/#reference/movies/box-office/get-the-weekend-box-office - * - * @access public - */ - public function getBoxOffice() - { - $array = $this->getJsonArray( - self::API_URL . 'movies/boxoffice' + return $array; + } + + /** + * Fetches weekend box office data from trakt.tv, updated every monday. + * + * @return array|bool + * @see http://docs.trakt.apiary.io/#reference/movies/box-office/get-the-weekend-box-office + */ + public function getBoxOffice() + { + $array = $this->getJsonArray( + self::API_URL.'movies/boxoffice' ); - if (!$array) { - return false; - } + if (! $array) { + return false; + } - return $array; - } + return $array; + } - /** - * Fetches shows calendar from trakt.tv . - * - * @param string $start Start date of calendar ie. 2015-09-01.Default value is today. - * @param int $days Number of days to lookup ahead. Default value is 7 days - * - * @return array|bool - * @see http://docs.trakt.apiary.io/#reference/calendars/all-shows/get-shows - * - * @access public - */ - public function getCalendar($start = '', $days = 7) - { - $array = $this->getJsonArray( - self::API_URL . 'calendars/all/shows/' . $start . '/' . $days + /** + * Fetches shows calendar from trakt.tv . + * + * @param string $start Start date of calendar ie. 2015-09-01.Default value is today. + * @param int $days Number of days to lookup ahead. Default value is 7 days + * + * @return array|bool + * @see http://docs.trakt.apiary.io/#reference/calendars/all-shows/get-shows + */ + public function getCalendar($start = '', $days = 7) + { + $array = $this->getJsonArray( + self::API_URL.'calendars/all/shows/'.$start.'/'.$days ); - if (!$array) { - return false; - } + if (! $array) { + return false; + } - return $array; - } + return $array; + } - /** - * Download JSON from Trakt, convert to array. - * - * @param string $URI URI to download. - * @param string $extended Extended info from trakt tv. - * Valid values: - * 'min' Returns enough info to match locally. (Default) - * 'images' Minimal info and all images. - * 'full' Complete info for an item. - * 'full,images' Complete info and all images. - * - * @return array|false - */ - private function getJsonArray($URI, $extended = 'min') - { - if ($extended === '') { - $extendedString = ''; - } else { - $extendedString = '?extended=' . $extended; - } + /** + * Download JSON from Trakt, convert to array. + * + * @param string $URI URI to download. + * @param string $extended Extended info from trakt tv. + * Valid values: + * 'min' Returns enough info to match locally. (Default) + * 'images' Minimal info and all images. + * 'full' Complete info for an item. + * 'full,images' Complete info and all images. + * + * @return array|false + */ + private function getJsonArray($URI, $extended = 'min') + { + if ($extended === '') { + $extendedString = ''; + } else { + $extendedString = '?extended='.$extended; + } - if (!empty($this->requestHeaders)) { - - try { - $json = $this->client->get( - $URI . $extendedString, + if (! empty($this->requestHeaders)) { + try { + $json = $this->client->get( + $URI.$extendedString, [ - 'headers' => $this->requestHeaders + 'headers' => $this->requestHeaders, ] )->getBody()->getContents(); - } catch (RequestException $e) { - if ($e->hasResponse()) { - if($e->getCode() === 404) { - ColorCLI::doEcho(ColorCLI::notice('Data not available on TraktTV server')); - } else if ($e->getCode() === 503) { - ColorCLI::doEcho(ColorCLI::notice('TraktTV service unavailable')); - } else if ($e->getCode() === 401) { - ColorCLI::doEcho(ColorCLI::notice('Unauthorized - OAuth must be provided for TraktTV')); - } else { - ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from TraktTV, server responded with code: ' . $e->getCode())); - } - } - } catch (\RuntimeException $e) { - ColorCLI::doEcho(ColorCLI::notice('Unknown error occurred!')); - } + } catch (RequestException $e) { + if ($e->hasResponse()) { + if ($e->getCode() === 404) { + ColorCLI::doEcho(ColorCLI::notice('Data not available on TraktTV server')); + } elseif ($e->getCode() === 503) { + ColorCLI::doEcho(ColorCLI::notice('TraktTV service unavailable')); + } elseif ($e->getCode() === 401) { + ColorCLI::doEcho(ColorCLI::notice('Unauthorized - OAuth must be provided for TraktTV')); + } else { + ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from TraktTV, server responded with code: '.$e->getCode())); + } + } + } catch (\RuntimeException $e) { + ColorCLI::doEcho(ColorCLI::notice('Unknown error occurred!')); + } - if (isset($json) && $json !== false) { - $json = json_decode($json, true); - if (!is_array($json) || (isset($json['status']) && $json['status'] === 'failure')) { - return false; - } - return $json; - } - } + if (isset($json) && $json !== false) { + $json = json_decode($json, true); + if (! is_array($json) || (isset($json['status']) && $json['status'] === 'failure')) { + return false; + } - return false; - } + return $json; + } + } - /** - * Fetches summary from trakt.tv for the movie. - * Accept a title (the-big-lebowski-1998), a IMDB id, or a TMDB id. - * - * @param string $movie Title or IMDB id. - * @param string $type imdbID: Return only the IMDB ID (returns string) - * full: Return all extended properties (minus images). (returns array) - * images: Return extended images properties (returns array) - * full,images: Return all extended properties (plus images). (returns array) - * - * @see http://docs.trakt.apiary.io/#reference/movies/summary/get-a-movie - * - * @return bool|array|string - * - * @access public - */ - public function movieSummary($movie = '', $type = 'imdbID') - { - switch ($type) { + return false; + } + + /** + * Fetches summary from trakt.tv for the movie. + * Accept a title (the-big-lebowski-1998), a IMDB id, or a TMDB id. + * + * @param string $movie Title or IMDB id. + * @param string $type imdbID: Return only the IMDB ID (returns string) + * full: Return all extended properties (minus images). (returns array) + * images: Return extended images properties (returns array) + * full,images: Return all extended properties (plus images). (returns array) + * + * @see http://docs.trakt.apiary.io/#reference/movies/summary/get-a-movie + * + * @return bool|array|string + */ + public function movieSummary($movie = '', $type = 'imdbID') + { + switch ($type) { case 'full': case 'images': case 'full,images': @@ -221,98 +214,94 @@ Class TraktAPI { default: $extended = 'min'; } - $array = $this->getJsonArray(self::API_URL . 'movies/' . $this->slugify($movie), $extended); - if (!$array) { - return false; - } else { - if ($type === 'imdbID' && isset($array['ids']['imdb'])) { - return $array['ids']['imdb']; - } - } + $array = $this->getJsonArray(self::API_URL.'movies/'.$this->slugify($movie), $extended); + if (! $array) { + return false; + } else { + if ($type === 'imdbID' && isset($array['ids']['imdb'])) { + return $array['ids']['imdb']; + } + } - return $array; - } + return $array; + } - /** - * Search for entry using on of the supported site IDs. - * - * @param integer $id The ID to look for. - * @param string $site One of the supported sites ('imdb', 'tmdb', 'trakt', 'tvdb', 'tvrage') - * @param integer $type videos.type flag (-1 for episodes). - * - * @return bool - */ - public function searchId($id, $site = 'trakt', $type = 0) - { - if (!in_array($site, $this->types) || !ctype_digit($id)) { - return null; - } else if ($site == 'imdb') { - $id = 'tt' . $id; - } + /** + * Search for entry using on of the supported site IDs. + * + * @param int $id The ID to look for. + * @param string $site One of the supported sites ('imdb', 'tmdb', 'trakt', 'tvdb', 'tvrage') + * @param int $type videos.type flag (-1 for episodes). + * + * @return bool + */ + public function searchId($id, $site = 'trakt', $type = 0) + { + if (! in_array($site, $this->types) || ! ctype_digit($id)) { + return null; + } elseif ($site == 'imdb') { + $id = 'tt'.$id; + } - switch (true) { + switch (true) { case $site == 'trakt' && ($type == 0 || $type == 2): - $type = $site . '-show'; + $type = $site.'-show'; break; case $site == 'trakt' && $type == 1: - $type = $site . '-movie'; + $type = $site.'-movie'; break; case $site == 'trakt' && $type == -1: - $type = $site . '-episode'; + $type = $site.'-episode'; break; default: } - $url = self::API_URL . "search?id_type=$type&id=$id"; + $url = self::API_URL."search?id_type=$type&id=$id"; - return $this->getJsonArray($url, ''); - } + return $this->getJsonArray($url, ''); + } - /** - * Fetches summary from trakt.tv for the show by doing a search. - * Accepts a search string - * - * @param string $show title - * @param string $type show - * - * @see http://docs.trakt.apiary.io/#reference/search/get-text-query-results - * - * @return bool|array|string - * - * @access public - */ - public function showSearch($show = '', $type = 'show') - { - $searchUrl = self::API_URL . 'search?query=' . - str_replace([' ', '_', '.'], '-', str_replace(['(', ')'], '', $show)) . - '&type=' . $type; + /** + * Fetches summary from trakt.tv for the show by doing a search. + * Accepts a search string. + * + * @param string $show title + * @param string $type show + * + * @see http://docs.trakt.apiary.io/#reference/search/get-text-query-results + * + * @return bool|array|string + */ + public function showSearch($show = '', $type = 'show') + { + $searchUrl = self::API_URL.'search?query='. + str_replace([' ', '_', '.'], '-', str_replace(['(', ')'], '', $show)). + '&type='.$type; - return $this->getJsonArray($searchUrl, ''); - } + return $this->getJsonArray($searchUrl, ''); + } - /** - * Fetches summary from trakt.tv for the show. - * Accepts a trakt slug (game-of-thrones), a IMDB id, or Trakt id. - * - * @param string $show Title or IMDB id. - * @param string $type full: Return all extended properties (minus images). (returns array) - * images: Return extended images properties (returns array) - * full,images: Return all extended properties (plus images). (returns array) - * - * @see http://docs.trakt.apiary.io/#reference/shows/summary/get-a-single-show - * - * @return bool|array|string - * - * @access public - */ - public function showSummary($show = '', $type = 'full') - { - if (empty($show)) { - return null; - } - $showUrl = self::API_URL . 'shows/' . $this->slugify($show); + /** + * Fetches summary from trakt.tv for the show. + * Accepts a trakt slug (game-of-thrones), a IMDB id, or Trakt id. + * + * @param string $show Title or IMDB id. + * @param string $type full: Return all extended properties (minus images). (returns array) + * images: Return extended images properties (returns array) + * full,images: Return all extended properties (plus images). (returns array) + * + * @see http://docs.trakt.apiary.io/#reference/shows/summary/get-a-single-show + * + * @return bool|array|string + */ + public function showSummary($show = '', $type = 'full') + { + if (empty($show)) { + return null; + } + $showUrl = self::API_URL.'shows/'.$this->slugify($show); - switch ($type) { + switch ($type) { case 'images': case 'full,images': $extended = $type; @@ -324,21 +313,21 @@ Class TraktAPI { $extended = ''; } - return $this->getJsonArray($showUrl, $extended); - } + return $this->getJsonArray($showUrl, $extended); + } - /** - * Generate and return a slug for a given ``$phrase``. - * - * @param $phrase - * - * @return mixed - */ - public function slugify($phrase) - { - $result = preg_replace('#[^a-z0-9\s-]#', '', strtolower($phrase)); - $result = preg_replace('#\s#', '-', trim(preg_replace('#[\s-]+#', ' ', $result))); + /** + * Generate and return a slug for a given ``$phrase``. + * + * @param $phrase + * + * @return mixed + */ + public function slugify($phrase) + { + $result = preg_replace('#[^a-z0-9\s-]#', '', strtolower($phrase)); + $result = preg_replace('#\s#', '-', trim(preg_replace('#[\s-]+#', ' ', $result))); - return $result; - } + return $result; + } } diff --git a/nntmux/processing/PostProcess.php b/nntmux/processing/PostProcess.php index 3567bfca7..f2a159754 100755 --- a/nntmux/processing/PostProcess.php +++ b/nntmux/processing/PostProcess.php @@ -1,112 +1,107 @@ <?php + namespace nntmux\processing; -use App\Models\Settings; -use dariusiii\rarinfo\Par2Info; -use dariusiii\rarinfo\SrrInfo; -use nntmux\ADE; -use nntmux\ADM; -use nntmux\AEBN; +use nntmux\Nfo; +use nntmux\XXX; +use nntmux\NNTP; use nntmux\Books; -use nntmux\Category; -use nntmux\ColorCLI; -use nntmux\Console; +use nntmux\db\DB; use nntmux\Games; -use nntmux\Groups; -use nntmux\Hotmovies; -use nntmux\Logger; use nntmux\Movie; use nntmux\Music; -use nntmux\NameFixer; -use nntmux\Nfo; -use nntmux\NNTP; -use nntmux\Popporn; +use nntmux\Groups; +use nntmux\Logger; +use nntmux\Console; use nntmux\Sharing; -use nntmux\processing\adult\AdultMovies; -use nntmux\processing\tv\TVDB; -use nntmux\processing\tv\TVMaze; -use nntmux\processing\tv\TMDB; -use nntmux\processing\tv\TraktTv; -use nntmux\ReleaseFiles; -use nntmux\db\DB; -use nntmux\processing\post\AniDB; -use nntmux\processing\post\ProcessAdditional; use nntmux\SpotNab; -use nntmux\XXX; +use nntmux\Category; +use nntmux\ColorCLI; +use nntmux\NameFixer; +use App\Models\Settings; +use nntmux\ReleaseFiles; +use dariusiii\rarinfo\SrrInfo; +use nntmux\processing\tv\TMDB; +use nntmux\processing\tv\TVDB; +use dariusiii\rarinfo\Par2Info; +use nntmux\processing\tv\TVMaze; +use nntmux\processing\post\AniDB; +use nntmux\processing\tv\TraktTv; +use nntmux\processing\post\ProcessAdditional; class PostProcess { - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * Class instance of debugging. - * - * @var Logger - */ - protected $debugging; + /** + * Class instance of debugging. + * + * @var Logger + */ + protected $debugging; - /** - * Instance of NameFixer. - * @var NameFixer - */ - protected $nameFixer; + /** + * Instance of NameFixer. + * @var NameFixer + */ + protected $nameFixer; - /** - * @var Par2Info - */ - protected $_par2Info; + /** + * @var Par2Info + */ + protected $_par2Info; - /** - * @var SrrInfo - */ - protected $_srrInfo; + /** + * @var SrrInfo + */ + protected $_srrInfo; - /** - * Use alternate NNTP provider when download fails? - * @var bool - */ - private $alternateNNTP; + /** + * Use alternate NNTP provider when download fails? + * @var bool + */ + private $alternateNNTP; - /** - * Add par2 info to rar list? - * @var bool - */ - private $addpar2; + /** + * Add par2 info to rar list? + * @var bool + */ + private $addpar2; - /** - * Should we echo to CLI? - * @var bool - */ - private $echooutput; + /** + * Should we echo to CLI? + * @var bool + */ + private $echooutput; - /** - * @var Groups - */ - private $groups; + /** + * @var Groups + */ + private $groups; - /** - * @var Nfo - */ - private $Nfo; + /** + * @var Nfo + */ + private $Nfo; - /** - * @var ReleaseFiles - */ - private $releaseFiles; + /** + * @var ReleaseFiles + */ + private $releaseFiles; - /** - * Constructor. - * - * @param array $options Pass in class instances. - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * Constructor. + * + * @param array $options Pass in class instances. + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => true, 'Logger' => null, 'Groups' => null, @@ -115,249 +110,249 @@ class PostProcess 'ReleaseFiles' => null, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - // Various. - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + // Various. + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - // Class instances. - $this->pdo = (($options['Settings'] instanceof DB) ? $options['Settings'] : new DB()); - $this->groups = (($options['Groups'] instanceof Groups) ? $options['Groups'] : new Groups(['Settings' => $this->pdo])); - $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 Nfo) ? $options['Nfo'] : new Nfo(['Echo' => $this->echooutput, 'Settings' => $this->pdo])); - $this->releaseFiles = (($options['ReleaseFiles'] instanceof ReleaseFiles) ? $options['ReleaseFiles'] : new ReleaseFiles($this->pdo)); + // Class instances. + $this->pdo = (($options['Settings'] instanceof DB) ? $options['Settings'] : new DB()); + $this->groups = (($options['Groups'] instanceof Groups) ? $options['Groups'] : new Groups(['Settings' => $this->pdo])); + $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 Nfo) ? $options['Nfo'] : new Nfo(['Echo' => $this->echooutput, 'Settings' => $this->pdo])); + $this->releaseFiles = (($options['ReleaseFiles'] instanceof ReleaseFiles) ? $options['ReleaseFiles'] : new ReleaseFiles($this->pdo)); - // Site settings. - $this->addpar2 = (int)Settings::value('..addpar2') !== 0; - $this->alternateNNTP = (int)Settings::value('..alternate_nntp') === 1; - } + // Site settings. + $this->addpar2 = (int) Settings::value('..addpar2') !== 0; + $this->alternateNNTP = (int) Settings::value('..alternate_nntp') === 1; + } - /** - * Go through every type of post proc. - * - * @param $nntp - * - * @return void - * @throws \Exception - */ - public function processAll($nntp): void - { - $this->processAdditional($nntp); - $this->processNfos($nntp); - $this->processSharing($nntp); - $this->processSpotnab(); - $this->processMovies(); - $this->processMusic(); - $this->processConsoles(); - $this->processGames(); - $this->processAnime(); - $this->processTv(); - $this->processXXX(); - $this->processBooks(); - } + /** + * Go through every type of post proc. + * + * @param $nntp + * + * @return void + * @throws \Exception + */ + public function processAll($nntp): void + { + $this->processAdditional($nntp); + $this->processNfos($nntp); + $this->processSharing($nntp); + $this->processSpotnab(); + $this->processMovies(); + $this->processMusic(); + $this->processConsoles(); + $this->processGames(); + $this->processAnime(); + $this->processTv(); + $this->processXXX(); + $this->processBooks(); + } - /** - * Lookup anidb if enabled - always run before tvrage. - * - * @return void - */ - public function processAnime(): void - { - if ((int)Settings::value('..lookupanidb') !== 0) { - (new AniDB(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processAnimeReleases(); - } - } + /** + * Lookup anidb if enabled - always run before tvrage. + * + * @return void + */ + public function processAnime(): void + { + if ((int) Settings::value('..lookupanidb') !== 0) { + (new AniDB(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processAnimeReleases(); + } + } - /** - * Process books using amazon.com. - * - * @return void - * @throws \Exception - */ - public function processBooks(): void - { - if ((int)Settings::value('..lookupbooks') !== 0) { - (new Books(['Echo' => $this->echooutput, 'Settings' => $this->pdo, ]))->processBookReleases(); - } - } + /** + * Process books using amazon.com. + * + * @return void + * @throws \Exception + */ + public function processBooks(): void + { + if ((int) Settings::value('..lookupbooks') !== 0) { + (new Books(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processBookReleases(); + } + } - /** - * Lookup console games if enabled. - * - * @return void - */ - public function processConsoles(): void - { - if ((int)Settings::value('..lookupgames') !== 0) { - (new Console(['Settings' => $this->pdo, 'Echo' => $this->echooutput]))->processConsoleReleases(); - } - } + /** + * Lookup console games if enabled. + * + * @return void + */ + public function processConsoles(): void + { + if ((int) Settings::value('..lookupgames') !== 0) { + (new Console(['Settings' => $this->pdo, 'Echo' => $this->echooutput]))->processConsoleReleases(); + } + } - /** - * Lookup games if enabled. - * - * @return void - * @throws \Exception - */ - public function processGames(): void - { - if ((int)Settings::value('..lookupgames') !== 0) { - (new Games(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processGamesReleases(); - } - } + /** + * Lookup games if enabled. + * + * @return void + * @throws \Exception + */ + public function processGames(): void + { + if ((int) Settings::value('..lookupgames') !== 0) { + (new Games(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processGamesReleases(); + } + } - /** - * Lookup imdb if enabled. - * - * @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. - * @param int|string|null $processMovies (Optional) 0 Don't process, 1 process all releases, - * 2 process renamed releases only, '' check site setting - * - * @return void - * @throws \Exception - */ - public function processMovies($groupID = '', $guidChar = '', $processMovies = ''): void - { - $processMovies = (is_numeric($processMovies) ? $processMovies : Settings::value('..lookupimdb')); - if ($processMovies > 0) { - (new Movie(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processMovieReleases($groupID, $guidChar, $processMovies); - } - } + /** + * Lookup imdb if enabled. + * + * @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. + * @param int|string|null $processMovies (Optional) 0 Don't process, 1 process all releases, + * 2 process renamed releases only, '' check site setting + * + * @return void + * @throws \Exception + */ + public function processMovies($groupID = '', $guidChar = '', $processMovies = ''): void + { + $processMovies = (is_numeric($processMovies) ? $processMovies : Settings::value('..lookupimdb')); + if ($processMovies > 0) { + (new Movie(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processMovieReleases($groupID, $guidChar, $processMovies); + } + } - /** - * Lookup music if enabled. - * - * @return void - */ - public function processMusic(): void - { - if ((int)Settings::value('..lookupmusic') !== 0) { - (new Music(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processMusicReleases(); - } - } + /** + * Lookup music if enabled. + * + * @return void + */ + public function processMusic(): void + { + if ((int) Settings::value('..lookupmusic') !== 0) { + (new Music(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processMusicReleases(); + } + } - /** - * Process nfo files. - * - * @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. - * - * @return void - * @throws \Exception - */ - public function processNfos(&$nntp, $groupID = '', $guidChar = ''): void - { - if ((int)Settings::value('..lookupnfo') === 1) { - $this->Nfo->processNfoFiles($nntp, $groupID, $guidChar, (int)Settings::value('..lookupimdb'), (int)Settings::value('..lookuptvrage')); - } - } + /** + * Process nfo files. + * + * @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. + * + * @return void + * @throws \Exception + */ + public function processNfos(&$nntp, $groupID = '', $guidChar = ''): void + { + if ((int) Settings::value('..lookupnfo') === 1) { + $this->Nfo->processNfoFiles($nntp, $groupID, $guidChar, (int) Settings::value('..lookupimdb'), (int) Settings::value('..lookuptvrage')); + } + } - /** - * Process comments. - * - * @param NNTP $nntp - */ - public function processSharing(&$nntp): void - { - (new Sharing(['Settings' => $this->pdo, 'NNTP' => $nntp]))->start(); - } + /** + * Process comments. + * + * @param NNTP $nntp + */ + public function processSharing(&$nntp): void + { + (new Sharing(['Settings' => $this->pdo, 'NNTP' => $nntp]))->start(); + } - /** - * Process all TV related releases which will assign their series/episode/rage data. - * - * @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. - * @param string|int|null $processTV (Optional) 0 Don't process, 1 process all releases, - * 2 process renamed releases only, '' check site setting - * - * @return void - * @throws \Exception - */ - public function processTv($groupID = '', $guidChar = '', $processTV = ''): void - { - $processTV = (is_numeric($processTV) ? $processTV : Settings::value('..lookuptvrage')); - if ($processTV > 0) { - (new TVDB(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processSite($groupID, $guidChar, $processTV); - (new TVMaze(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processSite($groupID, $guidChar, $processTV); - (new TMDB(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processSite($groupID, $guidChar, $processTV); - (new TraktTv(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processSite($groupID, $guidChar, $processTV); - } - } + /** + * Process all TV related releases which will assign their series/episode/rage data. + * + * @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. + * @param string|int|null $processTV (Optional) 0 Don't process, 1 process all releases, + * 2 process renamed releases only, '' check site setting + * + * @return void + * @throws \Exception + */ + public function processTv($groupID = '', $guidChar = '', $processTV = ''): void + { + $processTV = (is_numeric($processTV) ? $processTV : Settings::value('..lookuptvrage')); + if ($processTV > 0) { + (new TVDB(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processSite($groupID, $guidChar, $processTV); + (new TVMaze(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processSite($groupID, $guidChar, $processTV); + (new TMDB(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processSite($groupID, $guidChar, $processTV); + (new TraktTv(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processSite($groupID, $guidChar, $processTV); + } + } - /** - * Process Global IDs - */ - public function processSpotnab(): void - { - $spotnab = new SpotNab(); - $processed = $spotnab->processGID(); - if ($processed > 0) { - if ($this->echooutput) { - ColorCLI::doEcho( - ColorCLI::primary('Updating GID in releases table ' . $processed . ' release(s) updated') + /** + * Process Global IDs. + */ + public function processSpotnab(): void + { + $spotnab = new SpotNab(); + $processed = $spotnab->processGID(); + if ($processed > 0) { + if ($this->echooutput) { + ColorCLI::doEcho( + ColorCLI::primary('Updating GID in releases table '.$processed.' release(s) updated') ); - } - } - $spotnab->auto_post_discovery(); - $spotnab->fetch_discovery(); - $spotnab->fetch(); - $spotnab->post(); - $spotnab->auto_clean(); - } + } + } + $spotnab->auto_post_discovery(); + $spotnab->fetch_discovery(); + $spotnab->fetch(); + $spotnab->post(); + $spotnab->auto_clean(); + } - /** - * Lookup xxx if enabled. - * - * @throws \Exception - */ - public function processXXX(): void - { - if ((int)Settings::value('..lookupxxx') === 1) { - (new XXX(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processXXXReleases(); - } - } + /** + * Lookup xxx if enabled. + * + * @throws \Exception + */ + public function processXXX(): void + { + if ((int) Settings::value('..lookupxxx') === 1) { + (new XXX(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processXXXReleases(); + } + } - /** - * Check for passworded releases, RAR/ZIP contents and Sample/Media info. - * - * @note Called externally by tmux/bin/update_per_group and update/postprocess.php - * - * @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. - * - * @return void - */ - public function processAdditional(&$nntp, $groupID = '', $guidChar = ''): void - { - (new ProcessAdditional(['Echo' => $this->echooutput, 'NNTP' => $nntp, 'Settings' => $this->pdo, 'Groups' => $this->groups, 'NameFixer' => $this->nameFixer, 'Nfo' => $this->Nfo, 'ReleaseFiles' => $this->releaseFiles]))->start($groupID, $guidChar); - } + /** + * Check for passworded releases, RAR/ZIP contents and Sample/Media info. + * + * @note Called externally by tmux/bin/update_per_group and update/postprocess.php + * + * @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. + * + * @return void + */ + public function processAdditional(&$nntp, $groupID = '', $guidChar = ''): void + { + (new ProcessAdditional(['Echo' => $this->echooutput, 'NNTP' => $nntp, 'Settings' => $this->pdo, 'Groups' => $this->groups, 'NameFixer' => $this->nameFixer, 'Nfo' => $this->Nfo, 'ReleaseFiles' => $this->releaseFiles]))->start($groupID, $guidChar); + } - /** - * Attempt to get a better name from a par2 file and categorize the release. - * - * @note Called from NZBContents.php - * - * @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 int $show Only show result or apply iy. - * - * @return bool - * @throws \Exception - */ - public function parsePAR2($messageID, $relID, $groupID, &$nntp, $show): bool - { - if ($messageID === '') { - return false; - } + /** + * Attempt to get a better name from a par2 file and categorize the release. + * + * @note Called from NZBContents.php + * + * @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 int $show Only show result or apply iy. + * + * @return bool + * @throws \Exception + */ + public function parsePAR2($messageID, $relID, $groupID, &$nntp, $show): bool + { + if ($messageID === '') { + return false; + } - $query = $this->pdo->queryOneRow( + $query = $this->pdo->queryOneRow( sprintf(' SELECT id, groups_id, categories_id, name, searchname, UNIX_TIMESTAMP(postdate) AS post_date, id AS releases_id FROM releases @@ -367,49 +362,47 @@ class PostProcess ) ); - if ($query === false) { - return false; - } + if ($query === false) { + return false; + } - // Only get a new name if the category is OTHER. - $foundName = true; - if (in_array((int)$query['categories_id'], Category::OTHERS_GROUP, false)) { - $foundName = false; - } + // Only get a new name if the category is OTHER. + $foundName = true; + if (in_array((int) $query['categories_id'], Category::OTHERS_GROUP, false)) { + $foundName = false; + } - // Get the PAR2 file. - $par2 = $nntp->getMessages($this->groups->getNameByID($groupID), $messageID, $this->alternateNNTP); - if ($nntp->isError($par2)) { - return false; - } + // Get the PAR2 file. + $par2 = $nntp->getMessages($this->groups->getNameByID($groupID), $messageID, $this->alternateNNTP); + if ($nntp->isError($par2)) { + return false; + } - // Put the PAR2 into Par2Info, check if there's an error. - $this->_par2Info->setData($par2); - if ($this->_par2Info->error) { - return false; - } + // Put the PAR2 into Par2Info, check if there's an error. + $this->_par2Info->setData($par2); + if ($this->_par2Info->error) { + return false; + } - // Get the file list from Par2Info. - $files = $this->_par2Info->getFileList(); - if ($files !== false && count($files) > 0) { + // Get the file list from Par2Info. + $files = $this->_par2Info->getFileList(); + if ($files !== false && count($files) > 0) { + $filesAdded = 0; - $filesAdded = 0; + // Loop through the files. + foreach ($files as $file) { + if (! isset($file['name'])) { + continue; + } - // Loop through the files. - foreach ($files as $file) { + // If we found a name and added 10 files, stop. + if ($foundName === true && $filesAdded > 10) { + break; + } - if (!isset($file['name'])) { - continue; - } - - // If we found a name and added 10 files, stop. - if ($foundName === true && $filesAdded > 10) { - break; - } - - if ($this->addpar2) { - // Add to release files. - if ($filesAdded < 11 && + if ($this->addpar2) { + // Add to release files. + if ($filesAdded < 11 && $this->pdo->queryOneRow( sprintf(' SELECT releases_id @@ -423,29 +416,29 @@ class PostProcess ) { // Try to add the files to the DB. - if ($this->releaseFiles->add($relID, $file['name'], $file['hash_16K'], $file['size'], $query['post_date'], 0)) { - $filesAdded++; - } - } - } else { - $filesAdded++; - } + if ($this->releaseFiles->add($relID, $file['name'], $file['hash_16K'], $file['size'], $query['post_date'], 0)) { + $filesAdded++; + } + } + } else { + $filesAdded++; + } - // Try to get a new name. - if ($foundName === false) { - $query['textstring'] = $file['name']; - if ($this->nameFixer->checkName($query, 1, 'PAR2, ', 1, $show) === true) { - $foundName = true; - } - } - } + // Try to get a new name. + if ($foundName === false) { + $query['textstring'] = $file['name']; + if ($this->nameFixer->checkName($query, 1, 'PAR2, ', 1, $show) === true) { + $foundName = true; + } + } + } - // If we found some files. - if ($filesAdded > 0) { - $this->debugging->log(get_class(), __FUNCTION__, 'Added ' . $filesAdded . ' release_files from PAR2 for ' . $query['searchname'], Logger::LOG_INFO); + // If we found some files. + if ($filesAdded > 0) { + $this->debugging->log(get_class(), __FUNCTION__, 'Added '.$filesAdded.' release_files from PAR2 for '.$query['searchname'], Logger::LOG_INFO); - // Update the file count with the new file count + old file count. - $this->pdo->queryExec( + // Update the file count with the new file count + old file count. + $this->pdo->queryExec( sprintf(' UPDATE releases SET rarinnerfilecount = rarinnerfilecount + %d @@ -454,11 +447,12 @@ class PostProcess $relID ) ); - } - if ($foundName === true) { - return true; - } - } - return false; - } + } + if ($foundName === true) { + return true; + } + } + + return false; + } } diff --git a/nntmux/processing/ProcessReleases.php b/nntmux/processing/ProcessReleases.php index 86c789eec..aa95ff77b 100755 --- a/nntmux/processing/ProcessReleases.php +++ b/nntmux/processing/ProcessReleases.php @@ -1,128 +1,129 @@ <?php + namespace nntmux\processing; -use App\Models\MultigroupPosters; -use App\Models\ReleasesGroups; -use App\Models\ReleaseRegexes; -use App\Models\Settings; -use nntmux\Categorize; -use nntmux\Category; -use nntmux\ColorCLI; -use nntmux\ConsoleTools; +use nntmux\NZB; +use nntmux\NNTP; +use nntmux\db\DB; +use nntmux\PreDb; use nntmux\Genres; use nntmux\Groups; -use nntmux\NNTP; -use nntmux\NZB; -use nntmux\PreDb; -use nntmux\ReleaseCleaning; -use nntmux\ReleaseImage; +use nntmux\Category; +use nntmux\ColorCLI; use nntmux\Releases; -use nntmux\RequestIDLocal; +use nntmux\Categorize; +use App\Models\Settings; +use nntmux\ConsoleTools; +use nntmux\ReleaseImage; use nntmux\RequestIDWeb; -use nntmux\db\DB; +use nntmux\RequestIDLocal; +use nntmux\ReleaseCleaning; +use App\Models\ReleaseRegexes; +use App\Models\ReleasesGroups; +use App\Models\MultigroupPosters; class ProcessReleases { - const COLLFC_DEFAULT = 0; // Collection has default filecheck status - const COLLFC_COMPCOLL = 1; // Collection is a complete collection - const COLLFC_COMPPART = 2; // Collection is a complete collection and has all parts available - const COLLFC_SIZED = 3; // Collection has been calculated for total size - const COLLFC_INSERTED = 4; // Collection has been inserted into releases - const COLLFC_DELETE = 5; // Collection is ready for deletion + const COLLFC_DEFAULT = 0; // Collection has default filecheck status + const COLLFC_COMPCOLL = 1; // Collection is a complete collection + const COLLFC_COMPPART = 2; // Collection is a complete collection and has all parts available + const COLLFC_SIZED = 3; // Collection has been calculated for total size + const COLLFC_INSERTED = 4; // Collection has been inserted into releases + const COLLFC_DELETE = 5; // Collection is ready for deletion const COLLFC_TEMPCOMP = 15; // Collection is complete and being checked for complete parts const COLLFC_ZEROPART = 16; // Collection has a 00/0XX designator (temporary) const FILE_INCOMPLETE = 0; // We don't have all the parts yet for the file (binaries table partcheck column). - const FILE_COMPLETE = 1; // We have all the parts for the file (binaries table partcheck column). + const FILE_COMPLETE = 1; // We have all the parts for the file (binaries table partcheck column). /** * @var Groups */ - public $groups; + public $groups; - /** - * @var int - */ - public $collectionDelayTime; + /** + * @var int + */ + public $collectionDelayTime; - /** - * @var int - */ - public $crossPostTime; + /** + * @var int + */ + public $crossPostTime; - /** - * @var int - */ - public $releaseCreationLimit; + /** + * @var int + */ + public $releaseCreationLimit; - /** - * @var int - */ - public $completion; + /** + * @var int + */ + public $completion; - /** - * @var int - */ - public $processRequestIDs; + /** + * @var int + */ + public $processRequestIDs; - /** - * @var bool - */ - public $echoCLI; + /** + * @var bool + */ + public $echoCLI; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var ConsoleTools - */ - public $consoleTools; + /** + * @var ConsoleTools + */ + public $consoleTools; - /** - * @var NZB - */ - public $nzb; + /** + * @var NZB + */ + public $nzb; - /** - * @var ReleaseCleaning - */ - public $releaseCleaning; + /** + * @var ReleaseCleaning + */ + public $releaseCleaning; - /** - * @var Releases - */ - public $releases; + /** + * @var Releases + */ + public $releases; - /** - * @var ReleaseImage - */ - public $releaseImage; + /** + * @var ReleaseImage + */ + public $releaseImage; - /** - * @var array $tables List of table names to be using for method calls. - */ - protected $tables = []; + /** + * @var array List of table names to be using for method calls. + */ + protected $tables = []; - /** - * @var string $fromNamesQuery - */ - protected $fromNamesQuery; + /** + * @var string + */ + protected $fromNamesQuery; - /** - * @var int Time (hours) to wait before delete a stuck/broken collection. - */ - private $collectionTimeout; + /** + * @var int Time (hours) to wait before delete a stuck/broken collection. + */ + private $collectionTimeout; - /** - * @param array $options Class instances / Echo to cli ? - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances / Echo to cli ? + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => true, 'ConsoleTools' => null, 'Groups' => null, @@ -132,154 +133,152 @@ class ProcessReleases 'Releases' => null, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echoCLI = ($options['Echo'] && NN_ECHOCLI); + $this->echoCLI = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->consoleTools = ($options['ConsoleTools'] instanceof ConsoleTools ? $options['ConsoleTools'] : new ConsoleTools(['ColorCLI' => $this->pdo->log])); - $this->groups = ($options['Groups'] instanceof Groups ? $options['Groups'] : new Groups(['Settings' => $this->pdo])); - $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo)); - $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)); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->consoleTools = ($options['ConsoleTools'] instanceof ConsoleTools ? $options['ConsoleTools'] : new ConsoleTools(['ColorCLI' => $this->pdo->log])); + $this->groups = ($options['Groups'] instanceof Groups ? $options['Groups'] : new Groups(['Settings' => $this->pdo])); + $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo)); + $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)); - $dummy = Settings::value('..delaytime'); - $this->collectionDelayTime = ($dummy !== '' ? (int)$dummy : 2); - $dummy = Settings::value('..crossposttime'); - $this->crossPostTime = ($dummy !== '' ? (int)$dummy : 2); - $dummy = Settings::value('..maxnzbsprocessed'); - $this->releaseCreationLimit = ($dummy !== '' ? (int)$dummy : 1000); - $dummy = Settings::value('..completionpercent'); - $this->completion = ($dummy !== '' ? (int)$dummy : 0); - $this->processRequestIDs = (int)Settings::value('lookup_reqids'); - if ($this->completion > 100) { - $this->completion = 100; - echo ColorCLI::error(PHP_EOL . 'You have an invalid setting for completion. It cannot be higher than 100.'); - } - $this->collectionTimeout = (int)Settings::value('indexer.processing.collection_timeout'); - } + $dummy = Settings::value('..delaytime'); + $this->collectionDelayTime = ($dummy !== '' ? (int) $dummy : 2); + $dummy = Settings::value('..crossposttime'); + $this->crossPostTime = ($dummy !== '' ? (int) $dummy : 2); + $dummy = Settings::value('..maxnzbsprocessed'); + $this->releaseCreationLimit = ($dummy !== '' ? (int) $dummy : 1000); + $dummy = Settings::value('..completionpercent'); + $this->completion = ($dummy !== '' ? (int) $dummy : 0); + $this->processRequestIDs = (int) Settings::value('lookup_reqids'); + if ($this->completion > 100) { + $this->completion = 100; + echo ColorCLI::error(PHP_EOL.'You have an invalid setting for completion. It cannot be higher than 100.'); + } + $this->collectionTimeout = (int) Settings::value('indexer.processing.collection_timeout'); + } - /** - * Main method for creating releases/NZB files from collections. - * - * @param int $categorize - * @param int $postProcess - * @param string $groupName (optional) - * @param \nntmux\NNTP $nntp - * @param bool $echooutput - * - * @return int - * @throws \Exception - */ - public function processReleases($categorize, $postProcess, $groupName, &$nntp, $echooutput) - { - $this->echoCLI = ($echooutput && NN_ECHOCLI); - $groupID = ''; + /** + * Main method for creating releases/NZB files from collections. + * + * @param int $categorize + * @param int $postProcess + * @param string $groupName (optional) + * @param \nntmux\NNTP $nntp + * @param bool $echooutput + * + * @return int + * @throws \Exception + */ + public function processReleases($categorize, $postProcess, $groupName, &$nntp, $echooutput) + { + $this->echoCLI = ($echooutput && NN_ECHOCLI); + $groupID = ''; - if (!empty($groupName) && $groupName !== 'mgr') { - $groupInfo = $this->groups->getByName($groupName); - $groupID = $groupInfo['id']; - } + if (! empty($groupName) && $groupName !== 'mgr') { + $groupInfo = $this->groups->getByName($groupName); + $groupID = $groupInfo['id']; + } - $processReleases = microtime(true); - if ($this->echoCLI) { - ColorCLI::doEcho(ColorCLI::header('Starting release update process (' . date('Y-m-d H:i:s') . ')'), true); - } + $processReleases = microtime(true); + if ($this->echoCLI) { + ColorCLI::doEcho(ColorCLI::header('Starting release update process ('.date('Y-m-d H:i:s').')'), true); + } - if (!file_exists(Settings::value('..nzbpath'))) { - if ($this->echoCLI) { - ColorCLI::doEcho( - ColorCLI::error('Bad or missing nzb directory - ' . Settings::value('..nzbpath')), + if (! file_exists(Settings::value('..nzbpath'))) { + if ($this->echoCLI) { + ColorCLI::doEcho( + ColorCLI::error('Bad or missing nzb directory - '.Settings::value('..nzbpath')), true ); - } + } - return 0; - } + return 0; + } - $this->processIncompleteCollections($groupID); - $this->processCollectionSizes($groupID); - $this->deleteUnwantedCollections($groupID); + $this->processIncompleteCollections($groupID); + $this->processCollectionSizes($groupID); + $this->deleteUnwantedCollections($groupID); - $DIR = NN_MISC; + $DIR = NN_MISC; - $totalReleasesAdded = 0; - do { - $releasesCount = $this->createReleases($groupID); - $totalReleasesAdded += $releasesCount['added']; + $totalReleasesAdded = 0; + do { + $releasesCount = $this->createReleases($groupID); + $totalReleasesAdded += $releasesCount['added']; - $nzbFilesAdded = $this->createNZBs($groupID); - if ($this->processRequestIDs === 0) { - $this->processRequestIDs($groupID, 5000, true); - } else if ($this->processRequestIDs === 1) { - $this->processRequestIDs($groupID, 5000, true); - $this->processRequestIDs($groupID, 1000, false); - } else if ($this->processRequestIDs === 2) { - $requestIDTime = time(); - if ($this->echoCLI) { - ColorCLI::doEcho(ColorCLI::header('Process Releases -> Request ID Threaded lookup.')); - } - passthru("${DIR}update/nix/multiprocessing/requestid.php"); - if ($this->echoCLI) { - ColorCLI::doEcho( + $nzbFilesAdded = $this->createNZBs($groupID); + if ($this->processRequestIDs === 0) { + $this->processRequestIDs($groupID, 5000, true); + } elseif ($this->processRequestIDs === 1) { + $this->processRequestIDs($groupID, 5000, true); + $this->processRequestIDs($groupID, 1000, false); + } elseif ($this->processRequestIDs === 2) { + $requestIDTime = time(); + if ($this->echoCLI) { + ColorCLI::doEcho(ColorCLI::header('Process Releases -> Request ID Threaded lookup.')); + } + passthru("${DIR}update/nix/multiprocessing/requestid.php"); + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - "\nReleases updated in " . + "\nReleases updated in ". $this->consoleTools->convertTime(time() - $requestIDTime) ) ); - } - } + } + } - $this->categorizeReleases($categorize, $groupID); - $this->postProcessReleases($postProcess, $nntp); - $this->deleteCollections($groupID); + $this->categorizeReleases($categorize, $groupID); + $this->postProcessReleases($postProcess, $nntp); + $this->deleteCollections($groupID); - // This loops as long as the number of releases or nzbs added was >= the limit (meaning there are more waiting to be created) - } while ( - ($releasesCount['added'] + $releasesCount['dupes']) >= $this->releaseCreationLimit + // This loops as long as the number of releases or nzbs added was >= the limit (meaning there are more waiting to be created) + } while ( + ($releasesCount['added'] + $releasesCount['dupes']) >= $this->releaseCreationLimit || $nzbFilesAdded >= $this->releaseCreationLimit ); - // Only run if non-mgr as mgr is not specific to group - if ($groupName !== 'mgr') { - $this->deletedReleasesByGroup($groupID); - $this->deleteReleases(); - } + // Only run if non-mgr as mgr is not specific to group + if ($groupName !== 'mgr') { + $this->deletedReleasesByGroup($groupID); + $this->deleteReleases(); + } - return $totalReleasesAdded; - } + return $totalReleasesAdded; + } - /** - * Return all releases to other->misc category. - * - * @param string $where Optional "where" query parameter. - * - * @void - * @access public - */ - public function resetCategorize($where = ''): void - { - $this->pdo->queryExec( + /** + * Return all releases to other->misc category. + * + * @param string $where Optional "where" query parameter. + * + * @void + */ + public function resetCategorize($where = ''): void + { + $this->pdo->queryExec( sprintf('UPDATE releases SET categories_id = %d, iscategorized = 0 %s', Category::OTHER_MISC, $where) ); - } + } - /** - * Categorizes releases. - * - * @param string $type name or searchname | Categorize using the search name or subject. - * @param string $where Optional "where" query parameter. - * - * @return int Quantity of categorized releases. - * @throws \Exception - * @access public - */ - public function categorizeRelease($type, $where = ''): int - { - $cat = new Categorize(['Settings' => $this->pdo]); - $categorized = $total = 0; - $releases = $this->pdo->queryDirect( + /** + * Categorizes releases. + * + * @param string $type name or searchname | Categorize using the search name or subject. + * @param string $where Optional "where" query parameter. + * + * @return int Quantity of categorized releases. + * @throws \Exception + */ + public function categorizeRelease($type, $where = ''): int + { + $cat = new Categorize(['Settings' => $this->pdo]); + $categorized = $total = 0; + $releases = $this->pdo->queryDirect( sprintf(' SELECT id, fromname, %s, groups_id FROM releases %s', @@ -287,11 +286,11 @@ class ProcessReleases $where ) ); - if ($releases && $releases->rowCount()) { - $total = $releases->rowCount(); - foreach ($releases as $release) { - $catId = $cat->determineCategory($release['groups_id'], $release[$type], $release['fromname']); - $this->pdo->queryExec( + if ($releases && $releases->rowCount()) { + $total = $releases->rowCount(); + foreach ($releases as $release) { + $catId = $cat->determineCategory($release['groups_id'], $release[$type], $release['fromname']); + $this->pdo->queryExec( sprintf(' UPDATE releases SET categories_id = %d, iscategorized = 1 @@ -300,44 +299,45 @@ class ProcessReleases $release['id'] ) ); - $categorized++; - if ($this->echoCLI) { - $this->consoleTools->overWritePrimary( - 'Categorizing: ' . $this->consoleTools->percentString($categorized, $total) + $categorized++; + if ($this->echoCLI) { + $this->consoleTools->overWritePrimary( + 'Categorizing: '.$this->consoleTools->percentString($categorized, $total) ); - } - } - } - if ($this->echoCLI !== false && $categorized > 0) { - echo PHP_EOL; - } - return $categorized; - } + } + } + } + if ($this->echoCLI !== false && $categorized > 0) { + echo PHP_EOL; + } - /** - * @param $groupID - */ - public function processIncompleteCollections($groupID): void - { - $startTime = time(); - $this->initiateTableNames($groupID); + return $categorized; + } - if ($this->echoCLI) { - ColorCLI::doEcho(ColorCLI::header('Process Releases -> Attempting to find complete collections.')); - } + /** + * @param $groupID + */ + public function processIncompleteCollections($groupID): void + { + $startTime = time(); + $this->initiateTableNames($groupID); - $where = (!empty($groupID) ? ' AND c.groups_id = ' . $groupID . ' ' : ' '); + if ($this->echoCLI) { + ColorCLI::doEcho(ColorCLI::header('Process Releases -> Attempting to find complete collections.')); + } - $this->processStuckCollections($where); - $this->collectionFileCheckStage1($where); - $this->collectionFileCheckStage2($where); - $this->collectionFileCheckStage3($where); - $this->collectionFileCheckStage4($where); - $this->collectionFileCheckStage5($where); - $this->collectionFileCheckStage6($where); + $where = (! empty($groupID) ? ' AND c.groups_id = '.$groupID.' ' : ' '); - if ($this->echoCLI) { - $count = $this->pdo->queryOneRow( + $this->processStuckCollections($where); + $this->collectionFileCheckStage1($where); + $this->collectionFileCheckStage2($where); + $this->collectionFileCheckStage3($where); + $this->collectionFileCheckStage4($where); + $this->collectionFileCheckStage5($where); + $this->collectionFileCheckStage6($where); + + if ($this->echoCLI) { + $count = $this->pdo->queryOneRow( sprintf(' SELECT COUNT(c.id) AS complete FROM %s c @@ -347,28 +347,28 @@ class ProcessReleases $where ) ); - ColorCLI::doEcho( + ColorCLI::doEcho( ColorCLI::primary( - ($count === false ? 0 : $count['complete']) . ' collections were found to be complete. Time: ' . + ($count === false ? 0 : $count['complete']).' collections were found to be complete. Time: '. $this->consoleTools->convertTime(time() - $startTime) ), true ); - } - } + } + } - /** - * @param $groupID - */ - public function processCollectionSizes($groupID): void - { - $startTime = time(); - $this->initiateTableNames($groupID); + /** + * @param $groupID + */ + public function processCollectionSizes($groupID): void + { + $startTime = time(); + $this->initiateTableNames($groupID); - if ($this->echoCLI) { - ColorCLI::doEcho(ColorCLI::header('Process Releases -> Calculating collection sizes (in bytes).')); - } - // Get the total size in bytes of the collection for collections where filecheck = 2. - $checked = $this->pdo->queryExec( + if ($this->echoCLI) { + ColorCLI::doEcho(ColorCLI::header('Process Releases -> Calculating collection sizes (in bytes).')); + } + // Get the total size in bytes of the collection for collections where filecheck = 2. + $checked = $this->pdo->queryExec( sprintf(' UPDATE %s c SET c.filesize = @@ -384,60 +384,59 @@ class ProcessReleases $this->tables['bname'], self::COLLFC_SIZED, self::COLLFC_COMPPART, - (!empty($groupID) ? ' AND c.groups_id = ' . $groupID : ' ') + (! empty($groupID) ? ' AND c.groups_id = '.$groupID : ' ') ) ); - if ($checked !== false && $this->echoCLI) { - ColorCLI::doEcho( + if ($checked !== false && $this->echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - $checked->rowCount() . ' collections set to filecheck = 3(size calculated)' + $checked->rowCount().' collections set to filecheck = 3(size calculated)' ) ); - ColorCLI::doEcho(ColorCLI::primary($this->consoleTools->convertTime(time() - $startTime)), true); - } - } + ColorCLI::doEcho(ColorCLI::primary($this->consoleTools->convertTime(time() - $startTime)), true); + } + } - /** - * @param $groupID - * - * @throws \Exception - */ - public function deleteUnwantedCollections($groupID): void - { - $startTime = time(); - $this->initiateTableNames($groupID); + /** + * @param $groupID + * + * @throws \Exception + */ + public function deleteUnwantedCollections($groupID): void + { + $startTime = time(); + $this->initiateTableNames($groupID); - if ($this->echoCLI) { - ColorCLI::doEcho( + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::header( 'Process Releases -> Delete collections smaller/larger than minimum size/file count from group/site setting.' ) ); - } + } - $groupID === '' ? $groupIDs = $this->groups->getActiveIDs() : $groupIDs = [['id' => $groupID]]; + $groupID === '' ? $groupIDs = $this->groups->getActiveIDs() : $groupIDs = [['id' => $groupID]]; - $minSizeDeleted = $maxSizeDeleted = $minFilesDeleted = 0; + $minSizeDeleted = $maxSizeDeleted = $minFilesDeleted = 0; - $maxSizeSetting = Settings::value('.release.maxsizetoformrelease'); - $minSizeSetting = Settings::value('.release.minsizetoformrelease'); - $minFilesSetting = Settings::value('.release.minfilestoformrelease'); + $maxSizeSetting = Settings::value('.release.maxsizetoformrelease'); + $minSizeSetting = Settings::value('.release.minsizetoformrelease'); + $minFilesSetting = Settings::value('.release.minfilestoformrelease'); - foreach ($groupIDs as $grpID) { + foreach ($groupIDs as $grpID) { + $groupMinSizeSetting = $groupMinFilesSetting = 0; - $groupMinSizeSetting = $groupMinFilesSetting = 0; + $groupMinimums = $this->groups->getByID($grpID['id']); + if ($groupMinimums !== false) { + if (! empty($groupMinimums['minsizetoformrelease']) && $groupMinimums['minsizetoformrelease'] > 0) { + $groupMinSizeSetting = (int) $groupMinimums['minsizetoformrelease']; + } + if (! empty($groupMinimums['minfilestoformrelease']) && $groupMinimums['minfilestoformrelease'] > 0) { + $groupMinFilesSetting = (int) $groupMinimums['minfilestoformrelease']; + } + } - $groupMinimums = $this->groups->getByID($grpID['id']); - if ($groupMinimums !== false) { - if (!empty($groupMinimums['minsizetoformrelease']) && $groupMinimums['minsizetoformrelease'] > 0) { - $groupMinSizeSetting = (int)$groupMinimums['minsizetoformrelease']; - } - if (!empty($groupMinimums['minfilestoformrelease']) && $groupMinimums['minfilestoformrelease'] > 0) { - $groupMinFilesSetting = (int)$groupMinimums['minfilestoformrelease']; - } - } - - if ($this->pdo->queryOneRow( + if ($this->pdo->queryOneRow( sprintf(' SELECT SQL_NO_CACHE id FROM %s c @@ -448,8 +447,7 @@ class ProcessReleases ) ) !== false ) { - - $deleteQuery = $this->pdo->queryExec( + $deleteQuery = $this->pdo->queryExec( sprintf(' DELETE c, b, p FROM %s c LEFT JOIN %s b ON c.id = b.collections_id @@ -468,13 +466,12 @@ class ProcessReleases $minSizeSetting ) ); - if ($deleteQuery !== false) { - $minSizeDeleted += $deleteQuery->rowCount(); - } + if ($deleteQuery !== false) { + $minSizeDeleted += $deleteQuery->rowCount(); + } - - if ($maxSizeSetting > 0) { - $deleteQuery = $this->pdo->queryExec( + if ($maxSizeSetting > 0) { + $deleteQuery = $this->pdo->queryExec( sprintf(' DELETE c, b, p FROM %s c LEFT JOIN %s b ON c.id = b.collections_id @@ -488,13 +485,13 @@ class ProcessReleases $maxSizeSetting ) ); - if ($deleteQuery !== false) { - $maxSizeDeleted += $deleteQuery->rowCount(); - } - } + if ($deleteQuery !== false) { + $maxSizeDeleted += $deleteQuery->rowCount(); + } + } - if ($minFilesSetting > 0 || $groupMinFilesSetting > 0) { - $deleteQuery = $this->pdo->queryExec( + if ($minFilesSetting > 0 || $groupMinFilesSetting > 0) { + $deleteQuery = $this->pdo->queryExec( sprintf(' DELETE c, b, p FROM %s c LEFT JOIN %s b ON c.id = b.collections_id @@ -512,68 +509,68 @@ class ProcessReleases $minFilesSetting ) ); - if ($deleteQuery !== false) { - $minFilesDeleted += $deleteQuery->rowCount(); - } - } - } - } + if ($deleteQuery !== false) { + $minFilesDeleted += $deleteQuery->rowCount(); + } + } + } + } - if ($this->echoCLI) { - ColorCLI::doEcho( + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - 'Deleted ' . ($minSizeDeleted + $maxSizeDeleted + $minFilesDeleted) . ' collections: ' . PHP_EOL . - $minSizeDeleted . ' smaller than, ' . - $maxSizeDeleted . ' bigger than, ' . - $minFilesDeleted . ' with less files than site/group settings in: ' . + 'Deleted '.($minSizeDeleted + $maxSizeDeleted + $minFilesDeleted).' collections: '.PHP_EOL. + $minSizeDeleted.' smaller than, '. + $maxSizeDeleted.' bigger than, '. + $minFilesDeleted.' with less files than site/group settings in: '. $this->consoleTools->convertTime(time() - $startTime) ), true ); - } - } + } + } - /** - * @param $groupID - * - * @void - */ - protected function initiateTableNames($groupID): void - { - $this->tables = $this->groups->getCBPTableNames($groupID); - } + /** + * @param $groupID + * + * @void + */ + protected function initiateTableNames($groupID): void + { + $this->tables = $this->groups->getCBPTableNames($groupID); + } - /** - * Form fromNamesQuery for creating NZBs - * - * @void - */ - protected function formFromNamesQuery(): void - { - $posters = MultigroupPosters::commaSeparatedList(); - $this->fromNamesQuery = sprintf("AND r.fromname NOT IN('%s')", $posters); - } + /** + * Form fromNamesQuery for creating NZBs. + * + * @void + */ + protected function formFromNamesQuery(): void + { + $posters = MultigroupPosters::commaSeparatedList(); + $this->fromNamesQuery = sprintf("AND r.fromname NOT IN('%s')", $posters); + } - /** - * @param int|string $groupID (optional) - * - * @return array - * @throws \Exception - */ - public function createReleases($groupID): array - { - $startTime = time(); - $this->initiateTableNames($groupID); + /** + * @param int|string $groupID (optional) + * + * @return array + * @throws \Exception + */ + public function createReleases($groupID): array + { + $startTime = time(); + $this->initiateTableNames($groupID); - $categorize = new Categorize(['Settings' => $this->pdo]); - $returnCount = $duplicate = 0; + $categorize = new Categorize(['Settings' => $this->pdo]); + $returnCount = $duplicate = 0; - if ($this->echoCLI) { - ColorCLI::doEcho(ColorCLI::header('Process Releases -> Create releases from complete collections.')); - } + if ($this->echoCLI) { + ColorCLI::doEcho(ColorCLI::header('Process Releases -> Create releases from complete collections.')); + } - $this->pdo->ping(true); + $this->pdo->ping(true); - $collections = $this->pdo->queryDirect( + $collections = $this->pdo->queryDirect( sprintf(' SELECT SQL_NO_CACHE c.*, g.name AS gname FROM %s c @@ -582,33 +579,32 @@ class ProcessReleases AND c.filesize > 0 LIMIT %d', $this->tables['cname'], - (!empty($groupID) ? ' c.groups_id = ' . $groupID . ' AND ' : ' '), + (! empty($groupID) ? ' c.groups_id = '.$groupID.' AND ' : ' '), self::COLLFC_SIZED, $this->releaseCreationLimit ) ); - if ($this->echoCLI && $collections !== false) { - echo ColorCLI::primary($collections->rowCount() . ' Collections ready to be converted to releases.'); - } + if ($this->echoCLI && $collections !== false) { + echo ColorCLI::primary($collections->rowCount().' Collections ready to be converted to releases.'); + } - if ($collections instanceof \Traversable) { - $preDB = new PreDb(['Echo' => $this->echoCLI, 'Settings' => $this->pdo]); + if ($collections instanceof \Traversable) { + $preDB = new PreDb(['Echo' => $this->echoCLI, 'Settings' => $this->pdo]); - foreach ($collections as $collection) { - - $cleanRelName = $this->pdo->escapeString( + foreach ($collections as $collection) { + $cleanRelName = $this->pdo->escapeString( utf8_encode( str_replace(['#', '@', '$', '%', '^', '§', '¨', '©', 'Ö'], '', $collection['subject']) ) ); - $fromName = $this->pdo->escapeString( + $fromName = $this->pdo->escapeString( utf8_encode(trim($collection['fromname'], "'")) ); - // Look for duplicates, duplicates match on releases.name, releases.fromname and releases.size - // A 1% variance in size is considered the same size when the subject and poster are the same - $dupeCheck = $this->pdo->queryOneRow( + // Look for duplicates, duplicates match on releases.name, releases.fromname and releases.size + // A 1% variance in size is considered the same size when the subject and poster are the same + $dupeCheck = $this->pdo->queryOneRow( sprintf(" SELECT SQL_NO_CACHE id FROM releases @@ -622,33 +618,32 @@ class ProcessReleases ) ); - if ($dupeCheck === false) { - - $cleanedName = $this->releaseCleaning->releaseCleaner( + if ($dupeCheck === false) { + $cleanedName = $this->releaseCleaning->releaseCleaner( $collection['subject'], $collection['fromname'], $collection['filesize'], $collection['gname'] ); - if (is_array($cleanedName)) { - $properName = $cleanedName['properlynamed']; - $preID = $cleanerName['predb'] ?? false; - $isReqID = $cleanerName['requestid'] ?? false; - $cleanedName = $cleanedName['cleansubject']; - } else { - $properName = true; - $isReqID = $preID = false; - } + if (is_array($cleanedName)) { + $properName = $cleanedName['properlynamed']; + $preID = $cleanerName['predb'] ?? false; + $isReqID = $cleanerName['requestid'] ?? false; + $cleanedName = $cleanedName['cleansubject']; + } else { + $properName = true; + $isReqID = $preID = false; + } - if ($preID === false && $cleanedName !== '') { - // try to match the cleaned searchname to predb title or filename here - $preMatch = $preDB->matchPre($cleanedName); - if ($preMatch !== false) { - $cleanedName = $preMatch['title']; - $preID = $preMatch['predb_id']; - $properName = true; - } - } + if ($preID === false && $cleanedName !== '') { + // try to match the cleaned searchname to predb title or filename here + $preMatch = $preDB->matchPre($cleanedName); + if ($preMatch !== false) { + $cleanedName = $preMatch['title']; + $preID = $preMatch['predb_id']; + $properName = true; + } + } - $releaseID = $this->releases->insertRelease( + $releaseID = $this->releases->insertRelease( [ 'name' => $cleanRelName, 'searchname' => $this->pdo->escapeString(utf8_encode($cleanedName)), @@ -662,13 +657,13 @@ class ProcessReleases 'isrenamed' => $properName === true ? 1 : 0, 'reqidstatus' => $isReqID === true ? 1 : 0, 'predb_id' => $preID === false ? 0 : $preID, - 'nzbstatus' => NZB::NZB_NONE + 'nzbstatus' => NZB::NZB_NONE, ] ); - if ($releaseID !== false) { - // Update collections table to say we inserted the release. - $this->pdo->queryExec( + if ($releaseID !== false) { + // Update collections table to say we inserted the release. + $this->pdo->queryExec( sprintf(' UPDATE %s SET filecheck = %d, releases_id = %d @@ -680,8 +675,8 @@ class ProcessReleases ) ); - // Add the id of regex that matched the collection and release name to release_regexes table - ReleaseRegexes::query()->insert( + // Add the id of regex that matched the collection and release name to release_regexes table + ReleaseRegexes::query()->insert( [ 'releases_id' => $releaseID, 'collection_regex_id' => $collection['collection_regexes_id'], @@ -689,15 +684,15 @@ class ProcessReleases ] ); - if (preg_match_all('#(\S+):\S+#', $collection['xref'], $matches)) { - foreach ($matches[1] as $grp) { - //check if the group name is in a valid format - $grpTmp = $this->groups->isValidGroup($grp); - if ($grpTmp !== false) { - //check if the group already exists in database - $xrefGrpID = $this->groups->getIDByName($grpTmp); - if ($xrefGrpID === '') { - $xrefGrpID = $this->groups->add( + if (preg_match_all('#(\S+):\S+#', $collection['xref'], $matches)) { + foreach ($matches[1] as $grp) { + //check if the group name is in a valid format + $grpTmp = $this->groups->isValidGroup($grp); + if ($grpTmp !== false) { + //check if the group already exists in database + $xrefGrpID = $this->groups->getIDByName($grpTmp); + if ($xrefGrpID === '') { + $xrefGrpID = $this->groups->add( [ 'name' => $grpTmp, 'description' => 'Added by Release processing', @@ -707,39 +702,39 @@ class ProcessReleases 'active' => 0, 'backfill' => 0, 'minfilestoformrelease' => '', - 'minsizetoformrelease' => '' + 'minsizetoformrelease' => '', ] ); - } + } - $relGroupsChk = ReleasesGroups::query()->where( + $relGroupsChk = ReleasesGroups::query()->where( [ ['releases_id', '=', $releaseID], - ['groups_id', '=', $xrefGrpID] + ['groups_id', '=', $xrefGrpID], ] )->first(); - if ($relGroupsChk === null) { - ReleasesGroups::query()->insert( + if ($relGroupsChk === null) { + ReleasesGroups::query()->insert( [ 'releases_id' => $releaseID, 'groups_id' => $xrefGrpID, ] ); - } - } - } - } + } + } + } + } - $returnCount++; + $returnCount++; - if ($this->echoCLI) { - echo "Added $returnCount releases.\r"; - } - } - } else { - // The release was already in the DB, so delete the collection. - $this->pdo->queryExec( + if ($this->echoCLI) { + echo "Added $returnCount releases.\r"; + } + } + } else { + // The release was already in the DB, so delete the collection. + $this->pdo->queryExec( sprintf(' DELETE c, b, p FROM %s c @@ -752,45 +747,44 @@ class ProcessReleases $this->pdo->escapeString($collection['collectionhash']) ) ); - $duplicate++; - } - } - } + $duplicate++; + } + } + } - if ($this->echoCLI) { - ColorCLI::doEcho( + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - PHP_EOL . - number_format($returnCount) . - ' Releases added and ' . - number_format($duplicate) . - ' duplicate collections deleted in ' . + PHP_EOL. + number_format($returnCount). + ' Releases added and '. + number_format($duplicate). + ' duplicate collections deleted in '. $this->consoleTools->convertTime(time() - $startTime) ), true ); - } + } - return ['added' => $returnCount, 'dupes' => $duplicate]; - } + return ['added' => $returnCount, 'dupes' => $duplicate]; + } - /** - * Create NZB files from complete releases. - * - * @param int|string $groupID (optional) - * - * @return int - * @access public - */ - public function createNZBs($groupID): int - { - $startTime = time(); - $this->formFromNamesQuery(); + /** + * Create NZB files from complete releases. + * + * @param int|string $groupID (optional) + * + * @return int + */ + public function createNZBs($groupID): int + { + $startTime = time(); + $this->formFromNamesQuery(); - if ($this->echoCLI) { - ColorCLI::doEcho(ColorCLI::header('Process Releases -> Create the NZB, delete collections/binaries/parts.')); - } + if ($this->echoCLI) { + ColorCLI::doEcho(ColorCLI::header('Process Releases -> Create the NZB, delete collections/binaries/parts.')); + } - $releases = $this->pdo->queryDirect( + $releases = $this->pdo->queryDirect( sprintf(" SELECT SQL_NO_CACHE CONCAT(COALESCE(cp.title,'') , CASE WHEN cp.title IS NULL THEN '' ELSE ' > ' END , c.title) AS title, @@ -799,63 +793,61 @@ class ProcessReleases INNER JOIN categories c ON r.categories_id = c.id INNER JOIN categories cp ON cp.id = c.parentid WHERE %s nzbstatus = 0 %s", - (!empty($groupID) ? ' r.groups_id = ' . $groupID . ' AND ' : ' '), + (! empty($groupID) ? ' r.groups_id = '.$groupID.' AND ' : ' '), $this->fromNamesQuery ) ); - $nzbCount = 0; + $nzbCount = 0; - if ($releases && $releases->rowCount()) { - $total = $releases->rowCount(); - // Init vars for writing the NZB's. - $this->nzb->initiateForWrite($groupID); - foreach ($releases as $release) { + if ($releases && $releases->rowCount()) { + $total = $releases->rowCount(); + // Init vars for writing the NZB's. + $this->nzb->initiateForWrite($groupID); + foreach ($releases as $release) { + if ($this->nzb->writeNZBforReleaseId($release['id'], $release['guid'], $release['name'], $release['title']) === true) { + $nzbCount++; + if ($this->echoCLI) { + echo ColorCLI::primaryOver("Creating NZBs and deleting Collections:\t".$nzbCount.'/'.$total."\r"); + } + } + } + } - if ($this->nzb->writeNZBforReleaseId($release['id'], $release['guid'], $release['name'], $release['title']) === true) { - $nzbCount++; - if ($this->echoCLI) { - echo ColorCLI::primaryOver("Creating NZBs and deleting Collections:\t" . $nzbCount . '/' . $total . "\r"); - } - } - } - } + $totalTime = (time() - $startTime); - $totalTime = (time() - $startTime); - - if ($this->echoCLI) { - ColorCLI::doEcho( + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - number_format($nzbCount) . ' NZBs created/Collections deleted in ' . - $totalTime . ' seconds.' . PHP_EOL . - 'Total time: ' . ColorCLI::primary($this->consoleTools->convertTime($totalTime)) . PHP_EOL + number_format($nzbCount).' NZBs created/Collections deleted in '. + $totalTime.' seconds.'.PHP_EOL. + 'Total time: '.ColorCLI::primary($this->consoleTools->convertTime($totalTime)).PHP_EOL ) ); - } + } - return $nzbCount; - } + return $nzbCount; + } - /** - * Process RequestID's. - * - * @param int|string $groupID - * @param int $limit - * @param bool $local - * - * @access public - * @void - * @throws \Exception - */ - public function processRequestIDs($groupID = '', $limit = 5000, $local = true): void - { - if ($local === false && (int)Settings::value('..lookup_reqids') === 0) { - return; - } + /** + * Process RequestID's. + * + * @param int|string $groupID + * @param int $limit + * @param bool $local + * + * @void + * @throws \Exception + */ + public function processRequestIDs($groupID = '', $limit = 5000, $local = true): void + { + if ($local === false && (int) Settings::value('..lookup_reqids') === 0) { + return; + } - $startTime = time(); - if ($this->echoCLI) { - ColorCLI::doEcho( + $startTime = time(); + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::header( sprintf( 'Process Releases -> Request ID %s lookup -- limit %s', @@ -864,10 +856,10 @@ class ProcessReleases ) ) ); - } + } - if ($local === true) { - $foundRequestIDs = ( + if ($local === true) { + $foundRequestIDs = ( new RequestIDLocal( [ 'Echo' => $this->echoCLI, @@ -877,8 +869,8 @@ class ProcessReleases ] ) )->lookupRequestIDs(['GroupID' => $groupID, 'limit' => $limit, 'time' => 168]); - } else { - $foundRequestIDs = ( + } else { + $foundRequestIDs = ( new RequestIDWeb( [ 'Echo' => $this->echoCLI, @@ -888,35 +880,34 @@ class ProcessReleases ] ) )->lookupRequestIDs(['GroupID' => $groupID, 'limit' => $limit, 'time' => 168]); - } - if ($this->echoCLI) { - ColorCLI::doEcho( + } + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - number_format($foundRequestIDs) . - ' releases updated in ' . + number_format($foundRequestIDs). + ' releases updated in '. $this->consoleTools->convertTime(time() - $startTime) ), true ); - } - } + } + } - /** - * Categorize releases. - * - * @param int $categorize - * @param int|string $groupID (optional) - * - * @void - * @access public - * @throws \Exception - */ - public function categorizeReleases($categorize, $groupID = ''): void - { - $startTime = time(); - if ($this->echoCLI) { - echo ColorCLI::header('Process Releases -> Categorize releases.'); - } - switch ((int)$categorize) { + /** + * Categorize releases. + * + * @param int $categorize + * @param int|string $groupID (optional) + * + * @void + * @throws \Exception + */ + public function categorizeReleases($categorize, $groupID = ''): void + { + $startTime = time(); + if ($this->echoCLI) { + echo ColorCLI::header('Process Releases -> Categorize releases.'); + } + switch ((int) $categorize) { case 2: $type = 'searchname'; break; @@ -926,69 +917,67 @@ class ProcessReleases $type = 'name'; break; } - $this->categorizeRelease( + $this->categorizeRelease( $type, - (!empty($groupID) - ? 'WHERE categories_id = ' . Category::OTHER_MISC . ' AND iscategorized = 0 AND groups_id = ' . $groupID - : 'WHERE categories_id = ' . Category::OTHER_MISC . ' AND iscategorized = 0') + (! empty($groupID) + ? 'WHERE categories_id = '.Category::OTHER_MISC.' AND iscategorized = 0 AND groups_id = '.$groupID + : 'WHERE categories_id = '.Category::OTHER_MISC.' AND iscategorized = 0') ); - if ($this->echoCLI) { - ColorCLI::doEcho(ColorCLI::primary($this->consoleTools->convertTime(time() - $startTime)), true); - } - } + if ($this->echoCLI) { + ColorCLI::doEcho(ColorCLI::primary($this->consoleTools->convertTime(time() - $startTime)), true); + } + } - /** - * Post-process releases. - * - * @param int $postProcess - * @param NNTP $nntp - * - * @void - * @access public - * @throws \Exception - */ - public function postProcessReleases($postProcess, &$nntp): void - { - if ((int)$postProcess === 1) { - (new PostProcess(['Echo' => $this->echoCLI, 'Settings' => $this->pdo, 'Groups' => $this->groups]))->processAll($nntp); - } else { - if ($this->echoCLI) { - ColorCLI::doEcho( + /** + * Post-process releases. + * + * @param int $postProcess + * @param NNTP $nntp + * + * @void + * @throws \Exception + */ + public function postProcessReleases($postProcess, &$nntp): void + { + if ((int) $postProcess === 1) { + (new PostProcess(['Echo' => $this->echoCLI, 'Settings' => $this->pdo, 'Groups' => $this->groups]))->processAll($nntp); + } else { + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::info( - "\nPost-processing is not running inside the Process Releases class.\n" . + "\nPost-processing is not running inside the Process Releases class.\n". 'If you are using tmux or screen they might have their own scripts running Post-processing.' ) ); - } - } - } + } + } + } - /** - * @param $groupID - * - * @throws \Exception - */ - public function deleteCollections($groupID): void - { - $startTime = time(); - $this->initiateTableNames($groupID); + /** + * @param $groupID + * + * @throws \Exception + */ + public function deleteCollections($groupID): void + { + $startTime = time(); + $this->initiateTableNames($groupID); - $deletedCount = 0; + $deletedCount = 0; - // CBP older than retention. - if ($this->echoCLI) { - echo ( - ColorCLI::header('Process Releases -> Delete finished collections.' . PHP_EOL) . + // CBP older than retention. + if ($this->echoCLI) { + echo + ColorCLI::header('Process Releases -> Delete finished collections.'.PHP_EOL). ColorCLI::primary(sprintf( 'Deleting collections/binaries/parts older than %d hours.', Settings::value('..partretentionhours') - )) - ); - } + )); + } - $deleted = 0; - $deleteQuery = $this->pdo->queryExec( + $deleted = 0; + $deleteQuery = $this->pdo->queryExec( sprintf(' DELETE c, b, p FROM %s c @@ -1002,33 +991,32 @@ class ProcessReleases ) ); - if ($deleteQuery !== false) { - $deleted = $deleteQuery->rowCount(); - $deletedCount += $deleted; - } + if ($deleteQuery !== false) { + $deleted = $deleteQuery->rowCount(); + $deletedCount += $deleted; + } - $firstQuery = $fourthQuery = time(); + $firstQuery = $fourthQuery = time(); - if ($this->echoCLI) { - echo ColorCLI::primary( - 'Finished deleting ' . $deleted . ' old collections/binaries/parts in ' . - ($firstQuery - $startTime) . ' seconds.' . PHP_EOL + if ($this->echoCLI) { + echo ColorCLI::primary( + 'Finished deleting '.$deleted.' old collections/binaries/parts in '. + ($firstQuery - $startTime).' seconds.'.PHP_EOL ); - } + } - // Cleanup orphaned collections, binaries and parts - // this really shouldn't happen, but just incase - so we only run 1/200 of the time - if (random_int(0, 200) <= 1) { - // CBP collection orphaned with no binaries or parts. - if ($this->echoCLI) { - echo ( - ColorCLI::header('Process Releases -> Remove CBP orphans.' . PHP_EOL) . - ColorCLI::primary('Deleting orphaned collections.') - ); - } + // Cleanup orphaned collections, binaries and parts + // this really shouldn't happen, but just incase - so we only run 1/200 of the time + if (random_int(0, 200) <= 1) { + // CBP collection orphaned with no binaries or parts. + if ($this->echoCLI) { + echo + ColorCLI::header('Process Releases -> Remove CBP orphans.'.PHP_EOL). + ColorCLI::primary('Deleting orphaned collections.'); + } - $deleted = 0; - $deleteQuery = $this->pdo->queryExec( + $deleted = 0; + $deleteQuery = $this->pdo->queryExec( sprintf(' DELETE c, b, p FROM %s c @@ -1041,28 +1029,28 @@ class ProcessReleases ) ); - if ($deleteQuery !== false) { - $deleted = $deleteQuery->rowCount(); - $deletedCount += $deleted; - } + if ($deleteQuery !== false) { + $deleted = $deleteQuery->rowCount(); + $deletedCount += $deleted; + } - $secondQuery = time(); + $secondQuery = time(); - if ($this->echoCLI) { - echo ColorCLI::primary( - 'Finished deleting ' . $deleted . ' orphaned collections in ' . - ($secondQuery - $firstQuery) . ' seconds.' . PHP_EOL + if ($this->echoCLI) { + echo ColorCLI::primary( + 'Finished deleting '.$deleted.' orphaned collections in '. + ($secondQuery - $firstQuery).' seconds.'.PHP_EOL ); - } + } - // orphaned binaries - binaries with no parts or binaries with no collection - // Don't delete currently inserting binaries by checking the max id. - if ($this->echoCLI) { - echo ColorCLI::primary('Deleting orphaned binaries/parts with no collection.'); - } + // orphaned binaries - binaries with no parts or binaries with no collection + // Don't delete currently inserting binaries by checking the max id. + if ($this->echoCLI) { + echo ColorCLI::primary('Deleting orphaned binaries/parts with no collection.'); + } - $deleted = 0; - $deleteQuery = $this->pdo->queryExec( + $deleted = 0; + $deleteQuery = $this->pdo->queryExec( sprintf( 'DELETE b, p FROM %s b LEFT JOIN %s p ON b.id = p.binaries_id @@ -1076,27 +1064,27 @@ class ProcessReleases ) ); - if ($deleteQuery !== false) { - $deleted = $deleteQuery->rowCount(); - $deletedCount += $deleted; - } + if ($deleteQuery !== false) { + $deleted = $deleteQuery->rowCount(); + $deletedCount += $deleted; + } - $thirdQuery = time(); + $thirdQuery = time(); - if ($this->echoCLI) { - echo ColorCLI::primary( - 'Finished deleting ' . $deleted . ' binaries with no collections or parts in ' . - ($thirdQuery - $secondQuery) . ' seconds.' + if ($this->echoCLI) { + echo ColorCLI::primary( + 'Finished deleting '.$deleted.' binaries with no collections or parts in '. + ($thirdQuery - $secondQuery).' seconds.' ); - } + } - // orphaned parts - parts with no binary - // Don't delete currently inserting parts by checking the max id. - if ($this->echoCLI) { - echo ColorCLI::primary('Deleting orphaned parts with no binaries.'); - } - $deleted = 0; - $deleteQuery = $this->pdo->queryExec( + // orphaned parts - parts with no binary + // Don't delete currently inserting parts by checking the max id. + if ($this->echoCLI) { + echo ColorCLI::primary('Deleting orphaned parts with no binaries.'); + } + $deleted = 0; + $deleteQuery = $this->pdo->queryExec( sprintf(' DELETE p FROM %s p @@ -1108,30 +1096,30 @@ class ProcessReleases $this->maxQueryFormulator($this->tables['bname'], 20000) ) ); - if ($deleteQuery !== false) { - $deleted = $deleteQuery->rowCount(); - $deletedCount += $deleted; - } + if ($deleteQuery !== false) { + $deleted = $deleteQuery->rowCount(); + $deletedCount += $deleted; + } - $fourthQuery = time(); + $fourthQuery = time(); - if ($this->echoCLI) { - echo ColorCLI::primary( - 'Finished deleting ' . $deleted . ' parts with no binaries in ' . - ($fourthQuery - $thirdQuery) . ' seconds.' . PHP_EOL + if ($this->echoCLI) { + echo ColorCLI::primary( + 'Finished deleting '.$deleted.' parts with no binaries in '. + ($fourthQuery - $thirdQuery).' seconds.'.PHP_EOL ); - } - } // done cleaning up Binaries/Parts orphans + } + } // done cleaning up Binaries/Parts orphans - if ($this->echoCLI) { - echo ColorCLI::primary( + if ($this->echoCLI) { + echo ColorCLI::primary( 'Deleting collections that were missed after NZB creation.' ); - } + } - $deleted = 0; - // Collections that were missing on NZB creation. - $collections = $this->pdo->queryDirect( + $deleted = 0; + // Collections that were missing on NZB creation. + $collections = $this->pdo->queryDirect( sprintf(' SELECT SQL_NO_CACHE c.id FROM %s c @@ -1141,10 +1129,10 @@ class ProcessReleases ) ); - if ($collections instanceof \Traversable) { - foreach ($collections as $collection) { - $deleted++; - $this->pdo->queryExec( + if ($collections instanceof \Traversable) { + foreach ($collections as $collection) { + $deleted++; + $this->pdo->queryExec( sprintf(' DELETE c, b, p FROM %s c @@ -1157,51 +1145,50 @@ class ProcessReleases $collection['id'] ) ); - } - $deletedCount += $deleted; - } + } + $deletedCount += $deleted; + } - if ($this->echoCLI) { - ColorCLI::doEcho( + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - 'Finished deleting ' . $deleted . ' collections missed after NZB creation in ' . - (time() - $fourthQuery) . ' seconds.' . PHP_EOL . - 'Removed ' . - number_format($deletedCount) . - ' parts/binaries/collection rows in ' . - $this->consoleTools->convertTime($fourthQuery - $startTime) . PHP_EOL + 'Finished deleting '.$deleted.' collections missed after NZB creation in '. + (time() - $fourthQuery).' seconds.'.PHP_EOL. + 'Removed '. + number_format($deletedCount). + ' parts/binaries/collection rows in '. + $this->consoleTools->convertTime($fourthQuery - $startTime).PHP_EOL ) ); - } - } + } + } - /** - * Delete unwanted releases based on admin settings. - * This deletes releases based on group. - * - * @param int|string $groupID (optional) - * - * @void - * @access public - * @throws \Exception - */ - public function deletedReleasesByGroup($groupID = ''): void - { - $startTime = time(); - $minSizeDeleted = $maxSizeDeleted = $minFilesDeleted = 0; + /** + * Delete unwanted releases based on admin settings. + * This deletes releases based on group. + * + * @param int|string $groupID (optional) + * + * @void + * @throws \Exception + */ + public function deletedReleasesByGroup($groupID = ''): void + { + $startTime = time(); + $minSizeDeleted = $maxSizeDeleted = $minFilesDeleted = 0; - if ($this->echoCLI) { - echo ColorCLI::header('Process Releases -> Delete releases smaller/larger than minimum size/file count from group/site setting.'); - } + if ($this->echoCLI) { + echo ColorCLI::header('Process Releases -> Delete releases smaller/larger than minimum size/file count from group/site setting.'); + } - $groupID === '' ? $groupIDs = $this->groups->getActiveIDs() : $groupIDs = [['id' => $groupID]]; + $groupID === '' ? $groupIDs = $this->groups->getActiveIDs() : $groupIDs = [['id' => $groupID]]; - $maxSizeSetting = Settings::value('.release.maxsizetoformrelease'); - $minSizeSetting = Settings::value('.release.minsizetoformrelease'); - $minFilesSetting = Settings::value('.release.minfilestoformrelease'); + $maxSizeSetting = Settings::value('.release.maxsizetoformrelease'); + $minSizeSetting = Settings::value('.release.minsizetoformrelease'); + $minFilesSetting = Settings::value('.release.minfilestoformrelease'); - foreach ($groupIDs as $grpID) { - $releases = $this->pdo->queryDirect( + foreach ($groupIDs as $grpID) { + $releases = $this->pdo->queryDirect( sprintf(' SELECT SQL_NO_CACHE r.guid, r.id FROM releases r @@ -1214,15 +1201,15 @@ class ProcessReleases $minSizeSetting ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $minSizeDeleted++; - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $minSizeDeleted++; + } + } - if ($maxSizeSetting > 0) { - $releases = $this->pdo->queryDirect( + if ($maxSizeSetting > 0) { + $releases = $this->pdo->queryDirect( sprintf(' SELECT SQL_NO_CACHE id, guid FROM releases @@ -1232,15 +1219,15 @@ class ProcessReleases $maxSizeSetting ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $maxSizeDeleted++; - } - } - } - if ($minFilesSetting > 0) { - $releases = $this->pdo->queryDirect( + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $maxSizeDeleted++; + } + } + } + if ($minFilesSetting > 0) { + $releases = $this->pdo->queryDirect( sprintf(' SELECT SQL_NO_CACHE r.id, r.guid FROM releases r @@ -1253,143 +1240,142 @@ class ProcessReleases $minFilesSetting ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $minFilesDeleted++; - } - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $minFilesDeleted++; + } + } + } + } - if ($this->echoCLI) { - ColorCLI::doEcho( + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - 'Deleted ' . ($minSizeDeleted + $maxSizeDeleted + $minFilesDeleted) . - ' releases: ' . PHP_EOL . - $minSizeDeleted . ' smaller than, ' . $maxSizeDeleted . ' bigger than, ' . $minFilesDeleted . - ' with less files than site/groups setting in: ' . + 'Deleted '.($minSizeDeleted + $maxSizeDeleted + $minFilesDeleted). + ' releases: '.PHP_EOL. + $minSizeDeleted.' smaller than, '.$maxSizeDeleted.' bigger than, '.$minFilesDeleted. + ' with less files than site/groups setting in: '. $this->consoleTools->convertTime(time() - $startTime) ), true ); - } - } + } + } - /** - * Delete releases using admin settings. - * This deletes releases, regardless of group. - * - * @void - * @access public - * @throws \Exception - */ - public function deleteReleases(): void - { - $startTime = time(); - $category = new Category(['Settings' => $this->pdo]); - $genres = new Genres(['Settings' => $this->pdo]); - $passwordDeleted = $duplicateDeleted = $retentionDeleted = $completionDeleted = $disabledCategoryDeleted = 0; - $disabledGenreDeleted = $miscRetentionDeleted = $miscHashedDeleted = $categoryMinSizeDeleted = 0; + /** + * Delete releases using admin settings. + * This deletes releases, regardless of group. + * + * @void + * @throws \Exception + */ + public function deleteReleases(): void + { + $startTime = time(); + $category = new Category(['Settings' => $this->pdo]); + $genres = new Genres(['Settings' => $this->pdo]); + $passwordDeleted = $duplicateDeleted = $retentionDeleted = $completionDeleted = $disabledCategoryDeleted = 0; + $disabledGenreDeleted = $miscRetentionDeleted = $miscHashedDeleted = $categoryMinSizeDeleted = 0; - // Delete old releases and finished collections. - if ($this->echoCLI) { - ColorCLI::doEcho(ColorCLI::header('Process Releases -> Delete old releases and passworded releases.')); - } + // Delete old releases and finished collections. + if ($this->echoCLI) { + ColorCLI::doEcho(ColorCLI::header('Process Releases -> Delete old releases and passworded releases.')); + } - // Releases past retention. - if ((int)Settings::value('..releaseretentiondays') !== 0) { - $releases = $this->pdo->queryDirect( + // Releases past retention. + if ((int) Settings::value('..releaseretentiondays') !== 0) { + $releases = $this->pdo->queryDirect( sprintf( 'SELECT SQL_NO_CACHE id, guid FROM releases WHERE postdate < (NOW() - INTERVAL %d DAY)', - (int)Settings::value('..releaseretentiondays') + (int) Settings::value('..releaseretentiondays') ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $retentionDeleted++; - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $retentionDeleted++; + } + } + } - // Passworded releases. - if ((int)Settings::value('..deletepasswordedrelease') === 1) { - $releases = $this->pdo->queryDirect( + // Passworded releases. + if ((int) Settings::value('..deletepasswordedrelease') === 1) { + $releases = $this->pdo->queryDirect( sprintf( 'SELECT SQL_NO_CACHE id, guid FROM releases WHERE passwordstatus = %d', Releases::PASSWD_RAR ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $passwordDeleted++; - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $passwordDeleted++; + } + } + } - // Possibly passworded releases. - if ((int)Settings::value('..deletepossiblerelease') === 1) { - $releases = $this->pdo->queryDirect( + // Possibly passworded releases. + if ((int) Settings::value('..deletepossiblerelease') === 1) { + $releases = $this->pdo->queryDirect( sprintf( 'SELECT SQL_NO_CACHE id, guid FROM releases WHERE passwordstatus = %d', Releases::PASSWD_POTENTIAL ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $passwordDeleted++; - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $passwordDeleted++; + } + } + } - if ((int)$this->crossPostTime !== 0) { - // Crossposted releases. - $releases = $this->pdo->queryDirect( + if ((int) $this->crossPostTime !== 0) { + // Crossposted releases. + $releases = $this->pdo->queryDirect( sprintf( 'SELECT SQL_NO_CACHE id, guid FROM releases WHERE adddate > (NOW() - INTERVAL %d HOUR) GROUP BY name HAVING COUNT(name) > 1', $this->crossPostTime ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $duplicateDeleted++; - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $duplicateDeleted++; + } + } + } - if ($this->completion > 0) { - $releases = $this->pdo->queryDirect( + if ($this->completion > 0) { + $releases = $this->pdo->queryDirect( sprintf('SELECT SQL_NO_CACHE id, guid FROM releases WHERE completion < %d AND completion > 0', $this->completion) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $completionDeleted++; - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $completionDeleted++; + } + } + } - // Disabled categories. - $disabledCategories = $category->getDisabledIDs(); - if (count($disabledCategories) > 0) { - foreach ($disabledCategories as $disabledCategory) { - $releases = $this->pdo->queryDirect( - sprintf('SELECT SQL_NO_CACHE id, guid FROM releases WHERE categories_id = %d', (int)$disabledCategory['id']) + // Disabled categories. + $disabledCategories = $category->getDisabledIDs(); + if (count($disabledCategories) > 0) { + foreach ($disabledCategories as $disabledCategory) { + $releases = $this->pdo->queryDirect( + sprintf('SELECT SQL_NO_CACHE id, guid FROM releases WHERE categories_id = %d', (int) $disabledCategory['id']) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $disabledCategoryDeleted++; - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - } - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $disabledCategoryDeleted++; + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + } + } + } + } - // Delete smaller than category minimum sizes. - $categories = $this->pdo->queryDirect(' + // Delete smaller than category minimum sizes. + $categories = $this->pdo->queryDirect(' SELECT SQL_NO_CACHE c.id AS id, CASE WHEN c.minsizetoformrelease = 0 THEN cp.minsizetoformrelease ELSE c.minsizetoformrelease END AS minsize FROM categories c @@ -1397,35 +1383,35 @@ class ProcessReleases WHERE c.parentid IS NOT NULL' ); - if ($categories instanceof \Traversable) { - foreach ($categories as $category) { - if ((int)$category['minsize'] > 0) { - $releases = $this->pdo->queryDirect( + if ($categories instanceof \Traversable) { + foreach ($categories as $category) { + if ((int) $category['minsize'] > 0) { + $releases = $this->pdo->queryDirect( sprintf(' SELECT SQL_NO_CACHE r.id, r.guid FROM releases r WHERE r.categories_id = %d AND r.size < %d LIMIT 1000', - (int)$category['id'], - (int)$category['minsize'] + (int) $category['id'], + (int) $category['minsize'] ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $categoryMinSizeDeleted++; - } - } - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $categoryMinSizeDeleted++; + } + } + } + } + } - // Disabled music genres. - $genrelist = $genres->getDisabledIDs(); - if (count($genrelist) > 0) { - foreach ($genrelist as $genre) { - $releases = $this->pdo->queryDirect( + // Disabled music genres. + $genrelist = $genres->getDisabledIDs(); + if (count($genrelist) > 0) { + foreach ($genrelist as $genre) { + $releases = $this->pdo->queryDirect( sprintf(' SELECT SQL_NO_CACHE id, guid FROM releases @@ -1435,137 +1421,135 @@ class ProcessReleases FROM musicinfo WHERE musicinfo.genre_id = %d ) mi ON musicinfo_id = mid', - (int)$genre['id'] + (int) $genre['id'] ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $disabledGenreDeleted++; - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - } - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $disabledGenreDeleted++; + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + } + } + } + } - // Misc other. - if (Settings::value('..miscotherretentionhours') > 0) { - $releases = $this->pdo->queryDirect( + // Misc other. + if (Settings::value('..miscotherretentionhours') > 0) { + $releases = $this->pdo->queryDirect( sprintf(' SELECT SQL_NO_CACHE id, guid FROM releases WHERE categories_id = %d AND adddate <= NOW() - INTERVAL %d HOUR', Category::OTHER_MISC, - (int)Settings::value('..miscotherretentionhours') + (int) Settings::value('..miscotherretentionhours') ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $miscRetentionDeleted++; - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $miscRetentionDeleted++; + } + } + } - // Misc hashed. - if ((int)Settings::value('..mischashedretentionhours') > 0) { - $releases = $this->pdo->queryDirect( + // Misc hashed. + if ((int) Settings::value('..mischashedretentionhours') > 0) { + $releases = $this->pdo->queryDirect( sprintf(' SELECT SQL_NO_CACHE id, guid FROM releases WHERE categories_id = %d AND adddate <= NOW() - INTERVAL %d HOUR', Category::OTHER_HASHED, - (int)Settings::value('..mischashedretentionhours') + (int) Settings::value('..mischashedretentionhours') ) ); - if ($releases instanceof \Traversable) { - foreach ($releases as $release) { - $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); - $miscHashedDeleted++; - } - } - } + if ($releases instanceof \Traversable) { + foreach ($releases as $release) { + $this->releases->deleteSingle(['g' => $release['guid'], 'i' => $release['id']], $this->nzb, $this->releaseImage); + $miscHashedDeleted++; + } + } + } - if ($this->echoCLI) { - ColorCLI::doEcho( + if ($this->echoCLI) { + ColorCLI::doEcho( ColorCLI::primary( - 'Removed releases: ' . - number_format($retentionDeleted) . - ' past retention, ' . - number_format($passwordDeleted) . - ' passworded, ' . - number_format($duplicateDeleted) . - ' crossposted, ' . - number_format($disabledCategoryDeleted) . - ' from disabled categories, ' . - number_format($categoryMinSizeDeleted) . - ' smaller than category settings, ' . - number_format($disabledGenreDeleted) . - ' from disabled music genres, ' . - number_format($miscRetentionDeleted) . - ' from misc->other' . - number_format($miscHashedDeleted) . - ' from misc->hashed' . + 'Removed releases: '. + number_format($retentionDeleted). + ' past retention, '. + number_format($passwordDeleted). + ' passworded, '. + number_format($duplicateDeleted). + ' crossposted, '. + number_format($disabledCategoryDeleted). + ' from disabled categories, '. + number_format($categoryMinSizeDeleted). + ' smaller than category settings, '. + number_format($disabledGenreDeleted). + ' from disabled music genres, '. + number_format($miscRetentionDeleted). + ' from misc->other'. + number_format($miscHashedDeleted). + ' from misc->hashed'. ($this->completion > 0 - ? ', ' . number_format($completionDeleted) . ' under ' . $this->completion . '% completion.' + ? ', '.number_format($completionDeleted).' under '.$this->completion.'% completion.' : '.' ) ) ); - $totalDeleted = ( + $totalDeleted = ( $retentionDeleted + $passwordDeleted + $duplicateDeleted + $disabledCategoryDeleted + $disabledGenreDeleted + $miscRetentionDeleted + $miscHashedDeleted + $completionDeleted + $categoryMinSizeDeleted ); - if ($totalDeleted > 0) { - ColorCLI::doEcho( + if ($totalDeleted > 0) { + ColorCLI::doEcho( ColorCLI::primary( - 'Removed ' . number_format($totalDeleted) . ' releases in ' . + 'Removed '.number_format($totalDeleted).' releases in '. $this->consoleTools->convertTime(time() - $startTime) ) ); - } - } - } + } + } + } - /** - * Formulate part of a query to prevent deletion of currently inserting parts / binaries / collections. - * - * @param string $groupName - * @param int $difference - * - * @return string - * @access private - */ - private function maxQueryFormulator($groupName, $difference): string - { - $maxID = $this->pdo->queryOneRow( + /** + * Formulate part of a query to prevent deletion of currently inserting parts / binaries / collections. + * + * @param string $groupName + * @param int $difference + * + * @return string + */ + private function maxQueryFormulator($groupName, $difference): string + { + $maxID = $this->pdo->queryOneRow( sprintf(' SELECT IFNULL(MAX(id),0) AS max FROM %s', $groupName ) ); - return empty($maxID['max']) || $maxID['max'] < $difference ? 0 : $maxID['max'] - $difference; - } - /** - * Look if we have all the files in a collection (which have the file count in the subject). - * Set file check to complete. - * This means the the binary table has the same count as the file count in the subject, but - * the collection might not be complete yet since we might not have all the articles in the parts table. - * - * @param string $where - * - * @void - * @access private - */ - private function collectionFileCheckStage1(&$where): void - { + return empty($maxID['max']) || $maxID['max'] < $difference ? 0 : $maxID['max'] - $difference; + } - $this->pdo->queryExec( + /** + * Look if we have all the files in a collection (which have the file count in the subject). + * Set file check to complete. + * This means the the binary table has the same count as the file count in the subject, but + * the collection might not be complete yet since we might not have all the articles in the parts table. + * + * @param string $where + * + * @void + */ + private function collectionFileCheckStage1(&$where): void + { + $this->pdo->queryExec( sprintf(' UPDATE %s c INNER JOIN @@ -1587,24 +1571,23 @@ class ProcessReleases self::COLLFC_COMPCOLL ) ); - } + } - /** - * The first query sets filecheck to COLLFC_ZEROPART if there's a file that starts with 0 (ex. [00/100]). - * The second query sets filecheck to COLLFC_TEMPCOMP on everything left over, so anything that starts with 1 (ex. [01/100]). - * - * This is done because some collections start at 0 and some at 1, so if you were to assume the collection is complete - * at 0 then you would never get a complete collection if it starts with 1 and if it starts, you can end up creating - * a incomplete collection, since you assumed it was complete. - * - * @param string $where - * - * @void - * @access private - */ - private function collectionFileCheckStage2(&$where): void - { - $this->pdo->queryExec( + /** + * The first query sets filecheck to COLLFC_ZEROPART if there's a file that starts with 0 (ex. [00/100]). + * The second query sets filecheck to COLLFC_TEMPCOMP on everything left over, so anything that starts with 1 (ex. [01/100]). + * + * This is done because some collections start at 0 and some at 1, so if you were to assume the collection is complete + * at 0 then you would never get a complete collection if it starts with 1 and if it starts, you can end up creating + * a incomplete collection, since you assumed it was complete. + * + * @param string $where + * + * @void + */ + private function collectionFileCheckStage2(&$where): void + { + $this->pdo->queryExec( sprintf(' UPDATE %s c INNER JOIN @@ -1626,7 +1609,7 @@ class ProcessReleases self::COLLFC_ZEROPART ) ); - $this->pdo->queryExec( + $this->pdo->queryExec( sprintf(' UPDATE %s c SET filecheck = %d @@ -1637,21 +1620,19 @@ class ProcessReleases $where ) ); - } + } - /** - * Check if the files (binaries table) in a complete collection has all the parts. - * If we have all the parts, set binaries table partcheck to FILE_COMPLETE. - * - * @param string $where - * - * @void - * @access private - */ - private function collectionFileCheckStage3($where): void - { - - $this->pdo->queryExec( + /** + * Check if the files (binaries table) in a complete collection has all the parts. + * If we have all the parts, set binaries table partcheck to FILE_COMPLETE. + * + * @param string $where + * + * @void + */ + private function collectionFileCheckStage3($where): void + { + $this->pdo->queryExec( sprintf(' UPDATE %s b INNER JOIN @@ -1674,7 +1655,7 @@ class ProcessReleases self::FILE_COMPLETE ) ); - $this->pdo->queryExec( + $this->pdo->queryExec( sprintf(' UPDATE %s b INNER JOIN @@ -1697,22 +1678,20 @@ class ProcessReleases self::FILE_COMPLETE ) ); - } + } - /** - * Check if all files (binaries table) for a collection are complete (if they all have the "parts"). - * Set collections filecheck column to COLLFC_COMPPART. - * This means the collection is complete. - * - * @param string $where - * - * @void - * @access private - */ - private function collectionFileCheckStage4(&$where): void - { - - $this->pdo->queryExec( + /** + * Check if all files (binaries table) for a collection are complete (if they all have the "parts"). + * Set collections filecheck column to COLLFC_COMPPART. + * This means the collection is complete. + * + * @param string $where + * + * @void + */ + private function collectionFileCheckStage4(&$where): void + { + $this->pdo->queryExec( sprintf(' UPDATE %s c INNER JOIN (SELECT c.id FROM %s c @@ -1729,21 +1708,19 @@ class ProcessReleases self::COLLFC_COMPPART ) ); - } + } - /** - * If not all files (binaries table) had their parts on the previous stage, - * reset the collection filecheck column to COLLFC_COMPCOLL so we reprocess them next time. - * - * @param string $where - * - * @void - * @access private - */ - private function collectionFileCheckStage5(&$where): void - { - - $this->pdo->queryExec( + /** + * If not all files (binaries table) had their parts on the previous stage, + * reset the collection filecheck column to COLLFC_COMPCOLL so we reprocess them next time. + * + * @param string $where + * + * @void + */ + private function collectionFileCheckStage5(&$where): void + { + $this->pdo->queryExec( sprintf(' UPDATE %s c SET filecheck = %d @@ -1755,21 +1732,19 @@ class ProcessReleases $where ) ); - } + } - /** - * If a collection did not have the file count (ie: [00/12]) or the collection is incomplete after - * $this->collectionDelayTime hours, set the collection to complete to create it into a release/nzb. - * - * @param string $where - * - * @void - * @access private - */ - private function collectionFileCheckStage6(&$where): void - { - - $this->pdo->queryExec( + /** + * If a collection did not have the file count (ie: [00/12]) or the collection is incomplete after + * $this->collectionDelayTime hours, set the collection to complete to create it into a release/nzb. + * + * @param string $where + * + * @void + */ + private function collectionFileCheckStage6(&$where): void + { + $this->pdo->queryExec( sprintf(" UPDATE %s c SET filecheck = %d, totalfiles = (SELECT COUNT(b.id) FROM %s b WHERE b.collections_id = c.id) WHERE c.dateadded < NOW() - INTERVAL '%d' HOUR @@ -1783,22 +1758,21 @@ class ProcessReleases $where ) ); - } + } - /** - * If a collection has been stuck for $this->collectionTimeout hours, delete it, it's bad. - * - * @param string $where - * - * @void - * @access private - * @throws \Exception - */ - private function processStuckCollections($where): void - { - $lastRun = Settings::value('indexer.processing.last_run_time'); + /** + * If a collection has been stuck for $this->collectionTimeout hours, delete it, it's bad. + * + * @param string $where + * + * @void + * @throws \Exception + */ + private function processStuckCollections($where): void + { + $lastRun = Settings::value('indexer.processing.last_run_time'); - $obj = $this->pdo->queryExec( + $obj = $this->pdo->queryExec( sprintf(" DELETE c, b, p FROM %s c LEFT JOIN %s b ON (c.id=b.collections_id) @@ -1814,10 +1788,10 @@ class ProcessReleases $where ) ); - if ($this->echoCLI && is_object($obj) && $obj->rowCount()) { - ColorCLI::doEcho( - ColorCLI::primary('Deleted ' . $obj->rowCount() . ' broken/stuck collections.') + if ($this->echoCLI && is_object($obj) && $obj->rowCount()) { + ColorCLI::doEcho( + ColorCLI::primary('Deleted '.$obj->rowCount().' broken/stuck collections.') ); - } - } + } + } } diff --git a/nntmux/processing/ProcessReleasesMultiGroup.php b/nntmux/processing/ProcessReleasesMultiGroup.php index 310067caf..9a8890c71 100644 --- a/nntmux/processing/ProcessReleasesMultiGroup.php +++ b/nntmux/processing/ProcessReleasesMultiGroup.php @@ -2,77 +2,75 @@ namespace nntmux\processing; -use App\Models\MultigroupPosters; use nntmux\NZBMultiGroup; -use nntmux\utility\Utility; - +use App\Models\MultigroupPosters; class ProcessReleasesMultiGroup extends ProcessReleases { - /** - * @var NZBMultiGroup - */ - public $nzb; + /** + * @var NZBMultiGroup + */ + public $nzb; - /** - * ProcessReleasesMultiGroup constructor. - * - * @param array $options - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - parent::__construct($options); - $this->nzb = new NZBMultiGroup($this->pdo); - } + /** + * ProcessReleasesMultiGroup constructor. + * + * @param array $options + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + parent::__construct($options); + $this->nzb = new NZBMultiGroup($this->pdo); + } - /** - * Form fromNamesQuery for creating NZBs - * - * @void - */ - protected function formFromNamesQuery(): void - { - $this->fromNamesQuery = ''; - } + /** + * Form fromNamesQuery for creating NZBs. + * + * @void + */ + protected function formFromNamesQuery(): void + { + $this->fromNamesQuery = ''; + } - /** - * @param $fromName - * - * @return bool - */ - public static function isMultiGroup($fromName): bool - { - $poster = MultigroupPosters::query()->where('poster', '=', $fromName)->first(); - return (empty($poster) ? false : true); - } + /** + * @param $fromName + * + * @return bool + */ + public static function isMultiGroup($fromName): bool + { + $poster = MultigroupPosters::query()->where('poster', '=', $fromName)->first(); - /** - * This method exists to prevent the parent one from over-writing the $this->tables property. - * - * @param int $groupID Unused with mgr - * - * @return void - */ - protected function initiateTableNames($groupID): void - { - $this->tables = self::tableNames(); - } + return empty($poster) ? false : true; + } - /** - * Returns MGR table names - * - * @return array - */ - public static function tableNames(): array - { - return [ + /** + * This method exists to prevent the parent one from over-writing the $this->tables property. + * + * @param int $groupID Unused with mgr + * + * @return void + */ + protected function initiateTableNames($groupID): void + { + $this->tables = self::tableNames(); + } + + /** + * Returns MGR table names. + * + * @return array + */ + public static function tableNames(): array + { + return [ 'cname' => 'multigroup_collections', 'bname' => 'multigroup_binaries', 'pname' => 'multigroup_parts', 'prname' => 'multigroup_missed_parts', ]; - } + } } - diff --git a/nntmux/processing/Videos.php b/nntmux/processing/Videos.php index 24d81c391..79f678638 100755 --- a/nntmux/processing/Videos.php +++ b/nntmux/processing/Videos.php @@ -18,251 +18,251 @@ * @author niel * @copyright 2015 nZEDb */ + namespace nntmux\processing; use nntmux\db\DB; /** * Parent class for TV/Film and any similar classes to inherit from. - * - * @package nntmux\processing */ abstract class Videos { - // Video Type Identifiers - const TYPE_TV = 0; // Type of video is a TV Programme/Show - const TYPE_FILM = 1; // Type of video is a Film/Movie - const TYPE_ANIME = 2; // Type of video is a Anime + // Video Type Identifiers + const TYPE_TV = 0; // Type of video is a TV Programme/Show + const TYPE_FILM = 1; // Type of video is a Film/Movie + const TYPE_ANIME = 2; // Type of video is a Anime /** * @var DB */ - public $pdo; + public $pdo; - /** - * @var bool - */ - public $echooutput; + /** + * @var bool + */ + public $echooutput; - /** - * @var array sites The sites that we have an ID columns for in our video table. - */ - private static $sites = ['imdb', 'tmdb', 'trakt', 'tvdb', 'tvmaze', 'tvrage']; + /** + * @var array sites The sites that we have an ID columns for in our video table. + */ + private static $sites = ['imdb', 'tmdb', 'trakt', 'tvdb', 'tvmaze', 'tvrage']; - /** - * @var array Temp Array of cached failed lookups - */ - public $titleCache; + /** + * @var array Temp Array of cached failed lookups + */ + public $titleCache; - public function __construct(array $options = []) - { - $defaults = [ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - // Sets the default timezone for this script (and its children). - //date_default_timezone_set('UTC'); TODO: Make this a DTO instead and use as needed + // Sets the default timezone for this script (and its children). + //date_default_timezone_set('UTC'); TODO: Make this a DTO instead and use as needed - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->titleCache = []; - } + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->titleCache = []; + } - /** - * Main processing director function for scrapers - * Calls work query function and initiates processing - * - * @param $groupID - * @param $guidChar - * @param $process - * @param bool $local - */ - abstract protected function processSite($groupID, $guidChar, $process, $local = false): void; + /** + * Main processing director function for scrapers + * Calls work query function and initiates processing. + * + * @param $groupID + * @param $guidChar + * @param $process + * @param bool $local + */ + abstract protected function processSite($groupID, $guidChar, $process, $local = false): void; - /** - * Get video info from a Video ID and column. - * - * @param string $siteColumn - * @param integer $videoID - * - * @return array|false False if invalid site, or ID not found; Site id value otherwise. - */ - protected function getSiteIDFromVideoID($siteColumn, $videoID) - { - if (in_array($siteColumn, Videos::$sites, false)) { - $result = $this->pdo->queryOneRow(sprintf('SELECT %s FROM videos WHERE id = %d', $siteColumn, $videoID)); + /** + * Get video info from a Video ID and column. + * + * @param string $siteColumn + * @param int $videoID + * + * @return array|false False if invalid site, or ID not found; Site id value otherwise. + */ + protected function getSiteIDFromVideoID($siteColumn, $videoID) + { + if (in_array($siteColumn, self::$sites, false)) { + $result = $this->pdo->queryOneRow(sprintf('SELECT %s FROM videos WHERE id = %d', $siteColumn, $videoID)); - return $result[$siteColumn] ?? false; - } + return $result[$siteColumn] ?? false; + } - return false; - } + return false; + } - /** - * Get TV show local timezone from a Video ID - * - * @param integer $videoID - * - * @return string Empty string if no query return or tz style timezone - */ - protected function getLocalZoneFromVideoID($videoID): string - { - $result = $this->pdo->queryOneRow(sprintf('SELECT localzone FROM tv_info WHERE videos_id = %d', $videoID)); + /** + * Get TV show local timezone from a Video ID. + * + * @param int $videoID + * + * @return string Empty string if no query return or tz style timezone + */ + protected function getLocalZoneFromVideoID($videoID): string + { + $result = $this->pdo->queryOneRow(sprintf('SELECT localzone FROM tv_info WHERE videos_id = %d', $videoID)); - return $result['localzone'] ?? ''; - } + return $result['localzone'] ?? ''; + } + /** + * Get video info from a Site ID and column. + * + * @param string $siteColumn + * @param int $siteID + * + * @return int|false False if invalid site, or ID not found; video.id value otherwise. + */ + protected function getVideoIDFromSiteID($siteColumn, $siteID) + { + if (in_array($siteColumn, self::$sites, false)) { + $result = $this->pdo->queryOneRow(sprintf('SELECT id FROM videos WHERE %s = %d', $siteColumn, $siteID)); - /** - * Get video info from a Site ID and column. - * - * @param string $siteColumn - * @param integer $siteID - * - * @return int|false False if invalid site, or ID not found; video.id value otherwise. - */ - protected function getVideoIDFromSiteID($siteColumn, $siteID) - { - if (in_array($siteColumn, Videos::$sites, false)) { - $result = $this->pdo->queryOneRow(sprintf('SELECT id FROM videos WHERE %s = %d', $siteColumn, $siteID)); + return isset($result['id']) ? (int) $result['id'] : false; + } - return isset($result['id']) ? (int)$result['id'] : false; - } - return false; - } + return false; + } - /** - * Attempt a local lookup via the title first by exact match and then by like. - * Returns a false for no match or the Video ID of the match. - * - * @param $title - * @param $type - * @param int $source - * - * @return false|int - */ - public function getByTitle($title, $type, $source = 0) - { - // Check if we already have an entry for this show. - $res = $this->getTitleExact($title, $type, $source); - if (isset($res['id'])) { - return $res['id']; - } + /** + * Attempt a local lookup via the title first by exact match and then by like. + * Returns a false for no match or the Video ID of the match. + * + * @param $title + * @param $type + * @param int $source + * + * @return false|int + */ + public function getByTitle($title, $type, $source = 0) + { + // Check if we already have an entry for this show. + $res = $this->getTitleExact($title, $type, $source); + if (isset($res['id'])) { + return $res['id']; + } - $title2 = str_replace(' and ', ' & ', $title); - if ((string)$title !== (string)$title2) { - $res = $this->getTitleExact($title2, $type, $source); - if (isset($res['id'])) { - return $res['id']; - } - $pieces = explode(' ', $title2); - $title2 = '%'; - foreach ($pieces as $piece) { - $title2 .= str_replace(["'", '!'], '', $piece) . '%'; - } - $res = $this->getTitleLoose($title2, $type, $source); - if (isset($res['id'])) { - return $res['id']; - } - } + $title2 = str_replace(' and ', ' & ', $title); + if ((string) $title !== (string) $title2) { + $res = $this->getTitleExact($title2, $type, $source); + if (isset($res['id'])) { + return $res['id']; + } + $pieces = explode(' ', $title2); + $title2 = '%'; + foreach ($pieces as $piece) { + $title2 .= str_replace(["'", '!'], '', $piece).'%'; + } + $res = $this->getTitleLoose($title2, $type, $source); + if (isset($res['id'])) { + return $res['id']; + } + } - // Some words are spelled correctly 2 ways - // example theatre and theater - $title2 = str_replace('er', 're', $title); - if ((string)$title !== (string)$title2) { - $res = $this->getTitleExact($title2, $type, $source); - if (isset($res['id'])) { - return $res['id']; - } - $pieces = explode(' ', $title2); - $title2 = '%'; - foreach ($pieces as $piece) { - $title2 .= str_replace(["'", '!'], '', $piece) . '%'; - } - $res = $this->getTitleLoose($title2, $type, $source); - if (isset($res['id'])) { - return $res['id']; - } - } + // Some words are spelled correctly 2 ways + // example theatre and theater + $title2 = str_replace('er', 're', $title); + if ((string) $title !== (string) $title2) { + $res = $this->getTitleExact($title2, $type, $source); + if (isset($res['id'])) { + return $res['id']; + } + $pieces = explode(' ', $title2); + $title2 = '%'; + foreach ($pieces as $piece) { + $title2 .= str_replace(["'", '!'], '', $piece).'%'; + } + $res = $this->getTitleLoose($title2, $type, $source); + if (isset($res['id'])) { + return $res['id']; + } + } - // If there was not an exact title match, look for title with missing chars - // example release name :Zorro 1990, tvrage name Zorro (1990) - // Only search if the title contains more than one word to prevent incorrect matches - $pieces = explode(' ', $title); - if (count($pieces) > 1) { - $title2 = '%'; - foreach ($pieces as $piece) { - $title2 .= str_replace(["'", '!'], '', $piece) . '%'; - } - $res = $this->getTitleLoose($title2, $type, $source); - if (isset($res['id'])) { - return $res['id']; - } - } - return false; - } + // If there was not an exact title match, look for title with missing chars + // example release name :Zorro 1990, tvrage name Zorro (1990) + // Only search if the title contains more than one word to prevent incorrect matches + $pieces = explode(' ', $title); + if (count($pieces) > 1) { + $title2 = '%'; + foreach ($pieces as $piece) { + $title2 .= str_replace(["'", '!'], '', $piece).'%'; + } + $res = $this->getTitleLoose($title2, $type, $source); + if (isset($res['id'])) { + return $res['id']; + } + } - /** - * Supplementary function for getByTitle that queries for exact match - * - * @param $title - * @param $type - * @param int $source - * - * @return array|false - */ - public function getTitleExact($title, $type, $source = 0) - { - $return = false; - if (!empty($title)) { - $return = $this->pdo->queryOneRow( - sprintf(" + return false; + } + + /** + * Supplementary function for getByTitle that queries for exact match. + * + * @param $title + * @param $type + * @param int $source + * + * @return array|false + */ + public function getTitleExact($title, $type, $source = 0) + { + $return = false; + if (! empty($title)) { + $return = $this->pdo->queryOneRow( + sprintf(' SELECT v.id FROM videos v - WHERE v.title = %1\$s - AND v.type = %2\$d %3\$s", + WHERE v.title = %1$s + AND v.type = %2$d %3$s', $this->pdo->escapeString($title), $type, - ($source > 0 ? 'AND v.source = ' . $source : '') + ($source > 0 ? 'AND v.source = '.$source : '') ) ); - // Try for an alias - if ($return === false) { - $return = $this->pdo->queryOneRow( - sprintf(" + // Try for an alias + if ($return === false) { + $return = $this->pdo->queryOneRow( + sprintf(' SELECT v.id FROM videos v INNER JOIN videos_aliases va ON v.id = va.videos_id - WHERE va.title = %1\$s - AND v.type = %2\$d %3\$s", + WHERE va.title = %1$s + AND v.type = %2$d %3$s', $this->pdo->escapeString($title), $type, - ($source > 0 ? 'AND v.source = ' . $source : '') + ($source > 0 ? 'AND v.source = '.$source : '') ) ); - } - } + } + } - return $return; - } + return $return; + } - /** - * Supplementary function for getByTitle that queries for a like match - * - * @param $title - * @param $type - * @param int $source - * - * @return array|false - */ - public function getTitleLoose($title, $type, $source = 0) - { - $return = false; + /** + * Supplementary function for getByTitle that queries for a like match. + * + * @param $title + * @param $type + * @param int $source + * + * @return array|false + */ + public function getTitleLoose($title, $type, $source = 0) + { + $return = false; - if (!empty($title)) { - $return = $this->pdo->queryOneRow( + if (! empty($title)) { + $return = $this->pdo->queryOneRow( sprintf(' SELECT v.id FROM videos v @@ -270,12 +270,12 @@ abstract class Videos AND type = %d %s', $this->pdo->likeString(rtrim($title, '%'), false, false), $type, - ($source > 0 ? 'AND v.source = ' . $source : '') + ($source > 0 ? 'AND v.source = '.$source : '') ) ); - // Try for an alias - if ($return === false) { - $return = $this->pdo->queryOneRow( + // Try for an alias + if ($return === false) { + $return = $this->pdo->queryOneRow( sprintf(' SELECT v.id FROM videos v @@ -284,34 +284,34 @@ abstract class Videos AND type = %d %s', $this->pdo->likeString(rtrim($title, '%'), false, false), $type, - ($source > 0 ? 'AND v.source = ' . $source : '') + ($source > 0 ? 'AND v.source = '.$source : '') ) ); - } - } + } + } - return $return; - } + return $return; + } - /** - * Inserts aliases for videos - * - * @param $videoId - * @param array $aliases - */ - public function addAliases($videoId, array $aliases = []): void - { - if (!empty($aliases) && $videoId > 0) { - foreach ($aliases AS $key => $title) { - // Check for tvmaze style aka - if (is_array($title) && !empty($title['name'])) { - $title = $title['name']; - } - // Check if we have the AKA already - $check = $this->getAliases(0, $title); + /** + * Inserts aliases for videos. + * + * @param $videoId + * @param array $aliases + */ + public function addAliases($videoId, array $aliases = []): void + { + if (! empty($aliases) && $videoId > 0) { + foreach ($aliases as $key => $title) { + // Check for tvmaze style aka + if (is_array($title) && ! empty($title['name'])) { + $title = $title['name']; + } + // Check if we have the AKA already + $check = $this->getAliases(0, $title); - if ($check === false) { - $this->pdo->queryInsert( + if ($check === false) { + $this->pdo->queryInsert( sprintf(' INSERT IGNORE INTO videos_aliases (videos_id, title) @@ -320,37 +320,38 @@ abstract class Videos $this->pdo->escapeString($title) ) ); - } - } - } - } + } + } + } + } - /** - * Retrieves all aliases for given VideoID or VideoID for a given alias - * - * @param int $videoId - * @param string $alias - * - * @return \PDOStatement|false - */ - public function getAliases($videoId = 0, $alias = '') - { - $return = false; - $sql = ''; + /** + * Retrieves all aliases for given VideoID or VideoID for a given alias. + * + * @param int $videoId + * @param string $alias + * + * @return \PDOStatement|false + */ + public function getAliases($videoId = 0, $alias = '') + { + $return = false; + $sql = ''; - if ($videoId > 0) { - $sql = 'videos_id = ' . $videoId; - } else if ($alias !== '') { - $sql = 'title = ' . $this->pdo->escapeString($alias); - } + if ($videoId > 0) { + $sql = 'videos_id = '.$videoId; + } elseif ($alias !== '') { + $sql = 'title = '.$this->pdo->escapeString($alias); + } - if ($sql !== '') { - $return = $this->pdo->query(' + if ($sql !== '') { + $return = $this->pdo->query(' SELECT * FROM videos_aliases - WHERE ' . $sql, true, NN_CACHE_EXPIRY_MEDIUM + WHERE '.$sql, true, NN_CACHE_EXPIRY_MEDIUM ); - } - return (empty($return) ? false : $return); - } + } + + return empty($return) ? false : $return; + } } diff --git a/nntmux/processing/adult/ADE.php b/nntmux/processing/adult/ADE.php index 41fb0122d..6c9fa7073 100755 --- a/nntmux/processing/adult/ADE.php +++ b/nntmux/processing/adult/ADE.php @@ -1,226 +1,232 @@ <?php + namespace nntmux\processing\adult; /** - * Class adultdvdempire + * Class adultdvdempire. */ class ADE extends AdultMovies { - /** - * If a direct link is given parse it rather then search - * @var string - */ - protected $directLink = ''; + /** + * If a direct link is given parse it rather then search. + * @var string + */ + protected $directLink = ''; - /** - * Search keyword - * @var string - */ - protected $searchTerm = ''; + /** + * Search keyword. + * @var string + */ + protected $searchTerm = ''; - /** - * Define ADE Url here - */ - const ADE = 'http://www.adultdvdempire.com'; + /** + * Define ADE Url here. + */ + const ADE = 'http://www.adultdvdempire.com'; - /** - * Direct Url returned in getAll method - * - * @var string - */ - protected $_directUrl = ''; + /** + * Direct Url returned in getAll method. + * + * @var string + */ + protected $_directUrl = ''; - /** - * Sets the title in the getAll method - * - * @var string - */ - protected $_title = ''; + /** + * Sets the title in the getAll method. + * + * @var string + */ + protected $_title = ''; - /** Trailing urls */ - protected $_dvdQuery = '/dvd/search?q='; - protected $_scenes = '/scenes'; - protected $_boxCover = '/boxcover'; - protected $_backCover = '/backcover'; - protected $_reviews = '/reviews'; - protected $_trailers = '/trailers'; + /** Trailing urls */ + protected $_dvdQuery = '/dvd/search?q='; + protected $_scenes = '/scenes'; + protected $_boxCover = '/boxcover'; + protected $_backCover = '/backcover'; + protected $_reviews = '/reviews'; + protected $_trailers = '/trailers'; + protected $_url; + protected $_response; + protected $_res = []; + protected $_tmpResponse; + protected $_ch; - protected $_url; - protected $_response; - protected $_res = []; - protected $_tmpResponse; - protected $_ch; + public function __construct(array $options = []) + { + parent::__construct($options); + } - public function __construct(array $options = []) - { - parent::__construct($options); - } - - /** - * Gets Trailer Movies - * @return array - url, streamid, basestreamingurl - */ - protected function trailers() - { - $this->_response = getRawHtml(self::ADE . $this->_trailers . $this->_directUrl); - $this->_html->load($this->_response); - if (preg_match("/(\"|')(?P<swf>[^\"']+.swf)(\"|')/i", $this->_response, $matches)) { - $this->_res['trailers']['url'] = self::ADE . trim(trim($matches['swf']), '"'); - if (preg_match('#(?:streamID:\s\")(?P<streamid>[0-9A-Z]+)(?:\")#', + /** + * Gets Trailer Movies. + * @return array - url, streamid, basestreamingurl + */ + protected function trailers() + { + $this->_response = getRawHtml(self::ADE.$this->_trailers.$this->_directUrl); + $this->_html->load($this->_response); + if (preg_match("/(\"|')(?P<swf>[^\"']+.swf)(\"|')/i", $this->_response, $matches)) { + $this->_res['trailers']['url'] = self::ADE.trim(trim($matches['swf']), '"'); + if (preg_match('#(?:streamID:\s\")(?P<streamid>[0-9A-Z]+)(?:\")#', $this->_response, $matches) ) { - $this->_res['trailers']['streamid'] = trim($matches['streamid']); - } - if (preg_match('#(?:BaseStreamingUrl:\s\")(?P<baseurl>[\d]+.[\d]+.[\d]+.[\d]+)(?:\")#', + $this->_res['trailers']['streamid'] = trim($matches['streamid']); + } + if (preg_match('#(?:BaseStreamingUrl:\s\")(?P<baseurl>[\d]+.[\d]+.[\d]+.[\d]+)(?:\")#', $this->_response, $matches) ) { - $this->_res['trailers']['baseurl'] = $matches['baseurl']; - } - } + $this->_res['trailers']['baseurl'] = $matches['baseurl']; + } + } - return $this->_res; - } + return $this->_res; + } - /** - * Gets cover images for the xxx release - * @return array - Boxcover and backcover - */ - protected function covers() - { - if ($ret = $this->_html->find('div#Boxcover, img[itemprop=image]', 1)) { - $this->_res['boxcover'] = preg_replace('/m\.jpg/', 'h.jpg', $ret->src); - $this->_res['backcover'] = preg_replace('/m\.jpg/', 'bh.jpg', $ret->src); - } + /** + * Gets cover images for the xxx release. + * @return array - Boxcover and backcover + */ + protected function covers() + { + if ($ret = $this->_html->find('div#Boxcover, img[itemprop=image]', 1)) { + $this->_res['boxcover'] = preg_replace('/m\.jpg/', 'h.jpg', $ret->src); + $this->_res['backcover'] = preg_replace('/m\.jpg/', 'bh.jpg', $ret->src); + } - return $this->_res; - } + return $this->_res; + } - /** - * Gets the synopsis - * - * @return array - plot - */ - protected function synopsis() - { - $ret = $this->_html->find('meta[name=og:description]', 0)->content; - if ($ret !== false) { - $this->_res['synopsis'] = trim($ret); - } + /** + * Gets the synopsis. + * + * @return array - plot + */ + protected function synopsis() + { + $ret = $this->_html->find('meta[name=og:description]', 0)->content; + if ($ret !== false) { + $this->_res['synopsis'] = trim($ret); + } - return $this->_res; - } + return $this->_res; + } - /** - * Gets the cast members and/or awards - * - * - * @return array - cast, awards - */ - protected function cast() - { - $cast = []; - foreach ($this->_html->find('[Label="Performers - detail"]') as $a) { - if ($a->plaintext !== false) { - $cast[] = trim($a->plaintext); - } - } - $this->_res['cast'] = $cast; - return $this->_res; - } + /** + * Gets the cast members and/or awards. + * + * + * @return array - cast, awards + */ + protected function cast() + { + $cast = []; + foreach ($this->_html->find('[Label="Performers - detail"]') as $a) { + if ($a->plaintext !== false) { + $cast[] = trim($a->plaintext); + } + } + $this->_res['cast'] = $cast; - /** - * Gets Genres, if exists return array else return false - * @return mixed array - Genres - */ - protected function genres() - { - $genres = []; - foreach ($this->_html->find('[Label="Category"]') as $a) { - if ($a->plaintext !== false) { - $genres[] = trim($a->plaintext); - } - } - $this->_res['genres'] = $genres; - return $this->_res; - } + return $this->_res; + } - /** - * Gets Product Information and/or Features - * - * @param bool $extras - * @return array - ProductInfo/Extras = features - */ - protected function productInfo($extras = false) - { - $dofeature = null; - $this->_tmpResponse = str_ireplace('Section ProductInfo', 'spdinfo', $this->_response); - $this->_html->load($this->_tmpResponse); - if ($ret = $this->_html->find('div[class=spdinfo]', 0)) { - $this->_tmpResponse = trim($ret->outertext); - $ret = $this->_html->load($this->_tmpResponse); - foreach ($ret->find("text") as $strong) { - if (trim($strong->innertext) === 'Features') { - $dofeature = true; - } - if ($dofeature !== true) { - if (trim($strong->innertext) !== ' ') { - $this->_res['productinfo'][] = trim($strong->innertext); - } - } else { - if ($extras === true) { - $this->_res['extras'][] = trim($strong->innertext); - } - } - } + /** + * Gets Genres, if exists return array else return false. + * @return mixed array - Genres + */ + protected function genres() + { + $genres = []; + foreach ($this->_html->find('[Label="Category"]') as $a) { + if ($a->plaintext !== false) { + $genres[] = trim($a->plaintext); + } + } + $this->_res['genres'] = $genres; - array_shift($this->_res['productinfo']); - array_shift($this->_res['productinfo']); - $this->_res['productinfo'] = array_chunk($this->_res['productinfo'], 2, false); - } + return $this->_res; + } - return $this->_res; - } + /** + * Gets Product Information and/or Features. + * + * @param bool $extras + * @return array - ProductInfo/Extras = features + */ + protected function productInfo($extras = false) + { + $dofeature = null; + $this->_tmpResponse = str_ireplace('Section ProductInfo', 'spdinfo', $this->_response); + $this->_html->load($this->_tmpResponse); + if ($ret = $this->_html->find('div[class=spdinfo]', 0)) { + $this->_tmpResponse = trim($ret->outertext); + $ret = $this->_html->load($this->_tmpResponse); + foreach ($ret->find('text') as $strong) { + if (trim($strong->innertext) === 'Features') { + $dofeature = true; + } + if ($dofeature !== true) { + if (trim($strong->innertext) !== ' ') { + $this->_res['productinfo'][] = trim($strong->innertext); + } + } else { + if ($extras === true) { + $this->_res['extras'][] = trim($strong->innertext); + } + } + } - /** - * Searches xxx name. - * - * @param string $movie - * - * @return bool - True if releases has 90% match, else false - */ - public function processSite($movie): bool - { - if (empty($movie)) { - return false; - } - $this->_response = getRawHtml(self::ADE . $this->_dvdQuery . rawurlencode($movie)); - if ($this->_response !== false) { - $this->_html->load($this->_response); - if ($res = $this->_html->find('a[class=boxcover]')) { - foreach ($res as $ret) { - $title = $ret->title; - $title = str_replace('/XXX/', '', $title); - $title = preg_replace('/\(.*?\)|[-._]/', ' ', $title); - $url = (string)trim($ret->href); - similar_text(strtolower($movie), strtolower($title), $p); - if ($p >= 90) { - $this->_directUrl = self::ADE . $url; - $this->_title = trim($title); - $this->_html->clear(); - unset($this->_response); - $this->_response = getRawHtml($this->_directUrl); - $this->_html->load($this->_response); - return true; - } - continue; - } - return false; - } - return false; - } - return false; - } + array_shift($this->_res['productinfo']); + array_shift($this->_res['productinfo']); + $this->_res['productinfo'] = array_chunk($this->_res['productinfo'], 2, false); + } + + return $this->_res; + } + + /** + * Searches xxx name. + * + * @param string $movie + * + * @return bool - True if releases has 90% match, else false + */ + public function processSite($movie): bool + { + if (empty($movie)) { + return false; + } + $this->_response = getRawHtml(self::ADE.$this->_dvdQuery.rawurlencode($movie)); + if ($this->_response !== false) { + $this->_html->load($this->_response); + if ($res = $this->_html->find('a[class=boxcover]')) { + foreach ($res as $ret) { + $title = $ret->title; + $title = str_replace('/XXX/', '', $title); + $title = preg_replace('/\(.*?\)|[-._]/', ' ', $title); + $url = (string) trim($ret->href); + similar_text(strtolower($movie), strtolower($title), $p); + if ($p >= 90) { + $this->_directUrl = self::ADE.$url; + $this->_title = trim($title); + $this->_html->clear(); + unset($this->_response); + $this->_response = getRawHtml($this->_directUrl); + $this->_html->load($this->_response); + + return true; + } + continue; + } + + return false; + } + + return false; + } + + return false; + } } diff --git a/nntmux/processing/adult/ADM.php b/nntmux/processing/adult/ADM.php index b522a8820..59af1cb0e 100755 --- a/nntmux/processing/adult/ADM.php +++ b/nntmux/processing/adult/ADM.php @@ -1,125 +1,126 @@ <?php + namespace nntmux\processing\adult; use nntmux\db\DB; class ADM extends AdultMovies { - /** - * Override if 18 years+ or older - * Define Adult DVD Marketplace url - * Needed Search Queries Constant - */ - const ADMURL = 'http://www.adultdvdmarketplace.com'; - const IF18 = 'http://www.adultdvdmarketplace.com/xcart/adult_dvd/disclaimer.php?action=enter&site=intl&return_url='; - const TRAILINGSEARCH = '/xcart/adult_dvd/advanced_search.php?sort_by=relev&title='; + /** + * Override if 18 years+ or older + * Define Adult DVD Marketplace url + * Needed Search Queries Constant. + */ + const ADMURL = 'http://www.adultdvdmarketplace.com'; + const IF18 = 'http://www.adultdvdmarketplace.com/xcart/adult_dvd/disclaimer.php?action=enter&site=intl&return_url='; + const TRAILINGSEARCH = '/xcart/adult_dvd/advanced_search.php?sort_by=relev&title='; - /** - * Define a cookie file location for curl - * @var string string - */ - public $cookie = ''; + /** + * Define a cookie file location for curl. + * @var string string + */ + public $cookie = ''; - /** - * Direct Link given from outside url doesn't do a search - * @var string - */ - protected $directLink = ''; + /** + * Direct Link given from outside url doesn't do a search. + * @var string + */ + protected $directLink = ''; - /** - * Set this for what you are searching for. - * @var string - */ - protected $searchTerm = ''; + /** + * Set this for what you are searching for. + * @var string + */ + protected $searchTerm = ''; - /** - * Sets the directurl for the return results array - * @var string - */ - protected $_directUrl = ''; + /** + * Sets the directurl for the return results array. + * @var string + */ + protected $_directUrl = ''; - /** - * Results returned from each method - * - * @var array - */ - protected $_res = []; + /** + * Results returned from each method. + * + * @var array + */ + protected $_res = []; - /** - * Curl Raw Html - */ - protected $_response; + /** + * Curl Raw Html. + */ + protected $_response; - /** - * Add this to popurl to get results - * @var string - */ - protected $_trailUrl = ''; + /** + * Add this to popurl to get results. + * @var string + */ + protected $_trailUrl = ''; - /** - * This is set in the getAll method - * - * @var string - */ - protected $_title = ''; + /** + * This is set in the getAll method. + * + * @var string + */ + protected $_title = ''; - public function __construct(array $options = []) - { - parent::__construct($options); - $this->pdo = new DB(); - } + public function __construct(array $options = []) + { + parent::__construct($options); + $this->pdo = new DB(); + } - /** - * Get Box Cover Images - * @return array - boxcover,backcover - */ - protected function covers() - { - $baseUrl = 'http://www.adultdvdmarketplace.com/'; - if ($ret = $this->_html->find('a[rel=fancybox-button]', 0)) { - if (isset($ret->href) && preg_match('/images\/.*[\d]+\.jpg/i', $ret->href, $matches)) { - $this->_res['boxcover'] = $baseUrl . $matches[0]; - $this->_res['backcover'] = $baseUrl . str_ireplace('/front/i', 'back', $matches[0]); - } - } elseif ($ret = $this->_html->find('img[rel=license]', 0)) { - if (preg_match('/images\/.*[\d]+\.jpg/i', $ret->src, $matches)) { - $this->_res['boxcover'] = $baseUrl . $matches[0]; - } - } - return $this->_res; - } + /** + * Get Box Cover Images. + * @return array - boxcover,backcover + */ + protected function covers() + { + $baseUrl = 'http://www.adultdvdmarketplace.com/'; + if ($ret = $this->_html->find('a[rel=fancybox-button]', 0)) { + if (isset($ret->href) && preg_match('/images\/.*[\d]+\.jpg/i', $ret->href, $matches)) { + $this->_res['boxcover'] = $baseUrl.$matches[0]; + $this->_res['backcover'] = $baseUrl.str_ireplace('/front/i', 'back', $matches[0]); + } + } elseif ($ret = $this->_html->find('img[rel=license]', 0)) { + if (preg_match('/images\/.*[\d]+\.jpg/i', $ret->src, $matches)) { + $this->_res['boxcover'] = $baseUrl.$matches[0]; + } + } - /** - * Gets the synopsis - * - * @return array - */ - protected function synopsis() - { - $this->_res['synopsis'] = 'N/A'; - foreach ($this->_html->find('h3') as $heading) { - if (trim($heading->plaintext) === 'Description') { - $this->_res['synopsis'] = trim($heading->next_sibling()->plaintext); - } - } + return $this->_res; + } - return $this->_res; - } + /** + * Gets the synopsis. + * + * @return array + */ + protected function synopsis() + { + $this->_res['synopsis'] = 'N/A'; + foreach ($this->_html->find('h3') as $heading) { + if (trim($heading->plaintext) === 'Description') { + $this->_res['synopsis'] = trim($heading->next_sibling()->plaintext); + } + } - /** - * Get Product Information and Director - * - * - * @param bool $extras - * - * @return array - */ - protected function productInfo($extras = false) - { + return $this->_res; + } - foreach ($this->_html->find('ul.list-unstyled li') as $li) { - $category = explode(':', $li->plaintext); - switch (trim($category[0])) { + /** + * Get Product Information and Director. + * + * + * @param bool $extras + * + * @return array + */ + protected function productInfo($extras = false) + { + foreach ($this->_html->find('ul.list-unstyled li') as $li) { + $category = explode(':', $li->plaintext); + switch (trim($category[0])) { case 'Director': $this->_res['director'] = trim($category[1]); break; @@ -129,103 +130,103 @@ class ADM extends AdultMovies case 'SKU': $this->_res['productinfo'][trim($category[0])] = trim($category[1]); } - } + } - return $this->_res; - } + return $this->_res; + } - /** - * Gets the cast members - * @return array - */ - protected function cast() - { - $cast = []; - foreach ($this->_html->find('h3') as $heading) { - if (trim($heading->plaintext) === 'Cast') { - for ($next = $heading->next_sibling(); $next && $next->nodeName !== 'h3'; $next = $next->next_sibling()) { - if (preg_match_all('/search_performerid/', $next->href, $matches)) { - $cast[] = trim($next->plaintext); - } - } - } - } - $this->_res['cast'] = array_unique($cast); + /** + * Gets the cast members. + * @return array + */ + protected function cast() + { + $cast = []; + foreach ($this->_html->find('h3') as $heading) { + if (trim($heading->plaintext) === 'Cast') { + for ($next = $heading->next_sibling(); $next && $next->nodeName !== 'h3'; $next = $next->next_sibling()) { + if (preg_match_all('/search_performerid/', $next->href, $matches)) { + $cast[] = trim($next->plaintext); + } + } + } + } + $this->_res['cast'] = array_unique($cast); - return $this->_res; - } + return $this->_res; + } - /** - * Gets categories - * @return array - */ - protected function genres() - { - $genres = []; - foreach ($this->_html->find('ul.list-unstyled') as $li) { - $category = explode(':', $li->plaintext); - if (trim($category[0]) === 'Category') { - $genre = explode(',', $category[1]); - foreach($genre as $g) { - $genres[] = trim($g); - } - $this->_res['genres'] = $genres; - } - } + /** + * Gets categories. + * @return array + */ + protected function genres() + { + $genres = []; + foreach ($this->_html->find('ul.list-unstyled') as $li) { + $category = explode(':', $li->plaintext); + if (trim($category[0]) === 'Category') { + $genre = explode(',', $category[1]); + foreach ($genre as $g) { + $genres[] = trim($g); + } + $this->_res['genres'] = $genres; + } + } - return $this->_res; - } + return $this->_res; + } - /** - * Searches for match against searchterm - * - * @param $movie - * - * @return bool - true if search = 100% - */ - public function processSite($movie) - { - $result = false; - if (!empty($movie)) { - $this->_trailUrl = self::TRAILINGSEARCH . urlencode($movie); - $this->_response = getRawHtml(self::ADMURL . $this->_trailUrl, $this->cookie); - if ($this->_response !== false) { - $this->_html->load($this->_response); - if ($ret = $this->_html->find('img[rel=license]')) { - if (count($ret) > 0) { - foreach ($this->_html->find('img[rel=license]') as $ret) { - if (isset($ret->alt)) { - $title = trim($ret->alt, '"'); - $title = str_replace('/XXX/', '', $title); - $comparetitle = preg_replace('/[\W]/', '', $title); - $comparesearch = preg_replace('/[\W]/', '', $movie); - similar_text($comparetitle, $comparesearch, $p); - if ($p >= 90) { - if (preg_match('/\/(?<sku>\d+)\.jpg/i', $ret->src, $matches)) { - $this->_title = trim($title); - $this->_trailUrl = '/dvd_view_' . (string)$matches['sku'] . '.html'; - $this->_directUrl = self::ADMURL . $this->_trailUrl; - $this->_html->clear(); - unset($this->_response); - $this->_response = getRawHtml($this->_directUrl, $this->cookie); - $this->_html->load($this->_response); - $result = true; - } - } - } - } - } - } - } - } - return $result; - } + /** + * Searches for match against searchterm. + * + * @param $movie + * + * @return bool - true if search = 100% + */ + public function processSite($movie) + { + $result = false; + if (! empty($movie)) { + $this->_trailUrl = self::TRAILINGSEARCH.urlencode($movie); + $this->_response = getRawHtml(self::ADMURL.$this->_trailUrl, $this->cookie); + if ($this->_response !== false) { + $this->_html->load($this->_response); + if ($ret = $this->_html->find('img[rel=license]')) { + if (count($ret) > 0) { + foreach ($this->_html->find('img[rel=license]') as $ret) { + if (isset($ret->alt)) { + $title = trim($ret->alt, '"'); + $title = str_replace('/XXX/', '', $title); + $comparetitle = preg_replace('/[\W]/', '', $title); + $comparesearch = preg_replace('/[\W]/', '', $movie); + similar_text($comparetitle, $comparesearch, $p); + if ($p >= 90) { + if (preg_match('/\/(?<sku>\d+)\.jpg/i', $ret->src, $matches)) { + $this->_title = trim($title); + $this->_trailUrl = '/dvd_view_'.(string) $matches['sku'].'.html'; + $this->_directUrl = self::ADMURL.$this->_trailUrl; + $this->_html->clear(); + unset($this->_response); + $this->_response = getRawHtml($this->_directUrl, $this->cookie); + $this->_html->load($this->_response); + $result = true; + } + } + } + } + } + } + } + } + return $result; + } - protected function trailers() - { - // TODO: Implement trailers() method. + protected function trailers() + { + // TODO: Implement trailers() method. - return false; - } + return false; + } } diff --git a/nntmux/processing/adult/AEBN.php b/nntmux/processing/adult/AEBN.php index a84d02cde..35bba2a67 100755 --- a/nntmux/processing/adult/AEBN.php +++ b/nntmux/processing/adult/AEBN.php @@ -4,45 +4,44 @@ namespace nntmux\processing\adult; class AEBN extends AdultMovies { - /** - * Keyword to search - * - * @var string - */ - public $searchTerm = ''; + /** + * Keyword to search. + * + * @var string + */ + public $searchTerm = ''; - /** - * Url Constants used within this class - */ - const AEBNSURL = 'http://straight.theater.aebn.net'; - const IF18 = 'http://straight.theater.aebn.net/dispatcher/frontDoor?genreId=101&theaterId=13992&locale=en&refid=AEBN-000001'; - const TRAILINGSEARCH = '/dispatcher/fts?theaterId=13992&genreId=101&locale=en&count=30&imageType=Large&targetSearchMode=basic&isAdvancedSearch=false&isFlushAdvancedSearchCriteria=false&sortType=Relevance&userQuery=title%3A+%2B'; - const TRAILERURL = '/dispatcher/previewPlayer?locale=en&theaterId=13992&genreId=101&movieId='; + /** + * Url Constants used within this class. + */ + const AEBNSURL = 'http://straight.theater.aebn.net'; + const IF18 = 'http://straight.theater.aebn.net/dispatcher/frontDoor?genreId=101&theaterId=13992&locale=en&refid=AEBN-000001'; + const TRAILINGSEARCH = '/dispatcher/fts?theaterId=13992&genreId=101&locale=en&count=30&imageType=Large&targetSearchMode=basic&isAdvancedSearch=false&isFlushAdvancedSearchCriteria=false&sortType=Relevance&userQuery=title%3A+%2B'; + const TRAILERURL = '/dispatcher/previewPlayer?locale=en&theaterId=13992&genreId=101&movieId='; - /** - * Direct Url in getAll method - * - * @var string - */ - protected $_directUrl = ''; + /** + * Direct Url in getAll method. + * + * @var string + */ + protected $_directUrl = ''; - /** - * Raw Html response from curl - * - */ - protected $_response; + /** + * Raw Html response from curl. + */ + protected $_response; - /** - * @var string - */ - protected $_trailerUrl = ''; + /** + * @var string + */ + protected $_trailerUrl = ''; - /** - * Returned results in all methods except search/geturl - * - * @var array - */ - protected $_res = [ + /** + * Returned results in all methods except search/geturl. + * + * @var array + */ + protected $_res = [ 'backcover' => [], 'boxcover' => [], 'cast' => [], @@ -53,197 +52,196 @@ class AEBN extends AdultMovies 'trailers' => ['url' => []], ]; - /** - * Sets title in getAll method - * - * @var string - */ - protected $_title = ''; + /** + * Sets title in getAll method. + * + * @var string + */ + protected $_title = ''; + /** + * Sets the variables that used throughout the class. + * + * @param array $options + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + parent::__construct($options); + } - /** - * Sets the variables that used throughout the class - * - * @param array $options - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - parent::__construct($options); - } + /** + * Gets Trailer URL .. will be processed in XXX insertswf. + * + * @return array|bool + */ + protected function trailers() + { + $ret = $this->_html->find('a[itemprop=trailer]', 0); + if (! empty($ret) && preg_match('/movieId=(?<movieid>\d+)&/', trim($ret->href), $matches)) { + $movieid = $matches['movieid']; + $this->_res['trailers']['url'] = self::AEBNSURL.self::TRAILERURL.$movieid; + } - /** - * Gets Trailer URL .. will be processed in XXX insertswf - * - * @return array|bool - */ - protected function trailers() - { - $ret = $this->_html->find('a[itemprop=trailer]', 0); - if (!empty($ret) && preg_match('/movieId=(?<movieid>\d+)&/', trim($ret->href), $matches)) { - $movieid = $matches['movieid']; - $this->_res['trailers']['url'] = self::AEBNSURL . self::TRAILERURL . $movieid; - } + return $this->_res; + } - return $this->_res; - } + /** + * Gets the front and back cover of the box. + * + * @return array + */ + protected function covers() + { + $ret = $this->_html->find('div#md-boxCover, img[itemprop=thumbnailUrl]', 1); + if ($ret !== false) { + $ret = trim($ret->src); + if (strpos($ret, '//') === 0) { + $ret = 'http:'.$ret; + } + $this->_res['boxcover'] = str_ireplace('160w.jpg', 'xlf.jpg', $ret); + $this->_res['backcover'] = str_ireplace('160w.jpg', 'xlb.jpg', $ret); + } - /** - * Gets the front and back cover of the box - * - * @return array - */ - protected function covers() - { - $ret = $this->_html->find('div#md-boxCover, img[itemprop=thumbnailUrl]', 1); - if ($ret !== false) { - $ret = trim($ret->src); - if (strpos($ret, '//') === 0) { - $ret = 'http:' . $ret; - } - $this->_res['boxcover'] = str_ireplace('160w.jpg', 'xlf.jpg', $ret); - $this->_res['backcover'] = str_ireplace('160w.jpg', 'xlb.jpg', $ret); - } + return $this->_res; + } - return $this->_res; - } + /** + * Gets the Genres "Categories". + * + * @return array + */ + protected function genres() + { + if ($ret = $this->_html->find('div.md-detailsCategories', 0)) { + foreach ($ret->find('a[itemprop=genre]') as $genre) { + $this->_res['genres'][] = trim($genre->plaintext); + } + } + if (! empty($this->_res['genres'])) { + $this->_res['genres'] = array_unique($this->_res['genres']); + } - /** - * Gets the Genres "Categories". - * - * @return array - */ - protected function genres() - { - if ($ret = $this->_html->find('div.md-detailsCategories', 0)) { - foreach ($ret->find('a[itemprop=genre]') as $genre) { - $this->_res['genres'][] = trim($genre->plaintext); - } - } - if (!empty($this->_res['genres'])) { - $this->_res['genres'] = array_unique($this->_res['genres']); - } - return $this->_res; - } + return $this->_res; + } - /** - * Gets the Cast Members "Stars" and Director if any - * - * @return array - */ - protected function cast() - { - $this->_res = false; - if ($ret = $this->_html->find('div.starsFull', 0)) { - foreach ($ret->find('span[itemprop=name]') as $star) { - $this->_res['cast'][] = trim($star->plaintext); - } - } else { - if ($ret = $this->_html->find('div.detailsLink', 0)) { - foreach ($ret->find('span') as $star) { - if (strpos($star->plaintext, '/More/') !== false && strpos($star->plaintext, '/Stars/') !== false) { - $this->_res['cast'][] = trim($star->plaintext); - } - } - } - } + /** + * Gets the Cast Members "Stars" and Director if any. + * + * @return array + */ + protected function cast() + { + $this->_res = false; + if ($ret = $this->_html->find('div.starsFull', 0)) { + foreach ($ret->find('span[itemprop=name]') as $star) { + $this->_res['cast'][] = trim($star->plaintext); + } + } else { + if ($ret = $this->_html->find('div.detailsLink', 0)) { + foreach ($ret->find('span') as $star) { + if (strpos($star->plaintext, '/More/') !== false && strpos($star->plaintext, '/Stars/') !== false) { + $this->_res['cast'][] = trim($star->plaintext); + } + } + } + } - return $this->_res; - } + return $this->_res; + } - /** - * Gets the product information - * - * @param bool $extras - * - * @return array - */ - protected function productInfo($extras = false) - { - if ($ret = $this->_html->find('div#md-detailsLeft', 0)) { - foreach ($ret->find('div') as $div) { - foreach ($div->find('span') as $span) { - $span->plaintext = rawurldecode($span->plaintext); - $span->plaintext = preg_replace('/ /', '', $span->plaintext); - $this->_res['productinfo'][] = trim($span->plaintext); - } - } - if (false !== $key = array_search('Running Time:', $this->_res['productinfo'], false)) { - unset($this->_res['productinfo'][$key + 2]); - } - if (false !== $key = array_search('Director:' , $this->_res['productinfo'], false)) { - $this->_res['director'] = $this->_res['productinfo'][$key + 1]; - unset($this->_res['productinfo'][$key], $this->_res['productinfo'][$key + 1]); - } - $this->_res['productinfo'] = array_chunk($this->_res['productinfo'], 2, false); - } + /** + * Gets the product information. + * + * @param bool $extras + * + * @return array + */ + protected function productInfo($extras = false) + { + if ($ret = $this->_html->find('div#md-detailsLeft', 0)) { + foreach ($ret->find('div') as $div) { + foreach ($div->find('span') as $span) { + $span->plaintext = rawurldecode($span->plaintext); + $span->plaintext = preg_replace('/ /', '', $span->plaintext); + $this->_res['productinfo'][] = trim($span->plaintext); + } + } + if (false !== $key = array_search('Running Time:', $this->_res['productinfo'], false)) { + unset($this->_res['productinfo'][$key + 2]); + } + if (false !== $key = array_search('Director:', $this->_res['productinfo'], false)) { + $this->_res['director'] = $this->_res['productinfo'][$key + 1]; + unset($this->_res['productinfo'][$key], $this->_res['productinfo'][$key + 1]); + } + $this->_res['productinfo'] = array_chunk($this->_res['productinfo'], 2, false); + } - return $this->_res; - } + return $this->_res; + } - /** - * Gets the synopsis "plot" - * - * @return array - * - */ - protected function synopsis() - { - if ($ret = $this->_html->find('span[itemprop=about]', 0)) { - if ($ret === null) { - if ($ret = $this->_html->find('div.movieDetailDescription', 0)) { - $this->_res['synopsis'] = preg_replace('/Description:\s/', '', $this->_res['plot']); - } - } else { - $this->_res['synopsis'] = trim($ret->plaintext); - } - } + /** + * Gets the synopsis "plot". + * + * @return array + */ + protected function synopsis() + { + if ($ret = $this->_html->find('span[itemprop=about]', 0)) { + if ($ret === null) { + if ($ret = $this->_html->find('div.movieDetailDescription', 0)) { + $this->_res['synopsis'] = preg_replace('/Description:\s/', '', $this->_res['plot']); + } + } else { + $this->_res['synopsis'] = trim($ret->plaintext); + } + } - return $this->_res; - } + return $this->_res; + } - /** - * Searches for a XXX name - * - * @param string $movie - * - * @return bool - */ - public function processSite($movie): bool - { - if (empty($movie)) { - return false; - } - $this->_trailerUrl = self::TRAILINGSEARCH . urlencode($movie); - $this->_response = getRawHtml(self::AEBNSURL . $this->_trailerUrl, $this->cookie); - if ($this->_response !== false) { - $this->_html->load($this->_response); - $i = 1; - foreach ($this->_html->find('div.movie') as $mov) { - $string = 'a#FTSMovieSearch_link_title_detail_' . $i; - if ($ret = $mov->find($string, 0)) { - $title = str_replace('/XXX/', '', $ret->title); - $title = preg_replace('/\(.*?\)|[-._]/', ' ', $title); - $title = trim($title); - similar_text(strtolower($movie), strtolower($title), $p); - if ($p >= 90) { - $this->_title = trim($ret->title); - $this->_trailerUrl = html_entity_decode($ret->href); - $this->_directUrl = self::AEBNSURL . $this->_trailerUrl; - $this->_html->clear(); - unset($this->_response); - $this->_response = getRawHtml(self::AEBNSURL . $this->_trailerUrl, $this->cookie); - $this->_html->load($this->_response); + /** + * Searches for a XXX name. + * + * @param string $movie + * + * @return bool + */ + public function processSite($movie): bool + { + if (empty($movie)) { + return false; + } + $this->_trailerUrl = self::TRAILINGSEARCH.urlencode($movie); + $this->_response = getRawHtml(self::AEBNSURL.$this->_trailerUrl, $this->cookie); + if ($this->_response !== false) { + $this->_html->load($this->_response); + $i = 1; + foreach ($this->_html->find('div.movie') as $mov) { + $string = 'a#FTSMovieSearch_link_title_detail_'.$i; + if ($ret = $mov->find($string, 0)) { + $title = str_replace('/XXX/', '', $ret->title); + $title = preg_replace('/\(.*?\)|[-._]/', ' ', $title); + $title = trim($title); + similar_text(strtolower($movie), strtolower($title), $p); + if ($p >= 90) { + $this->_title = trim($ret->title); + $this->_trailerUrl = html_entity_decode($ret->href); + $this->_directUrl = self::AEBNSURL.$this->_trailerUrl; + $this->_html->clear(); + unset($this->_response); + $this->_response = getRawHtml(self::AEBNSURL.$this->_trailerUrl, $this->cookie); + $this->_html->load($this->_response); - return true; - } - continue; - } - $i++; - } - } + return true; + } + continue; + } + $i++; + } + } - return false; - } + return false; + } } diff --git a/nntmux/processing/adult/AdultMovies.php b/nntmux/processing/adult/AdultMovies.php index 82a4a6fcf..f029fe771 100644 --- a/nntmux/processing/adult/AdultMovies.php +++ b/nntmux/processing/adult/AdultMovies.php @@ -2,121 +2,120 @@ namespace nntmux\processing\adult; - abstract class AdultMovies { - /** - * @var \simple_html_dom - */ - protected $_html; + /** + * @var \simple_html_dom + */ + protected $_html; - /** - * @var string - */ - protected $_title; + /** + * @var string + */ + protected $_title; - /** - * @var string - */ - protected $_directUrl; + /** + * @var string + */ + protected $_directUrl; - /** - * AdultMovies constructor. - * - * @param array $options - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - $this->_html = new \simple_html_dom(); - } + /** + * AdultMovies constructor. + * + * @param array $options + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + $this->_html = new \simple_html_dom(); + } - /** - * @param bool $extras - * - * @return mixed - */ - abstract protected function productInfo($extras = false); + /** + * @param bool $extras + * + * @return mixed + */ + abstract protected function productInfo($extras = false); - /** - * @return mixed - */ - abstract protected function covers(); + /** + * @return mixed + */ + abstract protected function covers(); - /** - * @return mixed - */ - abstract protected function synopsis(); + /** + * @return mixed + */ + abstract protected function synopsis(); - /** - * @return mixed - */ - abstract protected function cast(); + /** + * @return mixed + */ + abstract protected function cast(); - /** - * @return mixed - */ - abstract protected function genres(); + /** + * @return mixed + */ + abstract protected function genres(); - /** - * @param string $movie - * - * @return mixed - */ - abstract public function processSite($movie); + /** + * @param string $movie + * + * @return mixed + */ + abstract public function processSite($movie); - /** - * @return mixed - */ - abstract protected function trailers(); + /** + * @return mixed + */ + abstract protected function trailers(); - /** - * Gets all information - * - * @return array|bool - */ - public function getAll() - { - $results = []; - if ($this->_directUrl !== null) { - $results['title'] = $this->_title; - $results['directurl'] = $this->_directUrl; - } + /** + * Gets all information. + * + * @return array|bool + */ + public function getAll() + { + $results = []; + if ($this->_directUrl !== null) { + $results['title'] = $this->_title; + $results['directurl'] = $this->_directUrl; + } - $dummy = $this->synopsis(); - if (is_array($dummy)) { - $results = array_merge($results, $dummy); - } + $dummy = $this->synopsis(); + if (is_array($dummy)) { + $results = array_merge($results, $dummy); + } - $dummy = $this->productInfo(true); - if (is_array($dummy)) { - $results = array_merge($results, $dummy); - } + $dummy = $this->productInfo(true); + if (is_array($dummy)) { + $results = array_merge($results, $dummy); + } - $dummy = $this->cast(); - if (is_array($dummy)) { - $results = array_merge($results, $dummy); - } + $dummy = $this->cast(); + if (is_array($dummy)) { + $results = array_merge($results, $dummy); + } - $dummy = $this->genres(); - if (is_array($dummy)) { - $results = array_merge($results, $dummy); - } + $dummy = $this->genres(); + if (is_array($dummy)) { + $results = array_merge($results, $dummy); + } - $dummy = $this->covers(); - if (is_array($dummy)) { - $results = array_merge($results, $dummy); - } + $dummy = $this->covers(); + if (is_array($dummy)) { + $results = array_merge($results, $dummy); + } - $dummy = $this->trailers(); - if (is_array($dummy)) { - $results = array_merge($results, $dummy); - } - if (empty($results)) { - return false; - } + $dummy = $this->trailers(); + if (is_array($dummy)) { + $results = array_merge($results, $dummy); + } + if (empty($results)) { + return false; + } - return $results; - } -} \ No newline at end of file + return $results; + } +} diff --git a/nntmux/processing/adult/Hotmovies.php b/nntmux/processing/adult/Hotmovies.php index 7bdec6028..ce5cb34c4 100755 --- a/nntmux/processing/adult/Hotmovies.php +++ b/nntmux/processing/adult/Hotmovies.php @@ -4,267 +4,264 @@ namespace nntmux\processing\adult; class Hotmovies extends AdultMovies { + /** + * Constant Urls used within this class + * Needed Search Queries Variables. + */ + const EXTRASEARCH = '&complete=on&search_in=video_title'; + const HMURL = 'http://www.hotmovies.com'; + const IF18 = true; + const TRAILINGSEARCH = '/search.php?words='; + /** + * Keyword Search. + * + * @var string + */ + protected $searchTerm = ''; + /** + * Define a cookie location. + * + * @var string + */ + public $cookie = ''; + /** + * If a direct link is set parse it instead of search for it. + * + * @var string + */ + protected $directLink = ''; + /** + * Sets the direct url in the getAll method. + * + * @var string + */ + protected $_directUrl = ''; - /** - * Constant Urls used within this class - * Needed Search Queries Variables - */ - const EXTRASEARCH = '&complete=on&search_in=video_title'; - const HMURL = 'http://www.hotmovies.com'; - const IF18 = true; - const TRAILINGSEARCH = '/search.php?words='; - /** - * Keyword Search. - * - * @var string - */ - protected $searchTerm = ''; - /** - * Define a cookie location - * - * @var string - */ - public $cookie = ''; - /** - * If a direct link is set parse it instead of search for it. - * - * @var string - */ - protected $directLink = ''; - /** - * Sets the direct url in the getAll method - * - * @var string - */ - protected $_directUrl = ''; + /** + * Sets the link to get in curl. + * + * @var string + */ + protected $_getLink = ''; - /** - * Sets the link to get in curl - * - * @var string - */ - protected $_getLink = ''; + /** + * POST parameters used with curl. + * + * @var array + */ + protected $_postParams = []; - /** - * POST parameters used with curl - * - * @var array - */ - protected $_postParams = []; + /** + * Results return from some methods. + * + * @var array + */ + protected $_res = []; - /** - * Results return from some methods - * - * @var array - */ - protected $_res = []; + /** + * Raw Html from Curl. + */ + protected $_response; - /** - * Raw Html from Curl - * - */ - protected $_response; + /** + * Sets the title in the getAll method. + * + * @var string + */ + protected $_title = ''; - /** - * Sets the title in the getAll method - * - * @var string - */ - protected $_title = ''; + /** + * Hotmovies constructor. + * + * @param array $options + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + parent::__construct($options); + } - /** - * Hotmovies constructor. - * - * @param array $options - * - * @throws \Exception - */ - public function __construct(array $options = []) - { - parent::__construct($options); - } + protected function trailers() + { + // TODO: Implement trailers() method. - protected function trailers() - { - // TODO: Implement trailers() method. + return false; + } - return false; - } + /** + * Gets the synopsis. + * + * @return array + */ + protected function synopsis(): array + { + $this->_res['synopsis'] = 'N/A'; + if ($this->_html->find('.desc_link', 0)) { + $ret = $this->_html->find('.video_description', 0); + if ($ret !== false) { + $this->_res['synopsis'] = trim($ret->innertext); + } + } - /** - * Gets the synopsis - * - * @return array - */ - protected function synopsis(): array - { - $this->_res['synopsis'] = 'N/A'; - if ($this->_html->find('.desc_link', 0)) { - $ret = $this->_html->find('.video_description', 0); - if ($ret !== false) { - $this->_res['synopsis'] = trim($ret->innertext); - } - } + return $this->_res; + } - return $this->_res; - } + /**Process ProductInfo + * + * @param bool $extras + * + * @return array + */ + protected function productInfo($extras = false): array + { + $studio = false; + $director = false; + if ($ret = $this->_html->find('div.page_video_info', 0)) { + foreach ($ret->find('text') as $e) { + $e = trim($e->innertext); + $rArray = [',', '...', ' :']; + $e = str_replace($rArray, '', $e); + if (stripos($e, 'Studio:') !== false) { + $studio = true; + } + if (strpos($e, 'Director:') !== false) { + $director = true; + $e = null; + } + if ($studio === true) { + if (stripos($e, 'Custodian of Records') === false) { + if (stripos($e, 'Description') === false) { + if ($director === true && ! empty($e)) { + $this->_res['director'] = $e; + $e = null; + $director = false; + } + if (! empty($e)) { + $this->_res['productinfo'][] = $e; + } + } else { + break; + } + } else { + break; + } + } + } + } + if (is_array($this->_res['productinfo'])) { + $this->_res['productinfo'] = array_chunk($this->_res['productinfo'], 2, false); + } - /**Process ProductInfo - * - * @param bool $extras - * - * @return array - */ - protected function productInfo($extras = false): array - { - $studio = false; - $director = false; - if ($ret = $this->_html->find('div.page_video_info', 0)) { - foreach ($ret->find('text') as $e) { - $e = trim($e->innertext); - $rArray = [',', '...', ' :']; - $e = str_replace($rArray, '', $e); - if (stripos($e, 'Studio:') !== false) { - $studio = true; - } - if (strpos($e, 'Director:') !== false) { - $director = true; - $e = null; - } - if ($studio === true) { - if (stripos($e, 'Custodian of Records') === false) { - if (stripos($e, 'Description') === false) { + return $this->_res; + } - if ($director === true && !empty($e)) { - $this->_res['director'] = $e; - $e = null; - $director = false; - } - if (!empty($e)) { - $this->_res['productinfo'][] = $e; - } - } else { - break; - } - } else { - break; - } - } - } - } - if (is_array($this->_res['productinfo'])) { - $this->_res['productinfo'] = array_chunk($this->_res['productinfo'], 2, false); - } + /** + * Gets the cast members and director. + * + * @return array + */ + protected function cast() + { + $cast = []; + if ($this->_html->find('.stars bottom_margin')) { + file_put_contents('hm_cast.txt', $this->_html->find('.stars bottom_margin')); + foreach ($this->_html->find('a[title]') as $e) { + $e = trim($e->title); + $e = preg_replace('/\((.*)\)/', '', $e); + $cast[] = trim($e); + } + $this->_res['cast'] = $cast; + } - return $this->_res; - } + return $this->_res; + } - /** - * Gets the cast members and director - * - * @return array - */ - protected function cast() - { - $cast = []; - if ($this->_html->find('.stars bottom_margin')) { - file_put_contents('hm_cast.txt', $this->_html->find('.stars bottom_margin')); - foreach ($this->_html->find('a[title]') as $e) { - $e = trim($e->title); - $e = preg_replace('/\((.*)\)/', '', $e); - $cast[] = trim($e); - } - $this->_res['cast'] = $cast; + /** + * Gets categories. + * + * @return array + */ + protected function genres() + { + $genres = []; + if ($ret = $this->_html->find('div.categories', 0)) { + foreach ($ret->find('a') as $e) { + if (strpos($e->title, ' -> ') !== false) { + $e = explode(' -> ', $e->plaintext); + $genres[] = trim($e[1]); + } + } + $this->_res['genres'] = $genres; + } - } + return $this->_res; + } - return $this->_res; - } + /** + * Get Box Cover Images. + * @return bool|array - boxcover,backcover + */ + protected function covers() + { + if ($ret = $this->_html->find('div#large_cover, img#cover', 1)) { + $this->_res['boxcover'] = trim($ret->src); + $this->_res['backcover'] = str_ireplace('.cover', '.back', trim($ret->src)); + } else { + return false; + } - /** - * Gets categories - * - * @return array - */ - protected function genres() - { - $genres = []; - if ($ret = $this->_html->find('div.categories',0)) { - foreach ($ret->find('a') as $e) { - if (strpos($e->title, ' -> ') !== false) { - $e = explode(' -> ',$e->plaintext); - $genres[] = trim($e[1]); - } - } - $this->_res['genres'] = $genres; - } - return $this->_res; - } + return $this->_res; + } - /** - * Get Box Cover Images - * @return bool|array - boxcover,backcover - */ - protected function covers() - { - if ($ret = $this->_html->find('div#large_cover, img#cover', 1)) { - $this->_res['boxcover'] = trim($ret->src); - $this->_res['backcover'] = str_ireplace('.cover', '.back', trim($ret->src)); - } else { - return false; - } + /** + * Searches for match against xxx movie name. + * + * @param string $movie + * + * @return bool , true if search >= 90% + */ + public function processSite($movie): bool + { + if (empty($movie)) { + return false; + } + $this->_response = false; + $this->_getLink = self::HMURL.self::TRAILINGSEARCH.urlencode($movie).self::EXTRASEARCH; + $this->_response = getRawHtml($this->_getLink, $this->cookie); + if ($this->_response !== false) { + $this->_html->load($this->_response); + if ($ret = $this->_html->find('h3[class=title]', 0)) { + if ($ret->find('a[title]', 0)) { + $ret = $ret->find('a[title]', 0); + $title = trim($ret->title); + $title = str_replace('/XXX/', '', $title); + $title = preg_replace('/\(.*?\)|[-._]/', ' ', $title); + if (! empty($title)) { + similar_text($movie, $title, $p); + if ($p >= 90) { + $this->_title = $title; + $this->_getLink = trim($ret->href); + $this->_directUrl = trim($ret->href); + $this->_html->clear(); + unset($this->_response); + if ($this->_getLink !== false) { + $this->_response = getRawHtml($this->_getLink, $this->cookie); + $this->_html->load($this->_response); + } else { + $this->_response = getRawHtml($this->_directUrl, $this->cookie); + $this->_html->load($this->_response); + } - return $this->_res; - } + return true; + } + } + } + } + } else { + return false; + } - /** - * Searches for match against xxx movie name - * - * @param string $movie - * - * @return bool , true if search >= 90% - */ - public function processSite($movie): bool - { - if (empty($movie)) { - return false; - } - $this->_response = false; - $this->_getLink = self::HMURL . self::TRAILINGSEARCH . urlencode($movie) . self::EXTRASEARCH; - $this->_response = getRawHtml($this->_getLink, $this->cookie); - if ($this->_response !== false) { - $this->_html->load($this->_response); - if ($ret = $this->_html->find('h3[class=title]', 0)) { - if ($ret->find('a[title]', 0)) { - $ret = $ret->find('a[title]', 0); - $title = trim($ret->title); - $title = str_replace('/XXX/', '', $title); - $title = preg_replace('/\(.*?\)|[-._]/', ' ', $title); - if (!empty($title)) { - similar_text($movie, $title, $p); - if ($p >= 90) { - $this->_title = $title; - $this->_getLink = trim($ret->href); - $this->_directUrl = trim($ret->href); - $this->_html->clear(); - unset($this->_response); - if ($this->_getLink !== false) { - $this->_response = getRawHtml($this->_getLink, $this->cookie); - $this->_html->load($this->_response); - } else { - $this->_response = getRawHtml($this->_directUrl, $this->cookie); - $this->_html->load($this->_response); - } - - return true; - } - } - } - } - } else { - return false; - } - - return false; - } + return false; + } } diff --git a/nntmux/processing/adult/Popporn.php b/nntmux/processing/adult/Popporn.php index 2fcf19403..26e396995 100755 --- a/nntmux/processing/adult/Popporn.php +++ b/nntmux/processing/adult/Popporn.php @@ -4,324 +4,323 @@ namespace nntmux\processing\adult; class Popporn extends AdultMovies { + /** + * Define a cookie file location for curl. + * + * @var string string + */ + public $cookie = ''; - /** - * Define a cookie file location for curl - * - * @var string string - */ - public $cookie = ''; + /** + * Set this for what you are searching for. + * + * @var string + */ + protected $searchTerm = ''; - /** - * Set this for what you are searching for. - * - * @var string - */ - protected $searchTerm = ''; + /** + * Override if 18 years+ or older + * Define Popporn url + * Needed Search Queries Constant. + */ + const IF18 = 'http://www.popporn.com/popporn/4'; + const POPURL = 'http://www.popporn.com'; + const TRAILINGSEARCH = '/results/index.cfm?v=4&g=0&searchtext='; - /** - * Override if 18 years+ or older - * Define Popporn url - * Needed Search Queries Constant - */ - const IF18 = 'http://www.popporn.com/popporn/4'; - const POPURL = 'http://www.popporn.com'; - const TRAILINGSEARCH = '/results/index.cfm?v=4&g=0&searchtext='; + /** + * Sets the directurl for the return results array. + * + * @var string + */ + protected $_directUrl = ''; - /** - * Sets the directurl for the return results array - * - * @var string - */ - protected $_directUrl = ''; + /** + * Curl Raw Html. + */ + protected $_response; - /** - * Curl Raw Html - */ - protected $_response; + /** + * Results returned from each method. + * + * @var array + */ + protected $_res = []; - /** - * Results returned from each method - * - * @var array - */ - protected $_res = []; + /** + * This is set in the getAll method. + * + * @var string + */ + protected $_title = ''; - /** - * This is set in the getAll method - * - * @var string - */ - protected $_title = ''; + /** + * Add this to popurl to get results. + * + * @var string + */ + protected $_trailUrl = ''; - /** - * Add this to popurl to get results - * - * @var string - */ - protected $_trailUrl = ''; + public function __construct(array $options = []) + { + parent::__construct($options); + } - public function __construct(array $options = []) - { - parent::__construct($options); - } + /** + * Get Box Cover Images. + * + * @return array - boxcover,backcover + */ + protected function covers(): array + { + if ($ret = $this->_html->find('div[id=box-art], a[rel=box-art]', 1)) { + $this->_res['boxcover'] = trim($ret->href); + if (false !== stripos(trim($ret->href), '_aa')) { + $this->_res['backcover'] = str_ireplace('_aa', '_bb', trim($ret->href)); + } else { + $this->_res['backcover'] = str_ireplace('.jpg', '_b.jpg', trim($ret->href)); + } + } else { + if ($ret = $this->_html->find('img.front', 0)) { + $this->_res['boxcover'] = $ret->src; + } + if ($ret = $this->_html->find('img.back', 0)) { + $this->_res['backcover'] = $ret->src; + } + } - /** - * Get Box Cover Images - * - * @return array - boxcover,backcover - */ - protected function covers(): array - { - if ($ret = $this->_html->find('div[id=box-art], a[rel=box-art]', 1)) { - $this->_res['boxcover'] = trim($ret->href); - if (false !== stripos(trim($ret->href), '_aa')) { - $this->_res['backcover'] = str_ireplace('_aa', '_bb', trim($ret->href)); - } else { - $this->_res['backcover'] = str_ireplace('.jpg', '_b.jpg', trim($ret->href)); - } - } else { - if ($ret = $this->_html->find('img.front', 0)) { - $this->_res['boxcover'] = $ret->src; - } - if ($ret = $this->_html->find('img.back', 0)) { - $this->_res['backcover'] = $ret->src; - } - } + return $this->_res; + } - return $this->_res; - } + /** + * Gets the synopsis. + * + * @return array|bool + */ + protected function synopsis() + { + if ($ret = $this->_html->find('div[id=product-info] ,h3[class=highlight]', 1)) { + if ($ret->next_sibling()->plaintext) { + if (stripos(trim($ret->next_sibling()->plaintext), 'POPPORN EXCLUSIVE') === false) { + $this->_res['synopsis'] = trim($ret->next_sibling()->plaintext); + } else { + if ($ret->next_sibling()->next_sibling()) { + $this->_res['synopsis'] = trim($ret->next_sibling()->next_sibling()->next_sibling()->plaintext); + } else { + $this->_res['synopsis'] = 'N/A'; + } + } + } + } - /** - * Gets the synopsis - * - * @return array|bool - */ - protected function synopsis() - { - if ($ret = $this->_html->find('div[id=product-info] ,h3[class=highlight]', 1)) { - if ($ret->next_sibling()->plaintext) { - if (stripos(trim($ret->next_sibling()->plaintext), 'POPPORN EXCLUSIVE') === false) { - $this->_res['synopsis'] = trim($ret->next_sibling()->plaintext); - } else { - if ($ret->next_sibling()->next_sibling()) { - $this->_res['synopsis'] = trim($ret->next_sibling()->next_sibling()->next_sibling()->plaintext); - } else { - $this->_res['synopsis'] = 'N/A'; - } - } - } - } + return $this->_res; + } - return $this->_res; - } + /** + * Gets trailer video. + * + * @return array|bool + */ + protected function trailers() + { + if ($ret = $this->_html->find('input#thickbox-trailer-link', 0)) { + $ret->value = trim($ret->value); + $ret->value = str_replace('..', '', $ret->value); + $tmprsp = $this->_response; + $this->_trailUrl = $ret->value; + if (preg_match_all('/productID="\+(?<id>[0-9]+),/', $this->_response, $matches)) { + $productid = $matches['id'][0]; + $random = ((float) mt_rand() / (float) mt_getrandmax()) * 5400000000000000; + $this->_trailUrl = '/com/tlavideo/vod/FlvAjaxSupportService.cfc?random='.$random; + $this->_postParams = 'method=pipeStreamLoc&productID='.$productid; + $ret = json_decode(json_decode($this->_response, true), true); + $this->_res['trailers']['baseurl'] = self::POPURL.'/flashmediaserver/trailerPlayer.swf'; + $this->_res['trailers']['flashvars'] = 'subscribe=false&image=&file='.self::POPURL.'/'.$ret['LOC'].'&autostart=false'; + unset($this->_response); + $this->_response = $tmprsp; + } + } - /** - * Gets trailer video - * - * @return array|bool - */ - protected function trailers() - { - if ($ret = $this->_html->find('input#thickbox-trailer-link', 0)) { - $ret->value = trim($ret->value); - $ret->value = str_replace('..', '', $ret->value); - $tmprsp = $this->_response; - $this->_trailUrl = $ret->value; - if (preg_match_all('/productID="\+(?<id>[0-9]+),/', $this->_response, $matches)) { - $productid = $matches['id'][0]; - $random = ((float)mt_rand() / (float)mt_getrandmax()) * 5400000000000000; - $this->_trailUrl = '/com/tlavideo/vod/FlvAjaxSupportService.cfc?random=' . $random; - $this->_postParams = 'method=pipeStreamLoc&productID=' . $productid; - $ret = json_decode(json_decode($this->_response, true), true); - $this->_res['trailers']['baseurl'] = self::POPURL . '/flashmediaserver/trailerPlayer.swf'; - $this->_res['trailers']['flashvars'] = 'subscribe=false&image=&file=' . self::POPURL . '/' . $ret['LOC'] . '&autostart=false'; - unset($this->_response); - $this->_response = $tmprsp; - } - } + return $this->_res; + } - return $this->_res; - } + /** + * Process ProductInfo And/or Extras. + * + * @param bool $extras + * + * @return array|bool + */ + protected function productInfo($extras = false) + { + $country = false; + if ($ret = $this->_html->find('div#lside', 0)) { + foreach ($ret->find('text') as $e) { + $e = trim($e->innertext); + $e = str_replace([', ', '...', ' '], '', $e); + if (stripos($e, 'Country:') !== false) { + $country = true; + } + if ($country === true) { + if (stripos($e, 'addthis_config') === false) { + if (! empty($e)) { + $this->_res['productinfo'][] = $e; + } + } else { + break; + } + } + } + } - /** - * Process ProductInfo And/or Extras - * - * @param bool $extras - * - * @return array|bool - */ - protected function productInfo($extras = false) - { - $country = false; - if ($ret = $this->_html->find('div#lside', 0)) { - foreach ($ret->find("text") as $e) { - $e = trim($e->innertext); - $e = str_replace([', ', '...', ' '], '', $e); - if (stripos($e, 'Country:') !== false) { - $country = true; - } - if ($country === true) { - if (stripos($e, 'addthis_config') === false) { - if (!empty($e)) { - $this->_res['productinfo'][] = $e; - } - } else { - break; - } - } - } - } + $this->_res['productinfo'] = array_chunk($this->_res['productinfo'], 2, false); - $this->_res['productinfo'] = array_chunk($this->_res['productinfo'], 2, false); + if ($extras === true) { + $features = false; + if ($this->_html->find('ul.stock-information', 0)) { + foreach ($this->_html->find('ul.stock-information') as $ul) { + foreach ($ul->find('li') as $e) { + $e = trim($e->plaintext); + if ($e === 'Features:') { + $features = true; + $e = null; + } + if ($features === true) { + if (! empty($e)) { + $this->_res['extras'][] = $e; + } + } + } + } + } + } - if ($extras === true) { - $features = false; - if ($this->_html->find('ul.stock-information', 0)) { - foreach ($this->_html->find('ul.stock-information') as $ul) { - foreach ($ul->find('li') as $e) { - $e = trim($e->plaintext); - if ($e === 'Features:') { - $features = true; - $e = null; - } - if ($features === true) { - if (!empty($e)) { - $this->_res['extras'][] = $e; - } - } - } - } - } - } + return $this->_res; + } - return $this->_res; - } + /** + * Gets the cast members and director. + * + * @return array|bool + */ + protected function cast() + { + $cast = false; + $director = false; + $er = []; + if ($ret = $this->_html->find('div#lside', 0)) { + foreach ($ret->find('text') as $e) { + $e = trim($e->innertext); + $e = str_replace(',', '', $e); + $e = str_replace(' ', '', $e); + if (stripos($e, 'Cast') !== false) { + $cast = true; + } + $e = str_replace('Cast:', '', $e); + if ($cast === true) { + if (stripos($e, 'Director:') !== false) { + $director = true; + $e = null; + } - /** - * Gets the cast members and director - * - * @return array|bool - */ - protected function cast() - { - $cast = false; - $director = false; - $er = []; - if ($ret = $this->_html->find('div#lside', 0)) { - foreach ($ret->find('text') as $e) { - $e = trim($e->innertext); - $e = str_replace(',', '', $e); - $e = str_replace(' ', '', $e); - if (stripos($e, 'Cast') !== false) { - $cast = true; - } - $e = str_replace('Cast:', '', $e); - if ($cast === true) { - if (stripos($e, 'Director:') !== false) { - $director = true; - $e = null; - } + if ($director === true) { + if (! empty($e)) { + $this->_res['director'] = $e; + $director = false; + $e = null; + } + } + if (stripos($e, 'Country:') === false) { + if (! empty($e)) { + $er[] = $e; + } + } else { + break; + } + } + } + } + $this->_res['cast'] = $er; - if ($director === true) { - if (!empty($e)) { - $this->_res['director'] = $e; - $director = false; - $e = null; - } - } - if (stripos($e, 'Country:') === false) { - if (!empty($e)) { - $er[] = $e; - } - } else { - break; - } - } - } - } - $this->_res['cast'] = $er; + return $this->_res; + } - return $this->_res; - } + /** + * Gets categories. + * + * @return array + */ + protected function genres() + { + $genres = []; + if ($ret = $this->_html->find('div[id=thekeywords], p[class=keywords]', 1)) { + foreach ($ret->find('a') as $e) { + $genres[] = trim($e->plaintext); + } + } + $this->_res['genres'] = $genres; - /** - * Gets categories - * - * @return array - */ - protected function genres() - { - $genres = []; - if ($ret = $this->_html->find('div[id=thekeywords], p[class=keywords]', 1)) { - foreach ($ret->find('a') as $e) { - $genres[] = trim($e->plaintext); - } - } - $this->_res['genres'] = $genres; + return $this->_res; + } - return $this->_res; - } + /** + * Searches for match against searchterm. + * + * @param string $movie + * + * @return bool , true if search >= 90% + */ + public function processSite($movie): bool + { + if (! empty($movie)) { + $this->_trailUrl = self::TRAILINGSEARCH.$movie; + $this->_response = getRawHtml(self::POPURL.$this->_trailUrl, $this->cookie); + if ($this->_response !== false) { + $this->_html->load($this->_response); + if ($ret = $this->_html->find('div.product-info, div.title', 1)) { + $this->_title = trim($ret->plaintext); + $title = str_replace('XXX', '', $ret->plaintext); + $title = preg_replace('/\(.*?\)|[-._]/i', ' ', $title); + $title = trim($title); + similar_text(strtolower($movie), strtolower($title), $p); + if ($p >= 90) { + if ($ret = $ret->find('a', 0)) { + $this->_trailUrl = trim($ret->href); + $this->_html->clear(); + unset($this->_response); + $this->_response = getRawHtml(self::POPURL.$this->_trailUrl, $this->cookie); + if ($this->_response !== false) { + $this->_html->load($this->_response); + if ($ret = $this->_html->find('#link-to-this', 0)) { + $this->_directUrl = trim($ret->href); + $this->_html->clear(); + unset($this->_response); + $this->_response = getRawHtml($this->_directUrl, $this->cookie); + $this->_html->load($this->_response); - /** - * Searches for match against searchterm - * - * @param string $movie - * - * @return bool , true if search >= 90% - */ - public function processSite($movie): bool - { - if (!empty($movie)) { - $this->_trailUrl = self::TRAILINGSEARCH . $movie; - $this->_response = getRawHtml(self::POPURL . $this->_trailUrl, $this->cookie); - if ($this->_response !== false) { - $this->_html->load($this->_response); - if ($ret = $this->_html->find('div.product-info, div.title', 1)) { - $this->_title = trim($ret->plaintext); - $title = str_replace('XXX', '', $ret->plaintext); - $title = preg_replace('/\(.*?\)|[-._]/i', ' ', $title); - $title = trim($title); - similar_text(strtolower($movie), strtolower($title), $p); - if ($p >= 90) { - if ($ret = $ret->find('a', 0)) { - $this->_trailUrl = trim($ret->href); - $this->_html->clear(); - unset($this->_response); - $this->_response = getRawHtml(self::POPURL . $this->_trailUrl, $this->cookie); - if ($this->_response !== false) { - $this->_html->load($this->_response); - if ($ret = $this->_html->find('#link-to-this', 0)) { - $this->_directUrl = trim($ret->href); - $this->_html->clear(); - unset($this->_response); - $this->_response = getRawHtml($this->_directUrl, $this->cookie); - $this->_html->load($this->_response); + return true; + } - return true; - } + return false; + } + } - return false; - } - } + return true; + } + } + } else { + $this->_response = getRawHtml(self::IF18, $this->cookie); + if ($this->_response !== false) { + $this->_html->load($this->_response); - return true; - } - } - } else { - $this->_response = getRawHtml(self::IF18, $this->cookie); - if ($this->_response !== false) { - $this->_html->load($this->_response); + return true; + } - return true; - } + return false; + } - return false; - } + return false; + } - return false; - } - - return false; - } + return false; + } } diff --git a/nntmux/processing/post/AniDB.php b/nntmux/processing/post/AniDB.php index 49b55fe66..1f8759818 100755 --- a/nntmux/processing/post/AniDB.php +++ b/nntmux/processing/post/AniDB.php @@ -2,71 +2,71 @@ namespace nntmux\processing\post; -use App\Models\Settings; -use nntmux\Category; -use nntmux\ColorCLI; use nntmux\NZB; use nntmux\db\DB; +use nntmux\Category; +use nntmux\ColorCLI; +use App\Models\Settings; use nntmux\db\populate\AniDB as PaDb; class AniDB { - const PROC_EXTFAIL = -1; // Release Anime title/episode # could not be extracted from searchname + const PROC_EXTFAIL = -1; // Release Anime title/episode # could not be extracted from searchname const PROC_NOMATCH = -2; // AniDB ID was not found in anidb table using extracted title/episode # const REGEX_NOFORN = 'English|Japanese|German|Danish|Flemish|Dutch|French|Swe(dish|sub)|Deutsch|Norwegian'; - /** - * @var bool Whether or not to echo messages to CLI - */ - public $echooutput; + /** + * @var bool Whether or not to echo messages to CLI + */ + public $echooutput; - /** - * @var PaDb - */ - public $padb; + /** + * @var PaDb + */ + public $padb; - /** - * @var DB - */ - public $pdo; + /** + * @var DB + */ + public $pdo; - /** - * @var int number of AniDB releases to process - */ - private $aniqty; + /** + * @var int number of AniDB releases to process + */ + private $aniqty; - /** - * @var int The status of the release being processed - */ - private $status; + /** + * @var int The status of the release being processed + */ + private $status; - /** - * @param array $options Class instances / Echo to cli. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * @param array $options Class instances / Echo to cli. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Settings' => null, ]; - $options += $defaults; + $options += $defaults; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $qty = Settings::value('..maxanidbprocessed'); - $this->aniqty = $qty ?? 100; + $qty = Settings::value('..maxanidbprocessed'); + $this->aniqty = $qty ?? 100; - $this->status = 'NULL'; - } + $this->status = 'NULL'; + } - /** - * Queues anime releases for processing - */ - public function processAnimeReleases(): void - { - $results = $this->pdo->queryDirect( + /** + * Queues anime releases for processing. + */ + public function processAnimeReleases(): void + { + $results = $this->pdo->queryDirect( sprintf(' SELECT searchname, id FROM releases @@ -81,21 +81,20 @@ class AniDB ) ); - if ($results instanceof \Traversable) { + if ($results instanceof \Traversable) { + $this->doRandomSleep(); - $this->doRandomSleep(); - - $this->padb = new PaDb( + $this->padb = new PaDb( [ 'Echo' => $this->echooutput, - 'Settings' => $this->pdo + 'Settings' => $this->pdo, ] ); - foreach ($results as $release) { - $matched = $this->matchAnimeRelease($release); - if ($matched === false) { - $this->pdo->queryExec( + foreach ($results as $release) { + $matched = $this->matchAnimeRelease($release); + if ($matched === false) { + $this->pdo->queryExec( sprintf(' UPDATE releases SET anidbid = %d @@ -104,24 +103,24 @@ class AniDB $release['id'] ) ); - } - } - } else { - ColorCLI::doEcho(ColorCLI::info('No anidb releases to process.'), true); - } - } + } + } + } else { + ColorCLI::doEcho(ColorCLI::info('No anidb releases to process.'), true); + } + } - /** - * Selects episode info for a local match - * - * @param int $anidbId - * @param int $episode - * - * @return array|bool - */ - private function checkAniDBInfo($anidbId, $episode = -1) - { - return $this->pdo->queryOneRow( + /** + * Selects episode info for a local match. + * + * @param int $anidbId + * @param int $episode + * + * @return array|bool + */ + private function checkAniDBInfo($anidbId, $episode = -1) + { + return $this->pdo->queryOneRow( sprintf(' SELECT ae.anidbid, ae.episode_no, ae.airdate, ae.episode_title @@ -132,67 +131,67 @@ class AniDB $episode ) ); - } + } - /** - * Sleeps between 10 and 15 seconds for AniDB API cooldown - */ - private function doRandomSleep(): void - { - sleep(random_int(10, 15)); - } + /** + * Sleeps between 10 and 15 seconds for AniDB API cooldown. + */ + private function doRandomSleep(): void + { + sleep(random_int(10, 15)); + } - /** - * Extracts anime title and episode info from release searchname - * - * @param string $cleanName - * - * @return array $matches - */ - private function extractTitleEpisode($cleanName = ''): array - { - $cleanName = str_replace('_', ' ', $cleanName); + /** + * Extracts anime title and episode info from release searchname. + * + * @param string $cleanName + * + * @return array $matches + */ + private function extractTitleEpisode($cleanName = ''): array + { + $cleanName = str_replace('_', ' ', $cleanName); - if (preg_match('/(^|.*\")(\[[a-zA-Z\.\!?-]+\][\s_]*)?(\[BD\][\s_]*)?(\[\d{3,4}[ip]\][\s_]*)?(?P<title>[\w\s_.+!?\'-\(\)]+)(New Edit|(Blu-?ray)?( ?Box)?( ?Set)?)?([ _]-[ _]|([ ._-]Epi?(sode)?[ ._-]?0?)?[ ._-]?|[ ._-]Vol\.|[ ._-]E)(?P<epno>\d{1,3}|Movie|OVA|Complete Series)(v\d|-\d+)?[-_. ].*[\[\(\"]/i', + if (preg_match('/(^|.*\")(\[[a-zA-Z\.\!?-]+\][\s_]*)?(\[BD\][\s_]*)?(\[\d{3,4}[ip]\][\s_]*)?(?P<title>[\w\s_.+!?\'-\(\)]+)(New Edit|(Blu-?ray)?( ?Box)?( ?Set)?)?([ _]-[ _]|([ ._-]Epi?(sode)?[ ._-]?0?)?[ ._-]?|[ ._-]Vol\.|[ ._-]E)(?P<epno>\d{1,3}|Movie|OVA|Complete Series)(v\d|-\d+)?[-_. ].*[\[\(\"]/i', $cleanName, $matches) ) { - $matches['epno'] = (int)$matches['epno']; - if (in_array($matches['epno'], ['Movie', 'OVA'], false)) { - $matches['epno'] = 1; - } - } else if (preg_match('/^(\[[a-zA-Z\.\-!?]+\][\s_]*)?(\[BD\])?(\[\d{3,4}[ip]\])?(?P<title>[\w\s_.+!?\'-\(\)]+)(New Edit|(Blu-?ray)?( ?Box)?( ?Set)?)?\s*[\(\[](BD|\d{3,4}[ipx])/i', + $matches['epno'] = (int) $matches['epno']; + if (in_array($matches['epno'], ['Movie', 'OVA'], false)) { + $matches['epno'] = 1; + } + } elseif (preg_match('/^(\[[a-zA-Z\.\-!?]+\][\s_]*)?(\[BD\])?(\[\d{3,4}[ip]\])?(?P<title>[\w\s_.+!?\'-\(\)]+)(New Edit|(Blu-?ray)?( ?Box)?( ?Set)?)?\s*[\(\[](BD|\d{3,4}[ipx])/i', $cleanName, $matches) ) { - $matches['epno'] = 1; - } else { - if (NN_DEBUG) { - ColorCLI::doEcho( - PHP_EOL . "Could not parse searchname {$cleanName}.", + $matches['epno'] = 1; + } else { + if (NN_DEBUG) { + ColorCLI::doEcho( + PHP_EOL."Could not parse searchname {$cleanName}.", true ); - } - $this->status = self::PROC_EXTFAIL; - } + } + $this->status = self::PROC_EXTFAIL; + } - if (!empty($matches['title'])) { - $matches['title'] = trim(str_replace(['_', '.'], ' ', $matches['title'])); - } + if (! empty($matches['title'])) { + $matches['title'] = trim(str_replace(['_', '.'], ' ', $matches['title'])); + } - return $matches; - } + return $matches; + } - /** - * Retrieves AniDB Info using a cleaned name - * - * @param string $searchName - * - * @return array|bool - */ - private function getAnidbByName($searchName = '') - { - return $this->pdo->queryOneRow( + /** + * Retrieves AniDB Info using a cleaned name. + * + * @param string $searchName + * + * @return array|bool + */ + private function getAnidbByName($searchName = '') + { + return $this->pdo->queryOneRow( sprintf(' SELECT at.anidbid, at.title FROM anidb_titles AS at @@ -200,90 +199,88 @@ class AniDB $this->pdo->likeString($searchName, true, true) ) ); - } + } - /** - * Matches the anime release to AniDB Info - * If no info is available locally the AniDB API is invoked - * - * @param array $release - * - * @return bool - */ - private function matchAnimeRelease(array $release = []): bool - { - $matched = false; - $type = 'Local'; + /** + * Matches the anime release to AniDB Info + * If no info is available locally the AniDB API is invoked. + * + * @param array $release + * + * @return bool + */ + private function matchAnimeRelease(array $release = []): bool + { + $matched = false; + $type = 'Local'; - // clean up the release name to ensure we get a good chance at getting a valid title - $cleanArr = $this->extractTitleEpisode($release['searchname']); + // clean up the release name to ensure we get a good chance at getting a valid title + $cleanArr = $this->extractTitleEpisode($release['searchname']); - if (is_array($cleanArr) && isset($cleanArr['title']) && is_numeric($cleanArr['epno'])) { + if (is_array($cleanArr) && isset($cleanArr['title']) && is_numeric($cleanArr['epno'])) { + echo ColorCLI::header(PHP_EOL.'Looking Up: '). + ColorCLI::primary(' Title: '.$cleanArr['title'].PHP_EOL. + ' Episode: '.$cleanArr['epno']); - echo ColorCLI::header(PHP_EOL . 'Looking Up: ') . - ColorCLI::primary(' Title: ' . $cleanArr['title'] . PHP_EOL . - ' Episode: ' . $cleanArr['epno']); + // get anidb number for the title of the name + $anidbId = $this->getAnidbByName($cleanArr['title']); - // get anidb number for the title of the name - $anidbId = $this->getAnidbByName($cleanArr['title']); + if ($anidbId === false) { + $tmpName = preg_replace('/\s/', '%', $cleanArr['title']); + $anidbId = $this->getAnidbByName($tmpName); + } - if ($anidbId === false) { - $tmpName = preg_replace('/\s/', '%', $cleanArr['title']); - $anidbId = $this->getAnidbByName($tmpName); - } + if (! empty($anidbId) && is_numeric($anidbId['anidbid']) && $anidbId['anidbid'] > 0) { + $updatedAni = $this->checkAniDBInfo($anidbId['anidbid'], $cleanArr['epno']); - if (!empty($anidbId) && is_numeric($anidbId['anidbid']) && $anidbId['anidbid'] > 0) { - - $updatedAni = $this->checkAniDBInfo($anidbId['anidbid'], $cleanArr['epno']); - - if ($updatedAni === false) { - if ($this->updateTimeCheck($anidbId['anidbid']) !== false) { - $this->padb->populateTable('info', $anidbId['anidbid']); - $this->doRandomSleep(); - $updatedAni = $this->checkAniDBInfo($anidbId['anidbid']); - $type = 'Remote'; - } else { - echo PHP_EOL . - ColorCLI::info('This AniDB ID was not found to be accurate locally, but has been updated too recently to check AniDB.') . + if ($updatedAni === false) { + if ($this->updateTimeCheck($anidbId['anidbid']) !== false) { + $this->padb->populateTable('info', $anidbId['anidbid']); + $this->doRandomSleep(); + $updatedAni = $this->checkAniDBInfo($anidbId['anidbid']); + $type = 'Remote'; + } else { + echo PHP_EOL. + ColorCLI::info('This AniDB ID was not found to be accurate locally, but has been updated too recently to check AniDB.'). PHP_EOL; - } - } + } + } - $this->updateRelease($anidbId['anidbid'], $release['id']); + $this->updateRelease($anidbId['anidbid'], $release['id']); - ColorCLI::doEcho( - ColorCLI::headerOver('Matched ' . $type . ' AniDB ID: ') . - ColorCLI::primary($anidbId['anidbid']) . - ColorCLI::alternateOver(' Title: ') . - ColorCLI::primary($anidbId['title']) . - ColorCLI::alternateOver(' Episode #: ') . - ColorCLI::primary($cleanArr['epno']) . - ColorCLI::alternateOver(' Episode Title: ') . + ColorCLI::doEcho( + ColorCLI::headerOver('Matched '.$type.' AniDB ID: '). + ColorCLI::primary($anidbId['anidbid']). + ColorCLI::alternateOver(' Title: '). + ColorCLI::primary($anidbId['title']). + ColorCLI::alternateOver(' Episode #: '). + ColorCLI::primary($cleanArr['epno']). + ColorCLI::alternateOver(' Episode Title: '). ColorCLI::primary($updatedAni['episode_title']) ); - $matched = true; - } else { - if (NN_DEBUG) { - ColorCLI::doEcho( - PHP_EOL . 'Could not match searchname:' . $release['searchname'], + $matched = true; + } else { + if (NN_DEBUG) { + ColorCLI::doEcho( + PHP_EOL.'Could not match searchname:'.$release['searchname'], true ); - } - $this->status = self::PROC_NOMATCH; - } - } + } + $this->status = self::PROC_NOMATCH; + } + } - return $matched; - } + return $matched; + } - /** - * @param $anidbId - * @param $relId - */ - private function updateRelease($anidbId, $relId): void - { - $this->pdo->queryExec( + /** + * @param $anidbId + * @param $relId + */ + private function updateRelease($anidbId, $relId): void + { + $this->pdo->queryExec( sprintf(' UPDATE releases SET anidbid = %d @@ -292,18 +289,18 @@ class AniDB $relId ) ); - } + } - /** - * Checks a specific Anime title's last update time - * - * @param int $anidbId - * - * @return bool|\PDOStatement Has it been 7 days since we last updated this AniDB ID or not? - */ - private function updateTimeCheck($anidbId) - { - return $this->pdo->queryOneRow( + /** + * Checks a specific Anime title's last update time. + * + * @param int $anidbId + * + * @return bool|\PDOStatement Has it been 7 days since we last updated this AniDB ID or not? + */ + private function updateTimeCheck($anidbId) + { + return $this->pdo->queryOneRow( sprintf(' SELECT anidbid FROM anidb_info ai @@ -312,5 +309,5 @@ class AniDB $anidbId ) ); - } + } } diff --git a/nntmux/processing/post/ProcessAdditional.php b/nntmux/processing/post/ProcessAdditional.php index ab82a945d..4c9f8a1f4 100755 --- a/nntmux/processing/post/ProcessAdditional.php +++ b/nntmux/processing/post/ProcessAdditional.php @@ -1,388 +1,388 @@ <?php + namespace nntmux\processing\post; -use App\Models\Settings; -use dariusiii\rarinfo\ArchiveInfo; -use dariusiii\rarinfo\Par2Info; -use nntmux\Categorize; +use nntmux\Nfo; +use nntmux\NZB; +use nntmux\NNTP; +use nntmux\db\DB; +use nntmux\Groups; use nntmux\Category; use nntmux\ColorCLI; -use nntmux\Groups; +use nntmux\Releases; use nntmux\NameFixer; -use nntmux\Nfo; -use nntmux\NNTP; -use nntmux\NZB; +use nntmux\Categorize; +use App\Models\Settings; use nntmux\ReleaseExtra; use nntmux\ReleaseFiles; use nntmux\ReleaseImage; -use nntmux\Releases; use nntmux\SphinxSearch; -use nntmux\db\DB; use nntmux\utility\Utility; +use dariusiii\rarinfo\Par2Info; +use dariusiii\rarinfo\ArchiveInfo; class ProcessAdditional { - /** - * How many compressed (rar/zip) files to check. - * @int - * @default 20 - */ - const maxCompressedFilesToCheck = 20; - - /** - * @var \nntmux\db\Settings - */ - public $pdo; - - /** - * @var bool - */ - protected $_echoDebug; - - /** - * Releases to work on. - * @var array - */ - protected $_releases; - - /** - * Count of releases to work on. - * @var int - */ - protected $_totalReleases; - - /** - * Current release we are working on. - * @var array - */ - protected $_release; - - /** - * @var \nntmux\NZB - */ - protected $_nzb; - - /** - * List of files with sizes/etc contained in the NZB. - * @var array - */ - protected $_nzbContents; - - /** - * @var \nntmux\Groups - */ - protected $_groups; - - /** - * @var \dariusiii\rarinfo\Par2Info - */ - protected $_par2Info; - - /** - * @var \dariusiii\rarinfo\ArchiveInfo - */ - protected $_archiveInfo; - - /** - * @var array|bool|string - */ - protected $_innerFileBlacklist; - - /** - * @var array|bool|int|string - */ - protected $_maxNestedLevels; - - /** - * @var array|bool|string - */ - protected $_7zipPath; - - /** - * @var array|bool|string - */ - protected $_unrarPath; - - /** - * @var string - */ - protected $_killString; - - /** - * @var bool|string - */ - protected $_showCLIReleaseID; - - /** - * @var int - */ - protected $_queryLimit; - - /** - * @var int - */ - protected $_segmentsToDownload; - - /** - * @var int - */ - protected $_maximumRarSegments; - - /** - * @var int - */ - protected $_maximumRarPasswordChecks; - - /** - * @var string - */ - protected $_maxSize; - - /** - * @var string - */ - protected $_minSize; - - /** - * @var bool - */ - protected $_processThumbnails; - - /** - * @var string - */ - protected $_audioSavePath; - - /** - * @var string - */ - protected $_supportFileRegex; - - /** - * @var bool - */ - protected $_echoCLI; - - /** - * @var \nntmux\NNTP - */ - protected $_nntp; - - /** - * @var \nntmux\ReleaseFiles - */ - protected $_releaseFiles; - - /** - * @var \nntmux\Categorize - */ - protected $_categorize; - - /** - * @var \nntmux\NameFixer - */ - protected $_nameFixer; - - /** - * @var \nntmux\ReleaseExtra - */ - protected $_releaseExtra; - - /** - * @var \nntmux\ReleaseImage - */ - protected $_releaseImage; - - /** - * @var \nntmux\Nfo - */ - protected $_nfo; - - /** - * @var bool - */ - protected $_extractUsingRarInfo; - - /** - * @var bool - */ - protected $_alternateNNTP; - - /** - * @var int - */ - protected $_ffMPEGDuration; - - /** - * @var bool - */ - protected $_addPAR2Files; - - /** - * @var bool - */ - protected $_processVideo; - - /** - * @var bool - */ - protected $_processJPGSample; - - /** - * @var bool - */ - protected $_processAudioSample; - - /** - * @var bool - */ - protected $_processMediaInfo; - - /** - * @var bool - */ - protected $_processAudioInfo; - - /** - * @var bool - */ - protected $_processPasswords; - - /** - * @var string - */ - protected $_audioFileRegex; - - /** - * @var string - */ - protected $_ignoreBookRegex; - - /** - * @var string - */ - protected $_videoFileRegex; - - - /** - * Have we created a video file for the current release? - * @var bool - */ - protected $_foundVideo; - - /** - * Have we found MediaInfo data for a Video for the current release? - * @var bool - */ - protected $_foundMediaInfo; - - /** - * Have we found MediaInfo data for a Audio file for the current release? - * @var bool - */ - protected $_foundAudioInfo; - - /** - * Have we created a short Audio file sample for the current release? - * @var bool - */ - protected $_foundAudioSample; - - /** - * Extension of the found audio file (MP3/FLAC/etc). - * @var string - */ - protected $_AudioInfoExtension; - - /** - * Have we downloaded a JPG file for the current release? - * @var bool - */ - protected $_foundJPGSample; - - /** - * Have we created a Video JPG image sample for the current release? - * @var bool - */ - protected $_foundSample; - - /** - * Have we found PAR2 info on this release? - * @var bool - */ - protected $_foundPAR2Info; - - /** - * Message ID's for found content to download. - * @var array - */ - protected $_sampleMessageIDs; - protected $_JPGMessageIDs; - protected $_MediaInfoMessageIDs; - protected $_AudioInfoMessageIDs; - protected $_RARFileMessageIDs; - - /** - * Password status of the current release. - * @var array - */ - protected $_passwordStatus; - - /** - * Does the current release have a password? - * @var bool - */ - protected $_releaseHasPassword; - - /** - * Does the current release have an NFO file? - * @var bool - */ - protected $_releaseHasNoNFO; - - /** - * Name of the current release's usenet group. - * @var string - */ - protected $_releaseGroupName; - - /** - * Number of file information added to DB (from rar/zip/par2 contents). - * @var int - */ - protected $_addedFileInfo; - - /** - * Number of file information we found from RAR/ZIP. - * (if some of it was already in DB, this count goes up, while the count above does not) - * @var int - */ - protected $_totalFileInfo; - - /** - * How many compressed (rar/zip) files have we checked. - * @var int - */ - protected $_compressedFilesChecked; - - /** - * Should we download the last rar? - * @var bool - */ - protected $_fetchLastFiles; - - /** - * Are we downloading the last rar? - * @var bool - */ - protected $_reverse; - - /** - * @param array $options Class instances / echo to cli. - */ - public function __construct(array $options = []) - { - $defaults = [ + /** + * How many compressed (rar/zip) files to check. + * @int + * @default 20 + */ + const maxCompressedFilesToCheck = 20; + + /** + * @var \nntmux\db\Settings + */ + public $pdo; + + /** + * @var bool + */ + protected $_echoDebug; + + /** + * Releases to work on. + * @var array + */ + protected $_releases; + + /** + * Count of releases to work on. + * @var int + */ + protected $_totalReleases; + + /** + * Current release we are working on. + * @var array + */ + protected $_release; + + /** + * @var \nntmux\NZB + */ + protected $_nzb; + + /** + * List of files with sizes/etc contained in the NZB. + * @var array + */ + protected $_nzbContents; + + /** + * @var \nntmux\Groups + */ + protected $_groups; + + /** + * @var \dariusiii\rarinfo\Par2Info + */ + protected $_par2Info; + + /** + * @var \dariusiii\rarinfo\ArchiveInfo + */ + protected $_archiveInfo; + + /** + * @var array|bool|string + */ + protected $_innerFileBlacklist; + + /** + * @var array|bool|int|string + */ + protected $_maxNestedLevels; + + /** + * @var array|bool|string + */ + protected $_7zipPath; + + /** + * @var array|bool|string + */ + protected $_unrarPath; + + /** + * @var string + */ + protected $_killString; + + /** + * @var bool|string + */ + protected $_showCLIReleaseID; + + /** + * @var int + */ + protected $_queryLimit; + + /** + * @var int + */ + protected $_segmentsToDownload; + + /** + * @var int + */ + protected $_maximumRarSegments; + + /** + * @var int + */ + protected $_maximumRarPasswordChecks; + + /** + * @var string + */ + protected $_maxSize; + + /** + * @var string + */ + protected $_minSize; + + /** + * @var bool + */ + protected $_processThumbnails; + + /** + * @var string + */ + protected $_audioSavePath; + + /** + * @var string + */ + protected $_supportFileRegex; + + /** + * @var bool + */ + protected $_echoCLI; + + /** + * @var \nntmux\NNTP + */ + protected $_nntp; + + /** + * @var \nntmux\ReleaseFiles + */ + protected $_releaseFiles; + + /** + * @var \nntmux\Categorize + */ + protected $_categorize; + + /** + * @var \nntmux\NameFixer + */ + protected $_nameFixer; + + /** + * @var \nntmux\ReleaseExtra + */ + protected $_releaseExtra; + + /** + * @var \nntmux\ReleaseImage + */ + protected $_releaseImage; + + /** + * @var \nntmux\Nfo + */ + protected $_nfo; + + /** + * @var bool + */ + protected $_extractUsingRarInfo; + + /** + * @var bool + */ + protected $_alternateNNTP; + + /** + * @var int + */ + protected $_ffMPEGDuration; + + /** + * @var bool + */ + protected $_addPAR2Files; + + /** + * @var bool + */ + protected $_processVideo; + + /** + * @var bool + */ + protected $_processJPGSample; + + /** + * @var bool + */ + protected $_processAudioSample; + + /** + * @var bool + */ + protected $_processMediaInfo; + + /** + * @var bool + */ + protected $_processAudioInfo; + + /** + * @var bool + */ + protected $_processPasswords; + + /** + * @var string + */ + protected $_audioFileRegex; + + /** + * @var string + */ + protected $_ignoreBookRegex; + + /** + * @var string + */ + protected $_videoFileRegex; + + /** + * Have we created a video file for the current release? + * @var bool + */ + protected $_foundVideo; + + /** + * Have we found MediaInfo data for a Video for the current release? + * @var bool + */ + protected $_foundMediaInfo; + + /** + * Have we found MediaInfo data for a Audio file for the current release? + * @var bool + */ + protected $_foundAudioInfo; + + /** + * Have we created a short Audio file sample for the current release? + * @var bool + */ + protected $_foundAudioSample; + + /** + * Extension of the found audio file (MP3/FLAC/etc). + * @var string + */ + protected $_AudioInfoExtension; + + /** + * Have we downloaded a JPG file for the current release? + * @var bool + */ + protected $_foundJPGSample; + + /** + * Have we created a Video JPG image sample for the current release? + * @var bool + */ + protected $_foundSample; + + /** + * Have we found PAR2 info on this release? + * @var bool + */ + protected $_foundPAR2Info; + + /** + * Message ID's for found content to download. + * @var array + */ + protected $_sampleMessageIDs; + protected $_JPGMessageIDs; + protected $_MediaInfoMessageIDs; + protected $_AudioInfoMessageIDs; + protected $_RARFileMessageIDs; + + /** + * Password status of the current release. + * @var array + */ + protected $_passwordStatus; + + /** + * Does the current release have a password? + * @var bool + */ + protected $_releaseHasPassword; + + /** + * Does the current release have an NFO file? + * @var bool + */ + protected $_releaseHasNoNFO; + + /** + * Name of the current release's usenet group. + * @var string + */ + protected $_releaseGroupName; + + /** + * Number of file information added to DB (from rar/zip/par2 contents). + * @var int + */ + protected $_addedFileInfo; + + /** + * Number of file information we found from RAR/ZIP. + * (if some of it was already in DB, this count goes up, while the count above does not). + * @var int + */ + protected $_totalFileInfo; + + /** + * How many compressed (rar/zip) files have we checked. + * @var int + */ + protected $_compressedFilesChecked; + + /** + * Should we download the last rar? + * @var bool + */ + protected $_fetchLastFiles; + + /** + * Are we downloading the last rar? + * @var bool + */ + protected $_reverse; + + /** + * @param array $options Class instances / echo to cli. + */ + public function __construct(array $options = []) + { + $defaults = [ 'Echo' => false, 'Categorize' => null, 'Groups' => null, @@ -396,226 +396,226 @@ class ProcessAdditional 'Settings' => null, 'SphinxSearch' => null, ]; - $options += $defaults; + $options += $defaults; - $this->_echoCLI = ($options['Echo'] && NN_ECHOCLI && (strtolower(PHP_SAPI) === 'cli')); - $this->_echoDebug = NN_DEBUG; + $this->_echoCLI = ($options['Echo'] && NN_ECHOCLI && (strtolower(PHP_SAPI) === 'cli')); + $this->_echoDebug = NN_DEBUG; - $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); - $this->_nntp = ($options['NNTP'] instanceof NNTP ? $options['NNTP'] : new NNTP(['Echo' => $this->_echoCLI, 'Settings' => $this->pdo])); + $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB()); + $this->_nntp = ($options['NNTP'] instanceof NNTP ? $options['NNTP'] : new NNTP(['Echo' => $this->_echoCLI, 'Settings' => $this->pdo])); - $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->_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->_nfo = ($options['Nfo'] instanceof Nfo ? $options['Nfo'] : new Nfo(['Echo' => $this->_echoCLI, 'Settings' => $this->pdo])); - $this->sphinx = ($options['SphinxSearch'] instanceof SphinxSearch ? $options['SphinxSearch'] : new SphinxSearch()); + $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->_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->_nfo = ($options['Nfo'] instanceof Nfo ? $options['Nfo'] : new Nfo(['Echo' => $this->_echoCLI, 'Settings' => $this->pdo])); + $this->sphinx = ($options['SphinxSearch'] instanceof SphinxSearch ? $options['SphinxSearch'] : new SphinxSearch()); - $this->_innerFileBlacklist = (Settings::value('indexer.ppa.innerfileblacklist') == '' ? false : Settings::value('indexer.ppa.innerfileblacklist')); - $this->_maxNestedLevels = (Settings::value('..maxnestedlevels') == 0 ? 3 : Settings::value('..maxnestedlevels')); - $this->_extractUsingRarInfo = (Settings::value('..extractusingrarinfo') == 0 ? false : true); - $this->_fetchLastFiles = (Settings::value('archive.fetch.end') == 0 ? false : true); + $this->_innerFileBlacklist = (Settings::value('indexer.ppa.innerfileblacklist') == '' ? false : Settings::value('indexer.ppa.innerfileblacklist')); + $this->_maxNestedLevels = (Settings::value('..maxnestedlevels') == 0 ? 3 : Settings::value('..maxnestedlevels')); + $this->_extractUsingRarInfo = (Settings::value('..extractusingrarinfo') == 0 ? false : true); + $this->_fetchLastFiles = (Settings::value('archive.fetch.end') == 0 ? false : true); - $this->_7zipPath = false; - $this->_unrarPath = false; + $this->_7zipPath = false; + $this->_unrarPath = false; - // Pass the binary extractors to ArchiveInfo. - $clients = []; - if (Settings::value('apps..unrarpath') != '') { - $clients += [ArchiveInfo::TYPE_RAR => Settings::value('apps..unrarpath')]; - $this->_unrarPath = Settings::value('apps..unrarpath'); - } - if (Settings::value('apps..7zippath') != '') { - $clients += [ArchiveInfo::TYPE_ZIP => Settings::value('apps..7zippath')]; - $this->_7zipPath = Settings::value('apps..7zippath'); - } - $this->_archiveInfo->setExternalClients($clients); + // Pass the binary extractors to ArchiveInfo. + $clients = []; + if (Settings::value('apps..unrarpath') != '') { + $clients += [ArchiveInfo::TYPE_RAR => Settings::value('apps..unrarpath')]; + $this->_unrarPath = Settings::value('apps..unrarpath'); + } + if (Settings::value('apps..7zippath') != '') { + $clients += [ArchiveInfo::TYPE_ZIP => Settings::value('apps..7zippath')]; + $this->_7zipPath = Settings::value('apps..7zippath'); + } + $this->_archiveInfo->setExternalClients($clients); - $this->_killString = '"'; - if (Settings::value('apps..timeoutpath') != '' && Settings::value('..timeoutseconds') > 0) { - $this->_killString = ( - '"' . Settings::value('apps..timeoutpath') . - '" --foreground --signal=KILL ' . - Settings::value('..timeoutseconds') . ' "' + $this->_killString = '"'; + if (Settings::value('apps..timeoutpath') != '' && Settings::value('..timeoutseconds') > 0) { + $this->_killString = ( + '"'.Settings::value('apps..timeoutpath'). + '" --foreground --signal=KILL '. + Settings::value('..timeoutseconds').' "' ); - } + } - $this->_showCLIReleaseID = (PHP_BINARY . ' ' . __DIR__ . DS . 'ProcessAdditional.php ReleaseID: '); + $this->_showCLIReleaseID = (PHP_BINARY.' '.__DIR__.DS.'ProcessAdditional.php ReleaseID: '); - // Maximum amount of releases to fetch per run. - $this->_queryLimit = - (Settings::value('..maxaddprocessed') != '') ? (int)Settings::value('..maxaddprocessed') : 25; + // Maximum amount of releases to fetch per run. + $this->_queryLimit = + (Settings::value('..maxaddprocessed') != '') ? (int) Settings::value('..maxaddprocessed') : 25; - // Maximum message ID's to download per file type in the NZB (video, jpg, etc). - $this->_segmentsToDownload = - (Settings::value('..segmentstodownload') != '') ? (int)Settings::value('..segmentstodownload') : 2; + // Maximum message ID's to download per file type in the NZB (video, jpg, etc). + $this->_segmentsToDownload = + (Settings::value('..segmentstodownload') != '') ? (int) Settings::value('..segmentstodownload') : 2; - // Maximum message ID's to download for a RAR file. - $this->_maximumRarSegments = - (Settings::value('..maxpartsprocessed') != '') ? (int)Settings::value('..maxpartsprocessed') : 3; + // Maximum message ID's to download for a RAR file. + $this->_maximumRarSegments = + (Settings::value('..maxpartsprocessed') != '') ? (int) Settings::value('..maxpartsprocessed') : 3; - // Maximum RAR files to check for a password before stopping. - $this->_maximumRarPasswordChecks = - (Settings::value('..passchkattempts') != '') ? (int)Settings::value('..passchkattempts') : 1; + // Maximum RAR files to check for a password before stopping. + $this->_maximumRarPasswordChecks = + (Settings::value('..passchkattempts') != '') ? (int) Settings::value('..passchkattempts') : 1; - $this->_maximumRarPasswordChecks = ($this->_maximumRarPasswordChecks < 1 ? 1 : $this->_maximumRarPasswordChecks); + $this->_maximumRarPasswordChecks = ($this->_maximumRarPasswordChecks < 1 ? 1 : $this->_maximumRarPasswordChecks); - // Maximum size of releases in GB. - $this->_maxSize = - (Settings::value('..maxsizetopostprocess') != '') ? (int)Settings::value('..maxsizetopostprocess') : 100; - $this->_maxSize = ($this->_maxSize > 0 ? ('AND r.size < ' . ($this->_maxSize * 1073741824)) : ''); - // Minimum size of releases in MB. - $this->_minSize = - (Settings::value('..minsizetopostprocess') != '') ? (int)Settings::value('..minsizetopostprocess') : 100; - $this->_minSize = ($this->_minSize > 0 ? ('AND r.size > ' . ($this->_minSize * 1048576)) : ''); + // Maximum size of releases in GB. + $this->_maxSize = + (Settings::value('..maxsizetopostprocess') != '') ? (int) Settings::value('..maxsizetopostprocess') : 100; + $this->_maxSize = ($this->_maxSize > 0 ? ('AND r.size < '.($this->_maxSize * 1073741824)) : ''); + // Minimum size of releases in MB. + $this->_minSize = + (Settings::value('..minsizetopostprocess') != '') ? (int) Settings::value('..minsizetopostprocess') : 100; + $this->_minSize = ($this->_minSize > 0 ? ('AND r.size > '.($this->_minSize * 1048576)) : ''); - // Use the alternate NNTP provider for downloading Message-ID's ? - $this->_alternateNNTP = (Settings::value('..alternate_nntp') == 1 ? true : false); + // Use the alternate NNTP provider for downloading Message-ID's ? + $this->_alternateNNTP = (Settings::value('..alternate_nntp') == 1 ? true : false); - $this->_ffMPEGDuration = (Settings::value('..ffmpeg_duration') != '') ? (int)Settings::value('..ffmpeg_duration') : 5; + $this->_ffMPEGDuration = (Settings::value('..ffmpeg_duration') != '') ? (int) Settings::value('..ffmpeg_duration') : 5; - $this->_addPAR2Files = (Settings::value('..addpar2') === '0') ? false : true; + $this->_addPAR2Files = (Settings::value('..addpar2') === '0') ? false : true; - if (!Settings::value('apps..ffmpegpath')) { - $this->_processAudioSample = $this->_processThumbnails = $this->_processVideo = false; - } else { - $this->_processAudioSample = (Settings::value('..saveaudiopreview') == 0) ? false : true; - $this->_processThumbnails = (Settings::value('..processthumbnails') == 0 ? false : true); - $this->_processVideo = (Settings::value('..processvideos') == 0) ? false : true; - } + if (! Settings::value('apps..ffmpegpath')) { + $this->_processAudioSample = $this->_processThumbnails = $this->_processVideo = false; + } else { + $this->_processAudioSample = (Settings::value('..saveaudiopreview') == 0) ? false : true; + $this->_processThumbnails = (Settings::value('..processthumbnails') == 0 ? false : true); + $this->_processVideo = (Settings::value('..processvideos') == 0) ? false : true; + } - $this->_processJPGSample = (Settings::value('..processjpg') == 0) ? false : true; - $this->_processMediaInfo = (Settings::value('apps..mediainfopath') == '') ? false : true; - $this->_processAudioInfo = $this->_processMediaInfo; - $this->_processPasswords = ( + $this->_processJPGSample = (Settings::value('..processjpg') == 0) ? false : true; + $this->_processMediaInfo = (Settings::value('apps..mediainfopath') == '') ? false : true; + $this->_processAudioInfo = $this->_processMediaInfo; + $this->_processPasswords = ( (((Settings::value('..checkpasswordedrar') == 0) ? false : true)) && ((Settings::value('apps..unrarpath') == '') ? false : true) ); - $this->_audioSavePath = NN_COVERS . 'audiosample' . DS; + $this->_audioSavePath = NN_COVERS.'audiosample'.DS; - $this->_audioFileRegex = '\.(AAC|AIFF|APE|AC3|ASF|DTS|FLAC|MKA|MKS|MP2|MP3|RA|OGG|OGM|W64|WAV|WMA)'; - $this->_ignoreBookRegex = '/\b(epub|lit|mobi|pdf|sipdf|html)\b.*\.rar(?!.{20,})/i'; - $this->_supportFileRegex = '/\.(vol\d{1,3}\+\d{1,3}|par2|srs|sfv|nzb'; - $this->_videoFileRegex = '\.(AVI|F4V|IFO|M1V|M2V|M4V|MKV|MOV|MP4|MPEG|MPG|MPGV|MPV|OGV|QT|RM|RMVB|TS|VOB|WMV)'; - } + $this->_audioFileRegex = '\.(AAC|AIFF|APE|AC3|ASF|DTS|FLAC|MKA|MKS|MP2|MP3|RA|OGG|OGM|W64|WAV|WMA)'; + $this->_ignoreBookRegex = '/\b(epub|lit|mobi|pdf|sipdf|html)\b.*\.rar(?!.{20,})/i'; + $this->_supportFileRegex = '/\.(vol\d{1,3}\+\d{1,3}|par2|srs|sfv|nzb'; + $this->_videoFileRegex = '\.(AVI|F4V|IFO|M1V|M2V|M4V|MKV|MOV|MP4|MPEG|MPG|MPGV|MPV|OGV|QT|RM|RMVB|TS|VOB|WMV)'; + } - /** - * Clear out the main temp path when done. - */ - public function __destruct() - { - $this->_clearMainTmpPath(); - } + /** + * Clear out the main temp path when done. + */ + public function __destruct() + { + $this->_clearMainTmpPath(); + } - /** - * Main method. - * - * @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. - * - * @void - */ - public function start($groupID = '', $guidChar = '') - { - $this->_setMainTempPath($guidChar, $groupID); + /** + * Main method. + * + * @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. + * + * @void + */ + public function start($groupID = '', $guidChar = '') + { + $this->_setMainTempPath($guidChar, $groupID); - // Fetch all the releases to work on. - $this->_fetchReleases($groupID, $guidChar); + // Fetch all the releases to work on. + $this->_fetchReleases($groupID, $guidChar); - // Check if we have releases to work on. - if ($this->_totalReleases > 0) { - // Echo start time and process description. - $this->_echoDescription(); + // Check if we have releases to work on. + if ($this->_totalReleases > 0) { + // Echo start time and process description. + $this->_echoDescription(); - $this->_processReleases(); - } - } + $this->_processReleases(); + } + } - /** - * @var string Main temp path to work on. - */ - protected $_mainTmpPath; + /** + * @var string Main temp path to work on. + */ + protected $_mainTmpPath; - /** - * @var string Temp path for current release. - */ - protected $tmpPath; + /** + * @var string Temp path for current release. + */ + protected $tmpPath; - /** - * Set up the path to the folder we will work in. - * - * @param string|int $groupID - * @param string $guidChar - * - * @throws ProcessAdditionalException - */ - protected function _setMainTempPath(&$guidChar, &$groupID = '') - { - // Set up the temporary files folder location. - $this->_mainTmpPath = (string)Settings::value('..tmpunrarpath'); + /** + * Set up the path to the folder we will work in. + * + * @param string|int $groupID + * @param string $guidChar + * + * @throws ProcessAdditionalException + */ + protected function _setMainTempPath(&$guidChar, &$groupID = '') + { + // Set up the temporary files folder location. + $this->_mainTmpPath = (string) Settings::value('..tmpunrarpath'); - // Check if it ends with a dir separator. - if (!preg_match('/[\/\\\\]$/', $this->_mainTmpPath)) { - $this->_mainTmpPath .= DS; - } + // Check if it ends with a dir separator. + if (! preg_match('/[\/\\\\]$/', $this->_mainTmpPath)) { + $this->_mainTmpPath .= DS; + } - // If we are doing per group, use the groupID has a inner path, so other scripts don't delete the files we are working on. - if ($groupID !== '') { - $this->_mainTmpPath .= ($groupID . DS); - } else if ($guidChar !== '') { - $this->_mainTmpPath .= ($guidChar . DS); - } + // If we are doing per group, use the groupID has a inner path, so other scripts don't delete the files we are working on. + if ($groupID !== '') { + $this->_mainTmpPath .= ($groupID.DS); + } elseif ($guidChar !== '') { + $this->_mainTmpPath .= ($guidChar.DS); + } - if (!is_dir($this->_mainTmpPath)) { - $old = umask(0777); - @mkdir($this->_mainTmpPath, 0777, true); - @chmod($this->_mainTmpPath, 0777); - @umask($old); - } + if (! is_dir($this->_mainTmpPath)) { + $old = umask(0777); + @mkdir($this->_mainTmpPath, 0777, true); + @chmod($this->_mainTmpPath, 0777); + @umask($old); + } - if (!is_dir($this->_mainTmpPath)) { - throw new ProcessAdditionalException('Could not create the tmpunrar folder (' . $this->_mainTmpPath . ')'); - } + if (! is_dir($this->_mainTmpPath)) { + throw new ProcessAdditionalException('Could not create the tmpunrar folder ('.$this->_mainTmpPath.')'); + } - $this->_clearMainTmpPath(); + $this->_clearMainTmpPath(); - $this->tmpPath = $this->_mainTmpPath; - } + $this->tmpPath = $this->_mainTmpPath; + } - /** - * Clear out old folders/files from the main temp folder. - */ - protected function _clearMainTmpPath() - { - if ($this->_mainTmpPath != '') { - $this->_recursivePathDelete( + /** + * Clear out old folders/files from the main temp folder. + */ + protected function _clearMainTmpPath() + { + if ($this->_mainTmpPath != '') { + $this->_recursivePathDelete( $this->_mainTmpPath, // These are folders we don't want to delete. [ // This is the actual temp folder. - $this->_mainTmpPath + $this->_mainTmpPath, ] ); - } - } + } + } - /** - * Get all releases that need to be processed. - * - * @param int|string $groupID - * @param string $guidChar - * - * @void - */ - protected function _fetchReleases($groupID, &$guidChar) - { - $this->_releases = $this->pdo->query( + /** + * Get all releases that need to be processed. + * + * @param int|string $groupID + * @param string $guidChar + * + * @void + */ + protected function _fetchReleases($groupID, &$guidChar) + { + $this->_releases = $this->pdo->query( sprintf(' SELECT r.id, r.id AS releases_id, r.guid, r.name, r.size, r.groups_id, r.nfostatus, r.fromname, r.completion, r.categories_id, r.searchname, r.predb_id, @@ -631,80 +631,79 @@ class ProcessAdditional LIMIT %d', $this->_maxSize, $this->_minSize, - ($groupID === '' ? '' : 'AND r.groups_id = ' . $groupID), - ($guidChar === '' ? '' : 'AND r.leftguid = ' . $this->pdo->escapeString($guidChar)), + ($groupID === '' ? '' : 'AND r.groups_id = '.$groupID), + ($guidChar === '' ? '' : 'AND r.leftguid = '.$this->pdo->escapeString($guidChar)), $this->_queryLimit ) ); - if (is_array($this->_releases)) { - $this->_totalReleases = count($this->_releases); - } else { - $this->_releases = []; - $this->_totalReleases = 0; - } - } + if (is_array($this->_releases)) { + $this->_totalReleases = count($this->_releases); + } else { + $this->_releases = []; + $this->_totalReleases = 0; + } + } - /** - * Output the description and start time. - * - * @void - */ - protected function _echoDescription() - { - if ($this->_totalReleases > 1 && $this->_echoCLI) { - $this->_echo( - PHP_EOL . - 'Additional post-processing, started at: ' . - date('D M d, Y G:i a') . - PHP_EOL . - 'Downloaded: (xB) = yEnc article, f= Failed ;Processing: z = ZIP file, r = RAR file' . - PHP_EOL . - 'Added: s = Sample image, j = JPEG image, A = Audio sample, a = Audio MediaInfo, v = Video sample' . - PHP_EOL . - 'Added: m = Video MediaInfo, n = NFO, ^ = File details from inside the RAR/ZIP' - , 'header'); - } - } + /** + * Output the description and start time. + * + * @void + */ + protected function _echoDescription() + { + if ($this->_totalReleases > 1 && $this->_echoCLI) { + $this->_echo( + PHP_EOL. + 'Additional post-processing, started at: '. + date('D M d, Y G:i a'). + PHP_EOL. + 'Downloaded: (xB) = yEnc article, f= Failed ;Processing: z = ZIP file, r = RAR file'. + PHP_EOL. + 'Added: s = Sample image, j = JPEG image, A = Audio sample, a = Audio MediaInfo, v = Video sample'. + PHP_EOL. + 'Added: m = Video MediaInfo, n = NFO, ^ = File details from inside the RAR/ZIP', 'header'); + } + } - /** - * Loop through the releases, processing them 1 at a time. - */ - protected function _processReleases() - { - foreach ($this->_releases as $this->_release) { - $this->_echo( - PHP_EOL . '[' . $this->_release['id'] . '][' . - $this->_readableBytesString($this->_release['size']) . ']', + /** + * Loop through the releases, processing them 1 at a time. + */ + protected function _processReleases() + { + foreach ($this->_releases as $this->_release) { + $this->_echo( + PHP_EOL.'['.$this->_release['id'].']['. + $this->_readableBytesString($this->_release['size']).']', 'primaryOver', false ); - cli_set_process_title($this->_showCLIReleaseID . $this->_release['id']); + cli_set_process_title($this->_showCLIReleaseID.$this->_release['id']); - // Create folder to store temporary files. - if ($this->_createTempFolder() === false) { - continue; - } + // Create folder to store temporary files. + if ($this->_createTempFolder() === false) { + continue; + } - // Get NZB contents. - if ($this->_getNZBContents() === false) { - continue; - } + // Get NZB contents. + if ($this->_getNZBContents() === false) { + continue; + } - // Reset the current release variables. - $this->_resetReleaseStatus(); + // Reset the current release variables. + $this->_resetReleaseStatus(); - // Go through the files in the NZB, get the amount of book files. - $totalBooks = $this->_processNZBContents(); + // Go through the files in the NZB, get the amount of book files. + $totalBooks = $this->_processNZBContents(); - // Check if this NZB is a large collection of books. - $bookFlood = false; - if ($totalBooks > 80 && ($totalBooks * 2) >= count($this->_nzbContents)) { - $bookFlood = true; - } + // Check if this NZB is a large collection of books. + $bookFlood = false; + if ($totalBooks > 80 && ($totalBooks * 2) >= count($this->_nzbContents)) { + $bookFlood = true; + } - if ($this->_processPasswords === true || + if ($this->_processPasswords === true || $this->_processThumbnails === true || $this->_processMediaInfo === true || $this->_processAudioInfo === true || @@ -712,509 +711,510 @@ class ProcessAdditional ) { // Process usenet Message-ID downloads. - $this->_processMessageIDDownloads(); + $this->_processMessageIDDownloads(); - // Process compressed (RAR/ZIP) files inside the NZB. - if ($bookFlood === false && $this->_NZBHasCompressedFile) { - // Download the RARs/ZIPs, extract the files inside them and insert the file info into the DB. - $this->_processNZBCompressedFiles(); + // Process compressed (RAR/ZIP) files inside the NZB. + if ($bookFlood === false && $this->_NZBHasCompressedFile) { + // Download the RARs/ZIPs, extract the files inside them and insert the file info into the DB. + $this->_processNZBCompressedFiles(); - // Download rar/zip in reverse order, to get the last rar or zip file. - if ($this->_fetchLastFiles == 1) { - $this->_processNZBCompressedFiles(true); - } + // Download rar/zip in reverse order, to get the last rar or zip file. + if ($this->_fetchLastFiles == 1) { + $this->_processNZBCompressedFiles(true); + } - if ($this->_releaseHasPassword === false) { - // Process the extracted files to get video/audio samples/etc. - $this->_processExtractedFiles(); - } - } - } + if ($this->_releaseHasPassword === false) { + // Process the extracted files to get video/audio samples/etc. + $this->_processExtractedFiles(); + } + } + } - // Update the release to say we processed it. - $this->_finalizeRelease(); + // Update the release to say we processed it. + $this->_finalizeRelease(); - // Delete all files / folders for this release. - $this->_recursivePathDelete($this->tmpPath); - } - if ($this->_echoCLI) { - echo PHP_EOL; - } - } + // Delete all files / folders for this release. + $this->_recursivePathDelete($this->tmpPath); + } + if ($this->_echoCLI) { + echo PHP_EOL; + } + } - /** - * Deletes files and folders recursively. - * - * @param string $path Path to a folder or file. - * @param string[] $ignoredFolders array with paths to folders to ignore. - * - * @void - * @access protected - */ - protected function _recursivePathDelete($path, $ignoredFolders = []) - { - if (is_dir($path)) { + /** + * Deletes files and folders recursively. + * + * @param string $path Path to a folder or file. + * @param string[] $ignoredFolders array with paths to folders to ignore. + * + * @void + */ + protected function _recursivePathDelete($path, $ignoredFolders = []) + { + if (is_dir($path)) { + $files = glob(rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.'*'); - $files = glob(rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*'); + foreach ($files as $file) { + $this->_recursivePathDelete($file, $ignoredFolders); + } - foreach ($files as $file) { - $this->_recursivePathDelete($file, $ignoredFolders); - } + if (in_array($path, $ignoredFolders)) { + return; + } - if (in_array($path, $ignoredFolders)) { - return; - } + @rmdir($path); + } elseif (is_file($path)) { + @unlink($path); + } + } - @rmdir($path); + /** + * Create a temporary storage folder for the current release. + * + * @return bool + */ + protected function _createTempFolder() + { + // Per release defaults. + $this->tmpPath = $this->_mainTmpPath.$this->_release['guid'].DS; + if (! is_dir($this->tmpPath)) { + $old = umask(0777); + @mkdir($this->tmpPath, 0777, true); + @chmod($this->tmpPath, 0777); + @umask($old); - } else if (is_file($path)) { - @unlink($path); - } - } + if (! is_dir($this->tmpPath)) { + $this->_echo('Unable to create directory: '.$this->tmpPath, 'warning'); - /** - * Create a temporary storage folder for the current release. - * - * @return bool - */ - protected function _createTempFolder() - { - // Per release defaults. - $this->tmpPath = $this->_mainTmpPath . $this->_release['guid'] . DS; - if (!is_dir($this->tmpPath)) { - $old = umask(0777); - @mkdir($this->tmpPath, 0777, true); - @chmod($this->tmpPath, 0777); - @umask($old); + return $this->_decrementPasswordStatus(); + } + } - if (!is_dir($this->tmpPath)) { - $this->_echo('Unable to create directory: ' . $this->tmpPath, 'warning'); - return $this->_decrementPasswordStatus(); - } - } - return true; - } + return true; + } - /** - * Get list of contents inside a release's NZB file. - * - * @return bool - */ - protected function _getNZBContents() - { - $nzbPath = $this->_nzb->NZBPath($this->_release['guid']); - if ($nzbPath === false) { - $this->_echo('NZB not found for GUID: ' . $this->_release['guid'], 'warning'); - return $this->_decrementPasswordStatus(); - } + /** + * Get list of contents inside a release's NZB file. + * + * @return bool + */ + protected function _getNZBContents() + { + $nzbPath = $this->_nzb->NZBPath($this->_release['guid']); + if ($nzbPath === false) { + $this->_echo('NZB not found for GUID: '.$this->_release['guid'], 'warning'); - $nzbContents = Utility::unzipGzipFile($nzbPath); - if (!$nzbContents) { - $this->_echo('NZB is empty or broken for GUID: ' . $this->_release['guid'], 'warning'); - return $this->_decrementPasswordStatus(); - } + return $this->_decrementPasswordStatus(); + } - // Get a list of files in the nzb. - $this->_nzbContents = $this->_nzb->nzbFileList($nzbContents, ['no-file-key' => false, 'strip-count' => true]); - if (count($this->_nzbContents) === 0) { - $this->_echo('NZB is potentially broken for GUID: ' . $this->_release['guid'], 'warning'); - return $this->_decrementPasswordStatus(); - } - // Sort keys. - ksort($this->_nzbContents, SORT_NATURAL); + $nzbContents = Utility::unzipGzipFile($nzbPath); + if (! $nzbContents) { + $this->_echo('NZB is empty or broken for GUID: '.$this->_release['guid'], 'warning'); - return true; - } + return $this->_decrementPasswordStatus(); + } - /** - * Decrement password status for the current release. - * - * @param bool $return Return value. - * - * @return bool - */ - protected function _decrementPasswordStatus($return = false) - { - $this->pdo->queryExec( + // Get a list of files in the nzb. + $this->_nzbContents = $this->_nzb->nzbFileList($nzbContents, ['no-file-key' => false, 'strip-count' => true]); + if (count($this->_nzbContents) === 0) { + $this->_echo('NZB is potentially broken for GUID: '.$this->_release['guid'], 'warning'); + + return $this->_decrementPasswordStatus(); + } + // Sort keys. + ksort($this->_nzbContents, SORT_NATURAL); + + return true; + } + + /** + * Decrement password status for the current release. + * + * @param bool $return Return value. + * + * @return bool + */ + protected function _decrementPasswordStatus($return = false) + { + $this->pdo->queryExec( sprintf( 'UPDATE releases SET passwordstatus = passwordstatus - 1 WHERE id = %d', $this->_release['id'] ) ); - return $return; - } - /** - * Current file we are working on inside a NZB. - * @var array - */ - protected $_currentNZBFile; + return $return; + } - /** - * Does the current NZB contain a compressed (RAR/ZIP) file? - * @var bool - */ - protected $_NZBHasCompressedFile; + /** + * Current file we are working on inside a NZB. + * @var array + */ + protected $_currentNZBFile; - /** - * Process the files inside the NZB, find Message-ID's to download. - * If we find files with book extensions, return the amount. - * - * @return int - */ - protected function _processNZBContents() - { - $totalBookFiles = 0; - foreach ($this->_nzbContents as $this->_currentNZBFile) { + /** + * Does the current NZB contain a compressed (RAR/ZIP) file? + * @var bool + */ + protected $_NZBHasCompressedFile; + + /** + * Process the files inside the NZB, find Message-ID's to download. + * If we find files with book extensions, return the amount. + * + * @return int + */ + protected function _processNZBContents() + { + $totalBookFiles = 0; + foreach ($this->_nzbContents as $this->_currentNZBFile) { // Check if it's not a nfo, nzb, par2 etc... - if (preg_match($this->_supportFileRegex . '|nfo\b|inf\b|ofn\b)($|[ ")\]-])(?!.{20,})/i', $this->_currentNZBFile['title'])) { - continue; - } + if (preg_match($this->_supportFileRegex.'|nfo\b|inf\b|ofn\b)($|[ ")\]-])(?!.{20,})/i', $this->_currentNZBFile['title'])) { + continue; + } - // Check if it's a rar/zip. - if ($this->_NZBHasCompressedFile === false && + // Check if it's a rar/zip. + if ($this->_NZBHasCompressedFile === false && preg_match( '/\.(part\d+|r\d+|rar|0+|0*10?|zipr\d{2,3}|zipx?)(\s*\.rar)*($|[ ")\]-])|"[a-f0-9]{32}\.[1-9]\d{1,2}".*\(\d+\/\d{2,}\)$/i', $this->_currentNZBFile['title'] ) ) { - $this->_NZBHasCompressedFile = true; - } + $this->_NZBHasCompressedFile = true; + } - // Look for a video sample, make sure it's not an image. - if ($this->_processThumbnails === true && + // Look for a video sample, make sure it's not an image. + if ($this->_processThumbnails === true && empty($this->_sampleMessageIDs) && preg_match('/sample/i', $this->_currentNZBFile['title']) && - !preg_match('/\.jpe?g/i', $this->_currentNZBFile['title']) + ! preg_match('/\.jpe?g/i', $this->_currentNZBFile['title']) ) { + if (isset($this->_currentNZBFile['segments'])) { + // Get the amount of segments for this file. + $segCount = (count($this->_currentNZBFile['segments']) - 1); + // If it's more than 1 try to get up to the site specified value of segments. + for ($i = 0; $i < $this->_segmentsToDownload; $i++) { + if ($i > $segCount) { + break; + } + $this->_sampleMessageIDs[] = (string) $this->_currentNZBFile['segments'][$i]; + } + } + } - if (isset($this->_currentNZBFile['segments'])) { - // Get the amount of segments for this file. - $segCount = (count($this->_currentNZBFile['segments']) - 1); - // If it's more than 1 try to get up to the site specified value of segments. - for ($i = 0; $i < $this->_segmentsToDownload; $i++) { - if ($i > $segCount) { - break; - } - $this->_sampleMessageIDs[] = (string)$this->_currentNZBFile['segments'][$i]; - } - } - } - - // Look for a JPG picture, make sure it's not a CD cover. - if ($this->_processJPGSample === true && + // Look for a JPG picture, make sure it's not a CD cover. + if ($this->_processJPGSample === true && empty($this->_JPGMessageIDs) && - !preg_match('/flac|lossless|mp3|music|inner-sanctum|sound/i', $this->_releaseGroupName) && + ! preg_match('/flac|lossless|mp3|music|inner-sanctum|sound/i', $this->_releaseGroupName) && preg_match('/\.jpe?g[. ")\]]/i', $this->_currentNZBFile['title']) ) { + if (isset($this->_currentNZBFile['segments'])) { + // Get the amount of segments for this file. + $segCount = (count($this->_currentNZBFile['segments']) - 1); + // If it's more than 1 try to get up to the site specified value of segments. + for ($i = 0; $i < $this->_segmentsToDownload; $i++) { + if ($i > $segCount) { + break; + } + $this->_JPGMessageIDs[] = (string) $this->_currentNZBFile['segments'][$i]; + } + } + } - if (isset($this->_currentNZBFile['segments'])) { - // Get the amount of segments for this file. - $segCount = (count($this->_currentNZBFile['segments']) - 1); - // If it's more than 1 try to get up to the site specified value of segments. - for ($i = 0; $i < $this->_segmentsToDownload; $i++) { - if ($i > $segCount) { - break; - } - $this->_JPGMessageIDs[] = (string)$this->_currentNZBFile['segments'][$i]; - } - } - } - - // Look for a video file, make sure it's not a sample, for MediaInfo. - if ($this->_processMediaInfo === true && + // Look for a video file, make sure it's not a sample, for MediaInfo. + if ($this->_processMediaInfo === true && empty($this->_MediaInfoMessageIDs) && - !preg_match('/sample/i', $this->_currentNZBFile['title']) && - preg_match('/' . $this->_videoFileRegex . '[. ")\]]/i', $this->_currentNZBFile['title']) + ! preg_match('/sample/i', $this->_currentNZBFile['title']) && + preg_match('/'.$this->_videoFileRegex.'[. ")\]]/i', $this->_currentNZBFile['title']) ) { + if (isset($this->_currentNZBFile['segments'][0])) { + $this->_MediaInfoMessageIDs = (string) $this->_currentNZBFile['segments'][0]; + } + } - if (isset($this->_currentNZBFile['segments'][0])) { - $this->_MediaInfoMessageIDs = (string)$this->_currentNZBFile['segments'][0]; - } - } - - // Look for a audio file. - if ($this->_processAudioInfo === true && + // Look for a audio file. + if ($this->_processAudioInfo === true && empty($this->_AudioInfoMessageIDs) && - preg_match('/' . $this->_audioFileRegex . '[. ")\]]/i', $this->_currentNZBFile['title'], $type) + preg_match('/'.$this->_audioFileRegex.'[. ")\]]/i', $this->_currentNZBFile['title'], $type) ) { + if (isset($this->_currentNZBFile['segments'])) { + // Get the extension. + $this->_AudioInfoExtension = $type[1]; + $this->_AudioInfoMessageIDs = (string) $this->_currentNZBFile['segments'][0]; + } + } - if (isset($this->_currentNZBFile['segments'])) { - // Get the extension. - $this->_AudioInfoExtension = $type[1]; - $this->_AudioInfoMessageIDs = (string)$this->_currentNZBFile['segments'][0]; - } - } + // Some releases contain many books, increment this to ignore them later. + if (preg_match($this->_ignoreBookRegex, $this->_currentNZBFile['title'])) { + $totalBookFiles++; + } + } - // Some releases contain many books, increment this to ignore them later. - if (preg_match($this->_ignoreBookRegex, $this->_currentNZBFile['title'])) { - $totalBookFiles++; - } - } - return $totalBookFiles; - } + return $totalBookFiles; + } - /** - * List of message-id's we have tried for rar/zip files. - * @var array - */ - protected $_triedCompressedMids = []; + /** + * List of message-id's we have tried for rar/zip files. + * @var array + */ + protected $_triedCompressedMids = []; - /** - * Process the NZB contents, find RAR/ZIP files, download them and extract them. - * - * @param bool $reverse Reverse sort $this->_nzbContents ? - To find the largest rar / zip file first. - */ - protected function _processNZBCompressedFiles($reverse = false) - { - $this->_reverse = $reverse; + /** + * Process the NZB contents, find RAR/ZIP files, download them and extract them. + * + * @param bool $reverse Reverse sort $this->_nzbContents ? - To find the largest rar / zip file first. + */ + protected function _processNZBCompressedFiles($reverse = false) + { + $this->_reverse = $reverse; - if ($this->_reverse) { - if (!krsort($this->_nzbContents)) { - return; - } - } else { - $this->_triedCompressedMids = []; - } + if ($this->_reverse) { + if (! krsort($this->_nzbContents)) { + return; + } + } else { + $this->_triedCompressedMids = []; + } - $failed = $downloaded = 0; - // Loop through the files, attempt to find if password-ed and files. Starting with what not to process. - foreach ($this->_nzbContents as $nzbFile) { - // TODO change this to max calculated size, as segments vary in size greatly. - if ($downloaded >= $this->_maximumRarSegments) { - break; - } else if ($failed >= $this->_maximumRarPasswordChecks) { - break; - } + $failed = $downloaded = 0; + // Loop through the files, attempt to find if password-ed and files. Starting with what not to process. + foreach ($this->_nzbContents as $nzbFile) { + // TODO change this to max calculated size, as segments vary in size greatly. + if ($downloaded >= $this->_maximumRarSegments) { + break; + } elseif ($failed >= $this->_maximumRarPasswordChecks) { + break; + } - if ($this->_releaseHasPassword === true) { - $this->_echo('Skipping processing of rar ' . $nzbFile['title'] . ' it has a password.', 'primaryOver', false); - break; - } + if ($this->_releaseHasPassword === true) { + $this->_echo('Skipping processing of rar '.$nzbFile['title'].' it has a password.', 'primaryOver', false); + break; + } - // Probably not a rar/zip. - if (!preg_match( + // Probably not a rar/zip. + if (! preg_match( '/\.(part\d+|r\d+|rar|0+|0*10?|zipr\d{2,3}|zipx?)(\s*\.rar)*($|[ ")\]-])|"[a-f0-9]{32}\.[1-9]\d{1,2}".*\(\d+\/\d{2,}\)$/i', $nzbFile['title'] ) ) { - continue; - } + continue; + } - // Get message-id's for the rar file. - $segCount = (count($nzbFile['segments']) - 1); - $mID = []; - for ($i = 0; $i < $this->_maximumRarSegments; $i++) { - if ($i > $segCount) { - break; - } - $segment = (string)$nzbFile['segments'][$i]; - if (!$this->_reverse) { - $this->_triedCompressedMids[] = $segment; - } else if (in_array($segment, $this->_triedCompressedMids)) { - // We already downloaded this file. - continue 2; - } - $mID[] = $segment; - } - // Nothing to download. - if (empty($mID)) { - continue; - } + // Get message-id's for the rar file. + $segCount = (count($nzbFile['segments']) - 1); + $mID = []; + for ($i = 0; $i < $this->_maximumRarSegments; $i++) { + if ($i > $segCount) { + break; + } + $segment = (string) $nzbFile['segments'][$i]; + if (! $this->_reverse) { + $this->_triedCompressedMids[] = $segment; + } elseif (in_array($segment, $this->_triedCompressedMids)) { + // We already downloaded this file. + continue 2; + } + $mID[] = $segment; + } + // Nothing to download. + if (empty($mID)) { + continue; + } - // Download the article(s) from usenet. - $fetchedBinary = $this->_nntp->getMessages($this->_releaseGroupName, $mID, $this->_alternateNNTP); - if ($this->_nntp->isError($fetchedBinary)) { - $fetchedBinary = false; - } + // Download the article(s) from usenet. + $fetchedBinary = $this->_nntp->getMessages($this->_releaseGroupName, $mID, $this->_alternateNNTP); + if ($this->_nntp->isError($fetchedBinary)) { + $fetchedBinary = false; + } - if ($fetchedBinary !== false) { + if ($fetchedBinary !== false) { // Echo we downloaded compressed file. - if ($this->_echoCLI) { - $this->_echo('(cB)', 'primaryOver', false); - } + if ($this->_echoCLI) { + $this->_echo('(cB)', 'primaryOver', false); + } - $downloaded++; + $downloaded++; - // Process the compressed file. - $decompressed = $this->_processCompressedData($fetchedBinary); + // Process the compressed file. + $decompressed = $this->_processCompressedData($fetchedBinary); - if ($decompressed === true || $this->_releaseHasPassword === true) { - break; - } + if ($decompressed === true || $this->_releaseHasPassword === true) { + break; + } + } else { + $failed++; + if ($this->_echoCLI) { + $this->_echo('f('.$failed.')', 'warningOver', false); + } + } + } + } - } else { - $failed++; - if ($this->_echoCLI) { - $this->_echo('f(' . $failed . ')', 'warningOver', false); - } - } - } - } + /** + * Check if the data is a ZIP / RAR file, extract files, get file info. + * + * @param string $compressedData + * + * @return bool + */ + protected function _processCompressedData(&$compressedData) + { + $this->_compressedFilesChecked++; + // Give the data to archive info so it can check if it's a rar. + if ($this->_archiveInfo->setData($compressedData, true) === false) { + $this->_debug('Data is probably not RAR or ZIP.'.PHP_EOL); - /** - * Check if the data is a ZIP / RAR file, extract files, get file info. - * - * @param string $compressedData - * - * @return bool - */ - protected function _processCompressedData(&$compressedData) - { - $this->_compressedFilesChecked++; - // Give the data to archive info so it can check if it's a rar. - if ($this->_archiveInfo->setData($compressedData, true) === false) { - $this->_debug('Data is probably not RAR or ZIP.' . PHP_EOL); - return false; - } + return false; + } - // Check if there's an error. - if ($this->_archiveInfo->error !== '') { - $this->_debug('ArchiveInfo Error: ' . $this->_archiveInfo->error); - return false; - } + // Check if there's an error. + if ($this->_archiveInfo->error !== '') { + $this->_debug('ArchiveInfo Error: '.$this->_archiveInfo->error); - // Get a summary of the compressed file. - $dataSummary = $this->_archiveInfo->getSummary(true); + return false; + } - // Check if the compressed file is encrypted. - 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; - return false; - } + // Get a summary of the compressed file. + $dataSummary = $this->_archiveInfo->getSummary(true); - switch ($dataSummary['main_type']) { + // Check if the compressed file is encrypted. + 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; + + return false; + } + + switch ($dataSummary['main_type']) { case ArchiveInfo::TYPE_RAR: if ($this->_echoCLI) { - $this->_echo('r', 'primaryOver', false); + $this->_echo('r', 'primaryOver', false); } if ($this->_extractUsingRarInfo === false && $this->_unrarPath !== false) { - $fileName = $this->tmpPath . uniqid() . '.rar'; - file_put_contents($fileName, $compressedData); - Utility::runCmd( - $this->_killString . $this->_unrarPath . - '" e -ai -ep -c- -id -inul -kb -or -p- -r -y "' . - $fileName . '" "' . $this->tmpPath . 'unrar/"' + $fileName = $this->tmpPath.uniqid().'.rar'; + file_put_contents($fileName, $compressedData); + Utility::runCmd( + $this->_killString.$this->_unrarPath. + '" e -ai -ep -c- -id -inul -kb -or -p- -r -y "'. + $fileName.'" "'.$this->tmpPath.'unrar/"' ); - unlink($fileName); + unlink($fileName); } break; case ArchiveInfo::TYPE_ZIP: if ($this->_echoCLI) { - $this->_echo('z', 'primaryOver', false); + $this->_echo('z', 'primaryOver', false); } if ($this->_extractUsingRarInfo === false && $this->_7zipPath !== false) { - $fileName = $this->tmpPath . uniqid() . '.zip'; - file_put_contents($fileName, $compressedData); - Utility::runCmd( - $this->_killString . $this->_7zipPath . '" x "' . - $fileName . '" -bd -y -o"' . $this->tmpPath . 'unzip/"' + $fileName = $this->tmpPath.uniqid().'.zip'; + file_put_contents($fileName, $compressedData); + Utility::runCmd( + $this->_killString.$this->_7zipPath.'" x "'. + $fileName.'" -bd -y -o"'.$this->tmpPath.'unzip/"' ); - unlink($fileName); + unlink($fileName); } break; default: return false; } - return $this->_processCompressedFileList(); - } + return $this->_processCompressedFileList(); + } - /** - * Get a list of all files in the compressed file, add the file info to the DB. - * - * @return bool - */ - protected function _processCompressedFileList() - { - // Get a list of files inside the Compressed file. - $files = $this->_archiveInfo->getArchiveFileList(); - if (!is_array($files) || count($files) === 0) { - return false; - } + /** + * Get a list of all files in the compressed file, add the file info to the DB. + * + * @return bool + */ + protected function _processCompressedFileList() + { + // Get a list of files inside the Compressed file. + $files = $this->_archiveInfo->getArchiveFileList(); + if (! is_array($files) || count($files) === 0) { + return false; + } - // Loop through the files. - foreach ($files as $file) { + // Loop through the files. + foreach ($files as $file) { + if ($this->_releaseHasPassword === true) { + break; + } - if ($this->_releaseHasPassword === true) { - break; - } + if (isset($file['name'])) { + if (isset($file['error'])) { + $this->_debug("Error: {$file['error']} (in: {$file['source']})"); + continue; + } - if (isset($file['name'])) { + if (isset($file['pass']) && $file['pass'] == true) { + $this->_releaseHasPassword = true; + $this->_passwordStatus[] = Releases::PASSWD_RAR; + break; + } - if (isset($file['error'])) { - $this->_debug("Error: {$file['error']} (in: {$file['source']})"); - continue; - } + if ($this->_innerFileBlacklist !== false && preg_match($this->_innerFileBlacklist, $file['name'])) { + $this->_releaseHasPassword = true; + $this->_passwordStatus[] = Releases::PASSWD_POTENTIAL; + break; + } - if (isset($file['pass']) && $file['pass'] == true) { - $this->_releaseHasPassword = true; - $this->_passwordStatus[] = Releases::PASSWD_RAR; - break; - } + $fileName = []; + if (preg_match('/[^\/\\\\]*\.[a-zA-Z0-9]*$/', $file['name'], $fileName)) { + $fileName = $fileName[0]; + } else { + $fileName = ''; + } - if ($this->_innerFileBlacklist !== false && preg_match($this->_innerFileBlacklist, $file['name'])) { - $this->_releaseHasPassword = true; - $this->_passwordStatus[] = Releases::PASSWD_POTENTIAL; - break; - } - - $fileName = []; - if (preg_match('/[^\/\\\\]*\.[a-zA-Z0-9]*$/', $file['name'], $fileName)) { - $fileName = $fileName[0]; - } else { - $fileName = ''; - } - - if ($this->_extractUsingRarInfo === true) { - // Extract files from the rar. - if (isset($file['compressed']) && $file['compressed'] == 0) { - @file_put_contents( - ($this->tmpPath . random_int(10, 999999) . '_' . $fileName), + if ($this->_extractUsingRarInfo === true) { + // Extract files from the rar. + if (isset($file['compressed']) && $file['compressed'] == 0) { + @file_put_contents( + ($this->tmpPath.random_int(10, 999999).'_'.$fileName), $this->_archiveInfo->getFileData($file['name'], $file['source']) ); - } // If the files are compressed, use a binary extractor. - else { - $this->_archiveInfo->extractFile($file['name'], $this->tmpPath . random_int(10, 999999) . '_' . $fileName); - } - } - } - $this->_addFileInfo($file); - } - if ($this->_addedFileInfo > 0) { - $this->sphinx->updateRelease($this->_release['id'], $this->pdo); - } - return ($this->_totalFileInfo > 0 ? true : false); - } + } // If the files are compressed, use a binary extractor. + else { + $this->_archiveInfo->extractFile($file['name'], $this->tmpPath.random_int(10, 999999).'_'.$fileName); + } + } + } + $this->_addFileInfo($file); + } + if ($this->_addedFileInfo > 0) { + $this->sphinx->updateRelease($this->_release['id'], $this->pdo); + } - /** - * Add info from files within RAR/ZIP/PAR2/etc... - * - * @param array $file - * - * @void - */ - protected function _addFileInfo(&$file) - { - // Don't add rar/zip files to the DB. - if (!isset($file['error']) && isset($file['source']) && - !preg_match($this->_supportFileRegex . '|part\d+|r\d{1,3}|zipr\d{2,3}|\d{2,3}|zipx|zip|rar)(\s*\.rar)?$/i', $file['name']) + return $this->_totalFileInfo > 0 ? true : false; + } + + /** + * Add info from files within RAR/ZIP/PAR2/etc... + * + * @param array $file + * + * @void + */ + protected function _addFileInfo(&$file) + { + // Don't add rar/zip files to the DB. + if (! isset($file['error']) && isset($file['source']) && + ! preg_match($this->_supportFileRegex.'|part\d+|r\d{1,3}|zipr\d{2,3}|\d{2,3}|zipx|zip|rar)(\s*\.rar)?$/i', $file['name']) ) { // Cache the amount of files we find in the RAR or ZIP, return this to say we did find RAR or ZIP content. - // This is so we don't download more RAR or ZIP files for no reason. - $this->_totalFileInfo++; + // This is so we don't download more RAR or ZIP files for no reason. + $this->_totalFileInfo++; - /* Check if we already have the file or not. - * Also make sure we don't add too many files, some releases have 100's of files, like PS3 releases. - */ - if ($this->_addedFileInfo < 11 && + /* Check if we already have the file or not. + * Also make sure we don't add too many files, some releases have 100's of files, like PS3 releases. + */ + if ($this->_addedFileInfo < 11 && $this->pdo->queryOneRow( sprintf( ' @@ -1226,147 +1226,142 @@ class ProcessAdditional ) ) === false ) { + if ($this->_releaseFiles->add($this->_release['id'], $file['name'], '', $file['size'], $file['date'], $file['pass'])) { + $this->_addedFileInfo++; - if ($this->_releaseFiles->add($this->_release['id'], $file['name'], '', $file['size'], $file['date'], $file['pass'])) { - $this->_addedFileInfo++; + if ($this->_echoCLI) { + $this->_echo('^', 'primaryOver', false); + } - if ($this->_echoCLI) { - $this->_echo('^', 'primaryOver', false); - } - - // Check for "codec spam" - if (preg_match('/alt\.binaries\.movies($|\.divx$)/', $this->_releaseGroupName) && + // Check for "codec spam" + if (preg_match('/alt\.binaries\.movies($|\.divx$)/', $this->_releaseGroupName) && preg_match('/[\/\\\\]Codec[\/\\\\]Setup\.exe/i', $file['name']) ) { - $this->_debug('Codec spam found, setting release to potentially passworded.' . PHP_EOL); - $this->_releaseHasPassword = true; - $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']; - $this->_release['releases_id'] = $this->_release['id']; - $this->_nameFixer->matchPredbFiles($this->_release, 1, 1, true, 1); - } - } - } - } - } + $this->_debug('Codec spam found, setting release to potentially passworded.'.PHP_EOL); + $this->_releaseHasPassword = true; + $this->_passwordStatus[] = Releases::PASSWD_POTENTIAL; + } //Run a PreDB filename check on insert to try and match the release + elseif (strpos($file['name'], '.') != 0 && strlen($file['name']) > 0) { + $this->_release['filename'] = $file['name']; + $this->_release['releases_id'] = $this->_release['id']; + $this->_nameFixer->matchPredbFiles($this->_release, 1, 1, true, 1); + } + } + } + } + } - /** - * Go through all the extracted files in the temp folder and process them. - */ - protected function _processExtractedFiles() - { - $nestedLevels = 0; + /** + * Go through all the extracted files in the temp folder and process them. + */ + protected function _processExtractedFiles() + { + $nestedLevels = 0; - // Go through all the files in the temp folder, look for compressed files, extract them and the nested ones. - while ($nestedLevels < $this->_maxNestedLevels) { + // Go through all the files in the temp folder, look for compressed files, extract them and the nested ones. + while ($nestedLevels < $this->_maxNestedLevels) { // Break out if we checked more than x compressed files. - if ($this->_compressedFilesChecked >= self::maxCompressedFilesToCheck) { - break; - } + if ($this->_compressedFilesChecked >= self::maxCompressedFilesToCheck) { + break; + } - $foundCompressedFile = false; + $foundCompressedFile = false; - // 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'); + // 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) { - foreach ($files as $file) { + if ($files instanceof \Traversable) { + foreach ($files as $file) { // Check if the file exists. - if (is_file($file[0])) { - $rarData = @file_get_contents($file[0]); - if ($rarData !== false) { - $this->_processCompressedData($rarData); - $foundCompressedFile = true; - } - @unlink($file[0]); - } - } - } + if (is_file($file[0])) { + $rarData = @file_get_contents($file[0]); + if ($rarData !== false) { + $this->_processCompressedData($rarData); + $foundCompressedFile = true; + } + @unlink($file[0]); + } + } + } - // If we found no compressed files, break out. - if ($foundCompressedFile === false) { - break; - } + // If we found no compressed files, break out. + if ($foundCompressedFile === false) { + break; + } - $nestedLevels++; - } + $nestedLevels++; + } - $fileType = []; + $fileType = []; - // Get all the remaining files in the temp dir. - $files = $this->_getTempDirectoryContents(); - if ($files instanceof \Traversable) { + // Get all the remaining files in the temp dir. + $files = $this->_getTempDirectoryContents(); + if ($files instanceof \Traversable) { + foreach ($files as $file) { + $file = (string) $file; - foreach ($files as $file) { - $file = (string)$file; + // Skip /. and /.. + if (preg_match('/[\/\\\\]\.{1,2}$/', $file)) { + continue; + } - // Skip /. and /.. - if (preg_match('/[\/\\\\]\.{1,2}$/', $file)) { - continue; - } - - if (is_file($file)) { + if (is_file($file)) { // Process PAR2 files. - if ($this->_foundPAR2Info === false && preg_match('/\.par2$/', $file)) { - $this->_siftPAR2Info($file); - } // Process NFO files. - else if ($this->_releaseHasNoNFO === true && preg_match('/(\.(nfo|inf|ofn)|info\.txt)$/i', $file)) { - $this->_processNfoFile($file); - } // Process audio files. - else if ( + if ($this->_foundPAR2Info === false && preg_match('/\.par2$/', $file)) { + $this->_siftPAR2Info($file); + } // Process NFO files. + elseif ($this->_releaseHasNoNFO === true && preg_match('/(\.(nfo|inf|ofn)|info\.txt)$/i', $file)) { + $this->_processNfoFile($file); + } // Process audio files. + elseif ( ($this->_foundAudioInfo === false || $this->_foundAudioSample === false) && - preg_match('/(.*)' . $this->_audioFileRegex . '$/i', $file, $fileType) + preg_match('/(.*)'.$this->_audioFileRegex.'$/i', $file, $fileType) ) { - // Try to get audio sample/audio media info. - @rename($file, $this->tmpPath . 'audiofile.' . $fileType[2]); - $this->_getAudioInfo($this->tmpPath . 'audiofile.' . $fileType[2], $fileType[2]); - @unlink($this->tmpPath . 'audiofile.' . $fileType[2]); - } // Process JPG files. - else if ($this->_foundJPGSample === false && preg_match('/\.jpe?g$/i', $file)) { - $this->_getJPGSample($file); - @unlink($file); - } // Video sample // video clip // video media info. - else if (($this->_foundSample === false || $this->_foundVideo === false || $this->_foundMediaInfo === false) && - preg_match('/(.*)' . $this->_videoFileRegex . '$/i', $file) + // Try to get audio sample/audio media info. + @rename($file, $this->tmpPath.'audiofile.'.$fileType[2]); + $this->_getAudioInfo($this->tmpPath.'audiofile.'.$fileType[2], $fileType[2]); + @unlink($this->tmpPath.'audiofile.'.$fileType[2]); + } // Process JPG files. + elseif ($this->_foundJPGSample === false && preg_match('/\.jpe?g$/i', $file)) { + $this->_getJPGSample($file); + @unlink($file); + } // Video sample // video clip // video media info. + elseif (($this->_foundSample === false || $this->_foundVideo === false || $this->_foundMediaInfo === false) && + preg_match('/(.*)'.$this->_videoFileRegex.'$/i', $file) ) { - $this->_processVideoFile($file); - } // Check if it's alt.binaries.u4e file. - else if (in_array($this->_releaseGroupName, ['alt.binaries.u4e', 'alt.binaries.mom']) && + $this->_processVideoFile($file); + } // Check if it's alt.binaries.u4e file. + elseif (in_array($this->_releaseGroupName, ['alt.binaries.u4e', 'alt.binaries.mom']) && preg_match('/Linux_2rename\.sh/i', $file) && ($this->_release['categories_id'] == Category::OTHER_HASHED || $this->_release['categories_id'] == Category::OTHER_MISC) ) { - $this->_processU4ETitle($file); - } + $this->_processU4ETitle($file); + } - // Check file's magic info. - else { - $output = Utility::fileInfo($file); - if (!empty($output)) { + // Check file's magic info. + else { + $output = Utility::fileInfo($file); + if (! empty($output)) { + switch (true) { - switch (true) { - - case ($this->_foundJPGSample === false && preg_match('/^JPE?G/i', $output)): + case $this->_foundJPGSample === false && preg_match('/^JPE?G/i', $output): $this->_getJPGSample($file); @unlink($file); break; - case ( + case ($this->_foundMediaInfo === false || $this->_foundSample === false || $this->_foundVideo === false) - && preg_match('/Matroska data|MPEG v4|MPEG sequence, v2|\WAVI\W/i', $output) - ): + && preg_match('/Matroska data|MPEG v4|MPEG sequence, v2|\WAVI\W/i', $output): $this->_processVideoFile($file); break; - case ( + case ($this->_foundAudioSample === false || $this->_foundAudioInfo === false) && - preg_match('/^FLAC|layer III|Vorbis audio/i', $output, $fileType) - ): + preg_match('/^FLAC|layer III|Vorbis audio/i', $output, $fileType): switch ($fileType[0]) { case 'FLAC': $fileType = 'FLAC'; @@ -1378,220 +1373,206 @@ class ProcessAdditional $fileType = 'OGG'; break; } - @rename($file, $this->tmpPath . 'audiofile.' . $fileType); - $this->_getAudioInfo($this->tmpPath . 'audiofile.' . $fileType, $fileType); - @unlink($this->tmpPath . 'audiofile.' . $fileType); + @rename($file, $this->tmpPath.'audiofile.'.$fileType); + $this->_getAudioInfo($this->tmpPath.'audiofile.'.$fileType, $fileType); + @unlink($this->tmpPath.'audiofile.'.$fileType); break; - case ($this->_foundPAR2Info === false && preg_match('/^Parity/i', $output)): + case $this->_foundPAR2Info === false && preg_match('/^Parity/i', $output): $this->_siftPAR2Info($file); break; } - } - } - } - } - } - } + } + } + } + } + } + } - /** - * Download all binaries from usenet and form samples / get media info / etc from them. - * - * @void - */ - protected function _processMessageIDDownloads() - { - $this->_processSampleMessageIDs(); - $this->_processMediaInfoMessageIDs(); - $this->_processAudioInfoMessageIDs(); - $this->_processJPGMessageIDs(); + /** + * Download all binaries from usenet and form samples / get media info / etc from them. + * + * @void + */ + protected function _processMessageIDDownloads() + { + $this->_processSampleMessageIDs(); + $this->_processMediaInfoMessageIDs(); + $this->_processAudioInfoMessageIDs(); + $this->_processJPGMessageIDs(); + } - } - - /** - * Download and process binaries for sample videos. - * - * @void - * @access protected - */ - protected function _processSampleMessageIDs() - { - // Download and process sample image. - if ($this->_foundSample === false || $this->_foundVideo === false) { - - if (!empty($this->_sampleMessageIDs)) { + /** + * Download and process binaries for sample videos. + * + * @void + */ + protected function _processSampleMessageIDs() + { + // Download and process sample image. + if ($this->_foundSample === false || $this->_foundVideo === false) { + if (! empty($this->_sampleMessageIDs)) { // Download it from usenet. - $sampleBinary = $this->_nntp->getMessages($this->_releaseGroupName, $this->_sampleMessageIDs, $this->_alternateNNTP); - if ($this->_nntp->isError($sampleBinary)) { - $sampleBinary = false; - } + $sampleBinary = $this->_nntp->getMessages($this->_releaseGroupName, $this->_sampleMessageIDs, $this->_alternateNNTP); + if ($this->_nntp->isError($sampleBinary)) { + $sampleBinary = false; + } - if ($sampleBinary !== false) { - if ($this->_echoCLI) { - $this->_echo('(sB)', 'primaryOver', false); - } + if ($sampleBinary !== false) { + if ($this->_echoCLI) { + $this->_echo('(sB)', 'primaryOver', false); + } - // Check if it's more than 40 bytes. - if (strlen($sampleBinary) > 40) { + // Check if it's more than 40 bytes. + if (strlen($sampleBinary) > 40) { + $fileLocation = $this->tmpPath.'sample_'.random_int(0, 99999).'.avi'; + // Try to create the file. + @file_put_contents($fileLocation, $sampleBinary); - $fileLocation = $this->tmpPath . 'sample_' . random_int(0, 99999) . '.avi'; - // Try to create the file. - @file_put_contents($fileLocation, $sampleBinary); + // Try to get a sample picture. + if ($this->_foundSample === false) { + $this->_foundSample = $this->_getSample($fileLocation); + } - // Try to get a sample picture. - if ($this->_foundSample === false) { - $this->_foundSample = $this->_getSample($fileLocation); - } + // Try to get a sample video. + if ($this->_foundVideo === false) { + $this->_foundVideo = $this->_getVideo($fileLocation); + } - // Try to get a sample video. - if ($this->_foundVideo === false) { - $this->_foundVideo = $this->_getVideo($fileLocation); - } - - // Try to get media info. Don't get it here if $mediaMsgID is not empty. + // Try to get media info. Don't get it here if $mediaMsgID is not empty. // 2014-06-28 -> Commented out, since the media info of a sample video is not indicative of the actual release.si /*if ($this->_foundMediaInfo === false && empty($mediaMsgID)) { $this->_foundMediaInfo = $this->_getMediaInfo($fileLocation); }*/ + } + } elseif ($this->_echoCLI) { + $this->_echo('f', 'warningOver', false); + } + } + } + } - } - } else if ($this->_echoCLI) { - $this->_echo('f', 'warningOver', false); - } - } - } - } - - /** - * Download and process binaries for media info from videos. - * - * @void - * @access protected - */ - protected function _processMediaInfoMessageIDs() - { - // Download and process mediainfo. Also try to get a sample if we didn't get one yet. - if ($this->_foundMediaInfo === false || $this->_foundSample === false || $this->_foundVideo === false) { - - if ($this->_foundMediaInfo === false && !empty($this->_MediaInfoMessageIDs)) { + /** + * Download and process binaries for media info from videos. + * + * @void + */ + protected function _processMediaInfoMessageIDs() + { + // Download and process mediainfo. Also try to get a sample if we didn't get one yet. + if ($this->_foundMediaInfo === false || $this->_foundSample === false || $this->_foundVideo === false) { + if ($this->_foundMediaInfo === false && ! empty($this->_MediaInfoMessageIDs)) { // Try to download it from usenet. - $mediaBinary = $this->_nntp->getMessages($this->_releaseGroupName, $this->_MediaInfoMessageIDs, $this->_alternateNNTP); - if ($this->_nntp->isError($mediaBinary)) { - // If error set it to false. - $mediaBinary = false; - } + $mediaBinary = $this->_nntp->getMessages($this->_releaseGroupName, $this->_MediaInfoMessageIDs, $this->_alternateNNTP); + if ($this->_nntp->isError($mediaBinary)) { + // If error set it to false. + $mediaBinary = false; + } - if ($mediaBinary !== false) { + if ($mediaBinary !== false) { + if ($this->_echoCLI) { + $this->_echo('(mB)', 'primaryOver', false); + } - if ($this->_echoCLI) { - $this->_echo('(mB)', 'primaryOver', false); - } + // If it's more than 40 bytes... + if (strlen($mediaBinary) > 40) { + $fileLocation = $this->tmpPath.'media.avi'; + // Create a file on the disk with it. + @file_put_contents($fileLocation, $mediaBinary); - // If it's more than 40 bytes... - if (strlen($mediaBinary) > 40) { + // Try to get media info. + if ($this->_foundMediaInfo === false) { + $this->_foundMediaInfo = $this->_getMediaInfo($fileLocation); + } - $fileLocation = $this->tmpPath . 'media.avi'; - // Create a file on the disk with it. - @file_put_contents($fileLocation, $mediaBinary); + // Try to get a sample picture. + if ($this->_foundSample === false) { + $this->_foundSample = $this->_getSample($fileLocation); + } - // Try to get media info. - if ($this->_foundMediaInfo === false) { - $this->_foundMediaInfo = $this->_getMediaInfo($fileLocation); - } + // Try to get a sample video. + if ($this->_foundVideo === false) { + $this->_foundVideo = $this->_getVideo($fileLocation); + } + } + } elseif ($this->_echoCLI) { + $this->_echo('f', 'warningOver', false); + } + } + } + } - // Try to get a sample picture. - if ($this->_foundSample === false) { - $this->_foundSample = $this->_getSample($fileLocation); - } + /** + * Download and process binaries for media info from songs. + * + * @void + */ + protected function _processAudioInfoMessageIDs() + { + // Download audio file, use media info to try to get the artist / album. + if (($this->_foundAudioInfo === false || $this->_foundAudioSample === false)) { + if (! empty($this->_AudioInfoMessageIDs)) { + // Try to download it from usenet. + $audioBinary = $this->_nntp->getMessages($this->_releaseGroupName, $this->_AudioInfoMessageIDs, $this->_alternateNNTP); + if ($this->_nntp->isError($audioBinary)) { + $audioBinary = false; + } - // Try to get a sample video. - if ($this->_foundVideo === false) { - $this->_foundVideo = $this->_getVideo($fileLocation); - } - } - } else if ($this->_echoCLI) { - $this->_echo('f', 'warningOver', false); - } - } - } - } + if ($audioBinary !== false) { + if ($this->_echoCLI) { + $this->_echo('(aB)', 'primaryOver', false); + } - /** - * Download and process binaries for media info from songs. - * - * @void - * @access protected - */ - protected function _processAudioInfoMessageIDs() - { - // Download audio file, use media info to try to get the artist / album. - if (($this->_foundAudioInfo === false || $this->_foundAudioSample === false)) { + $fileLocation = $this->tmpPath.'audio.'.$this->_AudioInfoExtension; + // Create a file with it. + @file_put_contents($fileLocation, $audioBinary); - if (!empty($this->_AudioInfoMessageIDs)) { - // Try to download it from usenet. - $audioBinary = $this->_nntp->getMessages($this->_releaseGroupName, $this->_AudioInfoMessageIDs, $this->_alternateNNTP); - if ($this->_nntp->isError($audioBinary)) { - $audioBinary = false; - } + // Try to get media info / sample of the audio file. + $this->_getAudioInfo($fileLocation, $this->_AudioInfoExtension); + } elseif ($this->_echoCLI) { + $this->_echo('f', 'warningOver', false); + } + } + } + } - if ($audioBinary !== false) { - if ($this->_echoCLI) { - $this->_echo('(aB)', 'primaryOver', false); - } - - $fileLocation = $this->tmpPath . 'audio.' . $this->_AudioInfoExtension; - // Create a file with it. - @file_put_contents($fileLocation, $audioBinary); - - // Try to get media info / sample of the audio file. - $this->_getAudioInfo($fileLocation, $this->_AudioInfoExtension); - - } else if ($this->_echoCLI) { - $this->_echo('f', 'warningOver', false); - } - } - } - } - - /** - * Download and process binaries for JPG pictures. - * - * @void - * @access protected - */ - protected function _processJPGMessageIDs() - { - // Download JPG file. - if ($this->_foundJPGSample === false && !empty($this->_JPGMessageIDs)) { + /** + * Download and process binaries for JPG pictures. + * + * @void + */ + protected function _processJPGMessageIDs() + { + // Download JPG file. + if ($this->_foundJPGSample === false && ! empty($this->_JPGMessageIDs)) { // Try to download it. - $jpgBinary = $this->_nntp->getMessages($this->_releaseGroupName, $this->_JPGMessageIDs, $this->_alternateNNTP); - if ($this->_nntp->isError($jpgBinary)) { - $jpgBinary = false; - } + $jpgBinary = $this->_nntp->getMessages($this->_releaseGroupName, $this->_JPGMessageIDs, $this->_alternateNNTP); + if ($this->_nntp->isError($jpgBinary)) { + $jpgBinary = false; + } - if ($jpgBinary !== false) { + if ($jpgBinary !== false) { + if ($this->_echoCLI) { + $this->_echo('(jB)', 'primaryOver', false); + } - if ($this->_echoCLI) { - $this->_echo('(jB)', 'primaryOver', false); - } + // Try to create a file with it. + @file_put_contents($this->tmpPath.'samplepicture.jpg', $jpgBinary); - // Try to create a file with it. - @file_put_contents($this->tmpPath . 'samplepicture.jpg', $jpgBinary); - - // Try to resize and move it. - $this->_foundJPGSample = ( + // Try to resize and move it. + $this->_foundJPGSample = ( $this->_releaseImage->saveImage( - $this->_release['guid'] . '_thumb', $this->tmpPath . 'samplepicture.jpg', + $this->_release['guid'].'_thumb', $this->tmpPath.'samplepicture.jpg', $this->_releaseImage->jpgSavePath, 650, 650 ) === 1 ? true : false ); - if ($this->_foundJPGSample !== false) { - // Update the DB to say we got it. - $this->pdo->queryExec( + if ($this->_foundJPGSample !== false) { + // Update the DB to say we got it. + $this->pdo->queryExec( sprintf( ' UPDATE releases @@ -1602,42 +1583,41 @@ class ProcessAdditional ) ); - if ($this->_echoCLI) { - $this->_echo('j', 'primaryOver', false); - } - } + if ($this->_echoCLI) { + $this->_echo('j', 'primaryOver', false); + } + } - @unlink($this->tmpPath . 'samplepicture.jpg'); + @unlink($this->tmpPath.'samplepicture.jpg'); + } elseif ($this->_echoCLI) { + $this->_echo('f', 'warningOver', false); + } + } + } - } else if ($this->_echoCLI) { - $this->_echo('f', 'warningOver', false); - } - } - } + /** + * Update the release to say we processed it. + */ + protected function _finalizeRelease() + { + $vSQL = $jSQL = ''; + $iSQL = ', haspreview = 0'; - /** - * Update the release to say we processed it. - */ - protected function _finalizeRelease() - { - $vSQL = $jSQL = ''; - $iSQL = ', haspreview = 0'; + // If samples exist from previous runs, set flags. + if (is_file($this->_releaseImage->imgSavePath.$this->_release['guid'].'_thumb.jpg')) { + $iSQL = ', haspreview = 1'; + } - // If samples exist from previous runs, set flags. - if (is_file($this->_releaseImage->imgSavePath . $this->_release['guid'] . '_thumb.jpg')) { - $iSQL = ', haspreview = 1'; - } + if (is_file($this->_releaseImage->vidSavePath.$this->_release['guid'].'.ogv')) { + $vSQL = ', videostatus = 1'; + } - if (is_file($this->_releaseImage->vidSavePath . $this->_release['guid'] . '.ogv')) { - $vSQL = ', videostatus = 1'; - } + if (is_file($this->_releaseImage->jpgSavePath.$this->_release['guid'].'_thumb.jpg')) { + $jSQL = ', jpgstatus = 1'; + } - if (is_file($this->_releaseImage->jpgSavePath . $this->_release['guid'] . '_thumb.jpg')) { - $jSQL = ', jpgstatus = 1'; - } - - // Get the amount of files we found inside the RAR/ZIP files. - $releaseFiles = $this->pdo->queryOneRow( + // Get the amount of files we found inside the RAR/ZIP files. + $releaseFiles = $this->pdo->queryOneRow( sprintf( ' SELECT COUNT(release_files.releases_id) AS count, @@ -1648,20 +1628,20 @@ class ProcessAdditional ) ); - if ($releaseFiles === false) { - $releaseFiles['count'] = $releaseFiles['size'] = 0; - } + if ($releaseFiles === false) { + $releaseFiles['count'] = $releaseFiles['size'] = 0; + } - $this->_passwordStatus = max($this->_passwordStatus); + $this->_passwordStatus = max($this->_passwordStatus); - // Set the release to no password if password processing is off. - if ($this->_processPasswords === false) { - $this->_releaseHasPassword = false; - } + // Set the release to no password if password processing is off. + if ($this->_processPasswords === false) { + $this->_releaseHasPassword = false; + } - // If we failed to get anything from the RAR/ZIPs, decrement the passwordstatus, if the rar/zip has no password. - if ($this->_releaseHasPassword === false && $this->_NZBHasCompressedFile && $releaseFiles['count'] == 0) { - $query = sprintf( + // If we failed to get anything from the RAR/ZIPs, decrement the passwordstatus, if the rar/zip has no password. + if ($this->_releaseHasPassword === false && $this->_NZBHasCompressedFile && $releaseFiles['count'] == 0) { + $query = sprintf( 'UPDATE releases SET passwordstatus = passwordstatus - 1, rarinnerfilecount = %d %s %s %s WHERE id = %d', @@ -1671,9 +1651,9 @@ class ProcessAdditional $jSQL, $this->_release['id'] ); - } // Else update the release with the password status (if the admin enabled the setting). - else { - $query = sprintf( + } // Else update the release with the password status (if the admin enabled the setting). + else { + $query = sprintf( 'UPDATE releases SET passwordstatus = %d, rarinnerfilecount = %d %s %s %s WHERE id = %d', @@ -1684,78 +1664,79 @@ class ProcessAdditional $jSQL, $this->_release['id'] ); - } + } - $this->pdo->queryExec($query); - } + $this->pdo->queryExec($query); + } - /** - * Return array of files in the Temp Directory. - * Optional, pass a regex to filter the files. - * - * @param string $pattern Regex, optional - * @param string $path Path to the folder (if empty, uses $this->tmpPath) - * - * @return \Iterator Object|bool - */ - protected function _getTempDirectoryContents($pattern = '', $path = '') - { - if ($path === '') { - $path = $this->tmpPath; - } - try { - if ($pattern !== '') { - return new \RegexIterator( + /** + * Return array of files in the Temp Directory. + * Optional, pass a regex to filter the files. + * + * @param string $pattern Regex, optional + * @param string $path Path to the folder (if empty, uses $this->tmpPath) + * + * @return \Iterator Object|bool + */ + protected function _getTempDirectoryContents($pattern = '', $path = '') + { + if ($path === '') { + $path = $this->tmpPath; + } + try { + if ($pattern !== '') { + return new \RegexIterator( new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($path) ), $pattern, \RecursiveRegexIterator::GET_MATCH ); - } else { - return new \RecursiveIteratorIterator( + } else { + return new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($path) ); - } - } catch (\Exception $e) { - $this->_debug('ERROR: Could not open temp dir: ' . $e->getMessage() . PHP_EOL); - return false; - } - } + } + } catch (\Exception $e) { + $this->_debug('ERROR: Could not open temp dir: '.$e->getMessage().PHP_EOL); - /** - * Fetch MediaInfo and a OGG sample for a Audio file. - * - * @param string $fileLocation - * @param string $fileExtension - * - * @return bool - */ - protected function _getAudioInfo($fileLocation, $fileExtension) - { - // Return values. - $retVal = $audVal = false; + return false; + } + } - // Check if audio sample fetching is on. - if ($this->_processAudioSample === false) { - $audVal = true; - } + /** + * Fetch MediaInfo and a OGG sample for a Audio file. + * + * @param string $fileLocation + * @param string $fileExtension + * + * @return bool + */ + protected function _getAudioInfo($fileLocation, $fileExtension) + { + // Return values. + $retVal = $audVal = false; - // Check if media info fetching is on. - if ($this->_processAudioInfo === false) { - $retVal = true; - } + // Check if audio sample fetching is on. + if ($this->_processAudioSample === false) { + $audVal = true; + } - // Make sure the category is music or other. - $rQuery = $this->pdo->queryOneRow( + // Check if media info fetching is on. + if ($this->_processAudioInfo === false) { + $retVal = true; + } + + // Make sure the category is music or other. + $rQuery = $this->pdo->queryOneRow( sprintf( 'SELECT searchname, fromname, categories_id AS id, groups_id FROM releases WHERE proc_pp = 0 AND id = %d', $this->_release['id'] ) ); - $musicParent = (string)Category::MUSIC_ROOT; - if ($rQuery === false || !preg_match( + $musicParent = (string) Category::MUSIC_ROOT; + if ($rQuery === false || ! preg_match( sprintf( '/%d\d{3}|%d|%d|%d/', $musicParent[0], @@ -1766,52 +1747,49 @@ class ProcessAdditional $rQuery['id'] ) ) { - return false; - } + return false; + } - if (is_file($fileLocation)) { + if (is_file($fileLocation)) { // Check if media info is enabled. - if ($retVal === false) { + if ($retVal === false) { // Get the media info for the file. - $xmlArray = Utility::runCmd( - $this->_killString . Settings::value('apps..mediainfopath') . '" --Output=XML "' . $fileLocation . '"' + $xmlArray = Utility::runCmd( + $this->_killString.Settings::value('apps..mediainfopath').'" --Output=XML "'.$fileLocation.'"' ); - if (is_array($xmlArray)) { + if (is_array($xmlArray)) { // Convert to array. - $arrXml = Utility::objectsIntoArray(@simplexml_load_string(implode("\n", $xmlArray))); + $arrXml = Utility::objectsIntoArray(@simplexml_load_string(implode("\n", $xmlArray))); - if (isset($arrXml['File']['track'])) { + if (isset($arrXml['File']['track'])) { + foreach ($arrXml['File']['track'] as $track) { + if (isset($track['Album']) && isset($track['Performer'])) { + if (NN_RENAME_MUSIC_MEDIAINFO && $this->_release['predb_id'] == 0) { + // Make the extension upper case. + $ext = strtoupper($fileExtension); - foreach ($arrXml['File']['track'] as $track) { + // Form a new search name. + if (! empty($track['Recorded_date']) && preg_match('/(?:19|20)\d\d/', $track['Recorded_date'], $Year)) { + $newName = $track['Performer'].' - '.$track['Album'].' ('.$Year[0].') '.$ext; + } else { + $newName = $track['Performer'].' - '.$track['Album'].' '.$ext; + } - if (isset($track['Album']) && isset($track['Performer'])) { + // Get the category or try to determine it. + if ($ext === 'MP3') { + $newCat = Category::MUSIC_MP3; + } elseif ($ext === 'FLAC') { + $newCat = Category::MUSIC_LOSSLESS; + } else { + $newCat = $this->_categorize->determineCategory($rQuery['groups_id'], $newName, $rQuery['fromname']); + } - if (NN_RENAME_MUSIC_MEDIAINFO && $this->_release['predb_id'] == 0) { - // Make the extension upper case. - $ext = strtoupper($fileExtension); - - // Form a new search name. - if (!empty($track['Recorded_date']) && preg_match('/(?:19|20)\d\d/', $track['Recorded_date'], $Year)) { - $newName = $track['Performer'] . ' - ' . $track['Album'] . ' (' . $Year[0] . ') ' . $ext; - } else { - $newName = $track['Performer'] . ' - ' . $track['Album'] . ' ' . $ext; - } - - // Get the category or try to determine it. - if ($ext === 'MP3') { - $newCat = Category::MUSIC_MP3; - } else if ($ext === 'FLAC') { - $newCat = Category::MUSIC_LOSSLESS; - } else { - $newCat = $this->_categorize->determineCategory($rQuery['groups_id'], $newName, $rQuery['fromname']); - } - - $newTitle = $this->pdo->escapeString(substr($newName, 0, 255)); - // Update the search name. - $this->pdo->queryExec( + $newTitle = $this->pdo->escapeString(substr($newName, 0, 255)); + // Update the search name. + $this->pdo->queryExec( sprintf( ' UPDATE releases @@ -1822,11 +1800,11 @@ class ProcessAdditional $this->_release['id'] ) ); - $this->sphinx->updateRelease($this->_release['id'], $this->pdo); + $this->sphinx->updateRelease($this->_release['id'], $this->pdo); - // Echo the changed name. - if ($this->_echoCLI) { - NameFixer::echoChangedReleaseName( + // Echo the changed name. + if ($this->_echoCLI) { + NameFixer::echoChangedReleaseName( [ 'new_name' => $newName, 'old_name' => $rQuery['searchname'], @@ -1834,68 +1812,68 @@ class ProcessAdditional 'old_category' => $rQuery['id'], 'group' => $rQuery['groups_id'], 'releases_id' => $this->_release['id'], - 'method' => 'ProcessAdditional->_getAudioInfo' + 'method' => 'ProcessAdditional->_getAudioInfo', ] ); - } - } + } + } - // Add the media info. - $this->_releaseExtra->addFromXml($this->_release['id'], $xmlArray); + // Add the media info. + $this->_releaseExtra->addFromXml($this->_release['id'], $xmlArray); - $retVal = true; - $this->_foundAudioInfo = true; - if ($this->_echoCLI) { - $this->_echo('a', 'primaryOver', false); - } - break; - } - } - } - } - } + $retVal = true; + $this->_foundAudioInfo = true; + if ($this->_echoCLI) { + $this->_echo('a', 'primaryOver', false); + } + break; + } + } + } + } + } - // Check if creating audio samples is enabled. - if ($audVal === false) { + // Check if creating audio samples is enabled. + if ($audVal === false) { // File name to store audio file. - $audioFileName = ($this->_release['guid'] . '.ogg'); + $audioFileName = ($this->_release['guid'].'.ogg'); - // Create an audio sample. - Utility::runCmd( - $this->_killString . - Settings::value('apps..ffmpegpath') . - '" -t 30 -i "' . - $fileLocation . - '" -acodec libvorbis -loglevel quiet -y "' . - $this->tmpPath . $audioFileName . + // Create an audio sample. + Utility::runCmd( + $this->_killString. + Settings::value('apps..ffmpegpath'). + '" -t 30 -i "'. + $fileLocation. + '" -acodec libvorbis -loglevel quiet -y "'. + $this->tmpPath.$audioFileName. '"' ); - // Check if the new file was created. - if (is_file($this->tmpPath . $audioFileName)) { + // Check if the new file was created. + if (is_file($this->tmpPath.$audioFileName)) { // Try to move the temp audio file. - $renamed = rename($this->tmpPath . $audioFileName, $this->_audioSavePath . $audioFileName); + $renamed = rename($this->tmpPath.$audioFileName, $this->_audioSavePath.$audioFileName); - if (!$renamed) { - // Try to copy it if it fails. - $copied = copy($this->tmpPath . $audioFileName, $this->_audioSavePath . $audioFileName); + if (! $renamed) { + // Try to copy it if it fails. + $copied = copy($this->tmpPath.$audioFileName, $this->_audioSavePath.$audioFileName); - // Delete the old file. - unlink($this->tmpPath . $audioFileName); + // Delete the old file. + unlink($this->tmpPath.$audioFileName); - // If it didn't copy continue. - if (!$copied) { - return false; - } - } + // If it didn't copy continue. + if (! $copied) { + return false; + } + } - // Try to set the file perms. - @chmod($this->_audioSavePath . $audioFileName, 0764); + // Try to set the file perms. + @chmod($this->_audioSavePath.$audioFileName, 0764); - // Update DB to said we got a audio sample. - $this->pdo->queryExec( + // Update DB to said we got a audio sample. + $this->pdo->queryExec( sprintf( ' UPDATE releases @@ -1905,36 +1883,36 @@ class ProcessAdditional ) ); - $audVal = $this->_foundAudioSample = true; + $audVal = $this->_foundAudioSample = true; - if ($this->_echoCLI) { - $this->_echo('A', 'primaryOver', false); - } + if ($this->_echoCLI) { + $this->_echo('A', 'primaryOver', false); + } + } + } + } - } - } - } - return ($retVal && $audVal); - } + return $retVal && $audVal; + } - /** - * Try to get JPG picture, resize it and store it on disk. - * - * @param string $fileLocation - */ - protected function _getJPGSample($fileLocation) - { - // Try to resize/move the image. - $this->_foundJPGSample = ( + /** + * Try to get JPG picture, resize it and store it on disk. + * + * @param string $fileLocation + */ + protected function _getJPGSample($fileLocation) + { + // Try to resize/move the image. + $this->_foundJPGSample = ( $this->_releaseImage->saveImage( - $this->_release['guid'] . '_thumb', + $this->_release['guid'].'_thumb', $fileLocation, $this->_releaseImage->jpgSavePath, 650, 650 ) === 1 ? true : false ); - // If it's successful, tell the DB. - if ($this->_foundJPGSample !== false) { - $this->pdo->queryExec( + // If it's successful, tell the DB. + if ($this->_foundJPGSample !== false) { + $this->pdo->queryExec( sprintf( ' UPDATE releases @@ -1944,224 +1922,223 @@ class ProcessAdditional $this->_release['id'] ) ); - } - } + } + } - /** - * Get accurate time from video segment. - * - * @param string $videoLocation - * - * @return string - */ - private function getVideoTime($videoLocation) - { - // Attempt to get the file extension as ffmpeg fails on some videos with the wrong extension, avconv however is fine. - if (preg_match('/(\.[a-zA-Z0-9]+)\s*$/', $videoLocation, $extension)) { - $extension = $extension[1]; - } else { - $extension = '.avi'; - } + /** + * Get accurate time from video segment. + * + * @param string $videoLocation + * + * @return string + */ + private function getVideoTime($videoLocation) + { + // Attempt to get the file extension as ffmpeg fails on some videos with the wrong extension, avconv however is fine. + if (preg_match('/(\.[a-zA-Z0-9]+)\s*$/', $videoLocation, $extension)) { + $extension = $extension[1]; + } else { + $extension = '.avi'; + } - $tmpVideo = ($this->tmpPath . uniqid() . $extension); - // Get the real duration of the file. - $time = Utility::runCmd( - $this->_killString . - Settings::value('apps..ffmpegpath') . - '" -i "' . $videoLocation . - '" -vcodec copy -y 2>&1 "' . - $tmpVideo . '"', + $tmpVideo = ($this->tmpPath.uniqid().$extension); + // Get the real duration of the file. + $time = Utility::runCmd( + $this->_killString. + Settings::value('apps..ffmpegpath'). + '" -i "'.$videoLocation. + '" -vcodec copy -y 2>&1 "'. + $tmpVideo.'"', false ); - @unlink($tmpVideo); + @unlink($tmpVideo); - if (empty($time) || !preg_match('/time=(\d{1,2}:\d{1,2}:)?(\d{1,2})\.(\d{1,2})\s*bitrate=/i', implode(' ', $time), $numbers)) { - return ''; - } else { - // Reduce the last number by 1, this is to make sure we don't ask avconv/ffmpeg for non existing data. - if ($numbers[3] > 0) { - $numbers[3] -= 1; - } else if ($numbers[1] > 0) { - $numbers[2] -= 1; - $numbers[3] = '99'; - } - // Manually pad the numbers in case they are 1 number. to get 02 for example instead of 2. - return ('00:00:' . str_pad($numbers[2], 2, '0', STR_PAD_LEFT) . '.' . str_pad($numbers[3], 2, '0', STR_PAD_LEFT)); - } - } + if (empty($time) || ! preg_match('/time=(\d{1,2}:\d{1,2}:)?(\d{1,2})\.(\d{1,2})\s*bitrate=/i', implode(' ', $time), $numbers)) { + return ''; + } else { + // Reduce the last number by 1, this is to make sure we don't ask avconv/ffmpeg for non existing data. + if ($numbers[3] > 0) { + $numbers[3] -= 1; + } elseif ($numbers[1] > 0) { + $numbers[2] -= 1; + $numbers[3] = '99'; + } + // Manually pad the numbers in case they are 1 number. to get 02 for example instead of 2. + return '00:00:'.str_pad($numbers[2], 2, '0', STR_PAD_LEFT).'.'.str_pad($numbers[3], 2, '0', STR_PAD_LEFT); + } + } - /** - * Try to get a preview image from a video file. - * - * @param string $fileLocation - * - * @return bool - */ - protected function _getSample($fileLocation) - { - if (!$this->_processThumbnails) { - return false; - } + /** + * Try to get a preview image from a video file. + * + * @param string $fileLocation + * + * @return bool + */ + protected function _getSample($fileLocation) + { + if (! $this->_processThumbnails) { + return false; + } - if (is_file($fileLocation)) { + if (is_file($fileLocation)) { // Create path to temp file. - $fileName = ($this->tmpPath . 'zzzz' . random_int(5, 12) . random_int(5, 12) . '.jpg'); + $fileName = ($this->tmpPath.'zzzz'.random_int(5, 12).random_int(5, 12).'.jpg'); - $time = $this->getVideoTime($fileLocation); + $time = $this->getVideoTime($fileLocation); - // Create the image. - Utility::runCmd( - $this->_killString . - Settings::value('apps..ffmpegpath') . - '" -i "' . - $fileLocation . - '" -ss ' . ($time === '' ? '00:00:03.00' : $time) . - ' -vframes 1 -loglevel quiet -y "' . - $fileName . + // Create the image. + Utility::runCmd( + $this->_killString. + Settings::value('apps..ffmpegpath'). + '" -i "'. + $fileLocation. + '" -ss '.($time === '' ? '00:00:03.00' : $time). + ' -vframes 1 -loglevel quiet -y "'. + $fileName. '"' ); - // Check if the file exists. - if (is_file($fileName)) { + // Check if the file exists. + if (is_file($fileName)) { // Try to resize/move the image. - $saved = $this->_releaseImage->saveImage( - $this->_release['guid'] . '_thumb', + $saved = $this->_releaseImage->saveImage( + $this->_release['guid'].'_thumb', $fileName, $this->_releaseImage->imgSavePath, 800, 600 ); - // Delete the temp file we created. - @unlink($fileName); + // Delete the temp file we created. + @unlink($fileName); - // Check if it saved. - if ($saved === 1) { + // Check if it saved. + if ($saved === 1) { + if ($this->_echoCLI) { + $this->_echo('s', 'primaryOver', false); + } - if ($this->_echoCLI) { - $this->_echo('s', 'primaryOver', false); - } - return true; - } - } - } - return false; - } + return true; + } + } + } - /** - * Try to get a preview video from a video file. - * - * @param string $fileLocation - * - * @return bool - */ - protected function _getVideo($fileLocation) - { - if (!$this->_processVideo) { - return false; - } + return false; + } - // Try to find an avi file. - if (is_file($fileLocation)) { + /** + * Try to get a preview video from a video file. + * + * @param string $fileLocation + * + * @return bool + */ + protected function _getVideo($fileLocation) + { + if (! $this->_processVideo) { + return false; + } + + // Try to find an avi file. + if (is_file($fileLocation)) { // Create a filename to store the temp file. - $fileName = ($this->tmpPath . 'zzzz' . $this->_release['guid'] . '.ogv'); + $fileName = ($this->tmpPath.'zzzz'.$this->_release['guid'].'.ogv'); - $newMethod = false; - // If wanted sample length is less than 60, try to get sample from the end of the video. - if ($this->_ffMPEGDuration < 60) { - // Get the real duration of the file. - $time = $this->getVideoTime($fileLocation); + $newMethod = false; + // If wanted sample length is less than 60, try to get sample from the end of the video. + if ($this->_ffMPEGDuration < 60) { + // Get the real duration of the file. + $time = $this->getVideoTime($fileLocation); - if ($time !== '' && preg_match('/(\d{2}).(\d{2})/', $time, $numbers)) { - $newMethod = true; + if ($time !== '' && preg_match('/(\d{2}).(\d{2})/', $time, $numbers)) { + $newMethod = true; - // Get the lowest time we can start making the video at based on how many seconds the admin wants the video to be. - if ($numbers[1] <= $this->_ffMPEGDuration) { - // If the clip is shorter than the length we want. + // Get the lowest time we can start making the video at based on how many seconds the admin wants the video to be. + if ($numbers[1] <= $this->_ffMPEGDuration) { + // If the clip is shorter than the length we want. - // The lowest we want is 0. - $lowestLength = '00:00:00.00'; + // The lowest we want is 0. + $lowestLength = '00:00:00.00'; + } else { + // If the clip is longer than the length we want. - } else { - // If the clip is longer than the length we want. + // The lowest we want is the the difference between the max video length and our wanted total time. + $lowestLength = ($numbers[1] - $this->_ffMPEGDuration); - // The lowest we want is the the difference between the max video length and our wanted total time. - $lowestLength = ($numbers[1] - $this->_ffMPEGDuration); - - // Form the time string. - $end = '.' . $numbers[2]; - switch (strlen($lowestLength)) { + // Form the time string. + $end = '.'.$numbers[2]; + switch (strlen($lowestLength)) { case 1: - $lowestLength = ('00:00:0' . (string)$lowestLength . $end); + $lowestLength = ('00:00:0'.(string) $lowestLength.$end); break; case 2: - $lowestLength = ('00:00:' . (string)$lowestLength . $end); + $lowestLength = ('00:00:'.(string) $lowestLength.$end); break; default: $lowestLength = '00:00:60.00'; } - } + } - // Try to get the sample (from the end instead of the start). - Utility::runCmd( - $this->_killString . - Settings::value('apps..ffmpegpath') . - '" -i "' . - $fileLocation . - '" -ss ' . $lowestLength . - ' -t ' . $this->_ffMPEGDuration . - ' -vcodec libtheora -filter:v scale=320:-1 ' . - ' -acodec libvorbis -loglevel quiet -y "' . - $fileName . + // Try to get the sample (from the end instead of the start). + Utility::runCmd( + $this->_killString. + Settings::value('apps..ffmpegpath'). + '" -i "'. + $fileLocation. + '" -ss '.$lowestLength. + ' -t '.$this->_ffMPEGDuration. + ' -vcodec libtheora -filter:v scale=320:-1 '. + ' -acodec libvorbis -loglevel quiet -y "'. + $fileName. '"' ); - } - } + } + } - if ($newMethod === false) { - // If longer than 60 or we could not get the video length, run the old way. - Utility::runCmd( - $this->_killString . - Settings::value('apps..ffmpegpath') . - '" -i "' . - $fileLocation . - '" -vcodec libtheora -filter:v scale=320:-1 -t ' . - $this->_ffMPEGDuration . - ' -acodec libvorbis -loglevel quiet -y "' . - $fileName . + if ($newMethod === false) { + // If longer than 60 or we could not get the video length, run the old way. + Utility::runCmd( + $this->_killString. + Settings::value('apps..ffmpegpath'). + '" -i "'. + $fileLocation. + '" -vcodec libtheora -filter:v scale=320:-1 -t '. + $this->_ffMPEGDuration. + ' -acodec libvorbis -loglevel quiet -y "'. + $fileName. '"' ); - } + } - // Until we find the video file. - if (is_file($fileName)) { + // Until we find the video file. + if (is_file($fileName)) { // Create a path to where the file should be moved. - $newFile = ($this->_releaseImage->vidSavePath . $this->_release['guid'] . '.ogv'); + $newFile = ($this->_releaseImage->vidSavePath.$this->_release['guid'].'.ogv'); - // Try to move the file to the new path. - $renamed = @rename($fileName, $newFile); + // Try to move the file to the new path. + $renamed = @rename($fileName, $newFile); - // If we couldn't rename it, try to copy it. - if (!$renamed) { + // If we couldn't rename it, try to copy it. + if (! $renamed) { + $copied = @copy($fileName, $newFile); - $copied = @copy($fileName, $newFile); + // Delete the old file. + @unlink($fileName); - // Delete the old file. - @unlink($fileName); + // If it didn't copy, continue. + if (! $copied) { + return false; + } + } - // If it didn't copy, continue. - if (!$copied) { - return false; - } - } + // Change the permissions. + @chmod($newFile, 0764); - // Change the permissions. - @chmod($newFile, 0764); - - // Update query to say we got the video. - $this->pdo->queryExec( + // Update query to say we got the video. + $this->pdo->queryExec( sprintf( ' UPDATE releases @@ -2170,73 +2147,77 @@ class ProcessAdditional $this->pdo->escapeString($this->_release['guid']) ) ); - if ($this->_echoCLI) { - $this->_echo('v', 'primaryOver', false); - } - return true; - } - } - return false; - } + if ($this->_echoCLI) { + $this->_echo('v', 'primaryOver', false); + } - /** - * Try to get media info xml from a video file. - * - * @param string $fileLocation - * - * @return bool - */ - protected function _getMediaInfo($fileLocation) - { - if (!$this->_processMediaInfo) { - return false; - } + return true; + } + } - // Look for the video file. - if (is_file($fileLocation)) { + return false; + } + + /** + * Try to get media info xml from a video file. + * + * @param string $fileLocation + * + * @return bool + */ + protected function _getMediaInfo($fileLocation) + { + if (! $this->_processMediaInfo) { + return false; + } + + // Look for the video file. + if (is_file($fileLocation)) { // Run media info on it. - $xmlArray = Utility::runCmd( - $this->_killString . Settings::value('apps..mediainfopath') . '" --Output=XML "' . $fileLocation . '"' + $xmlArray = Utility::runCmd( + $this->_killString.Settings::value('apps..mediainfopath').'" --Output=XML "'.$fileLocation.'"' ); - // Check if we got it. - if (is_array($xmlArray)) { + // Check if we got it. + if (is_array($xmlArray)) { // Convert it to string. - $xmlArray = implode("\n", $xmlArray); + $xmlArray = implode("\n", $xmlArray); - if (!preg_match('/<track type="(Audio|Video)">/i', $xmlArray)) { - return false; - } + if (! preg_match('/<track type="(Audio|Video)">/i', $xmlArray)) { + return false; + } - // Insert it into the DB. - $this->_releaseExtra->addFull($this->_release['id'], $xmlArray); - $this->_releaseExtra->addFromXml($this->_release['id'], $xmlArray); + // Insert it into the DB. + $this->_releaseExtra->addFull($this->_release['id'], $xmlArray); + $this->_releaseExtra->addFromXml($this->_release['id'], $xmlArray); - if ($this->_echoCLI) { - $this->_echo('m', 'primaryOver', false); - } - return true; - } - } - return false; - } + if ($this->_echoCLI) { + $this->_echo('m', 'primaryOver', false); + } - /** - * Get file info from inside PAR2, store it in DB, attempt to get a release name. - * - * @param string $fileLocation - */ - protected function _siftPAR2Info($fileLocation) - { - $this->_par2Info->open($fileLocation); + return true; + } + } - if ($this->_par2Info->error) { - return; - } + return false; + } - $releaseInfo = $this->pdo->queryOneRow( + /** + * Get file info from inside PAR2, store it in DB, attempt to get a release name. + * + * @param string $fileLocation + */ + protected function _siftPAR2Info($fileLocation) + { + $this->_par2Info->open($fileLocation); + + if ($this->_par2Info->error) { + return; + } + + $releaseInfo = $this->pdo->queryOneRow( sprintf( ' SELECT UNIX_TIMESTAMP(postdate) AS postdate, proc_pp @@ -2246,40 +2227,38 @@ class ProcessAdditional ) ); - if ($releaseInfo === false) { - return; - } + if ($releaseInfo === false) { + return; + } - // Only get a new name if the category is OTHER. - $foundName = true; - if (NN_RENAME_PAR2 && + // Only get a new name if the category is OTHER. + $foundName = true; + if (NN_RENAME_PAR2 && $releaseInfo['proc_pp'] === 0 && in_array( - (int)$this->_release['categories_id'], + (int) $this->_release['categories_id'], Category::OTHERS_GROUP ) ) { - $foundName = false; - } + $foundName = false; + } - $filesAdded = 0; + $filesAdded = 0; - $files = $this->_par2Info->getFileList(); - foreach ($files as $file) { + $files = $this->_par2Info->getFileList(); + foreach ($files as $file) { + if (! isset($file['name'])) { + continue; + } - if (!isset($file['name'])) { - continue; - } + // If we found a name and added 10 files, stop. + if ($foundName === true && $filesAdded > 10) { + break; + } - // If we found a name and added 10 files, stop. - if ($foundName === true && $filesAdded > 10) { - break; - } - - - // Add to release files. - if ($this->_addPAR2Files) { - if ($filesAdded < 11 && + // Add to release files. + if ($this->_addPAR2Files) { + if ($filesAdded < 11 && $this->pdo->queryOneRow( sprintf( 'SELECT releases_id FROM release_files WHERE releases_id = %d AND name = %s', @@ -2289,107 +2268,107 @@ class ProcessAdditional ) { // Try to add the files to the DB. - if ($this->_releaseFiles->add($this->_release['id'], $file['name'], $file['hash_16K'], $file['size'], $releaseInfo['postdate'], 0)) { - $filesAdded++; - } - } - } else { - $filesAdded++; - } + if ($this->_releaseFiles->add($this->_release['id'], $file['name'], $file['hash_16K'], $file['size'], $releaseInfo['postdate'], 0)) { + $filesAdded++; + } + } + } else { + $filesAdded++; + } - // Try to get a new name. - if ($foundName === false) { - $this->_release['textstring'] = $file['name']; - $this->_release['releases_id'] = $this->_release['id']; - if ($this->_nameFixer->checkName($this->_release, ($this->_echoCLI ? true : false), 'PAR2, ', 1, 1) === true) { - $foundName = true; - } - } - } - // Update the file count with the new file count + old file count. - $this->pdo->queryExec( + // Try to get a new name. + if ($foundName === false) { + $this->_release['textstring'] = $file['name']; + $this->_release['releases_id'] = $this->_release['id']; + if ($this->_nameFixer->checkName($this->_release, ($this->_echoCLI ? true : false), 'PAR2, ', 1, 1) === true) { + $foundName = true; + } + } + } + // Update the file count with the new file count + old file count. + $this->pdo->queryExec( sprintf( 'UPDATE releases SET rarinnerfilecount = rarinnerfilecount + %d WHERE id = %d', $filesAdded, $this->_release['id'] ) ); - $this->_foundPAR2Info = true; - } + $this->_foundPAR2Info = true; + } - /** - * Verify a file is a NFO and add it to the database. - * - * @param string $fileLocation - */ - protected function _processNfoFile($fileLocation) - { - $data = @file_get_contents($fileLocation); - if ($data !== false) { - if ($this->_nfo->isNFO($data, $this->_release['guid']) === true) { - if ($this->_nfo->addAlternateNfo($data, $this->_release, $this->_nntp) === true) { - $this->_releaseHasNoNFO = false; - } - } - } - } + /** + * Verify a file is a NFO and add it to the database. + * + * @param string $fileLocation + */ + protected function _processNfoFile($fileLocation) + { + $data = @file_get_contents($fileLocation); + if ($data !== false) { + if ($this->_nfo->isNFO($data, $this->_release['guid']) === true) { + if ($this->_nfo->addAlternateNfo($data, $this->_release, $this->_nntp) === true) { + $this->_releaseHasNoNFO = false; + } + } + } + } - /** - * Process a video file for a preview image/video and mediainfo. - * - * @param string $fileLocation - */ - protected function _processVideoFile($fileLocation) - { - // Try to get a sample with it. - if ($this->_foundSample === false) { - $this->_foundSample = $this->_getSample($fileLocation); - } + /** + * Process a video file for a preview image/video and mediainfo. + * + * @param string $fileLocation + */ + protected function _processVideoFile($fileLocation) + { + // Try to get a sample with it. + if ($this->_foundSample === false) { + $this->_foundSample = $this->_getSample($fileLocation); + } - /* Try to get a video with it. - * Don't get it here if _sampleMessageIDs is empty - * or has 1 message-id (Saves downloading another part). - */ - if ($this->_foundVideo === false && count($this->_sampleMessageIDs) < 2) { - $this->_foundVideo = $this->_getVideo($fileLocation); - } + /* Try to get a video with it. + * Don't get it here if _sampleMessageIDs is empty + * or has 1 message-id (Saves downloading another part). + */ + if ($this->_foundVideo === false && count($this->_sampleMessageIDs) < 2) { + $this->_foundVideo = $this->_getVideo($fileLocation); + } - // Try to get media info with it. - if ($this->_foundMediaInfo === false) { - $this->_foundMediaInfo = $this->_getMediaInfo($fileLocation); - } - } + // Try to get media info with it. + if ($this->_foundMediaInfo === false) { + $this->_foundMediaInfo = $this->_getMediaInfo($fileLocation); + } + } - /** - * Try to get a title from a Linux_2rename.sh file for alt.binaries.u4e group. - * - * @param string $fileLocation - */ - protected function _processU4ETitle($fileLocation) - { - // Open the file for reading. - $handle = @fopen($fileLocation, 'r'); - // Check if it failed. - if ($handle) { - // Loop over the file line by line. - while (($buffer = fgets($handle, 16384)) !== false) { - // Check if we find the word - if (stripos($buffer, 'mkdir') !== false) { + /** + * Try to get a title from a Linux_2rename.sh file for alt.binaries.u4e group. + * + * @param string $fileLocation + */ + protected function _processU4ETitle($fileLocation) + { + // Open the file for reading. + $handle = @fopen($fileLocation, 'r'); + // Check if it failed. + if ($handle) { + // Loop over the file line by line. + while (($buffer = fgets($handle, 16384)) !== false) { + // Check if we find the word + if (stripos($buffer, 'mkdir') !== false) { // Get a new name. - $newName = trim(str_replace('mkdir ', '', $buffer)); + $newName = trim(str_replace('mkdir ', '', $buffer)); - // Check if it's a empty string or not. - if (empty($newName)) { - continue; - } + // Check if it's a empty string or not. + if (empty($newName)) { + continue; + } - // Get a new category ID. - $newCategory = $this->_categorize->determineCategory($this->_release['groups_id'], $newName, $this->_release['fromname']); + // Get a new category ID. + $newCategory = $this->_categorize->determineCategory($this->_release['groups_id'], $newName, $this->_release['fromname']); - $newTitle = $this->pdo->escapeString(substr($newName, 0, 255)); - // Update the release with the data. - $this->pdo->queryExec( + $newTitle = $this->pdo->escapeString(substr($newName, 0, 255)); + // Update the release with the data. + $this->pdo->queryExec( sprintf( 'UPDATE releases SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL, consoleinfo_id = NULL, @@ -2401,11 +2380,11 @@ class ProcessAdditional $this->_release['id'] ) ); - $this->sphinx->updateRelease($this->_release['id'], $this->pdo); + $this->sphinx->updateRelease($this->_release['id'], $this->pdo); - // Echo the changed name to CLI. - if ($this->_echoCLI) { - NameFixer::echoChangedReleaseName( + // Echo the changed name to CLI. + if ($this->_echoCLI) { + NameFixer::echoChangedReleaseName( [ 'new_name' => $newName, 'old_name' => $this->_release['searchname'], @@ -2413,167 +2392,165 @@ class ProcessAdditional 'old_category' => $this->_release['categories_id'], 'group' => $this->_release['groups_id'], 'releases_id' => $this->_release['id'], - 'method' => 'ProcessAdditional->_processU4ETitle' + 'method' => 'ProcessAdditional->_processU4ETitle', ] ); - } + } - // Break out of the loop. - break; - } - } - // Close the file. - fclose($handle); - } - // Delete the file. - @unlink($fileLocation); - } + // Break out of the loop. + break; + } + } + // Close the file. + fclose($handle); + } + // Delete the file. + @unlink($fileLocation); + } - /** - * Convert bytes to KB/MB/GB/TB and return in human readable format. - * - * @example 240640 would return 235KB - * - * @param int $bytes - * - * @return string - */ - protected function _readableBytesString($bytes) - { - $kb = 1024; - $mb = 1048576; - $gb = 1073741824; - $tb = $kb * $gb; - if ($bytes < $kb) { - return $bytes . 'B'; - } else if ($bytes < $mb) { - return round($bytes / $kb, 1) . 'KB'; - } else if ($bytes < $gb) { - return round($bytes / $mb, 1) . 'MB'; - } else if ($bytes < $tb) { - return round($bytes / $gb, 1) . 'GB'; - } else { - return round($bytes / $tb, 1) . 'TB'; - } - } + /** + * Convert bytes to KB/MB/GB/TB and return in human readable format. + * + * @example 240640 would return 235KB + * + * @param int $bytes + * + * @return string + */ + protected function _readableBytesString($bytes) + { + $kb = 1024; + $mb = 1048576; + $gb = 1073741824; + $tb = $kb * $gb; + if ($bytes < $kb) { + return $bytes.'B'; + } elseif ($bytes < $mb) { + return round($bytes / $kb, 1).'KB'; + } elseif ($bytes < $gb) { + return round($bytes / $mb, 1).'MB'; + } elseif ($bytes < $tb) { + return round($bytes / $gb, 1).'GB'; + } else { + return round($bytes / $tb, 1).'TB'; + } + } - /** - * Comparison function for uSort, for sorting NZB files. - * - * @param array $a - * @param array $b - * - * @return int - */ - protected function _sortNZB($a, $b) - { - $pos = 0; - $af = $bf = false; - $a = preg_replace('/\d+[- ._]?(\/|\||[o0]f)[- ._]?\d+?(?![- ._]\d)/i', ' ', $a['title']); - $b = preg_replace('/\d+[- ._]?(\/|\||[o0]f)[- ._]?\d+?(?![- ._]\d)/i', ' ', $b['title']); + /** + * Comparison function for uSort, for sorting NZB files. + * + * @param array $a + * @param array $b + * + * @return int + */ + protected function _sortNZB($a, $b) + { + $pos = 0; + $af = $bf = false; + $a = preg_replace('/\d+[- ._]?(\/|\||[o0]f)[- ._]?\d+?(?![- ._]\d)/i', ' ', $a['title']); + $b = preg_replace('/\d+[- ._]?(\/|\||[o0]f)[- ._]?\d+?(?![- ._]\d)/i', ' ', $b['title']); - if (preg_match('/\.(part\d+|r\d+)(\s*\.rar)*($|[ ")\]-])/i', $a)) { - $af = true; - } - if (preg_match('/\.(part\d+|r\d+)(\s*\.rar)*($|[ ")\]-])/i', $b)) { - $bf = true; - } + if (preg_match('/\.(part\d+|r\d+)(\s*\.rar)*($|[ ")\]-])/i', $a)) { + $af = true; + } + if (preg_match('/\.(part\d+|r\d+)(\s*\.rar)*($|[ ")\]-])/i', $b)) { + $bf = true; + } - if (!$af && preg_match('/\.rar($|[ ")\]-])/i', $a)) { - $a = preg_replace('/\.rar(?:$|[ ")\]-])/i', '.*rar', $a); - $af = true; - } - if (!$bf && preg_match('/\.rar($|[ ")\]-])/i', $b)) { - $b = preg_replace('/\.rar(?:$|[ ")\]-])/i', '.*rar', $b); - $bf = true; - } + if (! $af && preg_match('/\.rar($|[ ")\]-])/i', $a)) { + $a = preg_replace('/\.rar(?:$|[ ")\]-])/i', '.*rar', $a); + $af = true; + } + if (! $bf && preg_match('/\.rar($|[ ")\]-])/i', $b)) { + $b = preg_replace('/\.rar(?:$|[ ")\]-])/i', '.*rar', $b); + $bf = true; + } - if (!$af && !$bf) { - return strnatcasecmp($a, $b); - } else if (!$bf) { - return -1; - } else if (!$af) { - return 1; - } + if (! $af && ! $bf) { + return strnatcasecmp($a, $b); + } elseif (! $bf) { + return -1; + } elseif (! $af) { + return 1; + } - if ($af && $bf) { - return strnatcasecmp($a, $b); - } else if ($af) { - return -1; - } else if ($bf) { - return 1; - } + if ($af && $bf) { + return strnatcasecmp($a, $b); + } elseif ($af) { + return -1; + } elseif ($bf) { + return 1; + } - return $pos; - } + return $pos; + } - /** - * Reset some variables for the current release. - */ - protected function _resetReleaseStatus() - { - // Only process for samples, previews and images if not disabled. - $this->_foundVideo = ($this->_processVideo ? false : true); - $this->_foundMediaInfo = ($this->_processMediaInfo ? false : true); - $this->_foundAudioInfo = ($this->_processAudioInfo ? false : true); - $this->_foundAudioSample = ($this->_processAudioSample ? false : true); - $this->_foundJPGSample = ($this->_processJPGSample ? false : true); - $this->_foundSample = ($this->_processThumbnails ? false : true); - $this->_foundSample = (($this->_release['disablepreview'] == 1) ? true : false); - $this->_foundPAR2Info = false; + /** + * Reset some variables for the current release. + */ + protected function _resetReleaseStatus() + { + // Only process for samples, previews and images if not disabled. + $this->_foundVideo = ($this->_processVideo ? false : true); + $this->_foundMediaInfo = ($this->_processMediaInfo ? false : true); + $this->_foundAudioInfo = ($this->_processAudioInfo ? false : true); + $this->_foundAudioSample = ($this->_processAudioSample ? false : true); + $this->_foundJPGSample = ($this->_processJPGSample ? false : true); + $this->_foundSample = ($this->_processThumbnails ? false : true); + $this->_foundSample = (($this->_release['disablepreview'] == 1) ? true : false); + $this->_foundPAR2Info = false; - $this->_passwordStatus = [Releases::PASSWD_NONE]; - $this->_releaseHasPassword = false; + $this->_passwordStatus = [Releases::PASSWD_NONE]; + $this->_releaseHasPassword = false; - $this->_releaseGroupName = $this->_groups->getNameByID($this->_release['groups_id']); + $this->_releaseGroupName = $this->_groups->getNameByID($this->_release['groups_id']); - $this->_releaseHasNoNFO = false; - // Make sure we don't already have an nfo. - if ($this->_release['nfostatus'] != 1) { - $this->_releaseHasNoNFO = true; - } + $this->_releaseHasNoNFO = false; + // Make sure we don't already have an nfo. + if ($this->_release['nfostatus'] != 1) { + $this->_releaseHasNoNFO = true; + } - $this->_NZBHasCompressedFile = false; + $this->_NZBHasCompressedFile = false; - $this->_sampleMessageIDs = $this->_JPGMessageIDs = $this->_MediaInfoMessageIDs = []; - $this->_AudioInfoMessageIDs = $this->_RARFileMessageIDs = []; - $this->_AudioInfoExtension = ''; + $this->_sampleMessageIDs = $this->_JPGMessageIDs = $this->_MediaInfoMessageIDs = []; + $this->_AudioInfoMessageIDs = $this->_RARFileMessageIDs = []; + $this->_AudioInfoExtension = ''; - $this->_addedFileInfo = 0; - $this->_totalFileInfo = 0; - $this->_compressedFilesChecked = 0; - } + $this->_addedFileInfo = 0; + $this->_totalFileInfo = 0; + $this->_compressedFilesChecked = 0; + } - /** - * Echo a string to CLI. - * - * @param string $string String to echo. - * @param string $type Method type. - * @param bool $newLine Print a new line at the end of the string. - * - * @void - */ - protected function _echo($string, $type, $newLine = true) - { - if ($this->_echoCLI) { - ColorCLI::doEcho(ColorCLI::$type($string), $newLine); - } - } + /** + * Echo a string to CLI. + * + * @param string $string String to echo. + * @param string $type Method type. + * @param bool $newLine Print a new line at the end of the string. + * + * @void + */ + protected function _echo($string, $type, $newLine = true) + { + if ($this->_echoCLI) { + ColorCLI::doEcho(ColorCLI::$type($string), $newLine); + } + } - /** - * Echo a string to CLI. For debugging. - * - * @param string $string - * @param bool $newline - * - * @void - */ - protected function _debug($string, $newline = true) - { - if ($this->_echoDebug) { - $this->_echo('DEBUG: ' . $string, 'debug', $newline); - } - } + /** + * Echo a string to CLI. For debugging. + * + * @param string $string + * @param bool $newline + * + * @void + */ + protected function _debug($string, $newline = true) + { + if ($this->_echoDebug) { + $this->_echo('DEBUG: '.$string, 'debug', $newline); + } + } } - -?> diff --git a/nntmux/processing/post/ProcessAdditionalException.php b/nntmux/processing/post/ProcessAdditionalException.php index db93f2348..22c58a251 100755 --- a/nntmux/processing/post/ProcessAdditionalException.php +++ b/nntmux/processing/post/ProcessAdditionalException.php @@ -18,8 +18,8 @@ * @author niel * @copyright 2015 nZEDb */ -namespace nntmux\processing\post; +namespace nntmux\processing\post; class ProcessAdditionalException extends \Exception { diff --git a/nntmux/processing/tv/TMDB.php b/nntmux/processing/tv/TMDB.php index b32fb63e8..5fbb2a1ba 100755 --- a/nntmux/processing/tv/TMDB.php +++ b/nntmux/processing/tv/TMDB.php @@ -1,415 +1,416 @@ <?php + namespace nntmux\processing\tv; -use App\Models\Settings; -use nntmux\ColorCLI; -use nntmux\ReleaseImage; -use Tmdb\ApiToken; use Tmdb\Client; -use Tmdb\Exception\TmdbApiException; +use Tmdb\ApiToken; +use nntmux\ColorCLI; +use App\Models\Settings; +use nntmux\ReleaseImage; use Tmdb\Helper\ImageHelper; +use Tmdb\Exception\TmdbApiException; use Tmdb\Repository\ConfigurationRepository; class TMDB extends TV { - const MATCH_PROBABILITY = 75; + const MATCH_PROBABILITY = 75; - /** - * @var string The URL for the image for poster - */ - public $posterUrl; + /** + * @var string The URL for the image for poster + */ + public $posterUrl; - /** - * @var ApiToken - */ - public $token; + /** + * @var ApiToken + */ + public $token; - /** - * @var Client - */ - public $client; + /** + * @var Client + */ + public $client; - /** - * @var ImageHelper - */ - public $helper; + /** + * @var ImageHelper + */ + public $helper; - /** - * @var ConfigurationRepository - */ - public $configRepository; + /** + * @var ConfigurationRepository + */ + public $configRepository; - /** - * @var \Tmdb\Model\Configuration - */ - public $config; + /** + * @var \Tmdb\Model\Configuration + */ + public $config; - /** - * Construct. Instantiate TMDB Class - * - * @param array $options Class instances. - * - * @access public - * @throws \Exception - */ - public function __construct(array $options = []) - { - parent::__construct($options); - $this->token = new ApiToken(Settings::value('APIs..tmdbkey')); - $this->client = new Client($this->token, [ + /** + * Construct. Instantiate TMDB Class. + * + * @param array $options Class instances. + * + * @throws \Exception + */ + public function __construct(array $options = []) + { + parent::__construct($options); + $this->token = new ApiToken(Settings::value('APIs..tmdbkey')); + $this->client = new Client($this->token, [ 'cache' => [ - 'enabled' => false - ] + 'enabled' => false, + ], ] ); - $this->configRepository = new ConfigurationRepository($this->client); - $this->config = $this->configRepository->load(); - $this->helper = new ImageHelper($this->config); - } + $this->configRepository = new ConfigurationRepository($this->client); + $this->config = $this->configRepository->load(); + $this->helper = new ImageHelper($this->config); + } - /** - * Fetch banner from site. - * - * @param $videoId - * @param $siteID - * - * @return bool - */ - public function getBanner($videoId, $siteID): bool - { - return false; - } + /** + * Fetch banner from site. + * + * @param $videoId + * @param $siteID + * + * @return bool + */ + public function getBanner($videoId, $siteID): bool + { + return false; + } - /** - * Main processing director function for TMDB - * Calls work query function and initiates processing - * - * @param $groupID - * @param $guidChar - * @param $process - * @param bool $local - */ - public function processSite ($groupID, $guidChar, $process, $local = false): void - { - $res = $this->getTvReleases($groupID, $guidChar, $process, parent::PROCESS_TMDB); + /** + * Main processing director function for TMDB + * Calls work query function and initiates processing. + * + * @param $groupID + * @param $guidChar + * @param $process + * @param bool $local + */ + public function processSite($groupID, $guidChar, $process, $local = false): void + { + $res = $this->getTvReleases($groupID, $guidChar, $process, parent::PROCESS_TMDB); - $tvcount = $res->rowCount(); - $lookupSetting = true; + $tvcount = $res->rowCount(); + $lookupSetting = true; - if ($this->echooutput && $tvcount > 0) { - echo ColorCLI::header('Processing TMDB lookup for ' . number_format($tvcount) . ' release(s).'); - } + if ($this->echooutput && $tvcount > 0) { + echo ColorCLI::header('Processing TMDB lookup for '.number_format($tvcount).' release(s).'); + } - if ($res instanceof \Traversable) { + if ($res instanceof \Traversable) { + $this->titleCache = []; - $this->titleCache = []; + foreach ($res as $row) { + $this->posterUrl = ''; + $tmdbid = false; - foreach ($res as $row) { + // Clean the show name for better match probability + $release = $this->parseInfo($row['searchname']); - $this->posterUrl = ''; - $tmdbid = false; - - // Clean the show name for better match probability - $release = $this->parseInfo($row['searchname']); - - if (is_array($release) && $release['name'] !== '') { - - if (in_array($release['cleanname'], $this->titleCache, false)) { - if ($this->echooutput) { - echo ColorCLI::headerOver('Title: ') . - ColorCLI::warningOver($release['cleanname']) . + if (is_array($release) && $release['name'] !== '') { + if (in_array($release['cleanname'], $this->titleCache, false)) { + if ($this->echooutput) { + echo ColorCLI::headerOver('Title: '). + ColorCLI::warningOver($release['cleanname']). ColorCLI::header(' already failed lookup for this site. Skipping.'); - } - $this->setVideoNotFound(parent::PROCESS_TRAKT, $row['id']); - continue; - } + } + $this->setVideoNotFound(parent::PROCESS_TRAKT, $row['id']); + continue; + } - // Find the Video ID if it already exists by checking the title against stored TMDB titles - $videoId = $this->getByTitle($release['cleanname'], parent::TYPE_TV, parent::SOURCE_TMDB); + // Find the Video ID if it already exists by checking the title against stored TMDB titles + $videoId = $this->getByTitle($release['cleanname'], parent::TYPE_TV, parent::SOURCE_TMDB); - // Force local lookup only - if ($local === true) { - $lookupSetting = false; - } + // Force local lookup only + if ($local === true) { + $lookupSetting = false; + } - // If lookups are allowed lets try to get it. - if ($videoId === false && $lookupSetting) { - if ($this->echooutput) { - echo ColorCLI::primaryOver('Checking TMDB for previously failed title: ') . - ColorCLI::headerOver($release['cleanname']) . + // If lookups are allowed lets try to get it. + if ($videoId === false && $lookupSetting) { + if ($this->echooutput) { + echo ColorCLI::primaryOver('Checking TMDB for previously failed title: '). + ColorCLI::headerOver($release['cleanname']). ColorCLI::primary('.'); - } + } - // Get the show from TMDB - $tmdbShow = $this->getShowInfo((string)$release['cleanname']); + // Get the show from TMDB + $tmdbShow = $this->getShowInfo((string) $release['cleanname']); - if (is_array($tmdbShow)) { - // Check if we have the TMDB ID already, if we do use that Video ID - $dupeCheck = $this->getVideoIDFromSiteID('tvdb', $tmdbShow['tvdb']); - if ($dupeCheck === false) { - $videoId = $this->add($tmdbShow); - $tmdbid = $tmdbShow['tmdb']; - } else { - $videoId = $dupeCheck; - // Update any missing fields and add site IDs - $this->update($videoId, $tmdbShow); - $tmdbid = $this->getSiteIDFromVideoID('tmdb', $videoId); - } - } - } else { - if ($this->echooutput) { - echo ColorCLI::primaryOver('Found local TMDB match for: ') . - ColorCLI::headerOver($release['cleanname']) . + if (is_array($tmdbShow)) { + // Check if we have the TMDB ID already, if we do use that Video ID + $dupeCheck = $this->getVideoIDFromSiteID('tvdb', $tmdbShow['tvdb']); + if ($dupeCheck === false) { + $videoId = $this->add($tmdbShow); + $tmdbid = $tmdbShow['tmdb']; + } else { + $videoId = $dupeCheck; + // Update any missing fields and add site IDs + $this->update($videoId, $tmdbShow); + $tmdbid = $this->getSiteIDFromVideoID('tmdb', $videoId); + } + } + } else { + if ($this->echooutput) { + echo ColorCLI::primaryOver('Found local TMDB match for: '). + ColorCLI::headerOver($release['cleanname']). ColorCLI::primary('. Attempting episode lookup!'); - } - $tmdbid = $this->getSiteIDFromVideoID('tmdb', $videoId); - } + } + $tmdbid = $this->getSiteIDFromVideoID('tmdb', $videoId); + } - if (is_numeric($videoId) && $videoId > 0 && is_numeric($tmdbid) && $tmdbid > 0) { - // Now that we have valid video and tmdb ids, try to get the poster - $this->getPoster($videoId, $tmdbid); + if (is_numeric($videoId) && $videoId > 0 && is_numeric($tmdbid) && $tmdbid > 0) { + // Now that we have valid video and tmdb ids, try to get the poster + $this->getPoster($videoId, $tmdbid); - $seasonNo = preg_replace('/^S0*/i', '', $release['season']); - $episodeNo = preg_replace('/^E0*/i', '', $release['episode']); + $seasonNo = preg_replace('/^S0*/i', '', $release['season']); + $episodeNo = preg_replace('/^E0*/i', '', $release['episode']); - if ($episodeNo === 'all') { - // Set the video ID and leave episode 0 - $this->setVideoIdFound($videoId, $row['id'], 0); - echo ColorCLI::primary('Found TMDB Match for Full Season!'); - continue; - } + if ($episodeNo === 'all') { + // Set the video ID and leave episode 0 + $this->setVideoIdFound($videoId, $row['id'], 0); + echo ColorCLI::primary('Found TMDB Match for Full Season!'); + continue; + } - // Download all episodes if new show to reduce API usage - if ($this->countEpsByVideoID($videoId) === false) { - $this->getEpisodeInfo($tmdbid, -1, -1, '', $videoId); - } + // Download all episodes if new show to reduce API usage + if ($this->countEpsByVideoID($videoId) === false) { + $this->getEpisodeInfo($tmdbid, -1, -1, '', $videoId); + } - // Check if we have the episode for this video ID - $episode = $this->getBySeasonEp($videoId, $seasonNo, $episodeNo, $release['airdate']); + // Check if we have the episode for this video ID + $episode = $this->getBySeasonEp($videoId, $seasonNo, $episodeNo, $release['airdate']); - if ($episode === false) { - // Send the request for the episode to TMDB - $tmdbEpisode = $this->getEpisodeInfo( + if ($episode === false) { + // Send the request for the episode to TMDB + $tmdbEpisode = $this->getEpisodeInfo( $tmdbid, $seasonNo, $episodeNo, $release['airdate'] ); - if ($tmdbEpisode) { - $episode = $this->addEpisode($videoId, $tmdbEpisode); - } - } + if ($tmdbEpisode) { + $episode = $this->addEpisode($videoId, $tmdbEpisode); + } + } - if ($episode !== false && is_numeric($episode) && $episode > 0) { - // Mark the releases video and episode IDs - $this->setVideoIdFound($videoId, $row['id'], $episode); - if ($this->echooutput) { - echo ColorCLI::primary('Found TMDB Match!'); - } - continue; - } - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_TRAKT, $row['id']); - } else { - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_TRAKT, $row['id']); - $this->titleCache[] = $release['cleanname']; - } - } else{ - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_TRAKT, $row['id']); - $this->titleCache[] = $release['cleanname']; - } - } - } - } + if ($episode !== false && is_numeric($episode) && $episode > 0) { + // Mark the releases video and episode IDs + $this->setVideoIdFound($videoId, $row['id'], $episode); + if ($this->echooutput) { + echo ColorCLI::primary('Found TMDB Match!'); + } + continue; + } + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_TRAKT, $row['id']); + } else { + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_TRAKT, $row['id']); + $this->titleCache[] = $release['cleanname']; + } + } else { + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_TRAKT, $row['id']); + $this->titleCache[] = $release['cleanname']; + } + } + } + } - /** - * Calls the API to perform initial show name match to TMDB title - * Returns a formatted array of show data or false if no match - * - * @param $cleanName - * - * @return array|bool - */ - protected function getShowInfo($cleanName) - { - $return = $response = false; + /** + * Calls the API to perform initial show name match to TMDB title + * Returns a formatted array of show data or false if no match. + * + * @param $cleanName + * + * @return array|bool + */ + protected function getShowInfo($cleanName) + { + $return = $response = false; - try { - $response = $this->client->getTvApi()->getTvshow($cleanName); - } catch (TmdbApiException $e) { - return false; - } + try { + $response = $this->client->getTvApi()->getTvshow($cleanName); + } catch (TmdbApiException $e) { + return false; + } - sleep(1); + sleep(1); - if (is_array($response) && !empty($response['results'])) { - $return = $this->matchShowInfo($response['results'], $cleanName); - } - return $return; - } + if (is_array($response) && ! empty($response['results'])) { + $return = $this->matchShowInfo($response['results'], $cleanName); + } - /** - * @param array $shows - * @param string $cleanName - * - * @return array|bool - */ - private function matchShowInfo($shows, $cleanName) - { - $return = false; - $highestMatch = 0; + return $return; + } - $show = []; - foreach ($shows AS $show) { - if ($this->checkRequiredAttr($show, 'tmdbS')) { - // Check for exact title match first and then terminate if found - if (strtolower($show['name']) === strtolower($cleanName)) { - $highest = $show; - break; - } - // Check each show title for similarity and then find the highest similar value - $matchPercent = $this->checkMatch(strtolower($show['name']), strtolower($cleanName), self::MATCH_PROBABILITY); + /** + * @param array $shows + * @param string $cleanName + * + * @return array|bool + */ + private function matchShowInfo($shows, $cleanName) + { + $return = false; + $highestMatch = 0; - // If new match has a higher percentage, set as new matched title - if ($matchPercent > $highestMatch) { - $highestMatch = $matchPercent; - $highest = $show; - } - } - } - if (!empty($highest)) { - try { - $showAlternativeTitles = $this->client->getTvApi()->getAlternativeTitles($highest['id']); - } catch (TmdbApiException $e) { - return false; - } + $show = []; + foreach ($shows as $show) { + if ($this->checkRequiredAttr($show, 'tmdbS')) { + // Check for exact title match first and then terminate if found + if (strtolower($show['name']) === strtolower($cleanName)) { + $highest = $show; + break; + } + // Check each show title for similarity and then find the highest similar value + $matchPercent = $this->checkMatch(strtolower($show['name']), strtolower($cleanName), self::MATCH_PROBABILITY); - try { - $showExternalIds = $this->client->getTvApi()->getExternalIds($highest['id']); - } catch (TmdbApiException $e) { - return false; - } + // If new match has a higher percentage, set as new matched title + if ($matchPercent > $highestMatch) { + $highestMatch = $matchPercent; + $highest = $show; + } + } + } + if (! empty($highest)) { + try { + $showAlternativeTitles = $this->client->getTvApi()->getAlternativeTitles($highest['id']); + } catch (TmdbApiException $e) { + return false; + } - if ($showAlternativeTitles !== null && is_array($showAlternativeTitles)) { - foreach ($showAlternativeTitles AS $aka) { - $highest['alternative_titles'][] = $aka['title']; - } - $highest['network'] = $show['networks'][0]['name'] ?? ''; - $highest['external_ids'] = $showExternalIds; - } - $return = $this->formatShowInfo($highest); - } - return $return; - } + try { + $showExternalIds = $this->client->getTvApi()->getExternalIds($highest['id']); + } catch (TmdbApiException $e) { + return false; + } - /** - * Retrieves the poster art for the processed show - * - * @param int $videoId -- the local Video ID - * @param int $showId -- the TMDB ID - * - * @return int - */ - public function getPoster($videoId, $showId = 0): int - { - $ri = new ReleaseImage($this->pdo); + if ($showAlternativeTitles !== null && is_array($showAlternativeTitles)) { + foreach ($showAlternativeTitles as $aka) { + $highest['alternative_titles'][] = $aka['title']; + } + $highest['network'] = $show['networks'][0]['name'] ?? ''; + $highest['external_ids'] = $showExternalIds; + } + $return = $this->formatShowInfo($highest); + } - // Try to get the Poster - $hascover = $ri->saveImage($videoId, $this->posterUrl, $this->imgSavePath); + return $return; + } - // Mark it retrieved if we saved an image - if ($hascover === 1) { - $this->setCoverFound($videoId); - } - return $hascover; - } + /** + * Retrieves the poster art for the processed show. + * + * @param int $videoId -- the local Video ID + * @param int $showId -- the TMDB ID + * + * @return int + */ + public function getPoster($videoId, $showId = 0): int + { + $ri = new ReleaseImage($this->pdo); - /** - * Gets the specific episode info for the parsed release after match - * Returns a formatted array of episode data or false if no match - * - * @param integer $tmdbid - * @param integer $season - * @param integer $episode - * @param string $airdate - * @param integer $videoId - * - * @return array|bool - */ - protected function getEpisodeInfo($tmdbid, $season, $episode, $airdate = '', $videoId = 0) - { - $return = false; + // Try to get the Poster + $hascover = $ri->saveImage($videoId, $this->posterUrl, $this->imgSavePath); - try { - $response = $this->client->getTvEpisodeApi()->getEpisode($tmdbid, $season, $episode); - } catch (TmdbApiException $e) { - return false; - } + // Mark it retrieved if we saved an image + if ($hascover === 1) { + $this->setCoverFound($videoId); + } - sleep(1); + return $hascover; + } - //Handle Single Episode Lookups - if (is_array($response) && $this->checkRequiredAttr($response, 'tmdbE')) { - $return = $this->formatEpisodeInfo($response); - } - return $return; - } + /** + * Gets the specific episode info for the parsed release after match + * Returns a formatted array of episode data or false if no match. + * + * @param int $tmdbid + * @param int $season + * @param int $episode + * @param string $airdate + * @param int $videoId + * + * @return array|bool + */ + protected function getEpisodeInfo($tmdbid, $season, $episode, $airdate = '', $videoId = 0) + { + $return = false; - /** - * Assigns API show response values to a formatted array for insertion - * Returns the formatted array - * - * @param $show - * - * @return array - */ - protected function formatShowInfo($show): array - { - $this->posterUrl = isset($show['poster_path']) ? 'https:' . $this->helper->getUrl($show['poster_path']) : ''; + try { + $response = $this->client->getTvEpisodeApi()->getEpisode($tmdbid, $season, $episode); + } catch (TmdbApiException $e) { + return false; + } - if (isset($show['external_ids']['imdb_id'])) { - preg_match('/tt(?P<imdbid>\d{6,7})$/i', $show['external_ids']['imdb_id'], $imdb); - } + sleep(1); - return [ + //Handle Single Episode Lookups + if (is_array($response) && $this->checkRequiredAttr($response, 'tmdbE')) { + $return = $this->formatEpisodeInfo($response); + } + + return $return; + } + + /** + * Assigns API show response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $show + * + * @return array + */ + protected function formatShowInfo($show): array + { + $this->posterUrl = isset($show['poster_path']) ? 'https:'.$this->helper->getUrl($show['poster_path']) : ''; + + if (isset($show['external_ids']['imdb_id'])) { + preg_match('/tt(?P<imdbid>\d{6,7})$/i', $show['external_ids']['imdb_id'], $imdb); + } + + return [ 'type' => parent::TYPE_TV, - 'title' => (string)$show['name'], - 'summary' => (string)$show['overview'], - 'started' => (string)$show['first_air_date'], - 'publisher' => isset($show['network']) ? (string)$show['network'] : '', + 'title' => (string) $show['name'], + 'summary' => (string) $show['overview'], + 'started' => (string) $show['first_air_date'], + 'publisher' => isset($show['network']) ? (string) $show['network'] : '', 'country' => $show['origin_country'][0] ?? '', 'source' => parent::SOURCE_TMDB, - 'imdb' => isset($imdb['imdbid']) ? (int)$imdb['imdbid'] : 0, - 'tvdb' => isset($show['external_ids']['tvdb_id']) ? (int)$show['external_ids']['tvdb_id'] : 0, + 'imdb' => isset($imdb['imdbid']) ? (int) $imdb['imdbid'] : 0, + 'tvdb' => isset($show['external_ids']['tvdb_id']) ? (int) $show['external_ids']['tvdb_id'] : 0, 'trakt' => 0, - 'tvrage' => isset($show['external_ids']['tvrage_id']) ? (int)$show['external_ids']['tvrage_id'] : 0, + 'tvrage' => isset($show['external_ids']['tvrage_id']) ? (int) $show['external_ids']['tvrage_id'] : 0, 'tvmaze' => 0, - 'tmdb' => (int)$show['id'], - 'aliases' => !empty($show['alternative_titles']) ? (array)$show['alternative_titles'] : '', - 'localzone' => "''" + 'tmdb' => (int) $show['id'], + 'aliases' => ! empty($show['alternative_titles']) ? (array) $show['alternative_titles'] : '', + 'localzone' => "''", ]; - } + } - /** - * Assigns API episode response values to a formatted array for insertion - * Returns the formatted array - * - * @param $episode - * - * @return array - */ - protected function formatEpisodeInfo($episode): array - { - return [ - 'title' => (string)$episode['name'], - 'series' => (int)$episode['season_number'], - 'episode' => (int)$episode['episode_number'], - 'se_complete' => 'S' . sprintf('%02d', $episode['season_number']) . 'E' . sprintf('%02d', $episode['episode_number']), - 'firstaired' => (string)$episode['air_date'], - 'summary' => (string)$episode['overview'] + /** + * Assigns API episode response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $episode + * + * @return array + */ + protected function formatEpisodeInfo($episode): array + { + return [ + 'title' => (string) $episode['name'], + 'series' => (int) $episode['season_number'], + 'episode' => (int) $episode['episode_number'], + 'se_complete' => 'S'.sprintf('%02d', $episode['season_number']).'E'.sprintf('%02d', $episode['episode_number']), + 'firstaired' => (string) $episode['air_date'], + 'summary' => (string) $episode['overview'], ]; - } + } } diff --git a/nntmux/processing/tv/TV.php b/nntmux/processing/tv/TV.php index 62d22855b..29d32f634 100755 --- a/nntmux/processing/tv/TV.php +++ b/nntmux/processing/tv/TV.php @@ -1,150 +1,151 @@ <?php + namespace nntmux\processing\tv; -use App\Models\Settings; -use nntmux\processing\Videos; -use nntmux\utility\Country; -use nntmux\utility\Utility; use nntmux\Category; use nntmux\ColorCLI; +use App\Models\Settings; +use nntmux\utility\Country; +use nntmux\utility\Utility; +use nntmux\processing\Videos; /** * Class TV -- abstract extension of Videos - * Contains functions suitable for re-use in all TV scrapers + * Contains functions suitable for re-use in all TV scrapers. */ abstract class TV extends Videos { - // Television Sources - const SOURCE_NONE = 0; // No Scrape source - const SOURCE_TVDB = 1; // Scrape source was TVDB - const SOURCE_TVMAZE = 2; // Scrape source was TVMAZE - const SOURCE_TMDB = 3; // Scrape source was TMDB - const SOURCE_TRAKT = 4; // Scrape source was Trakt - const SOURCE_IMDB = 5; // Scrape source was IMDB + // Television Sources + const SOURCE_NONE = 0; // No Scrape source + const SOURCE_TVDB = 1; // Scrape source was TVDB + const SOURCE_TVMAZE = 2; // Scrape source was TVMAZE + const SOURCE_TMDB = 3; // Scrape source was TMDB + const SOURCE_TRAKT = 4; // Scrape source was Trakt + const SOURCE_IMDB = 5; // Scrape source was IMDB // Anime Sources - const SOURCE_ANIDB = 10; // Scrape source was AniDB + const SOURCE_ANIDB = 10; // Scrape source was AniDB // Processing signifiers - const PROCESS_TVDB = 0; // Process TVDB First + const PROCESS_TVDB = 0; // Process TVDB First const PROCESS_TVMAZE = -1; // Process TVMaze Second - const PROCESS_TMDB = -2; // Process TMDB Third - const PROCESS_TRAKT = -3; // Process Trakt Fourth - const PROCESS_IMDB = -4; // Process IMDB Fifth + const PROCESS_TMDB = -2; // Process TMDB Third + const PROCESS_TRAKT = -3; // Process Trakt Fourth + const PROCESS_IMDB = -4; // Process IMDB Fifth const NO_MATCH_FOUND = -6; // Failed All Methods - const FAILED_PARSE = -100; // Failed Parsing + const FAILED_PARSE = -100; // Failed Parsing /** * @var int */ - public $tvqty; + public $tvqty; - /** - * @string Path to Save Images - */ - public $imgSavePath; + /** + * @string Path to Save Images + */ + public $imgSavePath; - /** - * @var array Site ID columns for TV - */ - public $siteColumns; + /** + * @var array Site ID columns for TV + */ + public $siteColumns; - /** - * @var string The TV categories_id lookup SQL language - */ - public $catWhere; + /** + * @var string The TV categories_id lookup SQL language + */ + public $catWhere; - /** - * @param array $options Class instances / Echo to CLI. - */ - public function __construct(array $options = []) - { - parent::__construct($options); - $this->catWhere = 'categories_id BETWEEN ' . Category::TV_ROOT . ' AND ' . Category::TV_OTHER . ' AND categories_id != ' . Category::TV_ANIME; - $this->tvqty = (Settings::value('..maxrageprocessed') != '') ? Settings::value('..maxrageprocessed') : 75; - $this->imgSavePath = NN_COVERS . 'tvshows' . DS; - $this->siteColumns = ['tvdb', 'trakt', 'tvrage', 'tvmaze', 'imdb', 'tmdb']; - } + /** + * @param array $options Class instances / Echo to CLI. + */ + public function __construct(array $options = []) + { + parent::__construct($options); + $this->catWhere = 'categories_id BETWEEN '.Category::TV_ROOT.' AND '.Category::TV_OTHER.' AND categories_id != '.Category::TV_ANIME; + $this->tvqty = (Settings::value('..maxrageprocessed') != '') ? Settings::value('..maxrageprocessed') : 75; + $this->imgSavePath = NN_COVERS.'tvshows'.DS; + $this->siteColumns = ['tvdb', 'trakt', 'tvrage', 'tvmaze', 'imdb', 'tmdb']; + } - /** - * Retrieve banner image from site using its API. - * - * @param $videoID - * @param $siteId - * - * @return mixed - */ - abstract protected function getBanner($videoID, $siteId); + /** + * Retrieve banner image from site using its API. + * + * @param $videoID + * @param $siteId + * + * @return mixed + */ + abstract protected function getBanner($videoID, $siteId); - /** - * Retrieve info of TV episode from site using its API. - * - * @param integer $siteId - * @param integer $series - * @param integer $episode - * - * @return array|false False on failure, an array of information fields otherwise. - */ - abstract protected function getEpisodeInfo($siteId, $series, $episode); + /** + * Retrieve info of TV episode from site using its API. + * + * @param int $siteId + * @param int $series + * @param int $episode + * + * @return array|false False on failure, an array of information fields otherwise. + */ + abstract protected function getEpisodeInfo($siteId, $series, $episode); - /** - * Retrieve poster image for TV episode from site using its API. - * - * @param integer $videoId ID from videos table. - * @param integer $siteId ID that this site uses for the programme. - * - * @return int - */ - abstract protected function getPoster($videoId, $siteId): int; + /** + * Retrieve poster image for TV episode from site using its API. + * + * @param int $videoId ID from videos table. + * @param int $siteId ID that this site uses for the programme. + * + * @return int + */ + abstract protected function getPoster($videoId, $siteId): int; - /** - * Retrieve info of TV programme from site using it's API. - * - * @param string $name Title of programme to look up. Usually a cleaned up version from releases table. - * - * @return array|false False on failure, an array of information fields otherwise. - */ - abstract protected function getShowInfo($name); + /** + * Retrieve info of TV programme from site using it's API. + * + * @param string $name Title of programme to look up. Usually a cleaned up version from releases table. + * + * @return array|false False on failure, an array of information fields otherwise. + */ + abstract protected function getShowInfo($name); - /** - * Assigns API show response values to a formatted array for insertion - * Returns the formatted array - * - * @param $show - * - * @return array - */ - abstract protected function formatShowInfo($show): array; + /** + * Assigns API show response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $show + * + * @return array + */ + abstract protected function formatShowInfo($show): array; - /** - * Assigns API episode response values to a formatted array for insertion - * Returns the formatted array - * - * @param $episode - * - * @return array - */ - abstract protected function formatEpisodeInfo($episode): array; + /** + * Assigns API episode response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $episode + * + * @return array + */ + abstract protected function formatEpisodeInfo($episode): array; - /** - * Retrieve releases for TV processing - * Returns a PDO Object of rows or false if none found - * - * @param string $groupID -- ID of the usenet group to process - * @param string $guidChar -- threading method by first guid character - * @param int $lookupSetting -- whether or not to use the API - * @param int $status -- release processing status of tv_episodes_id - * - * @return false|int|\PDOStatement - */ - public function getTvReleases($groupID = '', $guidChar = '', $lookupSetting = 1, $status = 0) - { - $ret = 0; - if ($lookupSetting === 0) { - return $ret; - } + /** + * Retrieve releases for TV processing + * Returns a PDO Object of rows or false if none found. + * + * @param string $groupID -- ID of the usenet group to process + * @param string $guidChar -- threading method by first guid character + * @param int $lookupSetting -- whether or not to use the API + * @param int $status -- release processing status of tv_episodes_id + * + * @return false|int|\PDOStatement + */ + public function getTvReleases($groupID = '', $guidChar = '', $lookupSetting = 1, $status = 0) + { + $ret = 0; + if ($lookupSetting === 0) { + return $ret; + } - $res = $this->pdo->queryDirect( + $res = $this->pdo->queryDirect( sprintf(' SELECT SQL_NO_CACHE r.searchname, r.id FROM releases r @@ -158,25 +159,26 @@ abstract class TV extends Videos LIMIT %d', $status, $this->catWhere, - ($groupID === '' ? '' : 'AND r.groups_id = ' . $groupID), - ($guidChar === '' ? '' : 'AND r.leftguid = ' . $this->pdo->escapeString($guidChar)), + ($groupID === '' ? '' : 'AND r.groups_id = '.$groupID), + ($guidChar === '' ? '' : 'AND r.leftguid = '.$this->pdo->escapeString($guidChar)), ($lookupSetting === 2 ? 'AND r.isrenamed = 1' : ''), $this->tvqty ) ); - return $res; - } - /** - * Updates the release when match for the current scraper is found - * - * @param $videoId - * @param $releaseId - * @param int $episodeId - */ - public function setVideoIdFound($videoId, $releaseId, $episodeId): void - { - $this->pdo->queryExec( + return $res; + } + + /** + * Updates the release when match for the current scraper is found. + * + * @param $videoId + * @param $releaseId + * @param int $episodeId + */ + public function setVideoIdFound($videoId, $releaseId, $episodeId): void + { + $this->pdo->queryExec( sprintf(' UPDATE releases SET videos_id = %d, tv_episodes_id = %d @@ -188,17 +190,17 @@ abstract class TV extends Videos $releaseId ) ); - } + } - /** - * Updates the release tv_episodes_id status when scraper match is not found - * - * @param $status - * @param $Id - */ - public function setVideoNotFound($status, $Id): void - { - $this->pdo->queryExec( + /** + * Updates the release tv_episodes_id status when scraper match is not found. + * + * @param $status + * @param $Id + */ + public function setVideoNotFound($status, $Id): void + { + $this->pdo->queryExec( sprintf(' UPDATE releases SET tv_episodes_id = %d @@ -209,39 +211,39 @@ abstract class TV extends Videos $Id ) ); - } + } - /** - * Inserts a new video ID into the database for TV shows - * If a duplicate is found it is handle by calling update instead - * - * @param array $show - * - * @return int - */ - public function add(array $show = []): int - { - $videoId = false; + /** + * Inserts a new video ID into the database for TV shows + * If a duplicate is found it is handle by calling update instead. + * + * @param array $show + * + * @return int + */ + public function add(array $show = []): int + { + $videoId = false; - // Check if the country is not a proper code and retrieve if not - if ($show['country'] !== '' && strlen($show['country']) > 2) { - $show['country'] = Country::countryCode($show['country'], $this->pdo); - } + // Check if the country is not a proper code and retrieve if not + if ($show['country'] !== '' && strlen($show['country']) > 2) { + $show['country'] = Country::countryCode($show['country'], $this->pdo); + } - // Check if video already exists based on site ID info - // if that fails be sure we're not inserting duplicates by checking the title - foreach ($this->siteColumns AS $column) { - if ($show[$column] > 0) { - $videoId = $this->getVideoIDFromSiteID($column, $show[$column]); - } - if ($videoId !== false) { - break; - } - } + // Check if video already exists based on site ID info + // if that fails be sure we're not inserting duplicates by checking the title + foreach ($this->siteColumns as $column) { + if ($show[$column] > 0) { + $videoId = $this->getVideoIDFromSiteID($column, $show[$column]); + } + if ($videoId !== false) { + break; + } + } - if ($videoId === false) { - // Insert the Show - $videoId = $this->pdo->queryInsert( + if ($videoId === false) { + // Insert the Show + $videoId = $this->pdo->queryInsert( sprintf(' INSERT INTO videos (type, title, countries_id, started, source, tvdb, trakt, tvrage, tvmaze, imdb, tmdb) @@ -259,8 +261,8 @@ abstract class TV extends Videos $show['tmdb'] ) ); - // Insert the supplementary show info - $this->pdo->queryInsert( + // Insert the supplementary show info + $this->pdo->queryInsert( sprintf(' INSERT INTO tv_info (videos_id, summary, publisher, localzone) VALUES (%d, %s, %s, %s)', @@ -270,31 +272,32 @@ abstract class TV extends Videos $this->pdo->escapeString($show['localzone']) ) ); - // If we have AKAs\aliases, insert those as well - if (!empty($show['aliases'])) { - $this->addAliases($videoId, $show['aliases']); - } - } else { - // If a local match was found, just update missing video info - $this->update($videoId, $show); - } - return (int)$videoId; - } + // If we have AKAs\aliases, insert those as well + if (! empty($show['aliases'])) { + $this->addAliases($videoId, $show['aliases']); + } + } else { + // If a local match was found, just update missing video info + $this->update($videoId, $show); + } - /** - * Inserts a new TV episode into the tv_episodes table following a match to a Video ID - * - * @param int $videoId - * @param array $episode - * - * @return false|int|string - */ - public function addEpisode($videoId, array $episode = []) - { - $episodeId = $this->getBySeasonEp($videoId, $episode['series'], $episode['episode'], $episode['firstaired']); + return (int) $videoId; + } - if ($episodeId === false) { - $episodeId = $this->pdo->queryInsert( + /** + * Inserts a new TV episode into the tv_episodes table following a match to a Video ID. + * + * @param int $videoId + * @param array $episode + * + * @return false|int|string + */ + public function addEpisode($videoId, array $episode = []) + { + $episodeId = $this->getBySeasonEp($videoId, $episode['series'], $episode['episode'], $episode['firstaired']); + + if ($episodeId === false) { + $episodeId = $this->pdo->queryInsert( sprintf(' INSERT INTO tv_episodes (videos_id, series, episode, se_complete, title, firstaired, summary) VALUES (%d, %d, %d, %s, %s, %s, %s) @@ -304,32 +307,33 @@ abstract class TV extends Videos $episode['episode'], $this->pdo->escapeString($episode['se_complete']), $this->pdo->escapeString($episode['title']), - ($episode['firstaired'] != '' ? $this->pdo->escapeString($episode['firstaired']) : "null"), + ($episode['firstaired'] != '' ? $this->pdo->escapeString($episode['firstaired']) : 'null'), $this->pdo->escapeString($episode['summary']), $this->pdo->escapeString($episode['se_complete']) ) ); - } - return $episodeId; - } + } - /** - * Updates the show info with data from the supplied array - * Only called when a duplicate show is found during insert - * - * @param int $videoId - * @param array $show - */ - public function update($videoId, array $show = []): void - { - if ($show['country'] !== '') { - $show['country'] = Country::countryCode($show['country'], $this->pdo); - } + return $episodeId; + } - $ifStringID = 'IF(%s = 0, %s, %s)'; - $ifStringInfo = "IF(%s = '', %s, %s)"; + /** + * Updates the show info with data from the supplied array + * Only called when a duplicate show is found during insert. + * + * @param int $videoId + * @param array $show + */ + public function update($videoId, array $show = []): void + { + if ($show['country'] !== '') { + $show['country'] = Country::countryCode($show['country'], $this->pdo); + } - $this->pdo->queryExec( + $ifStringID = 'IF(%s = 0, %s, %s)'; + $ifStringInfo = "IF(%s = '', %s, %s)"; + + $this->pdo->queryExec( sprintf(' UPDATE videos v LEFT JOIN tv_info tvi ON v.id = tvi.videos_id @@ -350,21 +354,21 @@ abstract class TV extends Videos $videoId ) ); - if (!empty($show['aliases'])) { - $this->addAliases($videoId, $show['aliases']); - } - } + if (! empty($show['aliases'])) { + $this->addAliases($videoId, $show['aliases']); + } + } - /** - * Deletes a TV show entirely from all child tables via the Video ID - * - * @param $id - * - * @return \PDOStatement|false - */ - public function delete($id) - { - return $this->pdo->queryExec( + /** + * Deletes a TV show entirely from all child tables via the Video ID. + * + * @param $id + * + * @return \PDOStatement|false + */ + public function delete($id) + { + return $this->pdo->queryExec( sprintf(' DELETE v, tvi, tve, va FROM videos v @@ -375,16 +379,16 @@ abstract class TV extends Videos $id ) ); - } + } - /** - * Sets the TV show's image column to found (1) - * - * @param $videoId - */ - public function setCoverFound($videoId): void - { - $this->pdo->queryExec( + /** + * Sets the TV show's image column to found (1). + * + * @param $videoId + */ + public function setCoverFound($videoId): void + { + $this->pdo->queryExec( sprintf(' UPDATE tv_info SET image = 1 @@ -392,21 +396,21 @@ abstract class TV extends Videos $videoId ) ); - } + } - /** - * Get site ID from a Video ID and the site's respective column. - * Returns the ID value or false if none found - * - * @param string $column - * @param int $id - * - * @return \PDOStatement|false - */ - public function getSiteByID($column, $id) - { - $return = false; - $video = $this->pdo->queryOneRow( + /** + * Get site ID from a Video ID and the site's respective column. + * Returns the ID value or false if none found. + * + * @param string $column + * @param int $id + * + * @return \PDOStatement|false + */ + public function getSiteByID($column, $id) + { + $return = false; + $video = $this->pdo->queryOneRow( sprintf(' SELECT %s FROM videos @@ -415,38 +419,39 @@ abstract class TV extends Videos $id ) ); - if ($column === '*') { - $return = $video; - } else if ($column !== '*' && isset($video[$column])) { - $return = $video[$column]; - } - return $return; - } + if ($column === '*') { + $return = $video; + } elseif ($column !== '*' && isset($video[$column])) { + $return = $video[$column]; + } - /** - * Retrieves the Episode ID using the Video ID and either: - * season/episode numbers OR the airdate - * - * Returns the Episode ID or false if not found - * - * @param $id - * @param $series - * @param $episode - * @param string $airdate - * - * @return int|false - */ - public function getBySeasonEp($id, $series, $episode, $airdate = '') - { - if ($series > 0 && $episode > 0) { - $queryString = sprintf('tve.series = %d AND tve.episode = %d', $series, $episode); - } else if (!empty($airdate)) { - $queryString = sprintf('DATE(tve.firstaired) = %s', $this->pdo->escapeString(date('Y-m-d', strtotime($airdate)))); - } else { - return false; - } + return $return; + } - $episodeArr = $this->pdo->queryOneRow( + /** + * Retrieves the Episode ID using the Video ID and either: + * season/episode numbers OR the airdate. + * + * Returns the Episode ID or false if not found + * + * @param $id + * @param $series + * @param $episode + * @param string $airdate + * + * @return int|false + */ + public function getBySeasonEp($id, $series, $episode, $airdate = '') + { + if ($series > 0 && $episode > 0) { + $queryString = sprintf('tve.series = %d AND tve.episode = %d', $series, $episode); + } elseif (! empty($airdate)) { + $queryString = sprintf('DATE(tve.firstaired) = %s', $this->pdo->escapeString(date('Y-m-d', strtotime($airdate)))); + } else { + return false; + } + + $episodeArr = $this->pdo->queryOneRow( sprintf(' SELECT tve.id FROM tv_episodes tve @@ -456,20 +461,20 @@ abstract class TV extends Videos $queryString ) ); - return $episodeArr['id'] ?? false; - } + return $episodeArr['id'] ?? false; + } - /** - * Returns (true) if episodes for a given Video ID exist or don't (false) - * - * @param $videoId - * - * @return bool - */ - public function countEpsByVideoID($videoId): bool - { - $count = $this->pdo->queryOneRow( + /** + * Returns (true) if episodes for a given Video ID exist or don't (false). + * + * @param $videoId + * + * @return bool + */ + public function countEpsByVideoID($videoId): bool + { + $count = $this->pdo->queryOneRow( sprintf(' SELECT count(id) AS num FROM tv_episodes @@ -477,307 +482,314 @@ abstract class TV extends Videos $videoId ) ); - return (isset($count['num']) && (int)$count['num'] > 0 ? true : false); - } - /** - * Parses a release searchname for specific TV show data - * Returns an array of show data - * - * @param $relname - * - * @return array|false - */ - public function parseInfo($relname) - { - $showInfo['name'] = $this->parseName($relname); + return isset($count['num']) && (int) $count['num'] > 0 ? true : false; + } - if (!empty($showInfo['name'])) { + /** + * Parses a release searchname for specific TV show data + * Returns an array of show data. + * + * @param $relname + * + * @return array|false + */ + public function parseInfo($relname) + { + $showInfo['name'] = $this->parseName($relname); + + if (! empty($showInfo['name'])) { // Retrieve the country from the cleaned name - $showInfo['country'] = $this->parseCountry($showInfo['name']); + $showInfo['country'] = $this->parseCountry($showInfo['name']); - // Clean show name. - $showInfo['cleanname'] = preg_replace('/ - \d{1,}$/i', '', $this->cleanName($showInfo['name'])); + // Clean show name. + $showInfo['cleanname'] = preg_replace('/ - \d{1,}$/i', '', $this->cleanName($showInfo['name'])); - // Get the Season/Episode/Airdate - $showInfo += $this->parseSeasonEp($relname); + // Get the Season/Episode/Airdate + $showInfo += $this->parseSeasonEp($relname); - if ((isset($showInfo['season']) && isset($showInfo['episode'])) || isset($showInfo['airdate'])) { - if (!isset($showInfo['airdate'])) { - // If year is present in the release name, add it to the cleaned name for title search - if (preg_match('/[^a-z0-9](?P<year>(19|20)(\d{2}))[^a-z0-9]/i', $relname, $yearMatch)) { - $showInfo['cleanname'] .= ' (' . $yearMatch['year'] . ')'; - } - // Check for multi episode release. - if (is_array($showInfo['episode'])) { - $showInfo['episode'] = $showInfo['episode'][0]; - } - $showInfo['airdate'] = ''; - } + if ((isset($showInfo['season']) && isset($showInfo['episode'])) || isset($showInfo['airdate'])) { + if (! isset($showInfo['airdate'])) { + // If year is present in the release name, add it to the cleaned name for title search + if (preg_match('/[^a-z0-9](?P<year>(19|20)(\d{2}))[^a-z0-9]/i', $relname, $yearMatch)) { + $showInfo['cleanname'] .= ' ('.$yearMatch['year'].')'; + } + // Check for multi episode release. + if (is_array($showInfo['episode'])) { + $showInfo['episode'] = $showInfo['episode'][0]; + } + $showInfo['airdate'] = ''; + } - return $showInfo; - } - } - if (NN_DEBUG) { - ColorCLI::doEcho('Failed to parse release: ' . $relname, true); - } - return false; - } + return $showInfo; + } + } + if (NN_DEBUG) { + ColorCLI::doEcho('Failed to parse release: '.$relname, true); + } - /** - * Parses the release searchname and returns a show title - * - * @param string $relname - * - * @return string - */ - private function parseName($relname) - { - $showName = ''; + return false; + } - $following = '[^a-z0-9](\d\d-\d\d|\d{1,3}x\d{2,3}|\(?(19|20)\d{2}\)?|(480|720|1080)[ip]|AAC2?|BD-?Rip|Blu-?Ray|D0?\d' . - '|DD5|DiVX|DLMux|DTS|DVD(-?Rip)?|E\d{2,3}|[HX][-_. ]?26[45]|ITA(-ENG)?|HEVC|[HPS]DTV|PROPER|REPACK|Season|Episode|' . + /** + * Parses the release searchname and returns a show title. + * + * @param string $relname + * + * @return string + */ + private function parseName($relname) + { + $showName = ''; + + $following = '[^a-z0-9](\d\d-\d\d|\d{1,3}x\d{2,3}|\(?(19|20)\d{2}\)?|(480|720|1080)[ip]|AAC2?|BD-?Rip|Blu-?Ray|D0?\d'. + '|DD5|DiVX|DLMux|DTS|DVD(-?Rip)?|E\d{2,3}|[HX][-_. ]?26[45]|ITA(-ENG)?|HEVC|[HPS]DTV|PROPER|REPACK|Season|Episode|'. 'S\d+[^a-z0-9]?((E\d+)[abr]?)*|WEB[-_. ]?(DL|Rip)|XViD)[^a-z0-9]?'; - // For names that don't start with the title. - if (preg_match('/^([^a-z0-9]{2,}|(sample|proof|repost)-)(?P<name>[\w .-]*?)' . $following . '/i', $relname, $matches)) { - $showName = $matches['name']; - } else if (preg_match('/^(?P<name>[a-z0-9][\w\' .-]*?)' . $following . '/i', $relname, $matches)) { - // For names that start with the title. - $showName = $matches['name']; - } - // If we still have any of the words in $following, remove them. - $showName = preg_replace('/' . $following . '/i', ' ', $showName); - // Remove leading date if present - $showName = preg_replace('/^\d{6}/', '', $showName); - // Remove periods, underscored, anything between parenthesis. - $showName = preg_replace('/\(.*?\)|[._]/i', ' ', $showName); - // Finally remove multiple spaces and trim leading spaces. - $showName = trim(preg_replace('/\s{2,}/', ' ', $showName)); - return $showName; - } + // For names that don't start with the title. + if (preg_match('/^([^a-z0-9]{2,}|(sample|proof|repost)-)(?P<name>[\w .-]*?)'.$following.'/i', $relname, $matches)) { + $showName = $matches['name']; + } elseif (preg_match('/^(?P<name>[a-z0-9][\w\' .-]*?)'.$following.'/i', $relname, $matches)) { + // For names that start with the title. + $showName = $matches['name']; + } + // If we still have any of the words in $following, remove them. + $showName = preg_replace('/'.$following.'/i', ' ', $showName); + // Remove leading date if present + $showName = preg_replace('/^\d{6}/', '', $showName); + // Remove periods, underscored, anything between parenthesis. + $showName = preg_replace('/\(.*?\)|[._]/i', ' ', $showName); + // Finally remove multiple spaces and trim leading spaces. + $showName = trim(preg_replace('/\s{2,}/', ' ', $showName)); - /** - * Parses the release searchname for the season/episode/airdate information - * - * @param $relname - * - * @return array - */ - private function parseSeasonEp($relname) - { - $episodeArr = []; + return $showName; + } - // S01E01-E02 and S01E01-02 - if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?e(\d{1,3})(?:[e-])(\d{1,3})[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = (int)$matches[2]; - $episodeArr['episode'] = [(int)$matches[3], (int)$matches[4]]; - } - //S01E0102 and S01E01E02 - lame no delimit numbering, regex would collide if there was ever 1000 ep season. - else if (preg_match('/^(.*?)[^a-z0-9]s(\d{2})[^a-z0-9]?e(\d{2})e?(\d{2})[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = (int)$matches[2]; - $episodeArr['episode'] = (int)$matches[3]; - } - // S01E01 and S01.E01 - else if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?e(\d{1,3})[abr]?[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = (int)$matches[2]; - $episodeArr['episode'] = (int)$matches[3]; - } - // S01 - else if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = (int)$matches[2]; - $episodeArr['episode'] = 'all'; - } - // S01D1 and S1D1 - else if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?d\d{1}[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = (int)$matches[2]; - $episodeArr['episode'] = 'all'; - } - // 1x01 and 101 - else if (preg_match('/^(.*?)[^a-z0-9](\d{1,2})x(\d{1,3})[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = (int)$matches[2]; - $episodeArr['episode'] = (int)$matches[3]; - } - // 2009.01.01 and 2009-01-01 - else if (preg_match('/^(.*?)[^a-z0-9](?P<airdate>(19|20)(\d{2})[.\/-](\d{2})[.\/-](\d{2}))[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = $matches[4] . $matches[5]; - $episodeArr['episode'] = $matches[5] . '/' . $matches[6]; - $episodeArr['airdate'] = date('Y-m-d', strtotime(preg_replace('/[^0-9]/i', '/', $matches['airdate']))); //yyyy-mm-dd - } - // 01.01.2009 - else if (preg_match('/^(.*?)[^a-z0-9](?P<airdate>(\d{2})[^a-z0-9](\d{2})[^a-z0-9](19|20)(\d{2}))[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = $matches[5] . $matches[6]; - $episodeArr['episode'] = $matches[3] . '/' . $matches[4]; - $episodeArr['airdate'] = date('Y-m-d', strtotime(preg_replace('/[^0-9]/i', '/', $matches['airdate']))); //yyyy-mm-dd - } - // 01.01.09 - else if (preg_match('/^(.*?)[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9]/i', $relname, $matches)) { - // Add extra logic to capture the proper YYYY year - $episodeArr['season'] = $matches[4] = ($matches[4] <= 99 && $matches[4] > 15) ? '19' . $matches[4] : '20' . $matches[4]; - $episodeArr['episode'] = $matches[2] . '/' . $matches[3]; - $tmpAirdate = $episodeArr['season'] . '/' . $episodeArr['episode']; - $episodeArr['airdate'] = date('Y-m-d', strtotime(preg_replace('/[^0-9]/i', '/', $tmpAirdate))); //yyyy-mm-dd - } - // 2009.E01 - else if (preg_match('/^(.*?)[^a-z0-9]20(\d{2})[^a-z0-9](\d{1,3})[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = '20' . $matches[2]; - $episodeArr['episode'] = (int)$matches[3]; - } - // 2009.Part1 - else if (preg_match('/^(.*?)[^a-z0-9](19|20)(\d{2})[^a-z0-9]Part(\d{1,2})[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = $matches[2] . $matches[3]; - $episodeArr['episode'] = (int)$matches[4]; - } - // Part1/Pt1 - else if (preg_match('/^(.*?)[^a-z0-9](?:Part|Pt)[^a-z0-9](\d{1,2})[^a-z0-9]/i', $relname, $matches)) { - $episodeArr['season'] = 1; - $episodeArr['episode'] = (int)$matches[2]; - } - //The.Pacific.Pt.VI.HDTV.XviD-XII / Part.IV - else if (preg_match('/^(.*?)[^a-z0-9](?:Part|Pt)[^a-z0-9]([ivx]+)/i', $relname, $matches)) { - $episodeArr['season'] = 1; - $epLow = strtolower($matches[2]); - $episodeArr['episode'] = Utility::convertRomanToInt($epLow); - } - // Band.Of.Brothers.EP06.Bastogne.DVDRiP.XviD-DEiTY - else if (preg_match('/^(.*?)[^a-z0-9]EP?[^a-z0-9]?(\d{1,3})/i', $relname, $matches)) { - $episodeArr['season'] = 1; - $episodeArr['episode'] = (int)$matches[2]; - } - // Season.1 - else if (preg_match('/^(.*?)[^a-z0-9]Seasons?[^a-z0-9]?(\d{1,2})/i', $relname, $matches)) { - $episodeArr['season'] = (int)$matches[2]; - $episodeArr['episode'] = 'all'; - } - return $episodeArr; - } + /** + * Parses the release searchname for the season/episode/airdate information. + * + * @param $relname + * + * @return array + */ + private function parseSeasonEp($relname) + { + $episodeArr = []; - /** - * Parses the cleaned release name to determine if it has a country appended - * - * @param string $showName - * - * @return string - */ - private function parseCountry($showName) - { - // Country or origin matching. - if (preg_match('/[^a-z0-9](US|UK|AU|NZ|CA|NL|Canada|Australia|America|United[^a-z0-9]States|United[^a-z0-9]Kingdom)/i', $showName, $countryMatch)) { - $currentCountry = strtolower($countryMatch[1]); - if ($currentCountry === 'canada') { - $country = 'CA'; - } else if ($currentCountry === 'australia') { - $country = 'AU'; - } else if ($currentCountry === 'america' || $currentCountry === 'united states') { - $country = 'US'; - } else if ($currentCountry === 'united kingdom') { - $country = 'UK'; - } else { - $country = strtoupper($countryMatch[1]); - } - } else { - $country = ''; - } - return $country; - } + // S01E01-E02 and S01E01-02 + if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?e(\d{1,3})(?:[e-])(\d{1,3})[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = (int) $matches[2]; + $episodeArr['episode'] = [(int) $matches[3], (int) $matches[4]]; + } + //S01E0102 and S01E01E02 - lame no delimit numbering, regex would collide if there was ever 1000 ep season. + elseif (preg_match('/^(.*?)[^a-z0-9]s(\d{2})[^a-z0-9]?e(\d{2})e?(\d{2})[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = (int) $matches[2]; + $episodeArr['episode'] = (int) $matches[3]; + } + // S01E01 and S01.E01 + elseif (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?e(\d{1,3})[abr]?[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = (int) $matches[2]; + $episodeArr['episode'] = (int) $matches[3]; + } + // S01 + elseif (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = (int) $matches[2]; + $episodeArr['episode'] = 'all'; + } + // S01D1 and S1D1 + elseif (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?d\d{1}[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = (int) $matches[2]; + $episodeArr['episode'] = 'all'; + } + // 1x01 and 101 + elseif (preg_match('/^(.*?)[^a-z0-9](\d{1,2})x(\d{1,3})[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = (int) $matches[2]; + $episodeArr['episode'] = (int) $matches[3]; + } + // 2009.01.01 and 2009-01-01 + elseif (preg_match('/^(.*?)[^a-z0-9](?P<airdate>(19|20)(\d{2})[.\/-](\d{2})[.\/-](\d{2}))[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = $matches[4].$matches[5]; + $episodeArr['episode'] = $matches[5].'/'.$matches[6]; + $episodeArr['airdate'] = date('Y-m-d', strtotime(preg_replace('/[^0-9]/i', '/', $matches['airdate']))); //yyyy-mm-dd + } + // 01.01.2009 + elseif (preg_match('/^(.*?)[^a-z0-9](?P<airdate>(\d{2})[^a-z0-9](\d{2})[^a-z0-9](19|20)(\d{2}))[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = $matches[5].$matches[6]; + $episodeArr['episode'] = $matches[3].'/'.$matches[4]; + $episodeArr['airdate'] = date('Y-m-d', strtotime(preg_replace('/[^0-9]/i', '/', $matches['airdate']))); //yyyy-mm-dd + } + // 01.01.09 + elseif (preg_match('/^(.*?)[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9]/i', $relname, $matches)) { + // Add extra logic to capture the proper YYYY year + $episodeArr['season'] = $matches[4] = ($matches[4] <= 99 && $matches[4] > 15) ? '19'.$matches[4] : '20'.$matches[4]; + $episodeArr['episode'] = $matches[2].'/'.$matches[3]; + $tmpAirdate = $episodeArr['season'].'/'.$episodeArr['episode']; + $episodeArr['airdate'] = date('Y-m-d', strtotime(preg_replace('/[^0-9]/i', '/', $tmpAirdate))); //yyyy-mm-dd + } + // 2009.E01 + elseif (preg_match('/^(.*?)[^a-z0-9]20(\d{2})[^a-z0-9](\d{1,3})[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = '20'.$matches[2]; + $episodeArr['episode'] = (int) $matches[3]; + } + // 2009.Part1 + elseif (preg_match('/^(.*?)[^a-z0-9](19|20)(\d{2})[^a-z0-9]Part(\d{1,2})[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = $matches[2].$matches[3]; + $episodeArr['episode'] = (int) $matches[4]; + } + // Part1/Pt1 + elseif (preg_match('/^(.*?)[^a-z0-9](?:Part|Pt)[^a-z0-9](\d{1,2})[^a-z0-9]/i', $relname, $matches)) { + $episodeArr['season'] = 1; + $episodeArr['episode'] = (int) $matches[2]; + } + //The.Pacific.Pt.VI.HDTV.XviD-XII / Part.IV + elseif (preg_match('/^(.*?)[^a-z0-9](?:Part|Pt)[^a-z0-9]([ivx]+)/i', $relname, $matches)) { + $episodeArr['season'] = 1; + $epLow = strtolower($matches[2]); + $episodeArr['episode'] = Utility::convertRomanToInt($epLow); + } + // Band.Of.Brothers.EP06.Bastogne.DVDRiP.XviD-DEiTY + elseif (preg_match('/^(.*?)[^a-z0-9]EP?[^a-z0-9]?(\d{1,3})/i', $relname, $matches)) { + $episodeArr['season'] = 1; + $episodeArr['episode'] = (int) $matches[2]; + } + // Season.1 + elseif (preg_match('/^(.*?)[^a-z0-9]Seasons?[^a-z0-9]?(\d{1,2})/i', $relname, $matches)) { + $episodeArr['season'] = (int) $matches[2]; + $episodeArr['episode'] = 'all'; + } - /** - * Supplementary to parseInfo - * Cleans a derived local 'showname' for better matching probability - * Returns the cleaned string - * - * @param $str - * - * @return string - */ - public function cleanName($str) - { - $str = str_replace(['.', '_'], ' ', $str); + return $episodeArr; + } - $str = str_replace(['à', 'á', 'â', 'ã', 'ä', 'æ', 'À', 'Á', 'Â', 'Ã', 'Ä'], 'a', $str); - $str = str_replace(['ç', 'Ç'], 'c', $str); - $str = str_replace(['Σ', 'è', 'é', 'ê', 'ë', 'È', 'É', 'Ê', 'Ë'], 'e', $str); - $str = str_replace(['ì', 'í', 'î', 'ï', 'Ì', 'Í', 'Î', 'Ï'], 'i', $str); - $str = str_replace(['ò', 'ó', 'ô', 'õ', 'ö', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö'], 'o', $str); - $str = str_replace(['ù', 'ú', 'û', 'ü', 'ū', 'Ú', 'Û', 'Ü', 'Ū'], 'u', $str); - $str = str_replace('ß', 'ss', $str); + /** + * Parses the cleaned release name to determine if it has a country appended. + * + * @param string $showName + * + * @return string + */ + private function parseCountry($showName) + { + // Country or origin matching. + if (preg_match('/[^a-z0-9](US|UK|AU|NZ|CA|NL|Canada|Australia|America|United[^a-z0-9]States|United[^a-z0-9]Kingdom)/i', $showName, $countryMatch)) { + $currentCountry = strtolower($countryMatch[1]); + if ($currentCountry === 'canada') { + $country = 'CA'; + } elseif ($currentCountry === 'australia') { + $country = 'AU'; + } elseif ($currentCountry === 'america' || $currentCountry === 'united states') { + $country = 'US'; + } elseif ($currentCountry === 'united kingdom') { + $country = 'UK'; + } else { + $country = strtoupper($countryMatch[1]); + } + } else { + $country = ''; + } - $str = str_replace('&', 'and', $str); - $str = preg_replace('/^(history|discovery) channel/i', '', $str); - $str = str_replace(['\'', ':', '!', '"', '#', '*', '’', ',', '(', ')', '?'], '', $str); - $str = str_replace('$', 's', $str); - $str = preg_replace('/\s{2,}/', ' ', $str); + return $country; + } - $str = trim($str, '\"'); - return trim($str); - } + /** + * Supplementary to parseInfo + * Cleans a derived local 'showname' for better matching probability + * Returns the cleaned string. + * + * @param $str + * + * @return string + */ + public function cleanName($str) + { + $str = str_replace(['.', '_'], ' ', $str); - /** - * Simple function that compares two strings of text - * Returns percentage of similarity - * - * @param $ourName - * @param $scrapeName - * @param $probability - * - * @return int|float - */ - public function checkMatch($ourName, $scrapeName, $probability) - { - similar_text($ourName, $scrapeName, $matchpct); + $str = str_replace(['à', 'á', 'â', 'ã', 'ä', 'æ', 'À', 'Á', 'Â', 'Ã', 'Ä'], 'a', $str); + $str = str_replace(['ç', 'Ç'], 'c', $str); + $str = str_replace(['Σ', 'è', 'é', 'ê', 'ë', 'È', 'É', 'Ê', 'Ë'], 'e', $str); + $str = str_replace(['ì', 'í', 'î', 'ï', 'Ì', 'Í', 'Î', 'Ï'], 'i', $str); + $str = str_replace(['ò', 'ó', 'ô', 'õ', 'ö', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö'], 'o', $str); + $str = str_replace(['ù', 'ú', 'û', 'ü', 'ū', 'Ú', 'Û', 'Ü', 'Ū'], 'u', $str); + $str = str_replace('ß', 'ss', $str); - if (NN_DEBUG) { - echo PHP_EOL . sprintf('Match Percentage: %d percent between %s and %s', $matchpct, $ourName, $scrapeName) . PHP_EOL; - } + $str = str_replace('&', 'and', $str); + $str = preg_replace('/^(history|discovery) channel/i', '', $str); + $str = str_replace(['\'', ':', '!', '"', '#', '*', '’', ',', '(', ')', '?'], '', $str); + $str = str_replace('$', 's', $str); + $str = preg_replace('/\s{2,}/', ' ', $str); - if ($matchpct >= $probability) { - return $matchpct; - } + $str = trim($str, '\"'); - return 0; + return trim($str); + } - } + /** + * Simple function that compares two strings of text + * Returns percentage of similarity. + * + * @param $ourName + * @param $scrapeName + * @param $probability + * + * @return int|float + */ + public function checkMatch($ourName, $scrapeName, $probability) + { + similar_text($ourName, $scrapeName, $matchpct); - // - /** - * Convert 2012-24-07 to 2012-07-24, there is probably a better way - * - * This shouldn't ever happen as I've never heard of a date starting with year being followed by day value. - * Could this be a mistake? i.e. trying to solve the mm-dd-yyyy/dd-mm-yyyy confusion into a yyyy-mm-dd? - * - * @param string|bool $date - * - * @return string - */ - public function checkDate($date) - { - if (!empty($date)) { - $chk = explode(' ', $date); - $chkd = explode('-', $chk[0]); - if ($chkd[1] > 12) { - $date = date('Y-m-d H:i:s', strtotime($chkd[1] . ' ' . $chkd[2] . ' ' . $chkd[0])); - } - } else { - $date = null; - } - return $date; - } + if (NN_DEBUG) { + echo PHP_EOL.sprintf('Match Percentage: %d percent between %s and %s', $matchpct, $ourName, $scrapeName).PHP_EOL; + } - /** - * Checks API response returns have all REQUIRED attributes set - * Returns true or false - * - * @param $array - * @param int $type - * - * @return bool - */ - public function checkRequiredAttr($array, $type) - { - $required = ['failedToMatchType']; + if ($matchpct >= $probability) { + return $matchpct; + } - switch ($type) { + return 0; + } + + // + + /** + * Convert 2012-24-07 to 2012-07-24, there is probably a better way. + * + * This shouldn't ever happen as I've never heard of a date starting with year being followed by day value. + * Could this be a mistake? i.e. trying to solve the mm-dd-yyyy/dd-mm-yyyy confusion into a yyyy-mm-dd? + * + * @param string|bool $date + * + * @return string + */ + public function checkDate($date) + { + if (! empty($date)) { + $chk = explode(' ', $date); + $chkd = explode('-', $chk[0]); + if ($chkd[1] > 12) { + $date = date('Y-m-d H:i:s', strtotime($chkd[1].' '.$chkd[2].' '.$chkd[0])); + } + } else { + $date = null; + } + + return $date; + } + + /** + * Checks API response returns have all REQUIRED attributes set + * Returns true or false. + * + * @param $array + * @param int $type + * + * @return bool + */ + public function checkRequiredAttr($array, $type) + { + $required = ['failedToMatchType']; + + switch ($type) { case 'tvdbS': $required = ['id', 'seriesName', 'overview', 'firstAired']; break; @@ -804,19 +816,20 @@ abstract class TV extends Videos break; } - if (is_array($required)) { - foreach ($required as $req) { - if (!in_array($type, ['tmdbS', 'tmdbE', 'traktS', 'traktE'], false)){ - if (!isset($array->$req)) { - return false; - } - } else { - if (!isset($array[$req])) { - return false; - } - } - } - } - return true; - } + if (is_array($required)) { + foreach ($required as $req) { + if (! in_array($type, ['tmdbS', 'tmdbE', 'traktS', 'traktE'], false)) { + if (! isset($array->$req)) { + return false; + } + } else { + if (! isset($array[$req])) { + return false; + } + } + } + } + + return true; + } } diff --git a/nntmux/processing/tv/TVDB.php b/nntmux/processing/tv/TVDB.php index fccdc16f5..9ef8e8031 100755 --- a/nntmux/processing/tv/TVDB.php +++ b/nntmux/processing/tv/TVDB.php @@ -1,481 +1,478 @@ <?php + namespace nntmux\processing\tv; -use Adrenth\Thetvdb\Client; -use Adrenth\Thetvdb\Exception\CouldNotLoginException; -use Adrenth\Thetvdb\Exception\InvalidArgumentException; -use Adrenth\Thetvdb\Exception\InvalidJsonInResponseException; -use Adrenth\Thetvdb\Exception\RequestFailedException; -use Adrenth\Thetvdb\Exception\UnauthorizedException; use nntmux\ColorCLI; use nntmux\ReleaseImage; +use Adrenth\Thetvdb\Client; +use Adrenth\Thetvdb\Exception\UnauthorizedException; +use Adrenth\Thetvdb\Exception\CouldNotLoginException; +use Adrenth\Thetvdb\Exception\RequestFailedException; +use Adrenth\Thetvdb\Exception\InvalidArgumentException; +use Adrenth\Thetvdb\Exception\InvalidJsonInResponseException; /** - * Class TVDB -- functions used to post process releases against TVDB + * Class TVDB -- functions used to post process releases against TVDB. */ class TVDB extends TV { - const TVDB_URL = 'https://api.thetvdb.com'; - const TVDB_API_KEY = '31740C28BAC74DEF'; - const MATCH_PROBABILITY = 75; + const TVDB_URL = 'https://api.thetvdb.com'; + const TVDB_API_KEY = '31740C28BAC74DEF'; + const MATCH_PROBABILITY = 75; - /** - * @var Client - */ - public $client; + /** + * @var Client + */ + public $client; - /** - * @var string Authorization token for TVDB v2 API - */ - public $token; + /** + * @var string Authorization token for TVDB v2 API + */ + public $token; - /** - * @string URL for show poster art - */ - public $posterUrl; + /** + * @string URL for show poster art + */ + public $posterUrl; - /** - * @var string URL for show fanart - */ - public $fanartUrl; + /** + * @var string URL for show fanart + */ + public $fanartUrl; - /** - * @bool Do a local lookup only if server is down - */ - private $local; + /** + * @bool Do a local lookup only if server is down + */ + private $local; - /** - * @param array $options Class instances / Echo to cli? - */ - public function __construct(array $options = []) - { - parent::__construct($options); - $this->client = new Client(); - $this->client->setLanguage('en'); - $this->posterUrl = self::TVDB_URL . DS . 'graphical/%s-g.jpg'; - $this->fanartUrl = self::TVDB_URL . DS . '_cache/fanart/original/%s-3.jpg'; - $this->local = false; + /** + * @param array $options Class instances / Echo to cli? + */ + public function __construct(array $options = []) + { + parent::__construct($options); + $this->client = new Client(); + $this->client->setLanguage('en'); + $this->posterUrl = self::TVDB_URL.DS.'graphical/%s-g.jpg'; + $this->fanartUrl = self::TVDB_URL.DS.'_cache/fanart/original/%s-3.jpg'; + $this->local = false; - // Check if we can get the time for API status - // If we can't then we set local to true - try { - $this->token = $this->client->authentication()->login(self::TVDB_API_KEY); - } catch (CouldNotLoginException $error) { - echo ColorCLI::warning('Could not reach TVDB API. Running in local mode only!'); - $this->local = true; - } catch (UnauthorizedException $error) { - echo ColorCLI::warning('Bad response from TVDB API. Running in local mode only!'); - $this->local = true; - } + // Check if we can get the time for API status + // If we can't then we set local to true + try { + $this->token = $this->client->authentication()->login(self::TVDB_API_KEY); + } catch (CouldNotLoginException $error) { + echo ColorCLI::warning('Could not reach TVDB API. Running in local mode only!'); + $this->local = true; + } catch (UnauthorizedException $error) { + echo ColorCLI::warning('Bad response from TVDB API. Running in local mode only!'); + $this->local = true; + } - if (strlen($this->token) > 0) { - $this->client->setToken($this->token); - } - } + if (strlen($this->token) > 0) { + $this->client->setToken($this->token); + } + } - /** - * Main processing director function for scrapers - * Calls work query function and initiates processing - * - * @param $groupID - * @param $guidChar - * @param $process - * @param bool $local - */ - public function processSite($groupID, $guidChar, $process, $local = false): void - { - $res = $this->getTvReleases($groupID, $guidChar, $process, parent::PROCESS_TVDB); + /** + * Main processing director function for scrapers + * Calls work query function and initiates processing. + * + * @param $groupID + * @param $guidChar + * @param $process + * @param bool $local + */ + public function processSite($groupID, $guidChar, $process, $local = false): void + { + $res = $this->getTvReleases($groupID, $guidChar, $process, parent::PROCESS_TVDB); - $tvcount = $res->rowCount(); + $tvcount = $res->rowCount(); - if ($this->echooutput && $tvcount > 0) { - echo ColorCLI::header('Processing TVDB lookup for ' . number_format($tvcount) . ' release(s).'); - } + if ($this->echooutput && $tvcount > 0) { + echo ColorCLI::header('Processing TVDB lookup for '.number_format($tvcount).' release(s).'); + } - if ($res instanceof \Traversable) { + if ($res instanceof \Traversable) { + $this->titleCache = []; - $this->titleCache = []; + foreach ($res as $row) { + $tvdbid = false; - foreach ($res as $row) { - - $tvdbid = false; - - // Clean the show name for better match probability - $release = $this->parseInfo($row['searchname']); - if (is_array($release) && $release['name'] != '') { - - if (in_array($release['cleanname'], $this->titleCache, false)) { - if ($this->echooutput) { - echo ColorCLI::headerOver('Title: ') . - ColorCLI::warningOver($release['cleanname']) . + // Clean the show name for better match probability + $release = $this->parseInfo($row['searchname']); + if (is_array($release) && $release['name'] != '') { + if (in_array($release['cleanname'], $this->titleCache, false)) { + if ($this->echooutput) { + echo ColorCLI::headerOver('Title: '). + ColorCLI::warningOver($release['cleanname']). ColorCLI::header(' already failed lookup for this site. Skipping.'); - } - $this->setVideoNotFound(parent::PROCESS_TVMAZE, $row['id']); - continue; - } + } + $this->setVideoNotFound(parent::PROCESS_TVMAZE, $row['id']); + continue; + } - // Find the Video ID if it already exists by checking the title. - $videoId = $this->getByTitle($release['cleanname'], parent::TYPE_TV); + // Find the Video ID if it already exists by checking the title. + $videoId = $this->getByTitle($release['cleanname'], parent::TYPE_TV); - if ($videoId !== false) { - $tvdbid = $this->getSiteByID('tvdb', $videoId); - } + if ($videoId !== false) { + $tvdbid = $this->getSiteByID('tvdb', $videoId); + } - // Force local lookup only - if ($local === true || $this->local === true) { - $lookupSetting = false; - } else { - $lookupSetting = true; - } + // Force local lookup only + if ($local === true || $this->local === true) { + $lookupSetting = false; + } else { + $lookupSetting = true; + } - if ($tvdbid === false && $lookupSetting) { + if ($tvdbid === false && $lookupSetting) { // If it doesnt exist locally and lookups are allowed lets try to get it. - if ($this->echooutput) { - echo ColorCLI::primaryOver('Video ID for ') . - ColorCLI::headerOver($release['cleanname']) . + if ($this->echooutput) { + echo ColorCLI::primaryOver('Video ID for '). + ColorCLI::headerOver($release['cleanname']). ColorCLI::primary(' not found in local db, checking web.'); - } + } - // Check if we have a valid country and set it in the array - $country = (isset($release['country']) && strlen($release['country']) == 2 - ? (string)$release['country'] + // Check if we have a valid country and set it in the array + $country = (isset($release['country']) && strlen($release['country']) == 2 + ? (string) $release['country'] : '' ); - // Get the show from TVDB - $tvdbShow = $this->getShowInfo((string)$release['cleanname'], $country); + // Get the show from TVDB + $tvdbShow = $this->getShowInfo((string) $release['cleanname'], $country); - if (is_array($tvdbShow)) { - $tvdbShow['country'] = $country; - $videoId = $this->add($tvdbShow); - $tvdbid = (int)$tvdbShow['tvdb']; - } - - } else if ($this->echooutput && $tvdbid !== false) { - echo ColorCLI::primaryOver('Video ID for ') . - ColorCLI::headerOver($release['cleanname']) . + if (is_array($tvdbShow)) { + $tvdbShow['country'] = $country; + $videoId = $this->add($tvdbShow); + $tvdbid = (int) $tvdbShow['tvdb']; + } + } elseif ($this->echooutput && $tvdbid !== false) { + echo ColorCLI::primaryOver('Video ID for '). + ColorCLI::headerOver($release['cleanname']). ColorCLI::primary(' found in local db, attempting episode match.'); - } + } - if (is_numeric($videoId) && $videoId > 0 && is_numeric($tvdbid) && $tvdbid > 0) { - // Now that we have valid video and tvdb ids, try to get the poster - $this->getPoster($videoId, $tvdbid); + if (is_numeric($videoId) && $videoId > 0 && is_numeric($tvdbid) && $tvdbid > 0) { + // Now that we have valid video and tvdb ids, try to get the poster + $this->getPoster($videoId, $tvdbid); - $seasonNo = (!empty($release['season']) ? preg_replace('/^S0*/i', '', $release['season']) : ''); - $episodeNo = (!empty($release['episode']) ? preg_replace('/^E0*/i', '', $release['episode']) : ''); + $seasonNo = (! empty($release['season']) ? preg_replace('/^S0*/i', '', $release['season']) : ''); + $episodeNo = (! empty($release['episode']) ? preg_replace('/^E0*/i', '', $release['episode']) : ''); - if ($episodeNo === 'all') { - // Set the video ID and leave episode 0 - $this->setVideoIdFound($videoId, $row['id'], 0); - echo ColorCLI::primary('Found TVDB Match for Full Season!'); - continue; - } + if ($episodeNo === 'all') { + // Set the video ID and leave episode 0 + $this->setVideoIdFound($videoId, $row['id'], 0); + echo ColorCLI::primary('Found TVDB Match for Full Season!'); + continue; + } - // Download all episodes if new show to reduce API/bandwidth usage - if ($this->countEpsByVideoID($videoId) === false) { - $this->getEpisodeInfo($tvdbid, -1, -1, '', $videoId); - } + // Download all episodes if new show to reduce API/bandwidth usage + if ($this->countEpsByVideoID($videoId) === false) { + $this->getEpisodeInfo($tvdbid, -1, -1, '', $videoId); + } - // Check if we have the episode for this video ID - $episode = $this->getBySeasonEp($videoId, $seasonNo, $episodeNo, $release['airdate']); + // Check if we have the episode for this video ID + $episode = $this->getBySeasonEp($videoId, $seasonNo, $episodeNo, $release['airdate']); - if ($episode === false && $lookupSetting) { - // Send the request for the episode to TVDB - $tvdbEpisode = $this->getEpisodeInfo( + if ($episode === false && $lookupSetting) { + // Send the request for the episode to TVDB + $tvdbEpisode = $this->getEpisodeInfo( $tvdbid, $seasonNo, $episodeNo, $release['airdate'] ); - if ($tvdbEpisode) { - $episode = $this->addEpisode($videoId, $tvdbEpisode); - } - } + if ($tvdbEpisode) { + $episode = $this->addEpisode($videoId, $tvdbEpisode); + } + } - if ($episode !== false && is_numeric($episode) && $episode > 0) { - // Mark the releases video and episode IDs - $this->setVideoIdFound($videoId, $row['id'], $episode); - if ($this->echooutput) { - echo ColorCLI::primary('Found TVDB Match!'); - } - } else { - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_TVMAZE, $row['id']); - } - } else { - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_TVMAZE, $row['id']); - $this->titleCache[] = $release['cleanname']; - } - } else { - //Parsing failed, take it out of the queue for examination - $this->setVideoNotFound(parent::FAILED_PARSE, $row['id']); - $this->titleCache[] = $release['cleanname']; - } - } - } - } + if ($episode !== false && is_numeric($episode) && $episode > 0) { + // Mark the releases video and episode IDs + $this->setVideoIdFound($videoId, $row['id'], $episode); + if ($this->echooutput) { + echo ColorCLI::primary('Found TVDB Match!'); + } + } else { + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_TVMAZE, $row['id']); + } + } else { + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_TVMAZE, $row['id']); + $this->titleCache[] = $release['cleanname']; + } + } else { + //Parsing failed, take it out of the queue for examination + $this->setVideoNotFound(parent::FAILED_PARSE, $row['id']); + $this->titleCache[] = $release['cleanname']; + } + } + } + } - /** - * Placeholder for Videos getBanner - * - * @param $videoID - * @param $siteId - * - * @return bool - */ - protected function getBanner($videoID, $siteId): bool - { - return false; - } + /** + * Placeholder for Videos getBanner. + * + * @param $videoID + * @param $siteId + * + * @return bool + */ + protected function getBanner($videoID, $siteId): bool + { + return false; + } - /** - * Calls the API to perform initial show name match to TVDB title - * Returns a formatted array of show data or false if no match - * - * @param string $cleanName - * - * @param string $country - * - * @return array|false - */ - protected function getShowInfo($cleanName, $country = '') - { - $return = $response = false; - $highestMatch = 0; - try { - $response = $this->client->search()->seriesByName($cleanName); - } catch (InvalidArgumentException $error) { - return false; - } catch (InvalidJsonInResponseException $error) { - if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { - return false; - } - } catch (RequestFailedException $error) { - return false; - } catch (UnauthorizedException $error) { - if (strpos($error->getMessage(), 'Unauthorized') === 0) { - return false; - } - } + /** + * Calls the API to perform initial show name match to TVDB title + * Returns a formatted array of show data or false if no match. + * + * @param string $cleanName + * + * @param string $country + * + * @return array|false + */ + protected function getShowInfo($cleanName, $country = '') + { + $return = $response = false; + $highestMatch = 0; + try { + $response = $this->client->search()->seriesByName($cleanName); + } catch (InvalidArgumentException $error) { + return false; + } catch (InvalidJsonInResponseException $error) { + if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { + return false; + } + } catch (RequestFailedException $error) { + return false; + } catch (UnauthorizedException $error) { + if (strpos($error->getMessage(), 'Unauthorized') === 0) { + return false; + } + } + if ($response === false && $country !== '') { + try { + $response = $this->client->search()->seriesByName(rtrim(str_replace($country, '', $cleanName))); + } catch (InvalidArgumentException $error) { + return false; + } catch (InvalidJsonInResponseException $error) { + if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { + return false; + } + } catch (RequestFailedException $error) { + return false; + } catch (UnauthorizedException $error) { + if (strpos($error->getMessage(), 'Unauthorized') === 0) { + return false; + } + } + } - if ($response === false && $country !== '') { - try { - $response = $this->client->search()->seriesByName(rtrim(str_replace($country, '', $cleanName))); - } catch (InvalidArgumentException $error) { - return false; - } catch (InvalidJsonInResponseException $error) { - if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { - return false; - } - } catch (RequestFailedException $error) { - return false; - } catch (UnauthorizedException $error) { - if (strpos($error->getMessage(), 'Unauthorized') === 0) { - return false; - } - } - } + sleep(1); - sleep(1); + if (is_array($response)) { + foreach ($response->getData() as $show) { + if ($this->checkRequiredAttr($show, 'tvdbS')) { + // Check for exact title match first and then terminate if found + if (strtolower($show->getSeriesName()) === strtolower($cleanName)) { + $highest = $show; + break; + } - if (is_array($response)) { - foreach ($response->getData() as $show) { - if ($this->checkRequiredAttr($show, 'tvdbS')) { - // Check for exact title match first and then terminate if found - if (strtolower($show->getSeriesName()) === strtolower($cleanName)) { - $highest = $show; - break; - } + // Check each show title for similarity and then find the highest similar value + $matchPercent = $this->checkMatch(strtolower($show->getSeriesName()), strtolower($cleanName), self::MATCH_PROBABILITY); - // Check each show title for similarity and then find the highest similar value - $matchPercent = $this->checkMatch(strtolower($show->getSeriesName()), strtolower($cleanName), self::MATCH_PROBABILITY); + // If new match has a higher percentage, set as new matched title + if ($matchPercent > $highestMatch) { + $highestMatch = $matchPercent; + $highest = $show; + } - // If new match has a higher percentage, set as new matched title - if ($matchPercent > $highestMatch) { - $highestMatch = $matchPercent; - $highest = $show; - } + // Check for show aliases and try match those too + if (! empty($show->getAliases())) { + foreach ($show->getAliases() as $key => $name) { + $matchPercent = $this->checkMatch(strtolower($name), strtolower($cleanName), $matchPercent); + if ($matchPercent > $highestMatch) { + $highestMatch = $matchPercent; + $highest = $show; + } + } + } + } + } + if (! empty($highest)) { + $return = $this->formatShowInfo($highest); + } + } - // Check for show aliases and try match those too - if (!empty($show->getAliases())) { - foreach ($show->getAliases() as $key => $name) { - $matchPercent = $this->checkMatch(strtolower($name), strtolower($cleanName), $matchPercent); - if ($matchPercent > $highestMatch) { - $highestMatch = $matchPercent; - $highest = $show; - } - } - } - } - } - if (!empty($highest)) { - $return = $this->formatShowInfo($highest); - } - } + return $return; + } - return $return; - } + /** + * Retrieves the poster art for the processed show. + * + * @param int $videoId -- the local Video ID + * @param int $showId -- the TVDB ID + * + * @return int + */ + public function getPoster($videoId, $showId): int + { + $ri = new ReleaseImage($this->pdo); - /** - * Retrieves the poster art for the processed show - * - * @param int $videoId -- the local Video ID - * @param int $showId -- the TVDB ID - * - * @return int - */ - public function getPoster($videoId, $showId): int - { - $ri = new ReleaseImage($this->pdo); + // Try to get the Poster + $hascover = $ri->saveImage($videoId, sprintf($this->posterUrl, $showId), $this->imgSavePath, '', ''); - // Try to get the Poster - $hascover = $ri->saveImage($videoId, sprintf($this->posterUrl, $showId), $this->imgSavePath, '', ''); + // Couldn't get poster, try fan art instead + if ($hascover !== 1) { + $hascover = $ri->saveImage($videoId, sprintf($this->fanartUrl, $showId), $this->imgSavePath, '', ''); + } + // Mark it retrieved if we saved an image + if ($hascover === 1) { + $this->setCoverFound($videoId); + } - // Couldn't get poster, try fan art instead - if ($hascover !== 1) { - $hascover = $ri->saveImage($videoId, sprintf($this->fanartUrl, $showId), $this->imgSavePath, '', ''); - } - // Mark it retrieved if we saved an image - if ($hascover === 1) { - $this->setCoverFound($videoId); - } - return $hascover; - } + return $hascover; + } - /** - * Gets the specific episode info for the parsed release after match - * Returns a formatted array of episode data or false if no match - * - * @param integer $tvdbid - * @param integer $season - * @param integer $episode - * @param string $airdate - * @param integer $videoId - * - * @return array|false - */ - protected function getEpisodeInfo($tvdbid, $season, $episode, $airdate = '', $videoId = 0) - { - $return = $response = false; + /** + * Gets the specific episode info for the parsed release after match + * Returns a formatted array of episode data or false if no match. + * + * @param int $tvdbid + * @param int $season + * @param int $episode + * @param string $airdate + * @param int $videoId + * + * @return array|false + */ + protected function getEpisodeInfo($tvdbid, $season, $episode, $airdate = '', $videoId = 0) + { + $return = $response = false; - if ($airdate !== '') { - try { - $response = $this->client->series()->getEpisodesWithQuery($tvdbid, ['firstAired' => $airdate]); - } catch (InvalidArgumentException $error) { - return false; - } catch (InvalidJsonInResponseException $error) { - if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { - return false; - } - } catch (RequestFailedException $error) { - return false; - } catch (UnauthorizedException $error) { - if (strpos($error->getMessage(), 'Unauthorized') === 0) { - return false; - } - } - } else if ($videoId > 0) { - try { - $response = $this->client->series()->getEpisodes($tvdbid); - } catch (InvalidArgumentException $error) { - return false; - } catch (InvalidJsonInResponseException $error) { - if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { - return false; - } - } catch (RequestFailedException $error) { - return false; - } catch (UnauthorizedException $error) { - if (strpos($error->getMessage(), 'Unauthorized') === 0) { - return false; - } - } - } else { - try { - $response = $this->client->series()->getEpisodesWithQuery($tvdbid, ['airedSeason' => $season, 'airedEpisode' => $episode]); - } catch (InvalidArgumentException $error) { - return false; - } catch (InvalidJsonInResponseException $error) { - if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { - return false; - } - } catch (RequestFailedException $error) { - return false; - } catch (UnauthorizedException $error) { - if (strpos($error->getMessage(), 'Unauthorized') === 0) { - return false; - } - } - } + if ($airdate !== '') { + try { + $response = $this->client->series()->getEpisodesWithQuery($tvdbid, ['firstAired' => $airdate]); + } catch (InvalidArgumentException $error) { + return false; + } catch (InvalidJsonInResponseException $error) { + if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { + return false; + } + } catch (RequestFailedException $error) { + return false; + } catch (UnauthorizedException $error) { + if (strpos($error->getMessage(), 'Unauthorized') === 0) { + return false; + } + } + } elseif ($videoId > 0) { + try { + $response = $this->client->series()->getEpisodes($tvdbid); + } catch (InvalidArgumentException $error) { + return false; + } catch (InvalidJsonInResponseException $error) { + if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { + return false; + } + } catch (RequestFailedException $error) { + return false; + } catch (UnauthorizedException $error) { + if (strpos($error->getMessage(), 'Unauthorized') === 0) { + return false; + } + } + } else { + try { + $response = $this->client->series()->getEpisodesWithQuery($tvdbid, ['airedSeason' => $season, 'airedEpisode' => $episode]); + } catch (InvalidArgumentException $error) { + return false; + } catch (InvalidJsonInResponseException $error) { + if (strpos($error->getMessage(), 'Could not decode JSON data') === 0 || strpos($error->getMessage(), 'Incorrect data structure') === 0) { + return false; + } + } catch (RequestFailedException $error) { + return false; + } catch (UnauthorizedException $error) { + if (strpos($error->getMessage(), 'Unauthorized') === 0) { + return false; + } + } + } - sleep(1); + sleep(1); - if (is_object($response->getData())) { - if ($this->checkRequiredAttr($response->getData(), 'tvdbE')) { - $return = $this->formatEpisodeInfo($response); - } - } else if ($videoId > 0 && is_array($response->getData())) { - foreach ($response->getData() as $singleEpisode) { - if ($this->checkRequiredAttr($singleEpisode, 'tvdbE')) { - $this->addEpisode($videoId, $this->formatEpisodeInfo($singleEpisode)); - } - } - } + if (is_object($response->getData())) { + if ($this->checkRequiredAttr($response->getData(), 'tvdbE')) { + $return = $this->formatEpisodeInfo($response); + } + } elseif ($videoId > 0 && is_array($response->getData())) { + foreach ($response->getData() as $singleEpisode) { + if ($this->checkRequiredAttr($singleEpisode, 'tvdbE')) { + $this->addEpisode($videoId, $this->formatEpisodeInfo($singleEpisode)); + } + } + } - return $return; - } + return $return; + } - /** - * Assigns API show response values to a formatted array for insertion - * Returns the formatted array - * - * @param $show - * - * @return array - */ - protected function formatShowInfo($show): array - { - preg_match('/tt(?P<imdbid>\d{6,7})$/i', $show->imdbId, $imdb); + /** + * Assigns API show response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $show + * + * @return array + */ + protected function formatShowInfo($show): array + { + preg_match('/tt(?P<imdbid>\d{6,7})$/i', $show->imdbId, $imdb); - return [ - 'type' => (int)parent::TYPE_TV, - 'title' => (string)$show->getSeriesName(), - 'summary' => (string)$show->getOverview(), + return [ + 'type' => (int) parent::TYPE_TV, + 'title' => (string) $show->getSeriesName(), + 'summary' => (string) $show->getOverview(), 'started' => $show->firstAired->format('Y-m-d'), - 'publisher' => (string)$show->getNetwork(), - 'source' => (int)parent::SOURCE_TVDB, - 'imdb' => (int)($imdb['imdbid'] ?? 0), - 'tvdb' => (int)$show->getid(), + 'publisher' => (string) $show->getNetwork(), + 'source' => (int) parent::SOURCE_TVDB, + 'imdb' => (int) ($imdb['imdbid'] ?? 0), + 'tvdb' => (int) $show->getid(), 'trakt' => 0, 'tvrage' => 0, 'tvmaze' => 0, 'tmdb' => 0, - 'aliases' => (!empty($show->getAliases()) ? $show->getAliases() : ''), - 'localzone' => "''" + 'aliases' => (! empty($show->getAliases()) ? $show->getAliases() : ''), + 'localzone' => "''", ]; - } + } - /** - * Assigns API episode response values to a formatted array for insertion - * Returns the formatted array - * - * @param $episode - * - * @return array - */ - protected function formatEpisodeInfo($episode): array - { - return [ - 'title' => (string)$episode->name, - 'series' => (int)$episode->season, - 'episode' => (int)$episode->number, - 'se_complete' => (string)'S' . sprintf('%02d', $episode->season) . 'E' . sprintf('%02d', $episode->number), + /** + * Assigns API episode response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $episode + * + * @return array + */ + protected function formatEpisodeInfo($episode): array + { + return [ + 'title' => (string) $episode->name, + 'series' => (int) $episode->season, + 'episode' => (int) $episode->number, + 'se_complete' => (string) 'S'.sprintf('%02d', $episode->season).'E'.sprintf('%02d', $episode->number), 'firstaired' => $episode->firstAired->format('Y-m-d'), - 'summary' => (string)$episode->overview + 'summary' => (string) $episode->overview, ]; - } + } } diff --git a/nntmux/processing/tv/TVMaze.php b/nntmux/processing/tv/TVMaze.php index d954dde7e..dae63f82a 100755 --- a/nntmux/processing/tv/TVMaze.php +++ b/nntmux/processing/tv/TVMaze.php @@ -1,428 +1,428 @@ <?php + namespace nntmux\processing\tv; -use JPinkney\TVMaze\TVMaze as Client; use nntmux\ColorCLI; use nntmux\ReleaseImage; +use JPinkney\TVMaze\TVMaze as Client; /** - * Class TVMaze + * Class TVMaze. * * Process information retrieved from the TVMaze API. */ class TVMaze extends TV { - const MATCH_PROBABILITY = 75; + const MATCH_PROBABILITY = 75; - /** - * Client for TVMaze API - * - * @var Client - */ - public $client; + /** + * Client for TVMaze API. + * + * @var Client + */ + public $client; - /** - * @var string The URL for the medium sized image for poster - */ - public $posterUrl; + /** + * @var string The URL for the medium sized image for poster + */ + public $posterUrl; - /** - * Construct. Instantiate TVMaze Client Class - * - * @param array $options Class instances. - * - * @access public - */ - public function __construct(array $options = []) - { - parent::__construct($options); - $this->client = new Client(); - } + /** + * Construct. Instantiate TVMaze Client Class. + * + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + parent::__construct($options); + $this->client = new Client(); + } - /** - * Fetch banner from site. - * - * @param $videoId - * @param $siteID - * - * @return bool - */ - public function getBanner($videoId, $siteID): bool - { - return false; - } + /** + * Fetch banner from site. + * + * @param $videoId + * @param $siteID + * + * @return bool + */ + public function getBanner($videoId, $siteID): bool + { + return false; + } - /** - * Main processing director function for scrapers - * Calls work query function and initiates processing - * - * @param $groupID - * @param $guidChar - * @param $process - * @param bool $local - */ - public function processSite ($groupID, $guidChar, $process, $local = false): void - { - $res = $this->getTvReleases($groupID, $guidChar, $process, parent::PROCESS_TVMAZE); + /** + * Main processing director function for scrapers + * Calls work query function and initiates processing. + * + * @param $groupID + * @param $guidChar + * @param $process + * @param bool $local + */ + public function processSite($groupID, $guidChar, $process, $local = false): void + { + $res = $this->getTvReleases($groupID, $guidChar, $process, parent::PROCESS_TVMAZE); - $tvcount = $res->rowCount(); + $tvcount = $res->rowCount(); - if ($this->echooutput && $tvcount > 0) { - echo ColorCLI::header('Processing TVMaze lookup for ' . number_format($tvcount) . ' release(s).'); - } + if ($this->echooutput && $tvcount > 0) { + echo ColorCLI::header('Processing TVMaze lookup for '.number_format($tvcount).' release(s).'); + } - if ($res instanceof \Traversable) { + if ($res instanceof \Traversable) { + $this->titleCache = []; - $this->titleCache = []; + foreach ($res as $row) { + $this->posterUrl = ''; + $tvmazeid = false; - foreach ($res as $row) { - - $this->posterUrl = ''; - $tvmazeid = false; - - // Clean the show name for better match probability - $release = $this->parseInfo($row['searchname']); - if (is_array($release) && $release['name'] !== '') { - - if (in_array($release['cleanname'], $this->titleCache, false)) { - if ($this->echooutput) { - echo ColorCLI::headerOver('Title: ') . - ColorCLI::warningOver($release['cleanname']) . + // Clean the show name for better match probability + $release = $this->parseInfo($row['searchname']); + if (is_array($release) && $release['name'] !== '') { + if (in_array($release['cleanname'], $this->titleCache, false)) { + if ($this->echooutput) { + echo ColorCLI::headerOver('Title: '). + ColorCLI::warningOver($release['cleanname']). ColorCLI::header(' already failed lookup for this site. Skipping.'); - } - $this->setVideoNotFound(parent::PROCESS_TMDB, $row['id']); - continue; - } + } + $this->setVideoNotFound(parent::PROCESS_TMDB, $row['id']); + continue; + } - // Find the Video ID if it already exists by checking the title against stored TVMaze titles - $videoId = $this->getByTitle($release['cleanname'], parent::TYPE_TV, parent::SOURCE_TVMAZE); + // Find the Video ID if it already exists by checking the title against stored TVMaze titles + $videoId = $this->getByTitle($release['cleanname'], parent::TYPE_TV, parent::SOURCE_TVMAZE); - // Force local lookup only - //$local = true, $lookupsetting = false and vice versa - $lookupSetting = $local !== true; + // Force local lookup only + //$local = true, $lookupsetting = false and vice versa + $lookupSetting = $local !== true; - if ($videoId === false && $lookupSetting) { - // If lookups are allowed lets try to get it. - if ($this->echooutput) { - echo ColorCLI::primaryOver('Checking TVMaze for previously failed title: ') . - ColorCLI::headerOver($release['cleanname']) . + if ($videoId === false && $lookupSetting) { + // If lookups are allowed lets try to get it. + if ($this->echooutput) { + echo ColorCLI::primaryOver('Checking TVMaze for previously failed title: '). + ColorCLI::headerOver($release['cleanname']). ColorCLI::primary('.'); - } + } - // Get the show from TVMaze - $tvmazeShow = $this->getShowInfo((string)$release['cleanname']); + // Get the show from TVMaze + $tvmazeShow = $this->getShowInfo((string) $release['cleanname']); - if (is_array($tvmazeShow)) { - $tvmazeid = (int)$tvmazeShow['tvmaze']; - // Check if we have the TVDB ID already, if we do use that Video ID, unless it is 0 - $dupeCheck = false; - if ((int)$tvmazeShow['tvdb'] !== 0) { - $dupeCheck = $this->getVideoIDFromSiteID('tvdb', $tvmazeShow['tvdb']); - } - if ($dupeCheck === false) { - $videoId = $this->add($tvmazeShow); - } else { - $videoId = $dupeCheck; - // Update any missing fields and add site IDs - $this->update($videoId, $tvmazeShow); - $tvmazeid = $this->getSiteIDFromVideoID('tvmaze', $videoId); - } - } - } else { - if ($this->echooutput) { - echo ColorCLI::primaryOver('Found local TVMaze match for: ') . - ColorCLI::headerOver($release['cleanname']) . + if (is_array($tvmazeShow)) { + $tvmazeid = (int) $tvmazeShow['tvmaze']; + // Check if we have the TVDB ID already, if we do use that Video ID, unless it is 0 + $dupeCheck = false; + if ((int) $tvmazeShow['tvdb'] !== 0) { + $dupeCheck = $this->getVideoIDFromSiteID('tvdb', $tvmazeShow['tvdb']); + } + if ($dupeCheck === false) { + $videoId = $this->add($tvmazeShow); + } else { + $videoId = $dupeCheck; + // Update any missing fields and add site IDs + $this->update($videoId, $tvmazeShow); + $tvmazeid = $this->getSiteIDFromVideoID('tvmaze', $videoId); + } + } + } else { + if ($this->echooutput) { + echo ColorCLI::primaryOver('Found local TVMaze match for: '). + ColorCLI::headerOver($release['cleanname']). ColorCLI::primary('. Attempting episode lookup!'); - } - $tvmazeid = $this->getSiteIDFromVideoID('tvmaze', $videoId); - } + } + $tvmazeid = $this->getSiteIDFromVideoID('tvmaze', $videoId); + } - if (is_numeric($videoId) && $videoId > 0 && is_numeric($tvmazeid) && $tvmazeid > 0) { - // Now that we have valid video and tvmaze ids, try to get the poster - $this->getPoster($videoId, $tvmazeid); + if (is_numeric($videoId) && $videoId > 0 && is_numeric($tvmazeid) && $tvmazeid > 0) { + // Now that we have valid video and tvmaze ids, try to get the poster + $this->getPoster($videoId, $tvmazeid); - $seasonNo = preg_replace('/^S0*/i', '', $release['season']); - $episodeNo = preg_replace('/^E0*/i', '', $release['episode']); + $seasonNo = preg_replace('/^S0*/i', '', $release['season']); + $episodeNo = preg_replace('/^E0*/i', '', $release['episode']); - if ($episodeNo === 'all') { - // Set the video ID and leave episode 0 - $this->setVideoIdFound($videoId, $row['id'], 0); - echo ColorCLI::primary('Found TVMaze Match for Full Season!'); - continue; - } + if ($episodeNo === 'all') { + // Set the video ID and leave episode 0 + $this->setVideoIdFound($videoId, $row['id'], 0); + echo ColorCLI::primary('Found TVMaze Match for Full Season!'); + continue; + } - // Download all episodes if new show to reduce API usage - if ($this->countEpsByVideoID($videoId) === false) { - $this->getEpisodeInfo($tvmazeid, -1, -1, '', $videoId); - } + // Download all episodes if new show to reduce API usage + if ($this->countEpsByVideoID($videoId) === false) { + $this->getEpisodeInfo($tvmazeid, -1, -1, '', $videoId); + } - // Check if we have the episode for this video ID - $episode = $this->getBySeasonEp($videoId, $seasonNo, $episodeNo, $release['airdate']); + // Check if we have the episode for this video ID + $episode = $this->getBySeasonEp($videoId, $seasonNo, $episodeNo, $release['airdate']); - if ($episode === false) { - // Send the request for the episode to TVMaze - $tvmazeEpisode = $this->getEpisodeInfo( + if ($episode === false) { + // Send the request for the episode to TVMaze + $tvmazeEpisode = $this->getEpisodeInfo( $tvmazeid, $seasonNo, $episodeNo, $release['airdate'] ); - if ($tvmazeEpisode) { - $episode = $this->addEpisode($videoId, $tvmazeEpisode); - } - } + if ($tvmazeEpisode) { + $episode = $this->addEpisode($videoId, $tvmazeEpisode); + } + } - if ($episode !== false && is_numeric($episode) && $episode > 0) { - // Mark the releases video and episode IDs - $this->setVideoIdFound($videoId, $row['id'], $episode); - if ($this->echooutput) { - echo ColorCLI::primary('Found TVMaze Match!'); - } - continue; - } - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_TMDB, $row['id']); - } else { - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_TMDB, $row['id']); - $this->titleCache[] = $release['cleanname']; - } - } else{ - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_TMDB, $row['id']); - $this->titleCache[] = $release['cleanname']; - } - } - } - } + if ($episode !== false && is_numeric($episode) && $episode > 0) { + // Mark the releases video and episode IDs + $this->setVideoIdFound($videoId, $row['id'], $episode); + if ($this->echooutput) { + echo ColorCLI::primary('Found TVMaze Match!'); + } + continue; + } + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_TMDB, $row['id']); + } else { + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_TMDB, $row['id']); + $this->titleCache[] = $release['cleanname']; + } + } else { + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_TMDB, $row['id']); + $this->titleCache[] = $release['cleanname']; + } + } + } + } - /** - * Calls the API to lookup the TvMaze info for a given TVDB or TVRage ID - * Returns a formatted array of show data or false if no match + /** + * Calls the API to lookup the TvMaze info for a given TVDB or TVRage ID + * Returns a formatted array of show data or false if no match. + * + * @param $site + * @param $siteId + * + * @return array|false + */ + protected function getShowInfoBySiteID($site, $siteId) + { + $return = $response = false; - * @param $site - * @param $siteId - * - * @return array|false - */ - protected function getShowInfoBySiteID($site, $siteId) - { - $return = $response = false; + //Try for the best match with AKAs embedded + $response = $this->client->getShowBySiteID($site, $siteId); - //Try for the best match with AKAs embedded - $response = $this->client->getShowBySiteID($site, $siteId); + sleep(1); - sleep(1); + if (is_array($response)) { + $return = $this->formatShowInfo($response); + } - if (is_array($response)) { - $return = $this->formatShowInfo($response); - } - return $return; - } + return $return; + } - /** - * Calls the API to perform initial show name match to TVDB title - * Returns a formatted array of show data or false if no match - * - * @param $cleanName - * - * @return array|false - */ - protected function getShowInfo($cleanName) - { - $return = $response = false; + /** + * Calls the API to perform initial show name match to TVDB title + * Returns a formatted array of show data or false if no match. + * + * @param $cleanName + * + * @return array|false + */ + protected function getShowInfo($cleanName) + { + $return = $response = false; - // TVMaze does NOT like shows with the year in them even without the parentheses - // Do this for the API Search only as a local lookup should require it - $cleanName = preg_replace('# \((19|20)\d{2}\)$#', '', $cleanName); + // TVMaze does NOT like shows with the year in them even without the parentheses + // Do this for the API Search only as a local lookup should require it + $cleanName = preg_replace('# \((19|20)\d{2}\)$#', '', $cleanName); - //Try for the best match with AKAs embedded - $response = $this->client->singleSearchAkas($cleanName); + //Try for the best match with AKAs embedded + $response = $this->client->singleSearchAkas($cleanName); - sleep(1); + sleep(1); - if (is_array($response)) { - $return = $this->matchShowInfo($response, $cleanName); - } - if ($return === false) { - //Try for the best match via full search (no AKAs can be returned but the search is better) - $response = $this->client->search($cleanName); - if (is_array($response)) { - $return = $this->matchShowInfo($response, $cleanName); - } - } - //If we didn't get any aliases do a direct alias lookup - if (is_array($return) && empty($return['aliases']) && is_numeric($return['tvmaze'])) { - $return['aliases'] = $this->client->getShowAKAs($return['tvmaze']); - } - return $return; - } + if (is_array($response)) { + $return = $this->matchShowInfo($response, $cleanName); + } + if ($return === false) { + //Try for the best match via full search (no AKAs can be returned but the search is better) + $response = $this->client->search($cleanName); + if (is_array($response)) { + $return = $this->matchShowInfo($response, $cleanName); + } + } + //If we didn't get any aliases do a direct alias lookup + if (is_array($return) && empty($return['aliases']) && is_numeric($return['tvmaze'])) { + $return['aliases'] = $this->client->getShowAKAs($return['tvmaze']); + } - /** - * @param $shows - * @param $cleanName - * - * @return array|bool - */ - private function matchShowInfo($shows, $cleanName) - { - $return = false; - $highestMatch = 0; + return $return; + } - foreach ($shows AS $show) { - if ($this->checkRequiredAttr($show, 'tvmazeS')) { - // Check for exact title match first and then terminate if found - if (strtolower($show->name) === strtolower($cleanName)) { - $highest = $show; - break; - } - // Check each show title for similarity and then find the highest similar value - $matchPercent = $this->checkMatch(strtolower($show->name), strtolower($cleanName), self::MATCH_PROBABILITY); + /** + * @param $shows + * @param $cleanName + * + * @return array|bool + */ + private function matchShowInfo($shows, $cleanName) + { + $return = false; + $highestMatch = 0; - // If new match has a higher percentage, set as new matched title - if ($matchPercent > $highestMatch) { - $highestMatch = $matchPercent; - $highest = $show; - } + foreach ($shows as $show) { + if ($this->checkRequiredAttr($show, 'tvmazeS')) { + // Check for exact title match first and then terminate if found + if (strtolower($show->name) === strtolower($cleanName)) { + $highest = $show; + break; + } + // Check each show title for similarity and then find the highest similar value + $matchPercent = $this->checkMatch(strtolower($show->name), strtolower($cleanName), self::MATCH_PROBABILITY); - // Check for show aliases and try match those too - if (is_array($show->akas) && !empty($show->akas)) { - foreach ($show->akas as $key => $aka) { - $matchPercent = $this->checkMatch(strtolower($aka['name']), strtolower($cleanName), $matchPercent); - if ($matchPercent > $highestMatch) { - $highestMatch = $matchPercent; - $highest = $show; - } - } - } - } - } - if (isset($highest)) { - $return = $this->formatShowInfo($highest); - } - return $return; - } + // If new match has a higher percentage, set as new matched title + if ($matchPercent > $highestMatch) { + $highestMatch = $matchPercent; + $highest = $show; + } - /** - * Retrieves the poster art for the processed show - * - * @param int $videoId -- the local Video ID - * @param int $showId -- the TVMaze ID - * - * @return int - */ - public function getPoster($videoId, $showId = 0): int - { - $ri = new ReleaseImage($this->pdo); + // Check for show aliases and try match those too + if (is_array($show->akas) && ! empty($show->akas)) { + foreach ($show->akas as $key => $aka) { + $matchPercent = $this->checkMatch(strtolower($aka['name']), strtolower($cleanName), $matchPercent); + if ($matchPercent > $highestMatch) { + $highestMatch = $matchPercent; + $highest = $show; + } + } + } + } + } + if (isset($highest)) { + $return = $this->formatShowInfo($highest); + } - // Try to get the Poster - $hascover = $ri->saveImage($videoId, $this->posterUrl, $this->imgSavePath, '', ''); + return $return; + } - // Mark it retrieved if we saved an image - if ($hascover === 1) { - $this->setCoverFound($videoId); - } - return $hascover; - } + /** + * Retrieves the poster art for the processed show. + * + * @param int $videoId -- the local Video ID + * @param int $showId -- the TVMaze ID + * + * @return int + */ + public function getPoster($videoId, $showId = 0): int + { + $ri = new ReleaseImage($this->pdo); - /** - * Gets the specific episode info for the parsed release after match - * Returns a formatted array of episode data or false if no match - * - * @param integer $tvmazeid - * @param integer $season - * @param integer $episode - * @param string $airdate - * @param integer $videoId - * - * @return array|false - */ - protected function getEpisodeInfo($tvmazeid, $season, $episode, $airdate = '', $videoId = 0) - { - $return = $response = false; + // Try to get the Poster + $hascover = $ri->saveImage($videoId, $this->posterUrl, $this->imgSavePath, '', ''); - if ($airdate !== '') { - $response = $this->client->getEpisodesByAirdate($tvmazeid, $airdate); - } else if ($videoId > 0) { - $response = $this->client->getEpisodesByShowID($tvmazeid); - } else { - $response = $this->client->getEpisodeByNumber($tvmazeid, $season, $episode); - } + // Mark it retrieved if we saved an image + if ($hascover === 1) { + $this->setCoverFound($videoId); + } - sleep(1); + return $hascover; + } - //Handle Single Episode Lookups - if (is_object($response)) { - if ($this->checkRequiredAttr($response, 'tvmazeE')) { - $return = $this->formatEpisodeInfo($response); - } - } else if (is_array($response)) { - //Handle new show/all episodes and airdate lookups - foreach ($response as $singleEpisode) { - if ($this->checkRequiredAttr($singleEpisode, 'tvmazeE')) { - // If this is an airdate lookup and it matches the airdate, set a return - if ($airdate !== '' && $airdate === $singleEpisode->airdate) { - $return = $this->formatEpisodeInfo($singleEpisode); - } else { - // Insert the episode - $this->addEpisode($videoId, $this->formatEpisodeInfo($singleEpisode)); - } - } - } - } + /** + * Gets the specific episode info for the parsed release after match + * Returns a formatted array of episode data or false if no match. + * + * @param int $tvmazeid + * @param int $season + * @param int $episode + * @param string $airdate + * @param int $videoId + * + * @return array|false + */ + protected function getEpisodeInfo($tvmazeid, $season, $episode, $airdate = '', $videoId = 0) + { + $return = $response = false; - return $return; - } + if ($airdate !== '') { + $response = $this->client->getEpisodesByAirdate($tvmazeid, $airdate); + } elseif ($videoId > 0) { + $response = $this->client->getEpisodesByShowID($tvmazeid); + } else { + $response = $this->client->getEpisodeByNumber($tvmazeid, $season, $episode); + } - /** - * Assigns API show response values to a formatted array for insertion - * Returns the formatted array - * - * @param $show - * - * @return array - */ - protected function formatShowInfo($show): array - { - $this->posterUrl = (string)($show->mediumImage ?? ''); + sleep(1); - return [ + //Handle Single Episode Lookups + if (is_object($response)) { + if ($this->checkRequiredAttr($response, 'tvmazeE')) { + $return = $this->formatEpisodeInfo($response); + } + } elseif (is_array($response)) { + //Handle new show/all episodes and airdate lookups + foreach ($response as $singleEpisode) { + if ($this->checkRequiredAttr($singleEpisode, 'tvmazeE')) { + // If this is an airdate lookup and it matches the airdate, set a return + if ($airdate !== '' && $airdate === $singleEpisode->airdate) { + $return = $this->formatEpisodeInfo($singleEpisode); + } else { + // Insert the episode + $this->addEpisode($videoId, $this->formatEpisodeInfo($singleEpisode)); + } + } + } + } + + return $return; + } + + /** + * Assigns API show response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $show + * + * @return array + */ + protected function formatShowInfo($show): array + { + $this->posterUrl = (string) ($show->mediumImage ?? ''); + + return [ 'type' => parent::TYPE_TV, - 'title' => (string)$show->name, - 'summary' => (string)$show->summary, - 'started' => (string)$show->premiered, - 'publisher' => (string)$show->network, - 'country' => (string)$show->country, + 'title' => (string) $show->name, + 'summary' => (string) $show->summary, + 'started' => (string) $show->premiered, + 'publisher' => (string) $show->network, + 'country' => (string) $show->country, 'source' => parent::SOURCE_TVMAZE, 'imdb' => 0, - 'tvdb' => (int)($show->externalIDs['thetvdb'] ?? 0), - 'tvmaze' => (int)$show->id, + 'tvdb' => (int) ($show->externalIDs['thetvdb'] ?? 0), + 'tvmaze' => (int) $show->id, 'trakt' => 0, - 'tvrage' => (int)($show->externalIDs['tvrage'] ?? 0), + 'tvrage' => (int) ($show->externalIDs['tvrage'] ?? 0), 'tmdb' => 0, - 'aliases' => !empty($show->akas) ? (array)$show->akas : '', - 'localzone' => "''" + 'aliases' => ! empty($show->akas) ? (array) $show->akas : '', + 'localzone' => "''", ]; - } + } - /** - * Assigns API episode response values to a formatted array for insertion - * Returns the formatted array - * - * @param $episode - * - * @return array - */ - protected function formatEpisodeInfo($episode): array - { - return [ - 'title' => (string)$episode->name, - 'series' => (int)$episode->season, - 'episode' => (int)$episode->number, - 'se_complete' => 'S' . sprintf('%02d', $episode->season) . 'E' . sprintf('%02d', $episode->number), - 'firstaired' => (string)$episode->airdate, - 'summary' => (string)$episode->summary + /** + * Assigns API episode response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $episode + * + * @return array + */ + protected function formatEpisodeInfo($episode): array + { + return [ + 'title' => (string) $episode->name, + 'series' => (int) $episode->season, + 'episode' => (int) $episode->number, + 'se_complete' => 'S'.sprintf('%02d', $episode->season).'E'.sprintf('%02d', $episode->number), + 'firstaired' => (string) $episode->airdate, + 'summary' => (string) $episode->summary, ]; - } + } } diff --git a/nntmux/processing/tv/TraktTv.php b/nntmux/processing/tv/TraktTv.php index 8a0fb7cef..fc969f80e 100755 --- a/nntmux/processing/tv/TraktTv.php +++ b/nntmux/processing/tv/TraktTv.php @@ -1,398 +1,392 @@ <?php + namespace nntmux\processing\tv; -use App\Models\Settings; -use nntmux\libraries\TraktAPI; use nntmux\ColorCLI; +use App\Models\Settings; use nntmux\ReleaseImage; use nntmux\utility\Time; +use nntmux\libraries\TraktAPI; /** - * Class TraktTv + * Class TraktTv. * * Process information retrieved from the Trakt API. */ class TraktTv extends TV { - const MATCH_PROBABILITY = 75; + const MATCH_PROBABILITY = 75; - /** - * Client for Trakt API - * - * @var TraktAPI - */ - public $client; + /** + * Client for Trakt API. + * + * @var TraktAPI + */ + public $client; - /** - * Utility to convert Time - * - * @var Time - */ - public $time; + /** + * Utility to convert Time. + * + * @var Time + */ + public $time; - /** - * The Trakt.tv API v2 Client ID (SHA256 hash - 64 characters long string). Used for movie and tv lookups. - * Create one here: https://trakt.tv/oauth/applications/new - * - * @var array|bool|string - */ - private $clientId; + /** + * The Trakt.tv API v2 Client ID (SHA256 hash - 64 characters long string). Used for movie and tv lookups. + * Create one here: https://trakt.tv/oauth/applications/new. + * + * @var array|bool|string + */ + private $clientId; - /** - * List of headers to send to Trakt.tv when making a request. - * - * @see http://docs.trakt.apiary.io/#introduction/required-headers - * @var array - */ - private $requestHeaders; + /** + * List of headers to send to Trakt.tv when making a request. + * + * @see http://docs.trakt.apiary.io/#introduction/required-headers + * @var array + */ + private $requestHeaders; - /** - * The URL to grab the TV poster - * - * @var string - */ - public $posterUrl; + /** + * The URL to grab the TV poster. + * + * @var string + */ + public $posterUrl; - /** - * The URL to grab the TV fanart - * - * @var string - */ - public $fanartUrl; + /** + * The URL to grab the TV fanart. + * + * @var string + */ + public $fanartUrl; - /** - * The localized (network airing) timezone of the show - * - * @var string - */ - private $localizedTZ; + /** + * The localized (network airing) timezone of the show. + * + * @var string + */ + private $localizedTZ; - - /** - * Construct. Set up API key. - * - * @param array $options Class instances. - * - * @access public - */ - public function __construct(array $options = []) - { - parent::__construct($options); - $this->clientId = Settings::value('APIs..trakttvclientkey'); - $this->requestHeaders = [ + /** + * Construct. Set up API key. + * + * @param array $options Class instances. + */ + public function __construct(array $options = []) + { + parent::__construct($options); + $this->clientId = Settings::value('APIs..trakttvclientkey'); + $this->requestHeaders = [ 'Content-Type' => 'application/json', 'trakt-api-version' => 2, 'trakt-api-key' => $this->clientId, - 'Content-Length' => 0 + 'Content-Length' => 0, ]; - $this->client = new TraktAPI($this->requestHeaders); - } + $this->client = new TraktAPI($this->requestHeaders); + } - /** - * Main processing director function for scrapers - * Calls work query function and initiates processing - * - * @param $groupID - * @param $guidChar - * @param $process - * @param bool $local - */ - public function processSite($groupID, $guidChar, $process, $local = false): void - { - $res = $this->getTvReleases($groupID, $guidChar, $process, parent::PROCESS_TRAKT); + /** + * Main processing director function for scrapers + * Calls work query function and initiates processing. + * + * @param $groupID + * @param $guidChar + * @param $process + * @param bool $local + */ + public function processSite($groupID, $guidChar, $process, $local = false): void + { + $res = $this->getTvReleases($groupID, $guidChar, $process, parent::PROCESS_TRAKT); - $tvcount = $res->rowCount(); + $tvcount = $res->rowCount(); - if ($this->echooutput && $tvcount > 1) { - echo ColorCLI::header('Processing TRAKT lookup for ' . number_format($tvcount) . ' release(s).'); - } + if ($this->echooutput && $tvcount > 1) { + echo ColorCLI::header('Processing TRAKT lookup for '.number_format($tvcount).' release(s).'); + } - if ($res instanceof \Traversable) { - foreach ($res as $row) { + if ($res instanceof \Traversable) { + foreach ($res as $row) { + $traktid = false; + $this->posterUrl = $this->fanartUrl = $this->localizedTZ = ''; - $traktid = false; - $this->posterUrl = $this->fanartUrl = $this->localizedTZ = ''; + // Clean the show name for better match probability + $release = $this->parseInfo($row['searchname']); + if (is_array($release) && $release['name'] != '') { + if (in_array($release['cleanname'], $this->titleCache, false)) { + if ($this->echooutput) { + echo ColorCLI::headerOver('Title: '). + ColorCLI::warningOver($release['cleanname']). + ColorCLI::header(' already failed lookup for this site. Skipping.'); + } + $this->setVideoNotFound(parent::PROCESS_IMDB, $row['id']); + continue; + } - // Clean the show name for better match probability - $release = $this->parseInfo($row['searchname']); - if (is_array($release) && $release['name'] != '') { - if (in_array($release['cleanname'], $this->titleCache, false)) { - if ($this->echooutput) { - echo ColorCLI::headerOver('Title: ') . - ColorCLI::warningOver( $release['cleanname']) . - ColorCLI::header( ' already failed lookup for this site. Skipping.'); - } - $this->setVideoNotFound(parent::PROCESS_IMDB, $row['id']); - continue; - } + // Find the Video ID if it already exists by checking the title. + $videoId = $this->getByTitle($release['cleanname'], parent::TYPE_TV, parent::SOURCE_TRAKT); - // Find the Video ID if it already exists by checking the title. - $videoId = $this->getByTitle($release['cleanname'], parent::TYPE_TV, parent::SOURCE_TRAKT); + // Force local lookup only + if ($local === true) { + $lookupSetting = false; + } else { + $lookupSetting = true; + } - // Force local lookup only - if ($local === true) { - $lookupSetting = false; - } else { - $lookupSetting = true; - } - - if ($videoId === false && $lookupSetting) { + if ($videoId === false && $lookupSetting) { // If it doesn't exist locally and lookups are allowed lets try to get it. - if ($this->echooutput) { - echo ColorCLI::primaryOver('Checking Trakt for previously failed title: ') . - ColorCLI::headerOver($release['cleanname']) . + if ($this->echooutput) { + echo ColorCLI::primaryOver('Checking Trakt for previously failed title: '). + ColorCLI::headerOver($release['cleanname']). ColorCLI::primary('.'); - } + } - // Get the show from TRAKT - $traktShow = $this->getShowInfo((string)$release['cleanname']); + // Get the show from TRAKT + $traktShow = $this->getShowInfo((string) $release['cleanname']); - if (is_array($traktShow)) { - $videoId = $this->add($traktShow); - $traktid = (int)$traktShow['trakt']; - } - - } else { - if ($this->echooutput) { - echo ColorCLI::primaryOver('Found local TMDB match for: ') . - ColorCLI::headerOver($release['cleanname']) . + if (is_array($traktShow)) { + $videoId = $this->add($traktShow); + $traktid = (int) $traktShow['trakt']; + } + } else { + if ($this->echooutput) { + echo ColorCLI::primaryOver('Found local TMDB match for: '). + ColorCLI::headerOver($release['cleanname']). ColorCLI::primary('. Attempting episode lookup!'); - } - $traktid = $this->getSiteIDFromVideoID('trakt', $videoId); - $this->localizedTZ = $this->getLocalZoneFromVideoID($videoId); - } + } + $traktid = $this->getSiteIDFromVideoID('trakt', $videoId); + $this->localizedTZ = $this->getLocalZoneFromVideoID($videoId); + } + if (is_numeric($videoId) && $videoId > 0 && is_numeric($traktid) && $traktid > 0) { + // Now that we have valid video and trakt ids, try to get the poster + //$this->getPoster($videoId, $traktid); - if (is_numeric($videoId) && $videoId > 0 && is_numeric($traktid) && $traktid > 0) { - // Now that we have valid video and trakt ids, try to get the poster - //$this->getPoster($videoId, $traktid); + $seasonNo = preg_replace('/^S0*/i', '', $release['season']); + $episodeNo = preg_replace('/^E0*/i', '', $release['episode']); - $seasonNo = preg_replace('/^S0*/i', '', $release['season']); - $episodeNo = preg_replace('/^E0*/i', '', $release['episode']); + if ($episodeNo === 'all') { + // Set the video ID and leave episode 0 + $this->setVideoIdFound($videoId, $row['id'], 0); + echo ColorCLI::primary('Found TRAKT Match for Full Season!'); + continue; + } - if ($episodeNo === 'all') { - // Set the video ID and leave episode 0 - $this->setVideoIdFound($videoId, $row['id'], 0); - echo ColorCLI::primary('Found TRAKT Match for Full Season!'); - continue; - } + // Check if we have the episode for this video ID + $episode = $this->getBySeasonEp($videoId, $seasonNo, $episodeNo, $release['airdate']); - // Check if we have the episode for this video ID - $episode = $this->getBySeasonEp($videoId, $seasonNo, $episodeNo, $release['airdate']); - - if ($episode === false && $lookupSetting) { - // Send the request for the episode to TRAKT - $traktEpisode = $this->getEpisodeInfo( + if ($episode === false && $lookupSetting) { + // Send the request for the episode to TRAKT + $traktEpisode = $this->getEpisodeInfo( $traktid, $seasonNo, $episodeNo ); - if ($traktEpisode) { - $episode = $this->addEpisode($videoId, $traktEpisode); - } - } + if ($traktEpisode) { + $episode = $this->addEpisode($videoId, $traktEpisode); + } + } - if ($episode !== false && is_numeric($episode) && $episode > 0) { - // Mark the releases video and episode IDs - $this->setVideoIdFound($videoId, $row['id'], $episode); - if ($this->echooutput) { - echo ColorCLI::primary('Found TRAKT Match!'); - } - continue; - } - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_IMDB, $row['id']); - } else { - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_IMDB, $row['id']); - $this->titleCache[] = $release['cleanname']; - } - } else { - //Processing failed, set the episode ID to the next processing group - $this->setVideoNotFound(parent::PROCESS_IMDB, $row['id']); - $this->titleCache[] = $release['cleanname']; - } - } - } - } - /** - * Fetch banner from site. - * - * @param $videoId - * @param $siteID - * - * @return bool - */ - public function getBanner($videoId, $siteID): bool - { - return false; - } + if ($episode !== false && is_numeric($episode) && $episode > 0) { + // Mark the releases video and episode IDs + $this->setVideoIdFound($videoId, $row['id'], $episode); + if ($this->echooutput) { + echo ColorCLI::primary('Found TRAKT Match!'); + } + continue; + } + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_IMDB, $row['id']); + } else { + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_IMDB, $row['id']); + $this->titleCache[] = $release['cleanname']; + } + } else { + //Processing failed, set the episode ID to the next processing group + $this->setVideoNotFound(parent::PROCESS_IMDB, $row['id']); + $this->titleCache[] = $release['cleanname']; + } + } + } + } - /** - * Retrieve info of TV episode from site using its API. - * - * @param integer $siteId - * @param integer $series - * @param integer $episode - * - * @return array|bool False on failure, an array of information fields otherwise. - */ - public function getEpisodeInfo($siteId, $series, $episode) - { - $return = false; + /** + * Fetch banner from site. + * + * @param $videoId + * @param $siteID + * + * @return bool + */ + public function getBanner($videoId, $siteID): bool + { + return false; + } - $response = $this->client->episodeSummary($siteId, $series, $episode); + /** + * Retrieve info of TV episode from site using its API. + * + * @param int $siteId + * @param int $series + * @param int $episode + * + * @return array|bool False on failure, an array of information fields otherwise. + */ + public function getEpisodeInfo($siteId, $series, $episode) + { + $return = false; - sleep(1); + $response = $this->client->episodeSummary($siteId, $series, $episode); - if (is_array($response)) { - if ($this->checkRequiredAttr($response, 'traktE')) { - $return = $this->formatEpisodeInfo($response); - } - } + sleep(1); - return $return; - } + if (is_array($response)) { + if ($this->checkRequiredAttr($response, 'traktE')) { + $return = $this->formatEpisodeInfo($response); + } + } - /** - * - */ - public function getMovieInfo(): void - { + return $return; + } - } + public function getMovieInfo(): void + { + } - /** - * Retrieve poster image for TV episode from site using its API. - * - * @param integer $videoId ID from videos table. - * @param integer $siteId ID that this site uses for the programme. - * - * @return int - */ - public function getPoster($videoId, $siteId): int - { - $hascover = 0; - $ri = new ReleaseImage($this->pdo); + /** + * Retrieve poster image for TV episode from site using its API. + * + * @param int $videoId ID from videos table. + * @param int $siteId ID that this site uses for the programme. + * + * @return int + */ + public function getPoster($videoId, $siteId): int + { + $hascover = 0; + $ri = new ReleaseImage($this->pdo); - if ($this->posterUrl !== '') { - // Try to get the Poster - $hascover = $ri->saveImage($videoId, $this->posterUrl, $this->imgSavePath, '', ''); - } + if ($this->posterUrl !== '') { + // Try to get the Poster + $hascover = $ri->saveImage($videoId, $this->posterUrl, $this->imgSavePath, '', ''); + } - // Couldn't get poster, try fan art instead - if ($hascover !== 1 && $this->fanartUrl !== '') { - $hascover = $ri->saveImage($videoId, $this->fanartUrl, $this->imgSavePath, '', ''); - } + // Couldn't get poster, try fan art instead + if ($hascover !== 1 && $this->fanartUrl !== '') { + $hascover = $ri->saveImage($videoId, $this->fanartUrl, $this->imgSavePath, '', ''); + } - // Mark it retrieved if we saved an image - if ($hascover === 1) { - $this->setCoverFound($videoId); - } - return $hascover; - } + // Mark it retrieved if we saved an image + if ($hascover === 1) { + $this->setCoverFound($videoId); + } - /** - * Retrieve info of TV programme from site using it's API. - * - * @param string $name Title of programme to look up. Usually a cleaned up version from releases table. - * - * @return array|false False on failure, an array of information fields otherwise. - */ - public function getShowInfo($name) - { - $return = $response = false; - $highestMatch = 0; + return $hascover; + } - // Trakt does NOT like shows with the year in them even without the parentheses - // Do this for the API Search only as a local lookup should require it - $name = preg_replace('# \((19|20)\d{2}\)$#', '', $name); + /** + * Retrieve info of TV programme from site using it's API. + * + * @param string $name Title of programme to look up. Usually a cleaned up version from releases table. + * + * @return array|false False on failure, an array of information fields otherwise. + */ + public function getShowInfo($name) + { + $return = $response = false; + $highestMatch = 0; - $response = (array)$this->client->showSearch($name); + // Trakt does NOT like shows with the year in them even without the parentheses + // Do this for the API Search only as a local lookup should require it + $name = preg_replace('# \((19|20)\d{2}\)$#', '', $name); - sleep(1); + $response = (array) $this->client->showSearch($name); - if (is_array($response)) { - foreach ($response as $show) { + sleep(1); + + if (is_array($response)) { + foreach ($response as $show) { // Check for exact title match first and then terminate if found - if ($show['show']['title'] === $name) { - $highest = $show; - break; - } + if ($show['show']['title'] === $name) { + $highest = $show; + break; + } - // Check each show title for similarity and then find the highest similar value - $matchPercent = $this->checkMatch($show['show']['title'], $name, self::MATCH_PROBABILITY); + // Check each show title for similarity and then find the highest similar value + $matchPercent = $this->checkMatch($show['show']['title'], $name, self::MATCH_PROBABILITY); - // If new match has a higher percentage, set as new matched title - if ($matchPercent > $highestMatch) { - $highestMatch = $matchPercent; - $highest = $show; - } - } - if (isset($highest)) { - $fullShow = $this->client->showSummary($highest['show']['ids']['trakt'], 'full'); - if ($this->checkRequiredAttr($fullShow, 'traktS')) { - $return = $this->formatShowInfo($fullShow); - } - } - } - return $return; - } + // If new match has a higher percentage, set as new matched title + if ($matchPercent > $highestMatch) { + $highestMatch = $matchPercent; + $highest = $show; + } + } + if (isset($highest)) { + $fullShow = $this->client->showSummary($highest['show']['ids']['trakt'], 'full'); + if ($this->checkRequiredAttr($fullShow, 'traktS')) { + $return = $this->formatShowInfo($fullShow); + } + } + } - /** - * Assigns API show response values to a formatted array for insertion - * Returns the formatted array - * - * @param $show - * - * @return array - */ - public function formatShowInfo($show): array - { - preg_match('/tt(?P<imdbid>\d{6,7})$/i', $show['ids']['imdb'], $imdb); - $this->posterUrl = $show['images']['poster']['thumb'] ?? ''; - $this->fanartUrl = $show['images']['fanart']['thumb'] ?? ''; - $this->localizedTZ = $show['airs']['timezone']; + return $return; + } - return [ - 'type' => (int)parent::TYPE_TV, - 'title' => (string)$show['title'], - 'summary' => (string)$show['overview'], - 'started' => (string)Time::localizeAirdate($show['first_aired'], $this->localizedTZ), - 'publisher' => (string)$show['network'], - 'country' => (string)$show['country'], - 'source' => (int)parent::SOURCE_TRAKT, - 'imdb' => (int)($imdb['imdbid'] ?? 0), - 'tvdb' => (int)($show['ids']['tvdb'] ?? 0), - 'trakt' => (int)$show['ids']['trakt'], - 'tvrage' => (int)($show['ids']['tvrage'] ?? 0), + /** + * Assigns API show response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $show + * + * @return array + */ + public function formatShowInfo($show): array + { + preg_match('/tt(?P<imdbid>\d{6,7})$/i', $show['ids']['imdb'], $imdb); + $this->posterUrl = $show['images']['poster']['thumb'] ?? ''; + $this->fanartUrl = $show['images']['fanart']['thumb'] ?? ''; + $this->localizedTZ = $show['airs']['timezone']; + + return [ + 'type' => (int) parent::TYPE_TV, + 'title' => (string) $show['title'], + 'summary' => (string) $show['overview'], + 'started' => (string) Time::localizeAirdate($show['first_aired'], $this->localizedTZ), + 'publisher' => (string) $show['network'], + 'country' => (string) $show['country'], + 'source' => (int) parent::SOURCE_TRAKT, + 'imdb' => (int) ($imdb['imdbid'] ?? 0), + 'tvdb' => (int) ($show['ids']['tvdb'] ?? 0), + 'trakt' => (int) $show['ids']['trakt'], + 'tvrage' => (int) ($show['ids']['tvrage'] ?? 0), 'tvmaze' => 0, - 'tmdb' => (int)($show['ids']['tmdb'] ?? 0), - 'aliases' => isset($show['aliases']) && !empty($show['aliases']) ? (array)$show['aliases'] : '', - 'localzone' => (string)$this->localizedTZ + 'tmdb' => (int) ($show['ids']['tmdb'] ?? 0), + 'aliases' => isset($show['aliases']) && ! empty($show['aliases']) ? (array) $show['aliases'] : '', + 'localzone' => (string) $this->localizedTZ, ]; - } + } - /** - * Assigns API episode response values to a formatted array for insertion - * Returns the formatted array - * - * @param $episode - * - * @return array - */ - public function formatEpisodeInfo($episode): array - { - return [ - 'title' => (string)$episode['title'], - 'series' => (int)$episode['season'], - 'episode' => (int)$episode['epsiode'], - 'se_complete' => (string)'S' . sprintf('%02d', $episode['season']) . 'E' . sprintf('%02d', $episode['episode']), - 'firstaired' => (string)Time::localizeAirdate($episode['first_aired'], $this->localizedTZ), - 'summary' => (string)$episode['overview'] + /** + * Assigns API episode response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $episode + * + * @return array + */ + public function formatEpisodeInfo($episode): array + { + return [ + 'title' => (string) $episode['title'], + 'series' => (int) $episode['season'], + 'episode' => (int) $episode['epsiode'], + 'se_complete' => (string) 'S'.sprintf('%02d', $episode['season']).'E'.sprintf('%02d', $episode['episode']), + 'firstaired' => (string) Time::localizeAirdate($episode['first_aired'], $this->localizedTZ), + 'summary' => (string) $episode['overview'], ]; - } + } } diff --git a/nntmux/utility/Country.php b/nntmux/utility/Country.php index 1ddf3d8f9..742c55fca 100755 --- a/nntmux/utility/Country.php +++ b/nntmux/utility/Country.php @@ -18,31 +18,30 @@ * @author ruhllatio * @copyright 2015 nZEDb */ + namespace nntmux\utility; use nntmux\db\DB; /** - * Class Country - * - * @package nntmux\utility + * Class Country. */ -Class Country +class Country { - /** - * Get a country code for a country name. - * - * @param string $country - * - * @param DB $pdo - * - * @return mixed - */ - public static function countryCode($country, $pdo) - { - $pdo = ($pdo instanceof DB ? $pdo : new DB()); - if (!is_array($country) && strlen($country) > 2) { - $code = $pdo->queryOneRow( + /** + * Get a country code for a country name. + * + * @param string $country + * + * @param DB $pdo + * + * @return mixed + */ + public static function countryCode($country, $pdo) + { + $pdo = ($pdo instanceof DB ? $pdo : new DB()); + if (! is_array($country) && strlen($country) > 2) { + $code = $pdo->queryOneRow( sprintf(' SELECT id FROM countries @@ -50,10 +49,11 @@ Class Country $pdo->escapeString($country) ) ); - if (isset($code['id'])) { - return $code['id']; - } - } - return ''; - } + if (isset($code['id'])) { + return $code['id']; + } + } + + return ''; + } } diff --git a/nntmux/utility/Git.php b/nntmux/utility/Git.php index fe66747e5..402bd9af1 100755 --- a/nntmux/utility/Git.php +++ b/nntmux/utility/Git.php @@ -18,105 +18,107 @@ * @author niel * @copyright 2014 nZEDb */ + namespace nntmux\utility; /** * Class Git - Wrapper for various git operations. - * @package nntmux\utility */ class Git extends \GitRepo { - private $branch; - private $mainBranches = ['dev', '0.5.x', '0.x']; + private $branch; + private $mainBranches = ['dev', '0.5.x', '0.x']; - public function __construct(array $options = []) - { - $defaults = [ + public function __construct(array $options = []) + { + $defaults = [ 'create' => false, 'initialise' => false, 'filepath' => NN_ROOT, ]; - $options += $defaults; + $options += $defaults; - parent::__construct($options['filepath'], $options['create'], $options['initialise']); - $this->branch = parent::active_branch(); - } + parent::__construct($options['filepath'], $options['create'], $options['initialise']); + $this->branch = parent::active_branch(); + } - /** - * Return the number of commits made to repo - */ - public function commits() - { - $count = 0; - $log = explode("\n", $this->log()); - foreach ($log as $line) { - if (preg_match('#^commit#', $line)) { - ++$count; - } - } - return $count; - } + /** + * Return the number of commits made to repo. + */ + public function commits() + { + $count = 0; + $log = explode("\n", $this->log()); + foreach ($log as $line) { + if (preg_match('#^commit#', $line)) { + ++$count; + } + } - /** - * @param string $options - * - * @return string - */ - public function describe($options = null) - { - return $this->run("describe $options"); - } + return $count; + } - public function getBranch() - { - return $this->branch; - } + /** + * @param string $options + * + * @return string + */ + public function describe($options = null) + { + return $this->run("describe $options"); + } - /** - * @param $gitObject - * - * @return bool - * @throws \Exception - */ - public function isCommited($gitObject) - { - $cmd = "cat-file -e $gitObject"; + public function getBranch() + { + return $this->branch; + } - try { - $result = $this->run($cmd); - } catch (\Exception $e) { - $message = explode("\n", $e->getMessage()); - if ($message[0] === "fatal: Not a valid object name $gitObject") { - $result = false; - } else { - throw new \Exception($message); - } - } - return ($result === ''); - } + /** + * @param $gitObject + * + * @return bool + * @throws \Exception + */ + public function isCommited($gitObject) + { + $cmd = "cat-file -e $gitObject"; - public function log($options = null) - { - return $this->run("log $options"); - } + try { + $result = $this->run($cmd); + } catch (\Exception $e) { + $message = explode("\n", $e->getMessage()); + if ($message[0] === "fatal: Not a valid object name $gitObject") { + $result = false; + } else { + throw new \Exception($message); + } + } - public function mainBranches() - { - return $this->mainBranches; - } + return $result === ''; + } - /** - * @param string $options - * - * @return string - */ - public function tag($options = null) - { - return $this->run("tag $options"); - } + public function log($options = null) + { + return $this->run("log $options"); + } - public function tagLatest() - { - return $this->describe("--tags --abbrev=0 HEAD"); - } + public function mainBranches() + { + return $this->mainBranches; + } + + /** + * @param string $options + * + * @return string + */ + public function tag($options = null) + { + return $this->run("tag $options"); + } + + public function tagLatest() + { + return $this->describe('--tags --abbrev=0 HEAD'); + } } diff --git a/nntmux/utility/SmartyUtils.php b/nntmux/utility/SmartyUtils.php index 4ff0ca512..bc1c7056c 100755 --- a/nntmux/utility/SmartyUtils.php +++ b/nntmux/utility/SmartyUtils.php @@ -18,7 +18,6 @@ * @author niel * @copyright 2014 nZEDb */ - use nntmux\Category; /** @@ -30,7 +29,7 @@ use nntmux\Category; */ function getCategoryValue($category) { - return Category::getCategoryValue($category); + return Category::getCategoryValue($category); } // Function inspired by c0r3@newznabforums adds country flags on the browse page. @@ -42,135 +41,134 @@ function getCategoryValue($category) */ function release_flag($text, $page) { - $code = $language = ""; + $code = $language = ''; - switch (true) { + switch (true) { case preg_match('/Arabic/i', $text): - $code = "pk"; - $language = "Arabic"; + $code = 'pk'; + $language = 'Arabic'; break; case preg_match('/Cantonese/i', $text): - $code = "tw"; - $language = "Cantonese"; + $code = 'tw'; + $language = 'Cantonese'; break; case preg_match('/Chinese|Mandarin|\bc[hn]\b/i', $text): - $code = "cn"; - $language = "Chinese"; + $code = 'cn'; + $language = 'Chinese'; break; case preg_match('/\bCzech\b/i', $text): - $code = "cz"; - $language = "Czech"; + $code = 'cz'; + $language = 'Czech'; break; case preg_match('/Danish/i', $text): - $code = "dk"; - $language = "Danish"; + $code = 'dk'; + $language = 'Danish'; break; case preg_match('/Finnish/i', $text): - $code = "fi"; - $language = "Finnish"; + $code = 'fi'; + $language = 'Finnish'; break; case preg_match('/Flemish|\b(Dutch|nl)\b|NlSub/i', $text): - $code = "nl"; - $language = "Dutch"; + $code = 'nl'; + $language = 'Dutch'; break; case preg_match('/French|Vostfr|Multi/i', $text): - $code = "fr"; - $language = "French"; + $code = 'fr'; + $language = 'French'; break; case preg_match('/German(bed)?|\bger\b/i', $text): - $code = "de"; - $language = "German"; + $code = 'de'; + $language = 'German'; break; case preg_match('/\bGreek\b/i', $text): - $code = "gr"; - $language = "Greek"; + $code = 'gr'; + $language = 'Greek'; break; case preg_match('/Hebrew|Yiddish/i', $text): - $code = "il"; - $language = "Hebrew"; + $code = 'il'; + $language = 'Hebrew'; break; case preg_match('/\bHindi\b/i', $text): - $code = "in"; - $language = "Hindi"; + $code = 'in'; + $language = 'Hindi'; break; case preg_match('/Hungarian|\bhun\b/i', $text): - $code = "hu"; - $language = "Hungarian"; + $code = 'hu'; + $language = 'Hungarian'; break; case preg_match('/Italian|\bita\b/i', $text): - $code = "it"; - $language = "Italian"; + $code = 'it'; + $language = 'Italian'; break; case preg_match('/Japanese|\bjp\b/i', $text): - $code = "jp"; - $language = "Japanese"; + $code = 'jp'; + $language = 'Japanese'; break; case preg_match('/Korean|\bkr\b/i', $text): - $code = "kr"; - $language = "Korean"; + $code = 'kr'; + $language = 'Korean'; break; case preg_match('/Norwegian/i', $text): - $code = "no"; - $language = "Norwegian"; + $code = 'no'; + $language = 'Norwegian'; break; case preg_match('/Polish/i', $text): - $code = "pl"; - $language = "Polish"; + $code = 'pl'; + $language = 'Polish'; break; case preg_match('/Portugese/i', $text): - $code = "pt"; - $language = "Portugese"; + $code = 'pt'; + $language = 'Portugese'; break; case preg_match('/Romanian/i', $text): - $code = "ro"; - $language = "Romanian"; + $code = 'ro'; + $language = 'Romanian'; break; case preg_match('/Spanish/i', $text): - $code = "es"; - $language = "Spanish"; + $code = 'es'; + $language = 'Spanish'; break; case preg_match('/Swe(dish|sub)/i', $text): - $code = "se"; - $language = "Swedish"; + $code = 'se'; + $language = 'Swedish'; break; case preg_match('/Tagalog|Filipino/i', $text): - $code = "ph"; - $language = "Tagalog|Filipino"; + $code = 'ph'; + $language = 'Tagalog|Filipino'; break; case preg_match('/\bThai\b/i', $text): - $code = "th"; - $language = "Thai"; + $code = 'th'; + $language = 'Thai'; break; case preg_match('/Turkish/i', $text): - $code = "tr"; - $language = "Turkish"; + $code = 'tr'; + $language = 'Turkish'; break; case preg_match('/Russian/i', $text): - $code = "ru"; - $language = "Russian"; + $code = 'ru'; + $language = 'Russian'; break; case preg_match('/Vietnamese/i', $text): - $code = "vn"; - $language = "Vietnamese"; + $code = 'vn'; + $language = 'Vietnamese'; break; } - if ($code !== '' && $page == "browse") { - $www = WWW_TOP; - if (!in_array(substr($www, -1), ['\\', '/'])) { - $www .= DS; - } + if ($code !== '' && $page == 'browse') { + $www = WWW_TOP; + if (! in_array(substr($www, -1), ['\\', '/'])) { + $www .= DS; + } - return - '<img title="' . $language . '" alt="' . $language . '" src="' . $www . 'themes/shared/images/flags/' . $code . '.png"/>'; - } else if ($page == "search") { - if ($code == "") { - return false; - } else { - return $code; - } - } - return ''; + return + '<img title="'.$language.'" alt="'.$language.'" src="'.$www.'themes/shared/images/flags/'.$code.'.png"/>'; + } elseif ($page == 'search') { + if ($code == '') { + return false; + } else { + return $code; + } + } + + return ''; } - -?> diff --git a/nntmux/utility/Time.php b/nntmux/utility/Time.php index ce38d6872..cae8b8c2b 100755 --- a/nntmux/utility/Time.php +++ b/nntmux/utility/Time.php @@ -18,29 +18,29 @@ * @author ruhllatio * @copyright 2015 nZEDb */ + namespace nntmux\utility; /** - * Class Time -- functions for working with time string and DTOs - * - * @package nntmux\utility + * Class Time -- functions for working with time string and DTOs. */ class Time { - /** - * For a given timestamp, calculate the localized show/episode airdate - * via the provided local airing timezone - * - * @param string $time - * @param string $zone - * - * @return string - */ - public static function localizeAirdate($time = '', $zone = '') - { - $datetime = new \DateTime($time); - $newzone = new \DateTimeZone($zone); - $datetime->setTimezone($newzone); - return $datetime->format('Y-m-d'); - } + /** + * For a given timestamp, calculate the localized show/episode airdate + * via the provided local airing timezone. + * + * @param string $time + * @param string $zone + * + * @return string + */ + public static function localizeAirdate($time = '', $zone = '') + { + $datetime = new \DateTime($time); + $newzone = new \DateTimeZone($zone); + $datetime->setTimezone($newzone); + + return $datetime->format('Y-m-d'); + } } diff --git a/nntmux/utility/Utility.php b/nntmux/utility/Utility.php index 019ef0079..11fc45905 100755 --- a/nntmux/utility/Utility.php +++ b/nntmux/utility/Utility.php @@ -1,79 +1,74 @@ <?php + namespace nntmux\utility; +use nntmux\db\DB; +use nntmux\Logger; +use nntmux\ColorCLI; +use Ramsey\Uuid\Uuid; use App\Models\Settings; use App\Extensions\util\Versions; -use nntmux\db\DB; -use nntmux\ColorCLI; -use nntmux\Logger; -use Ramsey\Uuid\Uuid; - /** - * Class Utility - * - * @package nntmux\utility + * Class Utility. */ class Utility { - /** - * Regex for detecting multi-platform path. Use it where needed so it can be updated in one location as required characters get added. - */ - const PATH_REGEX = '(?P<drive>[A-Za-z]:|)(?P<path>[/\w.-]+|)'; + /** + * Regex for detecting multi-platform path. Use it where needed so it can be updated in one location as required characters get added. + */ + const PATH_REGEX = '(?P<drive>[A-Za-z]:|)(?P<path>[/\w.-]+|)'; - const VERSION_REGEX = '#(?P<all>v(?P<digits>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<revision>\d+)(?:\.(?P<fix>\d+))?)(?:-(?P<suffix>(?:RC\d+|dev)))?)#'; + const VERSION_REGEX = '#(?P<all>v(?P<digits>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<revision>\d+)(?:\.(?P<fix>\d+))?)(?:-(?P<suffix>(?:RC\d+|dev)))?)#'; - /** - * Checks all levels of the supplied path are readable and executable by current user. - * - * @todo Make this recursive with a switch to only check end point. - * @param $path *nix path to directory or file - * - * @return bool|string True is successful, otherwise the part of the path that failed testing. - */ - public static function canExecuteRead($path) - { - $paths = explode('#/#', $path); - $fullPath = DS; - foreach ($paths as $singlePath) { - if ($singlePath !== '') { - $fullPath .= $singlePath . DS; - if (!is_readable($fullPath) || !is_executable($fullPath)) { - return "The '$fullPath' directory must be readable and executable by all ." .PHP_EOL; - } - } - } - return true; - } + /** + * Checks all levels of the supplied path are readable and executable by current user. + * + * @todo Make this recursive with a switch to only check end point. + * @param $path *nix path to directory or file + * + * @return bool|string True is successful, otherwise the part of the path that failed testing. + */ + public static function canExecuteRead($path) + { + $paths = explode('#/#', $path); + $fullPath = DS; + foreach ($paths as $singlePath) { + if ($singlePath !== '') { + $fullPath .= $singlePath.DS; + if (! is_readable($fullPath) || ! is_executable($fullPath)) { + return "The '$fullPath' directory must be readable and executable by all .".PHP_EOL; + } + } + } - /** - * - */ - public static function clearScreen(): void - { - if (self::isCLI()) { - if (self::isWin()) { - passthru('cls'); - } else { - passthru('clear'); - } - } - } + return true; + } - /** - * Replace all white space chars for a single space. - * - * @param string $text - * - * @return string - * - * @static - * @access public - */ - public static function collapseWhiteSpace($text): string - { - // Strip leading/trailing white space. - return trim( + public static function clearScreen(): void + { + if (self::isCLI()) { + if (self::isWin()) { + passthru('cls'); + } else { + passthru('clear'); + } + } + } + + /** + * Replace all white space chars for a single space. + * + * @param string $text + * + * @return string + * + * @static + */ + public static function collapseWhiteSpace($text): string + { + // Strip leading/trailing white space. + return trim( // Replace 2 or more white space for a single space. preg_replace('/\s{2,}/', ' ', @@ -81,29 +76,29 @@ class Utility str_replace(["\n", "\r"], ' ', $text) ) ); - } + } - /** - * Removes the preceeding or proceeding portion of a string - * relative to the last occurrence of the specified character. - * The character selected may be retained or discarded. - * - * @param string $character the character to search for. - * @param string $string the string to search through. - * @param string $side determines whether text to the left or the right of the character is returned. - * Options are: left, or right. - * @param bool $keep_character determines whether or not to keep the character. - * Options are: true, or false. - * - * @return string - */ - public static function cutStringUsingLast($character, $string, $side, $keep_character = true): string - { - $offset = ($keep_character ? 1 : 0); - $whole_length = strlen($string); - $right_length = (strlen(strrchr($string, $character)) - 1); - $left_length = ($whole_length - $right_length - 1); - switch ($side) { + /** + * Removes the preceeding or proceeding portion of a string + * relative to the last occurrence of the specified character. + * The character selected may be retained or discarded. + * + * @param string $character the character to search for. + * @param string $string the string to search through. + * @param string $side determines whether text to the left or the right of the character is returned. + * Options are: left, or right. + * @param bool $keep_character determines whether or not to keep the character. + * Options are: true, or false. + * + * @return string + */ + public static function cutStringUsingLast($character, $string, $side, $keep_character = true): string + { + $offset = ($keep_character ? 1 : 0); + $whole_length = strlen($string); + $right_length = (strlen(strrchr($string, $character)) - 1); + $left_length = ($whole_length - $right_length - 1); + switch ($side) { case 'left': $piece = substr($string, 0, $left_length + $offset); break; @@ -116,370 +111,368 @@ class Utility break; } - return $piece; - } + return $piece; + } - /** - * @param array|null $options - * - * @return array|null - */ - public static function getDirFiles(array $options = null): ?array - { - $defaults = [ + /** + * @param array|null $options + * + * @return array|null + */ + public static function getDirFiles(array $options = null): ?array + { + $defaults = [ 'dir' => false, 'ext' => '', // no full stop (period) separator should be used. 'file' => true, 'path' => '', 'regex' => '', ]; - $options += $defaults; - if (!$options['dir'] && !$options['file']) { - return null; - } + $options += $defaults; + if (! $options['dir'] && ! $options['file']) { + return null; + } - // Replace windows style path separators with unix style. - $iterator = new \FilesystemIterator( + // Replace windows style path separators with unix style. + $iterator = new \FilesystemIterator( str_replace('\\', '/', $options['path']), \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS ); - $files = []; - foreach ($iterator as $fileInfo) { - $file = $iterator->key(); - switch (true) { - case !$options['dir'] && $fileInfo->isDir(): + $files = []; + foreach ($iterator as $fileInfo) { + $file = $iterator->key(); + switch (true) { + case ! $options['dir'] && $fileInfo->isDir(): break; - case !empty($options['ext']) && $fileInfo->getExtension() != $options['ext']; + case ! empty($options['ext']) && $fileInfo->getExtension() != $options['ext']: break; - case (empty($options['regex']) || !preg_match($options['regex'], $file)): + case empty($options['regex']) || ! preg_match($options['regex'], $file): break; - case (!$options['file'] && $fileInfo->isFile()): + case ! $options['file'] && $fileInfo->isFile(): break; default: $files[] = $file; } - } + } - return $files; - } + return $files; + } - /** - * @return array - */ - public static function getThemesList(): array - { - $themes = scandir(NN_THEMES, SCANDIR_SORT_ASCENDING); - $themelist[] = 'None'; - foreach ($themes as $theme) { - if (strpos($theme, '.') === false && - is_dir(NN_THEMES . $theme) && + /** + * @return array + */ + public static function getThemesList(): array + { + $themes = scandir(NN_THEMES, SCANDIR_SORT_ASCENDING); + $themelist[] = 'None'; + foreach ($themes as $theme) { + if (strpos($theme, '.') === false && + is_dir(NN_THEMES.$theme) && ucfirst($theme) === $theme ) { - $themelist[] = $theme; - } - } + $themelist[] = $theme; + } + } - sort($themelist); - return $themelist; - } + sort($themelist); - public static function getValidVersionsFile() - { - return (new Versions())->getValidVersionsFile(); - } + return $themelist; + } - /** - * Detect if the command is accessible on the system. - * - * @param $cmd - * - * @return bool|null Returns true if found, false if not found, and null if which is not detected. - */ - public static function hasCommand($cmd): ?bool - { - if ('HAS_WHICH') { - $returnVal = shell_exec("which $cmd"); + public static function getValidVersionsFile() + { + return (new Versions())->getValidVersionsFile(); + } - return (empty($returnVal) ? false : true); - } + /** + * Detect if the command is accessible on the system. + * + * @param $cmd + * + * @return bool|null Returns true if found, false if not found, and null if which is not detected. + */ + public static function hasCommand($cmd): ?bool + { + if ('HAS_WHICH') { + $returnVal = shell_exec("which $cmd"); - return null; - } + return empty($returnVal) ? false : true; + } - /** - * Check for availability of which command - */ - public static function hasWhich(): bool - { - exec('which which', $output, $error); + return null; + } - return !$error; - } + /** + * Check for availability of which command. + */ + public static function hasWhich(): bool + { + exec('which which', $output, $error); - /** - * Check if user is running from CLI. - * - * @return bool - */ - public static function isCLI() - { - return (strtolower(PHP_SAPI) === 'cli'); - } + return ! $error; + } - public static function isGZipped($filename) - { - $gzipped = null; - if (($fp = fopen($filename, 'rb')) !== false) { - if (@fread($fp, 2) == "\x1F\x8B") { // this is a gzip'd file - fseek($fp, -4, SEEK_END); - if (strlen($datum = @fread($fp, 4)) == 4) { - $gzipped = $datum; - } - } - fclose($fp); - } + /** + * Check if user is running from CLI. + * + * @return bool + */ + public static function isCLI() + { + return strtolower(PHP_SAPI) === 'cli'; + } - return $gzipped; - } + public static function isGZipped($filename) + { + $gzipped = null; + if (($fp = fopen($filename, 'rb')) !== false) { + if (@fread($fp, 2) == "\x1F\x8B") { // this is a gzip'd file + fseek($fp, -4, SEEK_END); + if (strlen($datum = @fread($fp, 4)) == 4) { + $gzipped = $datum; + } + } + fclose($fp); + } - /** - * @param DB|null $pdo - * - * @return bool - * @throws \Exception - * @throws \RuntimeException - */ - public static function isPatched(DB $pdo = null): bool - { - $versions = self::getValidVersionsFile(); + return $gzipped; + } - if (!($pdo instanceof DB)) { - $pdo = new DB(); - } - $patch = Settings::value('..sqlpatch'); - $ver = $versions->versions->sql->file; + /** + * @param DB|null $pdo + * + * @return bool + * @throws \Exception + * @throws \RuntimeException + */ + public static function isPatched(DB $pdo = null): bool + { + $versions = self::getValidVersionsFile(); - // Check database patch version - if ($patch < $ver) { - $message = "\nYour database is not up to date. Reported patch levels\n Db: $patch\nfile: $ver\nPlease update.\n php " . - NN_ROOT . "./tmux nntmux:db\n"; - if (self::isCLI()) { - echo ColorCLI::error($message); - } - throw new \RuntimeException($message); - } + if (! ($pdo instanceof DB)) { + $pdo = new DB(); + } + $patch = Settings::value('..sqlpatch'); + $ver = $versions->versions->sql->file; - return true; - } + // Check database patch version + if ($patch < $ver) { + $message = "\nYour database is not up to date. Reported patch levels\n Db: $patch\nfile: $ver\nPlease update.\n php ". + NN_ROOT."./tmux nntmux:db\n"; + if (self::isCLI()) { + echo ColorCLI::error($message); + } + throw new \RuntimeException($message); + } - /** - * @return bool - */ - public static function isWin(): bool - { - return stripos(PHP_OS,'win') === 0; - } + return true; + } - /** - * @param array $elements - * @param string $prefix - * - * @return string - */ - public static function pathCombine(array $elements, $prefix = ''): string - { - return $prefix . implode(DS, $elements); - } + /** + * @return bool + */ + public static function isWin(): bool + { + return stripos(PHP_OS, 'win') === 0; + } - /** - * @param $text - */ - public static function stripBOM(&$text): void - { - $bom = pack('CCC', 0xef, 0xbb, 0xbf); - if (0 === strncmp($text, $bom, 3)) { - $text = substr($text, 3); - } - } + /** + * @param array $elements + * @param string $prefix + * + * @return string + */ + public static function pathCombine(array $elements, $prefix = ''): string + { + return $prefix.implode(DS, $elements); + } - /** - * Strips non-printing characters from a string. - * - * Operates directly on the text string, but also returns the result for situations requiring a - * return value (use in ternary, etc.)/ - * - * @param $text String variable to strip. - * - * @return string The stripped variable. - */ - public static function stripNonPrintingChars(&$text): string - { - $lowChars = [ + /** + * @param $text + */ + public static function stripBOM(&$text): void + { + $bom = pack('CCC', 0xef, 0xbb, 0xbf); + if (0 === strncmp($text, $bom, 3)) { + $text = substr($text, 3); + } + } + + /** + * Strips non-printing characters from a string. + * + * Operates directly on the text string, but also returns the result for situations requiring a + * return value (use in ternary, etc.)/ + * + * @param $text String variable to strip. + * + * @return string The stripped variable. + */ + public static function stripNonPrintingChars(&$text): string + { + $lowChars = [ "\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08", "\x09", "\x0A", "\x0B", "\x0C", "\x0D", "\x0E", "\x0F", "\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17", "\x18", "\x19", "\x1A", "\x1B", "\x1C", "\x1D", "\x1E", "\x1F", ]; - $text = str_replace($lowChars, '', $text); + $text = str_replace($lowChars, '', $text); - return $text; - } + return $text; + } - /** - * @param $path - * - * @return string - */ - public static function trailingSlash($path): string - { - if (substr($path, strlen($path) - 1) !== '/') { - $path .= '/'; - } + /** + * @param $path + * + * @return string + */ + public static function trailingSlash($path): string + { + if (substr($path, strlen($path) - 1) !== '/') { + $path .= '/'; + } - return $path; - } + return $path; + } - /** - * Unzip a gzip file, return the output. Return false on error / empty. - * - * @param string $filePath - * - * @return bool|string - */ - public static function unzipGzipFile($filePath) - { - /* Potential issues with this, so commenting out. - $length = Utility::isGZipped($filePath); - if ($length === false || $length === null) { - return false; - }*/ + /** + * Unzip a gzip file, return the output. Return false on error / empty. + * + * @param string $filePath + * + * @return bool|string + */ + public static function unzipGzipFile($filePath) + { + /* Potential issues with this, so commenting out. + $length = Utility::isGZipped($filePath); + if ($length === false || $length === null) { + return false; + }*/ - $string = ''; - $gzFile = @gzopen($filePath, 'rb', 0); - if ($gzFile) { - while (!gzeof($gzFile)) { - $temp = gzread($gzFile, 1024); - // Check for empty string. - // Without this the loop would be endless and consume 100% CPU. - // Do not set $string empty here, as the data might still be good. - if (!$temp) { - break; - } - $string .= $temp; - } - gzclose($gzFile); - } + $string = ''; + $gzFile = @gzopen($filePath, 'rb', 0); + if ($gzFile) { + while (! gzeof($gzFile)) { + $temp = gzread($gzFile, 1024); + // Check for empty string. + // Without this the loop would be endless and consume 100% CPU. + // Do not set $string empty here, as the data might still be good. + if (! $temp) { + break; + } + $string .= $temp; + } + gzclose($gzFile); + } - return ($string === '' ? false : $string); - } + return $string === '' ? false : $string; + } - public static function setCoversConstant($path) - { - if (!defined('NN_COVERS')) { - switch (true) { - case (substr($path, 0, 1) == '/' || + public static function setCoversConstant($path) + { + if (! defined('NN_COVERS')) { + switch (true) { + case substr($path, 0, 1) == '/' || substr($path, 1, 1) == ':' || - substr($path, 0, 1) == '\\'): + substr($path, 0, 1) == '\\': define('NN_COVERS', self::trailingSlash($path)); break; - case (strlen($path) > 0 && substr($path, 0, 1) != '/' && substr($path, 1, 1) != ':' && - substr($path, 0, 1) != '\\'): - define('NN_COVERS', realpath(NN_ROOT . self::trailingSlash($path))); + case strlen($path) > 0 && substr($path, 0, 1) != '/' && substr($path, 1, 1) != ':' && + substr($path, 0, 1) != '\\': + define('NN_COVERS', realpath(NN_ROOT.self::trailingSlash($path))); break; case empty($path): // Default to resources location. default: - define('NN_COVERS', NN_RES . 'covers' . DS); + define('NN_COVERS', NN_RES.'covers'.DS); } - } - } + } + } - /** - * Creates an array to be used with stream_context_create() to verify openssl certificates - * when connecting to a tls or ssl connection when using stream functions (fopen/file_get_contents/etc). - * - * @param bool $forceIgnore Force ignoring of verification. - * - * @return array - * @static - * @access public - */ - public static function streamSslContextOptions($forceIgnore = false): array - { - if (empty(NN_SSL_CAFILE) && empty(NN_SSL_CAPATH)) { - $options = [ + /** + * Creates an array to be used with stream_context_create() to verify openssl certificates + * when connecting to a tls or ssl connection when using stream functions (fopen/file_get_contents/etc). + * + * @param bool $forceIgnore Force ignoring of verification. + * + * @return array + * @static + */ + public static function streamSslContextOptions($forceIgnore = false): array + { + if (empty(NN_SSL_CAFILE) && empty(NN_SSL_CAPATH)) { + $options = [ 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ]; - } else { - $options = [ - 'verify_peer' => $forceIgnore ? false : (bool)NN_SSL_VERIFY_PEER, - 'verify_peer_name' => $forceIgnore ? false : (bool)NN_SSL_VERIFY_HOST, - 'allow_self_signed' => $forceIgnore ? true : (bool)NN_SSL_ALLOW_SELF_SIGNED, + } else { + $options = [ + 'verify_peer' => $forceIgnore ? false : (bool) NN_SSL_VERIFY_PEER, + 'verify_peer_name' => $forceIgnore ? false : (bool) NN_SSL_VERIFY_HOST, + 'allow_self_signed' => $forceIgnore ? true : (bool) NN_SSL_ALLOW_SELF_SIGNED, ]; - if (!empty(NN_SSL_CAFILE)) { - $options['cafile'] = NN_SSL_CAFILE; - } - if (!empty(NN_SSL_CAPATH)) { - $options['capath'] = NN_SSL_CAPATH; - } - } - // If we set the transport to tls and the server falls back to ssl, - // the context options would be for tls and would not apply to ssl, - // so set both tls and ssl context in case the server does not support tls. - return ['tls' => $options, 'ssl' => $options]; - } + if (! empty(NN_SSL_CAFILE)) { + $options['cafile'] = NN_SSL_CAFILE; + } + if (! empty(NN_SSL_CAPATH)) { + $options['capath'] = NN_SSL_CAPATH; + } + } + // If we set the transport to tls and the server falls back to ssl, + // the context options would be for tls and would not apply to ssl, + // so set both tls and ssl context in case the server does not support tls. + return ['tls' => $options, 'ssl' => $options]; + } - /** - * Set curl context options for verifying SSL certificates. - * - * @param bool $verify false = Ignore config.php and do not verify the openssl cert. - * true = Check config.php and verify based on those settings. - * If you know the certificate will be self-signed, pass false. - * - * @return array - * @static - * @access public - */ - public static function curlSslContextOptions($verify = true): array - { - $options = []; - if ($verify && NN_SSL_VERIFY_HOST && (!empty(NN_SSL_CAFILE) || !empty(NN_SSL_CAPATH))) { - $options += [ - CURLOPT_SSL_VERIFYPEER => (bool)NN_SSL_VERIFY_PEER, + /** + * Set curl context options for verifying SSL certificates. + * + * @param bool $verify false = Ignore config.php and do not verify the openssl cert. + * true = Check config.php and verify based on those settings. + * If you know the certificate will be self-signed, pass false. + * + * @return array + * @static + */ + public static function curlSslContextOptions($verify = true): array + { + $options = []; + if ($verify && NN_SSL_VERIFY_HOST && (! empty(NN_SSL_CAFILE) || ! empty(NN_SSL_CAPATH))) { + $options += [ + CURLOPT_SSL_VERIFYPEER => (bool) NN_SSL_VERIFY_PEER, CURLOPT_SSL_VERIFYHOST => NN_SSL_VERIFY_HOST ? 2 : 0, ]; - if (!empty(NN_SSL_CAFILE)) { - $options += [CURLOPT_CAINFO => NN_SSL_CAFILE]; - } - if (!empty(NN_SSL_CAPATH)) { - $options += [CURLOPT_CAPATH => NN_SSL_CAPATH]; - } - } else { - $options += [ + if (! empty(NN_SSL_CAFILE)) { + $options += [CURLOPT_CAINFO => NN_SSL_CAFILE]; + } + if (! empty(NN_SSL_CAPATH)) { + $options += [CURLOPT_CAPATH => NN_SSL_CAPATH]; + } + } else { + $options += [ CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0, ]; - } + } - return $options; - } + return $options; + } - /** - * Use cURL To download a web page into a string. - * - * @param array $options See details below. - * - * @return bool|mixed - * @access public - * @static - */ - public static function getUrl(array $options = []) - { - $defaults = [ + /** + * Use cURL To download a web page into a string. + * + * @param array $options See details below. + * + * @return bool|mixed + * @static + */ + public static function getUrl(array $options = []) + { + $defaults = [ 'url' => '', // String ; The URL to download. 'method' => 'get', // String ; Http method, get/post/etc.. 'postdata' => '', // String ; Data to send on post method. @@ -494,13 +487,13 @@ class Utility // you should use this instead if your cert is self signed. ]; - $options += $defaults; + $options += $defaults; - if (!$options['url']) { - return false; - } + if (! $options['url']) { + return false; + } - switch ($options['language']) { + switch ($options['language']) { case 'fr': case 'fr-fr': $options['language'] = 'fr-fr'; @@ -520,308 +513,315 @@ class Utility default: $options['language'] = 'en'; } - $header[] = 'Accept-Language: ' . $options['language']; - if (is_array($options['requestheaders'])) { - $header += $options['requestheaders']; - } + $header[] = 'Accept-Language: '.$options['language']; + if (is_array($options['requestheaders'])) { + $header += $options['requestheaders']; + } - $ch = curl_init(); + $ch = curl_init(); - $context = [ + $context = [ CURLOPT_URL => $options['url'], CURLOPT_HTTPHEADER => $header, CURLOPT_RETURNTRANSFER => 1, CURLOPT_FOLLOWLOCATION => 1, - CURLOPT_TIMEOUT => 15 + CURLOPT_TIMEOUT => 15, ]; - $context += self::curlSslContextOptions($options['verifycert']); - if (!empty($options['useragent'])) { - $context += [CURLOPT_USERAGENT => $options['useragent']]; - } - if (!empty($options['cookie'])) { - $context += [CURLOPT_COOKIE => $options['cookie']]; - } - if ($options['method'] === 'post') { - $context += [ + $context += self::curlSslContextOptions($options['verifycert']); + if (! empty($options['useragent'])) { + $context += [CURLOPT_USERAGENT => $options['useragent']]; + } + if (! empty($options['cookie'])) { + $context += [CURLOPT_COOKIE => $options['cookie']]; + } + if ($options['method'] === 'post') { + $context += [ CURLOPT_POST => 1, - CURLOPT_POSTFIELDS => $options['postdata'] + CURLOPT_POSTFIELDS => $options['postdata'], ]; - } - if ($options['debug']) { - $context += [ + } + if ($options['debug']) { + $context += [ CURLOPT_HEADER => true, CURLINFO_HEADER_OUT => true, CURLOPT_NOPROGRESS => false, - CURLOPT_VERBOSE => true + CURLOPT_VERBOSE => true, ]; - } - curl_setopt_array($ch, $context); + } + curl_setopt_array($ch, $context); - $buffer = curl_exec($ch); - $err = curl_errno($ch); - curl_close($ch); + $buffer = curl_exec($ch); + $err = curl_errno($ch); + curl_close($ch); - if ($err !== 0) { - return false; - } + if ($err !== 0) { + return false; + } - return $buffer; - } + return $buffer; + } + /** + * Get human readable size string from bytes. + * + * @param int $size Bytes number to convert. + * @param int $precision How many floating point units to add. + * + * @return string + */ + public static function bytesToSizeString($size, $precision = 0): string + { + static $units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + $step = 1024; + $i = 0; + while (($size / $step) > 0.9) { + $size /= $step; + $i++; + } - /** - * Get human readable size string from bytes. - * - * @param int $size Bytes number to convert. - * @param int $precision How many floating point units to add. - * - * @return string - */ - public static function bytesToSizeString($size, $precision = 0): string - { - static $units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - $step = 1024; - $i = 0; - while (($size / $step) > 0.9) { - $size /= $step; - $i++; - } - return round($size, $precision).$units[$i]; - } + return round($size, $precision).$units[$i]; + } - /** - * @param array $options - * - * @return string - */ - public static function getCoverURL(array $options = []): string - { - $defaults = [ + /** + * @param array $options + * + * @return string + */ + public static function getCoverURL(array $options = []): string + { + $defaults = [ 'id' => null, 'suffix' => '-cover.jpg', 'type' => '', ]; - $options += $defaults; - $fileSpecTemplate = '%s/%s%s'; - $fileSpec = ''; + $options += $defaults; + $fileSpecTemplate = '%s/%s%s'; + $fileSpec = ''; - if (!empty($options['id']) && in_array($options['type'], + if (! empty($options['id']) && in_array($options['type'], ['anime', 'audio', 'audiosample', 'book', 'console', 'games', 'movies', 'music', 'preview', 'sample', 'tvrage', 'video', 'xxx'], false ) ) { - $fileSpec = sprintf($fileSpecTemplate, $options['type'], $options['id'], $options['suffix']); - $fileSpec = file_exists(NN_COVERS . $fileSpec) ? $fileSpec : + $fileSpec = sprintf($fileSpecTemplate, $options['type'], $options['id'], $options['suffix']); + $fileSpec = file_exists(NN_COVERS.$fileSpec) ? $fileSpec : sprintf($fileSpecTemplate, $options['type'], 'no', $options['suffix']); - } + } - return $fileSpec; - } + return $fileSpec; + } - /** - * Converts XML to an associative array with namespace preservation -- use if intending to JSON encode - * @author Tamlyn from Outlandish.com - * - * @param \SimpleXMLElement $xml The SimpleXML parsed XML string data - * @param array $options - * - * @return array The associate array of the XML namespaced file - */ - public static function xmlToArray(\SimpleXMLElement $xml, array $options = []): array - { - $defaults = array( - 'namespaceSeparator' => ':',//you may want this to be something other than a colon + /** + * Converts XML to an associative array with namespace preservation -- use if intending to JSON encode. + * @author Tamlyn from Outlandish.com + * + * @param \SimpleXMLElement $xml The SimpleXML parsed XML string data + * @param array $options + * + * @return array The associate array of the XML namespaced file + */ + public static function xmlToArray(\SimpleXMLElement $xml, array $options = []): array + { + $defaults = [ + 'namespaceSeparator' => ':', //you may want this to be something other than a colon 'attributePrefix' => '@', //to distinguish between attributes and nodes with the same name 'alwaysArray' => [], //array of xml tag names which should always become arrays 'autoArray' => true, //only create arrays for tags which appear more than once 'textContent' => '$', //key used for the text content of elements 'autoText' => true, //skip textContent key if node has no attributes or child nodes 'keySearch' => false, //optional search and replace on tag and attribute names - 'keyReplace' => false //replace values for above search values (as passed to str_replace()) - ); - $options = array_merge($defaults, $options); - $namespaces = $xml->getDocNamespaces(); - $namespaces[''] = null; //add base (empty) namespace + 'keyReplace' => false, //replace values for above search values (as passed to str_replace()) + ]; + $options = array_merge($defaults, $options); + $namespaces = $xml->getDocNamespaces(); + $namespaces[''] = null; //add base (empty) namespace - $attributesArray = $tagsArray = []; - foreach ($namespaces as $prefix => $namespace) { - //get attributes from all namespaces - foreach ($xml->attributes($namespace) as $attributeName => $attribute) { - //replace characters in attribute name - if ($options['keySearch']) $attributeName = + $attributesArray = $tagsArray = []; + foreach ($namespaces as $prefix => $namespace) { + //get attributes from all namespaces + foreach ($xml->attributes($namespace) as $attributeName => $attribute) { + //replace characters in attribute name + if ($options['keySearch']) { + $attributeName = str_replace($options['keySearch'], $options['keyReplace'], $attributeName); - $attributeKey = $options['attributePrefix'] - . ($prefix ? $prefix . $options['namespaceSeparator'] : '') - . $attributeName; - $attributesArray[$attributeKey] = (string)$attribute; - } - //get child nodes from all namespaces - foreach ($xml->children($namespace) as $childXml) { - //recurse into child nodes - $childArray = self::xmlToArray($childXml, $options); - list($childTagName, $childProperties) = each($childArray); + } + $attributeKey = $options['attributePrefix'] + .($prefix ? $prefix.$options['namespaceSeparator'] : '') + .$attributeName; + $attributesArray[$attributeKey] = (string) $attribute; + } + //get child nodes from all namespaces + foreach ($xml->children($namespace) as $childXml) { + //recurse into child nodes + $childArray = self::xmlToArray($childXml, $options); + list($childTagName, $childProperties) = each($childArray); - //replace characters in tag name - if ($options['keySearch']) $childTagName = + //replace characters in tag name + if ($options['keySearch']) { + $childTagName = str_replace($options['keySearch'], $options['keyReplace'], $childTagName); - //add namespace prefix, if any - if ($prefix) $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName; + } + //add namespace prefix, if any + if ($prefix) { + $childTagName = $prefix.$options['namespaceSeparator'].$childTagName; + } - if (!isset($tagsArray[$childTagName])) { - //only entry with this key - //test if tags of this type should always be arrays, no matter the element count - $tagsArray[$childTagName] = - in_array($childTagName, $options['alwaysArray'], false) || !$options['autoArray'] - ? array($childProperties) : $childProperties; - } elseif ( + if (! isset($tagsArray[$childTagName])) { + //only entry with this key + //test if tags of this type should always be arrays, no matter the element count + $tagsArray[$childTagName] = + in_array($childTagName, $options['alwaysArray'], false) || ! $options['autoArray'] + ? [$childProperties] : $childProperties; + } elseif ( is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName]) === range(0, count($tagsArray[$childTagName]) - 1) ) { - //key already exists and is integer indexed array - $tagsArray[$childTagName][] = $childProperties; - } else { - //key exists so convert to integer indexed array with previous value in position 0 - $tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties); - } - } - } + //key already exists and is integer indexed array + $tagsArray[$childTagName][] = $childProperties; + } else { + //key exists so convert to integer indexed array with previous value in position 0 + $tagsArray[$childTagName] = [$tagsArray[$childTagName], $childProperties]; + } + } + } - //get text content of node - $textContentArray = []; - $plainText = trim((string)$xml); - if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText; + //get text content of node + $textContentArray = []; + $plainText = trim((string) $xml); + if ($plainText !== '') { + $textContentArray[$options['textContent']] = $plainText; + } - //stick it all together - $propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '') + //stick it all together + $propertiesArray = ! $options['autoText'] || $attributesArray || $tagsArray || ($plainText === '') ? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText; - //return node as array - return array( - $xml->getName() => $propertiesArray - ); - } + //return node as array + return [ + $xml->getName() => $propertiesArray, + ]; + } + // Central function for sending site email. - // Central function for sending site email. + /** + * @param $to + * @param $subject + * @param $contents + * @param $from + * + * @return bool + * @throws \nntmux\LoggerException + * @throws \InvalidArgumentException + * @throws \Exception + * @throws \phpmailerException + */ + public static function sendEmail($to, $subject, $contents, $from): bool + { + //Setup the body first since we need it regardless of sending method. + $eol = PHP_EOL; - /** - * @param $to - * @param $subject - * @param $contents - * @param $from - * - * @return bool - * @throws \nntmux\LoggerException - * @throws \InvalidArgumentException - * @throws \Exception - * @throws \phpmailerException - */ - public static function sendEmail($to, $subject, $contents, $from): bool - { - //Setup the body first since we need it regardless of sending method. - $eol = PHP_EOL; + $body = '<html>'.$eol; + $body .= '<body style=\'font-family:Verdana, Verdana, Geneva, sans-serif; font-size:12px; color:#666666;\'>'.$eol; + $body .= $contents; + $body .= '</body>'.$eol; + $body .= '</html>'.$eol; - $body = '<html>' . $eol; - $body .= '<body style=\'font-family:Verdana, Verdana, Geneva, sans-serif; font-size:12px; color:#666666;\'>' . $eol; - $body .= $contents; - $body .= '</body>' . $eol; - $body .= '</html>' . $eol; + if (PHPMAILER_ENABLED === true) { + $mail = new \PHPMailer; - if (PHPMAILER_ENABLED === true) { - $mail = new \PHPMailer; - - // Check to make sure the user has their settings correct. - if (PHPMAILER_USE_SMTP === true) { - if ((!defined('PHPMAILER_SMTP_HOST') || PHPMAILER_SMTP_HOST === '') || - (!defined('PHPMAILER_SMTP_PORT') || PHPMAILER_SMTP_PORT === '') + // Check to make sure the user has their settings correct. + if (PHPMAILER_USE_SMTP === true) { + if ((! defined('PHPMAILER_SMTP_HOST') || PHPMAILER_SMTP_HOST === '') || + (! defined('PHPMAILER_SMTP_PORT') || PHPMAILER_SMTP_PORT === '') ) { - throw new \phpmailerException( + throw new \phpmailerException( 'You opted to use SMTP but the PHPMAILER_SMTP_HOST and/or PHPMAILER_SMTP_PORT is/are not defined correctly! Either fix the missing/incorrect values or change PHPMAILER_USE_SMTP to false in the www/settings.php' ); - } + } - // 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_USER') || PHPMAILER_SMTP_USER === '') || - (!defined('PHPMAILER_SMTP_PASSWORD') || PHPMAILER_SMTP_PASSWORD === '') + // 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_USER') || PHPMAILER_SMTP_USER === '') || + (! defined('PHPMAILER_SMTP_PASSWORD') || PHPMAILER_SMTP_PASSWORD === '') ) { - throw new \phpmailerException( + throw new \phpmailerException( 'You opted to use SMTP and SMTP Auth but the PHPMAILER_SMTP_USER and/or PHPMAILER_SMTP_PASSWORD is/are not defined correctly. Please set them in www/settings.php' ); - } - } - } + } + } + } - //Finally we can send the mail. - $mail->isHTML(true); + //Finally we can send the mail. + $mail->isHTML(true); - if (PHPMAILER_USE_SMTP) { - $mail->isSMTP(); + if (PHPMAILER_USE_SMTP) { + $mail->isSMTP(); - $mail->Host = PHPMAILER_SMTP_HOST; - $mail->Port = PHPMAILER_SMTP_PORT; + $mail->Host = PHPMAILER_SMTP_HOST; + $mail->Port = PHPMAILER_SMTP_PORT; - $mail->SMTPSecure = PHPMAILER_SMTP_SECURE; + $mail->SMTPSecure = PHPMAILER_SMTP_SECURE; - if (PHPMAILER_SMTP_AUTH) { - $mail->SMTPAuth = true; - $mail->Username = PHPMAILER_SMTP_USER; - $mail->Password = PHPMAILER_SMTP_PASSWORD; - } - } + if (PHPMAILER_SMTP_AUTH) { + $mail->SMTPAuth = true; + $mail->Username = PHPMAILER_SMTP_USER; + $mail->Password = PHPMAILER_SMTP_PASSWORD; + } + } - $fromEmail = (PHPMAILER_FROM_EMAIL === '') ? Settings::value('site.main.email') : PHPMAILER_FROM_EMAIL; - $fromName = (PHPMAILER_FROM_NAME === '') ? Settings::value('site.main.title') : PHPMAILER_FROM_NAME; - $replyTo = (PHPMAILER_REPLYTO === '') ? $from : PHPMAILER_REPLYTO; + $fromEmail = (PHPMAILER_FROM_EMAIL === '') ? Settings::value('site.main.email') : PHPMAILER_FROM_EMAIL; + $fromName = (PHPMAILER_FROM_NAME === '') ? Settings::value('site.main.title') : PHPMAILER_FROM_NAME; + $replyTo = (PHPMAILER_REPLYTO === '') ? $from : PHPMAILER_REPLYTO; - (PHPMAILER_BCC !== '') ? $mail->addBCC(PHPMAILER_BCC) : null; + (PHPMAILER_BCC !== '') ? $mail->addBCC(PHPMAILER_BCC) : null; - $mail->setFrom($fromEmail, $fromName); - $mail->addAddress($to); - $mail->addReplyTo($replyTo); - $mail->Subject = $subject; - $mail->Body = $body; - $mail->AltBody = $mail->html2text($body, true); + $mail->setFrom($fromEmail, $fromName); + $mail->addAddress($to); + $mail->addReplyTo($replyTo); + $mail->Subject = $subject; + $mail->Body = $body; + $mail->AltBody = $mail->html2text($body, true); - $sent = $mail->send(); + $sent = $mail->send(); - if (!$sent) { - (new Logger())->log(__CLASS__, __FUNCTION__, $mail->ErrorInfo, Logger::LOG_ERROR); - throw new \phpmailerException('Unable to send mail. Error: ' . $mail->ErrorInfo); - } + if (! $sent) { + (new Logger())->log(__CLASS__, __FUNCTION__, $mail->ErrorInfo, Logger::LOG_ERROR); + throw new \phpmailerException('Unable to send mail. Error: '.$mail->ErrorInfo); + } - return $sent; - } + return $sent; + } - // We don't use PHPMAILER so send the email using PHP mail function - $headers = 'From: ' . $from . $eol; - $headers .= 'Reply-To: ' . $from . $eol; - $headers .= 'Return-Path: ' . $from . $eol; - $headers .= 'X-Mailer: newznab' . $eol; - $headers .= 'MIME-Version: 1.0' . $eol; - $headers .= 'Content-type: text/html; charset=iso-8859-1' . $eol; - $headers .= $eol; + // We don't use PHPMAILER so send the email using PHP mail function + $headers = 'From: '.$from.$eol; + $headers .= 'Reply-To: '.$from.$eol; + $headers .= 'Return-Path: '.$from.$eol; + $headers .= 'X-Mailer: newznab'.$eol; + $headers .= 'MIME-Version: 1.0'.$eol; + $headers .= 'Content-type: text/html; charset=iso-8859-1'.$eol; + $headers .= $eol; - return mail($to, $subject, $body, $headers); - } + return mail($to, $subject, $body, $headers); + } - /** - * Return file type/info using magic numbers. - * Try using `file` program where available, fallback to using PHP's finfo class. - * - * @param string $path Path to the file / folder to check. - * - * @return string File info. Empty string on failure. - * @throws \Exception - */ - public static function fileInfo($path) - { - $magicPath = Settings::value('apps.indexer.magic_file_path'); - if (self::hasCommand('file') && (!self::isWin() || !empty($magicPath))) { - $magicSwitch = empty($magicPath) ? '' : " -m $magicPath"; - $output = self::runCmd('file' . $magicSwitch . ' -b "' . $path . '"'); + /** + * Return file type/info using magic numbers. + * Try using `file` program where available, fallback to using PHP's finfo class. + * + * @param string $path Path to the file / folder to check. + * + * @return string File info. Empty string on failure. + * @throws \Exception + */ + public static function fileInfo($path) + { + $magicPath = Settings::value('apps.indexer.magic_file_path'); + if (self::hasCommand('file') && (! self::isWin() || ! empty($magicPath))) { + $magicSwitch = empty($magicPath) ? '' : " -m $magicPath"; + $output = self::runCmd('file'.$magicSwitch.' -b "'.$path.'"'); - if (is_array($output)) { - switch (count($output)) { + if (is_array($output)) { + switch (count($output)) { case 0: $output = ''; break; @@ -832,209 +832,209 @@ class Utility $output = implode(' ', $output); break; } - } else { - $output = ''; - } - } else { - $fileInfo = empty($magicPath) ? finfo_open(FILEINFO_RAW) : finfo_open(FILEINFO_RAW, $magicPath); + } else { + $output = ''; + } + } else { + $fileInfo = empty($magicPath) ? finfo_open(FILEINFO_RAW) : finfo_open(FILEINFO_RAW, $magicPath); - $output = finfo_file($fileInfo, $path); - if (empty($output)) { - $output = ''; - } - finfo_close($fileInfo); - } + $output = finfo_file($fileInfo, $path); + if (empty($output)) { + $output = ''; + } + finfo_close($fileInfo); + } - return $output; - } + return $output; + } + /** + * @param $code + * + * @return bool + */ + public function checkStatus($code) + { + return ($code === 0) ? true : false; + } - /** - * @param $code - * - * @return bool - */ - public function checkStatus($code) - { - return ($code === 0) ? true : false; - } + /** + * Convert Code page 437 chars to UTF. + * + * @param string $string + * + * @return string + */ + public static function cp437toUTF($string): string + { + return iconv('CP437', 'UTF-8//IGNORE//TRANSLIT', $string); + } - /** - * Convert Code page 437 chars to UTF. - * - * @param string $string - * - * @return string - */ - public static function cp437toUTF($string): string - { - return iconv('CP437', 'UTF-8//IGNORE//TRANSLIT', $string); - } + /** + * Fetches an embeddable video to a IMDB trailer from http://www.traileraddict.com. + * + * @param $imdbID + * + * @return string + */ + public static function imdb_trailers($imdbID): string + { + $xml = self::getUrl(['url' => 'http://api.traileraddict.com/?imdb='.$imdbID]); + if ($xml !== false) { + if (preg_match('#(v\.traileraddict\.com/\d+)#i', $xml, $html)) { + return 'https://'.$html[1]; + } + } - /** - * Fetches an embeddable video to a IMDB trailer from http://www.traileraddict.com - * - * @param $imdbID - * - * @return string - */ - public static function imdb_trailers($imdbID): string - { - $xml = Utility::getUrl(['url' => 'http://api.traileraddict.com/?imdb=' . $imdbID]); - if ($xml !== false) { - if (preg_match('#(v\.traileraddict\.com/\d+)#i', $xml, $html)) { - return 'https://' . $html[1]; - } - } - return ''; - } + return ''; + } - /** - * Check if O/S is windows. - * - * @return bool - */ - public static function isWindows(): bool - { - return Utility::isWin(); - } + /** + * Check if O/S is windows. + * + * @return bool + */ + public static function isWindows(): bool + { + return self::isWin(); + } - /** - * Convert obj to array. - * - * @param $arrObjData - * @param array $arrSkipIndices - * - * @return array - */ - public static function objectsIntoArray($arrObjData, array $arrSkipIndices = []): array - { - $arrData = []; + /** + * Convert obj to array. + * + * @param $arrObjData + * @param array $arrSkipIndices + * + * @return array + */ + public static function objectsIntoArray($arrObjData, array $arrSkipIndices = []): array + { + $arrData = []; - // If input is object, convert into array. - if (is_object($arrObjData)) { - $arrObjData = get_object_vars($arrObjData); - } + // 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 = Utility::objectsIntoArray($value, $arrSkipIndices); - } - if (in_array($index, $arrSkipIndices, false)) { - continue; - } - $arrData[$index] = $value; - } - } + if (is_array($arrObjData)) { + foreach ($arrObjData as $index => $value) { + // Recursive call. + if (is_object($value) || is_array($value)) { + $value = self::objectsIntoArray($value, $arrSkipIndices); + } + if (in_array($index, $arrSkipIndices, false)) { + continue; + } + $arrData[$index] = $value; + } + } - return $arrData; - } + return $arrData; + } - /** - * Run CLI command. - * - * @param string $command - * @param bool $debug - * - * @return array - */ - public static function runCmd($command, $debug = false) - { - $nl = PHP_EOL; - if (Utility::isWindows() && strpos(PHP_VERSION, '5.3') !== false) { - $command = "\"" . $command . "\""; - } + /** + * Run CLI command. + * + * @param string $command + * @param bool $debug + * + * @return array + */ + public static function runCmd($command, $debug = false) + { + $nl = PHP_EOL; + if (self::isWindows() && strpos(PHP_VERSION, '5.3') !== false) { + $command = '"'.$command.'"'; + } - if ($debug) { - echo '-Running Command: ' . $nl . ' ' . $command . $nl; - } + if ($debug) { + echo '-Running Command: '.$nl.' '.$command.$nl; + } - $output = []; - $status = 1; - @exec($command, $output, $status); + $output = []; + $status = 1; + @exec($command, $output, $status); - if ($debug) { - echo '-Command Output: ' . $nl . ' ' . implode($nl . ' ', $output) . $nl; - } + if ($debug) { + echo '-Command Output: '.$nl.' '.implode($nl.' ', $output).$nl; + } - return $output; - } + return $output; + } - /** - * Remove unsafe chars from a filename. - * - * @param string $filename - * - * @return string - */ - public static function safeFilename($filename) - { - return trim(preg_replace('/[^\w\s.-]*/i', '', $filename)); - } + /** + * Remove unsafe chars from a filename. + * + * @param string $filename + * + * @return string + */ + public static function safeFilename($filename) + { + return trim(preg_replace('/[^\w\s.-]*/i', '', $filename)); + } - /** - * @return string - */ - public static function generateUuid(): string - { - return Uuid::uuid4()->toString(); - } + /** + * @return string + */ + public static function generateUuid(): string + { + return Uuid::uuid4()->toString(); + } - public static function startsWith($haystack, $needle) - { - return (strpos($haystack, $needle) === 0); - } + public static function startsWith($haystack, $needle) + { + return strpos($haystack, $needle) === 0; + } - public static function endsWith($haystack, $needle) - { - $length = strlen($needle); - $start = $length * -1; + public static function endsWith($haystack, $needle) + { + $length = strlen($needle); + $start = $length * -1; - return (substr($haystack, $start) === $needle); - } + return substr($haystack, $start) === $needle; + } - public static function responseXmlToObject($input) - { - $input = str_replace('<newznab:', '<', $input); + public static function responseXmlToObject($input) + { + $input = str_replace('<newznab:', '<', $input); - return @simplexml_load_string($input); - } + return @simplexml_load_string($input); + } - /** - * @note: Convert non-UTF-8 characters into UTF-8 - * Function taken from http://stackoverflow.com/a/19366999 - * - * @param $data - * - * @return array|string - */ - public static function encodeAsUTF8($data) - { - if (is_array($data)) { - foreach ($data as $key => $value) { - $data[$key] = Utility::encodeAsUTF8($value); - } - } else { - if (is_string($data)) { - return utf8_encode($data); - } - } + /** + * @note: Convert non-UTF-8 characters into UTF-8 + * Function taken from http://stackoverflow.com/a/19366999 + * + * @param $data + * + * @return array|string + */ + public static function encodeAsUTF8($data) + { + if (is_array($data)) { + foreach ($data as $key => $value) { + $data[$key] = self::encodeAsUTF8($value); + } + } else { + if (is_string($data)) { + return utf8_encode($data); + } + } - return $data; - } + return $data; + } - /** - * This function turns a roman numeral into an integer - * - * @param string $string - * - * @return int $e - */ - public static function convertRomanToInt($string): int - { - switch (strtolower($string)) { + /** + * This function turns a roman numeral into an integer. + * + * @param string $string + * + * @return int $e + */ + public static function convertRomanToInt($string): int + { + switch (strtolower($string)) { case 'i': $e = 1; break; case 'ii': $e = 2; @@ -1078,19 +1078,19 @@ class Utility default: $e = 0; } - return $e; - } + return $e; + } - /** - * Display error/error code. - * @param int $errorCode - * @param string $errorText - */ - public static function showApiError($errorCode = 900, $errorText = ''): void - { - if ($errorText === '') { - switch ($errorCode) { + /** + * Display error/error code. + * @param int $errorCode + * @param string $errorText + */ + public static function showApiError($errorCode = 900, $errorText = ''): void + { + if ($errorText === '') { + switch ($errorCode) { case 100: $errorText = 'Incorrect user credentials'; break; @@ -1143,82 +1143,86 @@ class Utility $errorText = 'Unknown error'; break; } - } + } - $response = - "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . - '<error code="' . $errorCode . '" description="' . $errorText . "\"/>\n"; - header('Content-type: text/xml'); - header('Content-Length: ' . strlen($response) ); - header('X-NNTmux: API ERROR [' . $errorCode . '] ' . $errorText); + $response = + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n". + '<error code="'.$errorCode.'" description="'.$errorText."\"/>\n"; + header('Content-type: text/xml'); + header('Content-Length: '.strlen($response)); + header('X-NNTmux: API ERROR ['.$errorCode.'] '.$errorText); - exit($response); - } + exit($response); + } - /** - * Simple function to reduce duplication in html string formatting - * - * @param $string - * - * @return string - */ - public static function htmlfmt($string): string - { - return htmlspecialchars($string, ENT_QUOTES, 'utf-8'); - } + /** + * Simple function to reduce duplication in html string formatting. + * + * @param $string + * + * @return string + */ + public static function htmlfmt($string): string + { + return htmlspecialchars($string, ENT_QUOTES, 'utf-8'); + } - /** - * Convert multi to single dimensional array - * Code taken from http://stackoverflow.com/a/12309103 - * - * @param $array - * - * @param $separator - * - * @return string - */ - public static function convertMultiArray($array, $separator): string - { - return implode("$separator",array_map(function($a) {return implode(',',$a);},$array)); - } + /** + * Convert multi to single dimensional array + * Code taken from http://stackoverflow.com/a/12309103. + * + * @param $array + * + * @param $separator + * + * @return string + */ + public static function convertMultiArray($array, $separator): string + { + return implode("$separator", array_map(function ($a) { + return implode(',', $a); + }, $array)); + } - /** - * @param string $tableName - * @param $start - * @param $num - * - * @return array - */ - public static function getRange($tableName, $start, $num): array - { - $pdo = new DB(); - return $pdo->query( + /** + * @param string $tableName + * @param $start + * @param $num + * + * @return array + */ + public static function getRange($tableName, $start, $num): array + { + $pdo = new DB(); + + return $pdo->query( sprintf( 'SELECT * %s FROM %s ORDER BY createddate DESC %s', ($tableName === 'xxxinfo' ? ', UNCOMPRESS(plot) AS plot' : ''), $tableName, - ($start === false ? '' : ('LIMIT ' . $num . ' OFFSET ' . $start)) + ($start === false ? '' : ('LIMIT '.$num.' OFFSET '.$start)) ) ); - } + } - /** - * @param string $tableName - * - * @return int - */ - public static function getCount($tableName): int - { - $pdo = new DB(); - $res = $pdo->queryOneRow(sprintf('SELECT COUNT(id) AS num FROM %s', $tableName)); - return ($res === false ? 0 : $res['num']); - } + /** + * @param string $tableName + * + * @return int + */ + public static function getCount($tableName): int + { + $pdo = new DB(); + $res = $pdo->queryOneRow(sprintf('SELECT COUNT(id) AS num FROM %s', $tableName)); - /** - * @return bool - */ - public static function checkCsrfToken(): bool - { - return !empty($_POST['_token']) && hash_equals($_SESSION['token'], $_POST['_token']); - } + return $res === false ? 0 : $res['num']; + } + + /** + * @return bool + */ + public static function checkCsrfToken(): bool + { + return ! empty($_POST['_token']) && hash_equals($_SESSION['token'], $_POST['_token']); + } } diff --git a/nntmux/utility/Versions.php b/nntmux/utility/Versions.php index 40ce1f378..713d824c9 100755 --- a/nntmux/utility/Versions.php +++ b/nntmux/utility/Versions.php @@ -1,320 +1,330 @@ <?php + namespace nntmux\utility; -if (!defined('GIT_PRE_COMMIT')) { - define('GIT_PRE_COMMIT', false); +if (! defined('GIT_PRE_COMMIT')) { + define('GIT_PRE_COMMIT', false); } use nntmux\ColorCLI; class Versions { - /** - * These constants are bitwise for checking what was changed. - */ - const UPDATED_GIT_COMMIT = 1; - const UPDATED_GIT_TAG = 2; - const UPDATED_SQL_DB_PATCH = 4; - const UPDATED_SQL_FILE_LAST = 8; + /** + * These constants are bitwise for checking what was changed. + */ + const UPDATED_GIT_COMMIT = 1; + const UPDATED_GIT_TAG = 2; + const UPDATED_SQL_DB_PATCH = 4; + const UPDATED_SQL_FILE_LAST = 8; - /** - * @var Git instance variable. - */ - public $git; + /** + * @var Git instance variable. + */ + public $git; - /** - * @var ColorCLI - */ - public $out; + /** + * @var ColorCLI + */ + public $out; - /** - * @var int - */ - protected $_changes = 0; + /** + * @var int + */ + protected $_changes = 0; - /** - * @var null|string - */ - protected $_filespec; + /** + * @var null|string + */ + protected $_filespec; - /** - * @var string highest tag value - */ - protected $_gitHighestTag; + /** + * @var string highest tag value + */ + protected $_gitHighestTag; - /** - * @var array of stable branches. - */ - protected $_stable = ['0.x']; + /** + * @var array of stable branches. + */ + protected $_stable = ['0.x']; - /** - * Shortcut to the newznab->versions node to make method work shorter. - * @var object SimpleXMLElement - */ - protected $_vers; + /** + * Shortcut to the newznab->versions node to make method work shorter. + * @var object SimpleXMLElement + */ + protected $_vers; - /** - * @var object simpleXMLElement - */ - protected $_xml; + /** + * @var object simpleXMLElement + */ + protected $_xml; - /** - * Class constructor initialises the SimpleXML object and sets a few properties. - * @param string $filepath Optional filespec for the XML file to use. Will use default otherwise. - * - * @throws \Exception If the XML is invalid. - * @throws \RuntimeException If version file does not exist. - */ - public function __construct($filepath = null) - { - if (empty($filepath)) { - if (defined('NN_VERSIONS')) { - $filepath = NN_VERSIONS; - } - } + /** + * Class constructor initialises the SimpleXML object and sets a few properties. + * @param string $filepath Optional filespec for the XML file to use. Will use default otherwise. + * + * @throws \Exception If the XML is invalid. + * @throws \RuntimeException If version file does not exist. + */ + public function __construct($filepath = null) + { + if (empty($filepath)) { + if (defined('NN_VERSIONS')) { + $filepath = NN_VERSIONS; + } + } - if (!file_exists($filepath)) { - throw new \RuntimeException("Versions file '$filepath' does not exist!'"); - } - $this->_filespec = $filepath; + if (! file_exists($filepath)) { + throw new \RuntimeException("Versions file '$filepath' does not exist!'"); + } + $this->_filespec = $filepath; - $this->out = new ColorCLI(); - $this->git = new Git(); + $this->out = new ColorCLI(); + $this->git = new Git(); - $this->getValidVersionsFile(); - } + $this->getValidVersionsFile(); + } - public function changes(): int - { - return $this->_changes; - } + public function changes(): int + { + return $this->_changes; + } - /** - * Run all checks - * @param boolean $update Whether the XML should be updated by the check. - * @return boolean True if any of the checks actually caused an update (not if it indicated one was needed), flase otherwise - */ - public function checkAll($update = true) - { - $this->checkGitTag($update); - $this->checkSQLDb($update); - $this->checkGitCommit($update); - return $this->hasChanged(); - } + /** + * Run all checks. + * @param bool $update Whether the XML should be updated by the check. + * @return bool True if any of the checks actually caused an update (not if it indicated one was needed), flase otherwise + */ + public function checkAll($update = true) + { + $this->checkGitTag($update); + $this->checkSQLDb($update); + $this->checkGitCommit($update); - /** - * Checks the git commit number against the XML's stored value. - * @param boolean $update Whether the XML should be updated by the check. - * @return integer|boolean The new git commit number, or false. - */ - public function checkGitCommit($update = true) - { - // Since Dec 2014 we no longer maintain the git commit count in the XML file, as it is no - // longer used in the code base. - if ((int)$this->_vers->sql->db >= 307) { - return 0; - } + return $this->hasChanged(); + } - $count = $this->git->commits(); - if (GIT_PRE_COMMIT === true || $this->_vers->git->commit->__toString() < $count) { - // Allow pre-commit to override the commit number (often branch number is higher than dev's) - if ($update) { - if (GIT_PRE_COMMIT === true) { - // only the pre-commit script is allowed to set the NEXT commit number - $count++; - } - if ($count !== $this->_vers->git->commit) { - echo ColorCLI::primary("Updating commit number to {$count}"); - $this->_vers->git->commit = $count; - $this->_changes |= self::UPDATED_GIT_COMMIT; - } - } - return $this->_vers->git->commit; - } - return false; - } + /** + * Checks the git commit number against the XML's stored value. + * @param bool $update Whether the XML should be updated by the check. + * @return int|bool The new git commit number, or false. + */ + public function checkGitCommit($update = true) + { + // Since Dec 2014 we no longer maintain the git commit count in the XML file, as it is no + // longer used in the code base. + if ((int) $this->_vers->sql->db >= 307) { + return 0; + } - /** - * Checks the git's latest version tag against the XML's stored value. Version should be - * Major.Minor.Revision[.fix] (**commit number is NOT revision**) - * @param boolean $update Whether the XML should be updated by the check. - * @return boolean The new git's latest version tag, or false. - */ - public function checkGitTag($update = true) - { - trigger_error( + $count = $this->git->commits(); + if (GIT_PRE_COMMIT === true || $this->_vers->git->commit->__toString() < $count) { + // Allow pre-commit to override the commit number (often branch number is higher than dev's) + if ($update) { + if (GIT_PRE_COMMIT === true) { + // only the pre-commit script is allowed to set the NEXT commit number + $count++; + } + if ($count !== $this->_vers->git->commit) { + echo ColorCLI::primary("Updating commit number to {$count}"); + $this->_vers->git->commit = $count; + $this->_changes |= self::UPDATED_GIT_COMMIT; + } + } + + return $this->_vers->git->commit; + } + + return false; + } + + /** + * Checks the git's latest version tag against the XML's stored value. Version should be + * Major.Minor.Revision[.fix] (**commit number is NOT revision**). + * @param bool $update Whether the XML should be updated by the check. + * @return bool The new git's latest version tag, or false. + */ + public function checkGitTag($update = true) + { + trigger_error( 'This method is deprecated. Use app/extensions/utils/Versions::checkGitTag() instead.' ); - $branch = $this->git->getBranch(); - $this->_gitHighestTag = $latest = trim($this->git->tagLatest()); - $ver = preg_match('#v(\d+\.\d+\.\d+).*#', $latest, $matches) ? $matches[1] : $latest; + $branch = $this->git->getBranch(); + $this->_gitHighestTag = $latest = trim($this->git->tagLatest()); + $ver = preg_match('#v(\d+\.\d+\.\d+).*#', $latest, $matches) ? $matches[1] : $latest; - if (!in_array($branch, $this->_stable, false)) { - if (version_compare($this->_vers->git->tag, '0.0.0', '!=')) { - $this->_vers->git->tag = '0.0.0'; - $this->_changes |= self::UPDATED_GIT_TAG; - } - return $this->_vers->git->tag; - } - // Check if version file's entry is the same as current branch's tag - if (version_compare($this->_vers->git->tag, $latest, '!=')) { - if ($update) { - echo ColorCLI::primaryOver('Updating tag version to ') . ColorCLI::headerOver($latest); - $this->_vers->git->tag = $ver; - $this->_changes |= self::UPDATED_GIT_TAG; - } else { - echo ColorCLI::primaryOver('Leaving tag version at ') . + if (! in_array($branch, $this->_stable, false)) { + if (version_compare($this->_vers->git->tag, '0.0.0', '!=')) { + $this->_vers->git->tag = '0.0.0'; + $this->_changes |= self::UPDATED_GIT_TAG; + } + + return $this->_vers->git->tag; + } + // Check if version file's entry is the same as current branch's tag + if (version_compare($this->_vers->git->tag, $latest, '!=')) { + if ($update) { + echo ColorCLI::primaryOver('Updating tag version to ').ColorCLI::headerOver($latest); + $this->_vers->git->tag = $ver; + $this->_changes |= self::UPDATED_GIT_TAG; + } else { + echo ColorCLI::primaryOver('Leaving tag version at '). ColorCLI::headerOver($this->_vers->git->tag); - } - return $this->_vers->git->tag; - } else { - echo ColorCLI::primaryOver('Tag version is ') . ColorCLI::header($latest); - } - return false; - } + } - /** - * Checks the database sqlpatch setting against the XML's stored value. - * - * @param boolean $update Whether the XML should be updated by the check. - * - * @return boolean The new database sqlpatch version, or false. - */ - public function checkSQLDb($update = false): bool - { - $this->checkSQLFileLatest($update); + return $this->_vers->git->tag; + } else { + echo ColorCLI::primaryOver('Tag version is ').ColorCLI::header($latest); + } - //$settings = new DB(); - //$setting = $settings->getSetting('sqlpatch'); + return false; + } - if ($this->_vers->sql->db->__toString() !== $this->_vers->sql->file->__toString()) { - if ($update) { - echo ColorCLI::primaryOver('Updating Db revision to ' . $this->_vers->sql->file); - $this->_vers->sql->db = $this->_vers->sql->file->__toString(); - $this->_changes |= self::UPDATED_SQL_DB_PATCH; - } - return $this->_vers->patch->db; - } - return false; - } + /** + * Checks the database sqlpatch setting against the XML's stored value. + * + * @param bool $update Whether the XML should be updated by the check. + * + * @return bool The new database sqlpatch version, or false. + */ + public function checkSQLDb($update = false): bool + { + $this->checkSQLFileLatest($update); - /** - * Checks the numeric value from the last SQL patch file, updating the versions file if desired. - * - * @param bool $update Whether to update the versions file. - * - * @return bool|int False if there is a problem, otherwise the number from the last patch file. - */ - public function checkSQLFileLatest($update = true) - { - $options = [ - 'data' => NN_RES . 'db' . DS . 'schema' . DS . 'data' . DS, + //$settings = new DB(); + //$setting = $settings->getSetting('sqlpatch'); + + if ($this->_vers->sql->db->__toString() !== $this->_vers->sql->file->__toString()) { + if ($update) { + echo ColorCLI::primaryOver('Updating Db revision to '.$this->_vers->sql->file); + $this->_vers->sql->db = $this->_vers->sql->file->__toString(); + $this->_changes |= self::UPDATED_SQL_DB_PATCH; + } + + return $this->_vers->patch->db; + } + + return false; + } + + /** + * Checks the numeric value from the last SQL patch file, updating the versions file if desired. + * + * @param bool $update Whether to update the versions file. + * + * @return bool|int False if there is a problem, otherwise the number from the last patch file. + */ + public function checkSQLFileLatest($update = true) + { + $options = [ + 'data' => NN_RES.'db'.DS.'schema'.DS.'data'.DS, 'ext' => 'sql', - 'path' => NN_RES . 'db' . DS . 'patches' . DS . 'mysql', - 'regex' => - '#^' . Utility::PATH_REGEX . '(?P<patch>\d{4})~(?P<table>\w+)\.sql$#', + 'path' => NN_RES.'db'.DS.'patches'.DS.'mysql', + 'regex' => '#^'.Utility::PATH_REGEX.'(?P<patch>\d{4})~(?P<table>\w+)\.sql$#', 'safe' => true, ]; - $files = Utility::getDirFiles($options); - natsort($files); + $files = Utility::getDirFiles($options); + natsort($files); - $last = preg_match($options['regex'], end($files), $matches) ? (int)$matches['patch'] : false; + $last = preg_match($options['regex'], end($files), $matches) ? (int) $matches['patch'] : false; - if ($update) { - if ($last !== false && $this->_vers->sql->file->__toString() !== $last) { - echo ColorCLI::primary('Updating latest patch file to ' . $last); - $this->_vers->sql->file = $last; - $this->_changes |= self::UPDATED_SQL_FILE_LAST; - } + if ($update) { + if ($last !== false && $this->_vers->sql->file->__toString() !== $last) { + echo ColorCLI::primary('Updating latest patch file to '.$last); + $this->_vers->sql->file = $last; + $this->_changes |= self::UPDATED_SQL_FILE_LAST; + } - if ($this->_vers->sql->file->__toString() !== $last) { - $this->_vers->sql->file = $last; - $this->_changes |= self::UPDATED_SQL_DB_PATCH; - } - } - return $last; - } + if ($this->_vers->sql->file->__toString() !== $last) { + $this->_vers->sql->file = $last; + $this->_changes |= self::UPDATED_SQL_DB_PATCH; + } + } - public function getCommit() - { - return $this->_vers->git->commit->__toString(); - } + return $last; + } - public function getGitHookPrecommit() - { - return $this->_vers->git->hooks->precommit->__toString(); - } + public function getCommit() + { + return $this->_vers->git->commit->__toString(); + } - public function getSQLPatchFromDb() - { - return $this->_vers->sql->db->__toString(); - } + public function getGitHookPrecommit() + { + return $this->_vers->git->hooks->precommit->__toString(); + } - public function getSQLPatchFromFiles() - { - return $this->_vers->sql->file->__toString(); - } + public function getSQLPatchFromDb() + { + return $this->_vers->sql->db->__toString(); + } - public function getTagVersion() - { - if (empty($this->_gitHighestTag)) { - $this->checkGitTag(); - } - return $this->_gitHighestTag; - } + public function getSQLPatchFromFiles() + { + return $this->_vers->sql->file->__toString(); + } - /** - * @param null|string $filepath - * - * @return object|\SimpleXMLElement - * @throws \Exception - */ - public function getValidVersionsFile($filepath = null) - { - $filepath = $filepath ?? $this->_filespec; + public function getTagVersion() + { + if (empty($this->_gitHighestTag)) { + $this->checkGitTag(); + } - $temp = libxml_use_internal_errors(true); - $this->_xml = simplexml_load_string(file_get_contents($filepath)); - libxml_use_internal_errors($temp); + return $this->_gitHighestTag; + } - if ($this->_xml === false) { - if (Utility::isCLI()) { - ColorCLI::error("Your versions XML file ($filepath) is broken, try updating from git."); - } - throw new \RuntimeException("Failed to open versions XML file '$filepath'"); - } + /** + * @param null|string $filepath + * + * @return object|\SimpleXMLElement + * @throws \Exception + */ + public function getValidVersionsFile($filepath = null) + { + $filepath = $filepath ?? $this->_filespec; - if ($this->_xml->count() > 0) { - $vers = $this->_xml->xpath('/nntmux/versions'); + $temp = libxml_use_internal_errors(true); + $this->_xml = simplexml_load_string(file_get_contents($filepath)); + libxml_use_internal_errors($temp); - if ($vers[0]->count() === 0) { - ColorCLI::error('Your versions XML file ({NN_VERSIONS}) does not contain version info, try updating from git.'); - throw new \RuntimeException("Failed to find versions node in XML file '$filepath'"); - } - ColorCLI::primary('Your versions XML file ({NN_VERSIONS}) looks okay, continuing.'); - $this->_vers = &$this->_xml->versions; - } else { - throw new \RuntimeException("No elements in file!\n"); - } + if ($this->_xml === false) { + if (Utility::isCLI()) { + ColorCLI::error("Your versions XML file ($filepath) is broken, try updating from git."); + } + throw new \RuntimeException("Failed to open versions XML file '$filepath'"); + } - return $this->_xml; - } + if ($this->_xml->count() > 0) { + $vers = $this->_xml->xpath('/nntmux/versions'); - /** - * Check whether the XML has been changed by one of the methods here. - * @return boolean True if the XML has been changed. - */ - public function hasChanged(): bool - { - return $this->_changes !== 0; - } + if ($vers[0]->count() === 0) { + ColorCLI::error('Your versions XML file ({NN_VERSIONS}) does not contain version info, try updating from git.'); + throw new \RuntimeException("Failed to find versions node in XML file '$filepath'"); + } + ColorCLI::primary('Your versions XML file ({NN_VERSIONS}) looks okay, continuing.'); + $this->_vers = &$this->_xml->versions; + } else { + throw new \RuntimeException("No elements in file!\n"); + } - public function save(): void - { - if ($this->hasChanged()) { - $this->_xml->asXML($this->_filespec); - $this->_changes = 0; - } - } + return $this->_xml; + } + + /** + * Check whether the XML has been changed by one of the methods here. + * @return bool True if the XML has been changed. + */ + public function hasChanged(): bool + { + return $this->_changes !== 0; + } + + public function save(): void + { + if ($this->hasChanged()) { + $this->_xml->asXML($this->_filespec); + $this->_changes = 0; + } + } } diff --git a/public/admin/ajax.php b/public/admin/ajax.php index bd2a5ef9d..c21dd11c1 100644 --- a/public/admin/ajax.php +++ b/public/admin/ajax.php @@ -1,152 +1,152 @@ <?php -use nntmux\Binaries; -use nntmux\Regexes; use nntmux\Groups; +use nntmux\Regexes; use nntmux\Sharing; +use nntmux\Binaries; use nntmux\ReleaseComments; // This script waits for ajax queries from the web. -if (!isset($_GET['action'])) { - exit(); +if (! isset($_GET['action'])) { + exit(); } -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; // Make sure the user is an admin and logged in. $admin = new AdminPage; $settings = ['Settings' => $admin->settings]; -switch($_GET['action']) { +switch ($_GET['action']) { case 'binary_blacklist_delete': $id = (int) $_GET['row_id']; (new Binaries($settings))->deleteBlacklist($id); - print "Blacklist $id deleted."; + echo "Blacklist $id deleted."; break; case 'category_regex_delete': $id = (int) $_GET['row_id']; (new Regexes(['Settings' => $admin->settings, 'Table_Name' => 'category_regexes']))->deleteRegex($id); - print "Regex $id deleted."; + echo "Regex $id deleted."; break; case 'collection_regex_delete': $id = (int) $_GET['row_id']; (new Regexes(['Settings' => $admin->settings, 'Table_Name' => 'collection_regexes']))->deleteRegex($id); - print "Regex $id deleted."; + echo "Regex $id deleted."; break; case 'release_naming_regex_delete': $id = (int) $_GET['row_id']; (new Regexes(['Settings' => $admin->settings, 'Table_Name' => 'release_naming_regexes']))->deleteRegex($id); - print "Regex $id deleted."; + echo "Regex $id deleted."; break; case 'group_edit_purge_all': session_write_close(); (new Groups($settings))->purge(); - print 'All groups purged.'; + echo 'All groups purged.'; break; case 'group_edit_reset_all': (new Groups($settings))->resetall(); - print 'All groups reset.'; + echo 'All groups reset.'; break; case 'group_edit_purge_single': - $id = (int)$_GET['group_id']; + $id = (int) $_GET['group_id']; session_write_close(); (new Groups($settings))->purge($id); - print "Group $id purged."; + echo "Group $id purged."; break; case 'group_edit_reset_single': - $id = (int)$_GET['group_id']; + $id = (int) $_GET['group_id']; session_write_close(); (new Groups($settings))->reset($id); - print "Group $id reset."; + echo "Group $id reset."; break; case 'group_edit_delete_single': - $id = (int)$_GET['group_id']; + $id = (int) $_GET['group_id']; session_write_close(); (new Groups($settings))->delete($id); - print "Group $id deleted."; + echo "Group $id deleted."; break; case 'toggle_group_active_status': - print (new Groups($settings))->updateGroupStatus((int)$_GET['group_id'], 'active', (isset($_GET['group_status']) ? (int)$_GET['group_status'] : 0)); + print (new Groups($settings))->updateGroupStatus((int) $_GET['group_id'], 'active', (isset($_GET['group_status']) ? (int) $_GET['group_status'] : 0)); break; case 'toggle_group_backfill_status': print (new Groups($settings))->updateGroupStatus( - (int)$_GET['group_id'], + (int) $_GET['group_id'], 'backfill', - (isset($_GET['backfill_status']) ? (int)$_GET['backfill_status'] : 0) + (isset($_GET['backfill_status']) ? (int) $_GET['backfill_status'] : 0) ); break; case 'sharing_toggle_status': $admin->settings->queryExec(sprintf('UPDATE sharing_sites SET enabled = %d WHERE id = %d', $_GET['site_status'], $_GET['site_id'])); - print ($_GET['site_status'] === 1 ? 'Activated' : 'Deactivated') . ' site ' . $_GET['site_id']; + echo($_GET['site_status'] === 1 ? 'Activated' : 'Deactivated').' site '.$_GET['site_id']; break; case 'sharing_toggle_enabled': $admin->settings->queryExec(sprintf('UPDATE sharing SET enabled = %d', $_GET['enabled_status'])); - print ($_GET['enabled_status'] === 1 ? 'Enabled' : 'Disabled') . ' sharing!'; + echo($_GET['enabled_status'] === 1 ? 'Enabled' : 'Disabled').' sharing!'; break; case 'sharing_start_position': $admin->settings->queryExec(sprintf('UPDATE sharing SET start_position = %d', $_GET['start_position'])); - print ($_GET['start_position'] === 1 ? 'Enabled' : 'Disabled') . ' fetching from start of group!'; + echo($_GET['start_position'] === 1 ? 'Enabled' : 'Disabled').' fetching from start of group!'; break; case 'sharing_reset_settings': $guid = $admin->settings->queryOneRow('SELECT site_guid FROM sharing'); $guid = ($guid === false ? '' : $guid['site_guid']); (new Sharing(['Settings' => $admin->settings]))->initSettings($guid); - print 'Re-initiated sharing settings!'; + echo 'Re-initiated sharing settings!'; break; case 'sharing_purge_site': $guid = $admin->settings->queryOneRow(sprintf('SELECT site_guid FROM sharing_sites WHERE id = %d', $_GET['purge_site'])); if ($guid === false) { - print 'Error purging site ' . $_GET['purge_site'] . '!'; + echo 'Error purging site '.$_GET['purge_site'].'!'; } else { - $ids = $admin->settings->query(sprintf('SELECT id FROM release_comments WHERE siteid = %s', $admin->settings->escapeString($guid['site_guid']))); - $total = count($ids); - if ($total > 0) { - $rc = new ReleaseComments($admin->settings); - foreach ($ids as $id) { - $rc->deleteComment($id['id']); - } - } - $admin->settings->queryExec(sprintf('UPDATE sharing_sites SET comments = 0 WHERE id = %d', $_GET['purge_site'])); - print 'Deleted ' . $total . ' comments for site ' . $_GET['purge_site']; + $ids = $admin->settings->query(sprintf('SELECT id FROM release_comments WHERE siteid = %s', $admin->settings->escapeString($guid['site_guid']))); + $total = count($ids); + if ($total > 0) { + $rc = new ReleaseComments($admin->settings); + foreach ($ids as $id) { + $rc->deleteComment($id['id']); + } + } + $admin->settings->queryExec(sprintf('UPDATE sharing_sites SET comments = 0 WHERE id = %d', $_GET['purge_site'])); + echo 'Deleted '.$total.' comments for site '.$_GET['purge_site']; } break; case 'sharing_toggle_posting': $admin->settings->queryExec(sprintf('UPDATE sharing SET posting = %d', $_GET['posting_status'])); - print ($_GET['posting_status'] === 1 ? 'Enabled' : 'Disabled') . ' posting!'; + echo($_GET['posting_status'] === 1 ? 'Enabled' : 'Disabled').' posting!'; break; case 'sharing_toggle_fetching': $admin->settings->queryExec(sprintf('UPDATE sharing SET fetching = %d', $_GET['fetching_status'])); - print ($_GET['fetching_status'] === 1 ? 'Enabled' : 'Disabled') . ' fetching!'; + echo($_GET['fetching_status'] === 1 ? 'Enabled' : 'Disabled').' fetching!'; break; - case 'sharing_toggle_site_auto_enabling'; + case 'sharing_toggle_site_auto_enabling': $admin->settings->queryExec(sprintf('UPDATE sharing SET auto_enable = %d', $_GET['auto_status'])); - print ($_GET['auto_status'] === 1 ? 'Enabled' : 'Disabled') . ' automatic site enabling!'; + echo($_GET['auto_status'] === 1 ? 'Enabled' : 'Disabled').' automatic site enabling!'; break; case 'sharing_toggle_hide_users': $admin->settings->queryExec(sprintf('UPDATE sharing SET hide_users = %d', $_GET['hide_status'])); - print ($_GET['hide_status'] === 1? 'Enabled' : 'Disabled') . ' hiding of user names!'; + echo($_GET['hide_status'] === 1 ? 'Enabled' : 'Disabled').' hiding of user names!'; break; - case 'sharing_toggle_all_sites': + case 'sharing_toggle_all_sites' : $admin->settings->queryExec(sprintf('UPDATE sharing_sites SET enabled = %d', $_GET['toggle_all'])); break; } diff --git a/public/admin/ajax_binaryblacklist-list.php b/public/admin/ajax_binaryblacklist-list.php index 24c4b21e3..b747f2359 100644 --- a/public/admin/ajax_binaryblacklist-list.php +++ b/public/admin/ajax_binaryblacklist-list.php @@ -1,16 +1,15 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Binaries; // login check $admin = new AdminPage; -$bin = new Binaries(); +$bin = new Binaries(); -if (isset($_GET['action']) && $_GET['action'] == "2") -{ - $id = (int)$_GET['bin_id']; - $bin->deleteBlacklist($id); - print "Blacklist $id deleted."; +if (isset($_GET['action']) && $_GET['action'] == '2') { + $id = (int) $_GET['bin_id']; + $bin->deleteBlacklist($id); + echo "Blacklist $id deleted."; } diff --git a/public/admin/ajax_group-edit.php b/public/admin/ajax_group-edit.php index ba5c9a14a..41041d255 100644 --- a/public/admin/ajax_group-edit.php +++ b/public/admin/ajax_group-edit.php @@ -1,45 +1,45 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Groups; $admin = new AdminPage; -$group = new Groups(['Settings' => $admin->settings]); +$group = new Groups(['Settings' => $admin->settings]); // session_write_close(); allows the admin to use the site while the ajax request is being processed. if (isset($_GET['action']) && $_GET['action'] === 2) { - $id = (int)$_GET['group_id']; - session_write_close(); - $group->delete($id); - print "Group $id deleted."; -} else if (isset($_GET['action']) && $_GET['action'] === 3) { - $id = (int)$_GET['group_id']; - session_write_close(); - $group->reset($id); - print "Group $id reset."; -} else if (isset($_GET['action']) && $_GET['action'] === 4) { - $id = (int)$_GET['group_id']; - session_write_close(); - $group->purge($id); - print "Group $id purged."; -} else if (isset($_GET['action']) && $_GET['action'] === 5) { - $group->resetall(); - print 'All groups reset.'; -} else if (isset($_GET['action']) && $_GET['action'] === 6) { - session_write_close(); - $group->purge(); - print 'All groups purged.'; + $id = (int) $_GET['group_id']; + session_write_close(); + $group->delete($id); + echo "Group $id deleted."; +} elseif (isset($_GET['action']) && $_GET['action'] === 3) { + $id = (int) $_GET['group_id']; + session_write_close(); + $group->reset($id); + echo "Group $id reset."; +} elseif (isset($_GET['action']) && $_GET['action'] === 4) { + $id = (int) $_GET['group_id']; + session_write_close(); + $group->purge($id); + echo "Group $id purged."; +} elseif (isset($_GET['action']) && $_GET['action'] === 5) { + $group->resetall(); + echo 'All groups reset.'; +} elseif (isset($_GET['action']) && $_GET['action'] === 6) { + session_write_close(); + $group->purge(); + echo 'All groups purged.'; } else { - if (isset($_GET['group_id'])) { - $id = (int)$_GET['group_id']; - if(isset($_GET['group_status'])) { - $status = isset($_GET['group_status']) ? (int)$_GET['group_status'] : 0; - print $group->updateGroupStatus($id, 'active', $status); - } - if(isset($_GET['backfill_status'])) { - $status = isset($_GET['backfill_status']) ? (int)$_GET['backfill_status'] : 0; - print $group->updateGroupStatus($id, 'backfill', $status); - } - } + if (isset($_GET['group_id'])) { + $id = (int) $_GET['group_id']; + if (isset($_GET['group_status'])) { + $status = isset($_GET['group_status']) ? (int) $_GET['group_status'] : 0; + echo $group->updateGroupStatus($id, 'active', $status); + } + if (isset($_GET['backfill_status'])) { + $status = isset($_GET['backfill_status']) ? (int) $_GET['backfill_status'] : 0; + echo $group->updateGroupStatus($id, 'backfill', $status); + } + } } diff --git a/public/admin/ajax_regex-list.php b/public/admin/ajax_regex-list.php index 600f6ab20..71937fc34 100644 --- a/public/admin/ajax_regex-list.php +++ b/public/admin/ajax_regex-list.php @@ -1,16 +1,15 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\ReleaseRegex; // login check $admin = new AdminPage; -$regex = new ReleaseRegex(); +$regex = new ReleaseRegex(); -if (isset($_GET['action']) && $_GET['action'] == "2") -{ - $id = (int)$_GET['regex_id']; - $regex->delete($id); - print "Regex $id deleted."; +if (isset($_GET['action']) && $_GET['action'] == '2') { + $id = (int) $_GET['regex_id']; + $regex->delete($id); + echo "Regex $id deleted."; } diff --git a/public/admin/ajax_regex.php b/public/admin/ajax_regex.php index a8bde6002..b27c8a802 100644 --- a/public/admin/ajax_regex.php +++ b/public/admin/ajax_regex.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Regexes; use nntmux\Binaries; @@ -8,20 +8,20 @@ use nntmux\Binaries; // Login Check $admin = new AdminPage; -if (!isset($_GET['action'])) { - exit(); +if (! isset($_GET['action'])) { + exit(); } -switch($_GET['action']) { +switch ($_GET['action']) { case 1: $id = (int) $_GET['col_id']; (new Regexes(['Settings' => $admin->settings]))->deleteRegex($id); - print "Regex $id deleted."; + echo "Regex $id deleted."; break; case 2: $id = (int) $_GET['bin_id']; (new Binaries(['Settings' => $admin->settings]))->deleteBlacklist($id); - print "Blacklist $id deleted."; + echo "Blacklist $id deleted."; break; } diff --git a/public/admin/ajax_sharing_settings.php b/public/admin/ajax_sharing_settings.php index fa2e583bf..8c5db6f2e 100644 --- a/public/admin/ajax_sharing_settings.php +++ b/public/admin/ajax_sharing_settings.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\db\DB; use nntmux\Sharing; @@ -11,93 +11,75 @@ $admin = new AdminPage; $db = new 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'])); - if ($_GET['site_status'] == 1) { - print 'Activated site ' . $_GET['site_ID']; - } else { - print 'Deactivated site ' . $_GET['site_ID']; - } -} - -else if (isset($_GET['enabled_status'])) { - $db->queryExec(sprintf('UPDATE sharing SET enabled = %d', $_GET['enabled_status'])); - if ($_GET['enabled_status'] == 1) { - print 'Enabled sharing!'; - } else { - print 'Disabled sharing!'; - } -} - -else if (isset($_GET['posting_status'])) { - $db->queryExec(sprintf('UPDATE sharing SET posting = %d', $_GET['posting_status'])); - if ($_GET['posting_status'] == 1) { - print 'Enabled posting!'; - } else { - print 'Disabled posting!'; - } -} - -else if (isset($_GET['fetching_status'])) { - $db->queryExec(sprintf('UPDATE sharing SET fetching = %d', $_GET['fetching_status'])); - if ($_GET['fetching_status'] == 1) { - print 'Enabled fetching!'; - } else { - print 'Disabled fetching!'; - } -} - -else if (isset($_GET['auto_status'])) { - $db->queryExec(sprintf('UPDATE sharing SET auto_enable = %d', $_GET['auto_status'])); - if ($_GET['auto_status'] == 1) { - print 'Enabled automatic site enabling!'; - } else { - print 'Disabled automatic site enabling!'; - } -} - -else if (isset($_GET['hide_status'])) { - $db->queryExec(sprintf('UPDATE sharing SET hide_users = %d', $_GET['hide_status'])); - if ($_GET['hide_status'] == 1) { - print 'Enabled hiding of user names!'; - } else { - print 'Disabled hiding of user names!'; - } -} - -else if (isset($_GET['start_position'])) { - $db->queryExec(sprintf('UPDATE sharing SET start_position = %d', $_GET['start_position'])); - if ($_GET['start_position'] == 1) { - print 'Enabled fetching from start of group!'; - } else { - print 'Disabled fetching from start of group!'; - } -} - -else if (isset($_GET['toggle_all'])) { - $db->queryExec(sprintf('UPDATE sharing_sites SET enabled = %d', $_GET['toggle_all'])); -} - -else if (isset($_GET['reset_settings'])) { - $guid = $db->queryOneRow('SELECT site_guid FROM sharing'); - $guid = ($guid === false ? '' : $guid['site_guid']); - (new Sharing(['Settings' => $admin->settings]))->initSettings($guid); - print 'Re-initiated sharing settings!'; -} - -else if (isset($_GET['purge_site'])) { - $guid = $db->queryOneRow(sprintf('SELECT site_guid FROM sharing_sites WHERE id = %d', $_GET['purge_site'])); - if ($guid === false) { - print 'Error purging site ' . $_GET['purge_site'] . '!'; - } else { - $ids = $db->query(sprintf('SELECT id FROM release_comments WHERE siteid = %s', $db->escapeString($guid['site_guid']))); - $total = count($ids); - if ($total > 0) { - $rc = new ReleaseComments(); - foreach ($ids as $id) { - $rc->deleteComment($id['id']); - } - } - $db->queryExec(sprintf('UPDATE sharing_sites SET comments = 0 WHERE id = %d', $_GET['purge_site'])); - print 'Deleted ' . $total . ' comments for site ' . $_GET['purge_site']; - } + $db->queryExec(sprintf('UPDATE sharing_sites SET enabled = %d WHERE id = %d', $_GET['site_status'], $_GET['site_ID'])); + if ($_GET['site_status'] == 1) { + echo 'Activated site '.$_GET['site_ID']; + } else { + echo 'Deactivated site '.$_GET['site_ID']; + } +} elseif (isset($_GET['enabled_status'])) { + $db->queryExec(sprintf('UPDATE sharing SET enabled = %d', $_GET['enabled_status'])); + if ($_GET['enabled_status'] == 1) { + echo 'Enabled sharing!'; + } else { + echo 'Disabled sharing!'; + } +} elseif (isset($_GET['posting_status'])) { + $db->queryExec(sprintf('UPDATE sharing SET posting = %d', $_GET['posting_status'])); + if ($_GET['posting_status'] == 1) { + echo 'Enabled posting!'; + } else { + echo 'Disabled posting!'; + } +} elseif (isset($_GET['fetching_status'])) { + $db->queryExec(sprintf('UPDATE sharing SET fetching = %d', $_GET['fetching_status'])); + if ($_GET['fetching_status'] == 1) { + echo 'Enabled fetching!'; + } else { + echo 'Disabled fetching!'; + } +} elseif (isset($_GET['auto_status'])) { + $db->queryExec(sprintf('UPDATE sharing SET auto_enable = %d', $_GET['auto_status'])); + if ($_GET['auto_status'] == 1) { + echo 'Enabled automatic site enabling!'; + } else { + echo 'Disabled automatic site enabling!'; + } +} elseif (isset($_GET['hide_status'])) { + $db->queryExec(sprintf('UPDATE sharing SET hide_users = %d', $_GET['hide_status'])); + if ($_GET['hide_status'] == 1) { + echo 'Enabled hiding of user names!'; + } else { + echo 'Disabled hiding of user names!'; + } +} elseif (isset($_GET['start_position'])) { + $db->queryExec(sprintf('UPDATE sharing SET start_position = %d', $_GET['start_position'])); + if ($_GET['start_position'] == 1) { + echo 'Enabled fetching from start of group!'; + } else { + echo 'Disabled fetching from start of group!'; + } +} elseif (isset($_GET['toggle_all'])) { + $db->queryExec(sprintf('UPDATE sharing_sites SET enabled = %d', $_GET['toggle_all'])); +} elseif (isset($_GET['reset_settings'])) { + $guid = $db->queryOneRow('SELECT site_guid FROM sharing'); + $guid = ($guid === false ? '' : $guid['site_guid']); + (new Sharing(['Settings' => $admin->settings]))->initSettings($guid); + echo 'Re-initiated sharing settings!'; +} elseif (isset($_GET['purge_site'])) { + $guid = $db->queryOneRow(sprintf('SELECT site_guid FROM sharing_sites WHERE id = %d', $_GET['purge_site'])); + if ($guid === false) { + echo 'Error purging site '.$_GET['purge_site'].'!'; + } else { + $ids = $db->query(sprintf('SELECT id FROM release_comments WHERE siteid = %s', $db->escapeString($guid['site_guid']))); + $total = count($ids); + if ($total > 0) { + $rc = new ReleaseComments(); + foreach ($ids as $id) { + $rc->deleteComment($id['id']); + } + } + $db->queryExec(sprintf('UPDATE sharing_sites SET comments = 0 WHERE id = %d', $_GET['purge_site'])); + echo 'Deleted '.$total.' comments for site '.$_GET['purge_site']; + } } diff --git a/public/admin/ajax_welcome_msg.php b/public/admin/ajax_welcome_msg.php index 042cbe921..44ac3bcf6 100644 --- a/public/admin/ajax_welcome_msg.php +++ b/public/admin/ajax_welcome_msg.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Sites; @@ -8,11 +8,10 @@ use nntmux\Sites; $admin = new AdminPage; $s = new Sites(); -if (isset($_GET['action'])) -{ - if ($_GET['action'] == "1") - $s->updateItem("showadminwelcome", 1); - else - $s->updateItem("showadminwelcome", 0); +if (isset($_GET['action'])) { + if ($_GET['action'] == '1') { + $s->updateItem('showadminwelcome', 1); + } else { + $s->updateItem('showadminwelcome', 0); + } } - diff --git a/public/admin/anidb-delete.php b/public/admin/anidb-delete.php index baacadc5f..2a1f99803 100644 --- a/public/admin/anidb-delete.php +++ b/public/admin/anidb-delete.php @@ -1,16 +1,15 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\AniDB; $page = new AdminPage(); -if (isset($_GET['id'])) -{ - $AniDB = new AniDB(); - $AniDB->deleteTitle($_GET['id']); +if (isset($_GET['id'])) { + $AniDB = new AniDB(); + $AniDB->deleteTitle($_GET['id']); } $referrer = $_SERVER['HTTP_REFERER']; -header("Location: " . $referrer); +header('Location: '.$referrer); diff --git a/public/admin/anidb-edit.php b/public/admin/anidb-edit.php index b61ad43fb..4ec769c17 100644 --- a/public/admin/anidb-edit.php +++ b/public/admin/anidb-edit.php @@ -1,12 +1,12 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\AniDB; -$page = new AdminPage(); +$page = new AdminPage(); $AniDB = new AniDB(['Settings' => $page->settings]); -$id = 0; +$id = 0; // Set the current action. $action = $_REQUEST['action'] ?? 'view'; @@ -29,24 +29,24 @@ switch ($action) { $_POST['airdates'], $_POST['episodetitles']); - if (!empty($_POST['from'])) { - header('Location:' . $_POST['from']); - exit; + if (! empty($_POST['from'])) { + header('Location:'.$_POST['from']); + exit; } - header('Location:' . WWW_TOP . '/anidb-list.php'); + 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); + $page->title = 'AniDB Edit'; + $AniDBAPIArray = $AniDB->getAnimeInfo($_GET['id']); + $page->smarty->assign('anime', $AniDBAPIArray); } break; } -$page->title = 'Edit AniDB Data'; +$page->title = 'Edit AniDB Data'; $page->content = $page->smarty->fetch('anidb-edit.tpl'); $page->render(); diff --git a/public/admin/anidb-list.php b/public/admin/anidb-list.php index 7b5f4f9fa..9cd2bf82c 100644 --- a/public/admin/anidb-list.php +++ b/public/admin/anidb-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\AniDB; @@ -11,25 +11,26 @@ $AniDB = new AniDB(); $page->title = 'AniDB List'; $aname = ''; -if (isset($_REQUEST['animetitle']) && !empty($_REQUEST['animetitle'])) - $aname = $_REQUEST['animetitle']; +if (isset($_REQUEST['animetitle']) && ! empty($_REQUEST['animetitle'])) { + $aname = $_REQUEST['animetitle']; +} $animecount = $AniDB->getAnimeCount($aname); $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='); +$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); +$page->smarty->assign('animetitle', $aname); $anidblist = $AniDB->getAnimeRange($offset, ITEMS_PER_PAGE, $aname); -$page->smarty->assign('anidblist',$anidblist); +$page->smarty->assign('anidblist', $anidblist); $page->content = $page->smarty->fetch('anidb-list.tpl'); $page->render(); diff --git a/public/admin/anidb-remove.php b/public/admin/anidb-remove.php index c8f136905..590420557 100644 --- a/public/admin/anidb-remove.php +++ b/public/admin/anidb-remove.php @@ -1,19 +1,20 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; + +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Releases; -$page = new AdminPage(); +$page = new AdminPage(); $releases = new Releases(['Settings' => $page->settings]); $success = false; -if (isset($_GET["id"])) { - $success = $releases->removeAnidbIdFromReleases($_GET["id"]); - $page->smarty->assign('anidbid', $_GET["id"]); +if (isset($_GET['id'])) { + $success = $releases->removeAnidbIdFromReleases($_GET['id']); + $page->smarty->assign('anidbid', $_GET['id']); } $page->smarty->assign('success', $success); -$page->title = "Remove anidbID from Releases"; +$page->title = 'Remove anidbID from Releases'; $page->content = $page->smarty->fetch('anidb-remove.tpl'); $page->render(); diff --git a/public/admin/binaryblacklist-edit.php b/public/admin/binaryblacklist-edit.php index f9cf2bb64..881d5bfd1 100644 --- a/public/admin/binaryblacklist-edit.php +++ b/public/admin/binaryblacklist-edit.php @@ -1,42 +1,43 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; + +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Binaries; use nntmux\Category; $page = new AdminPage(); -$bin = new Binaries(['Settings' => $page->settings]); +$bin = new Binaries(['Settings' => $page->settings]); $error = ''; $regex = ['id' => '', 'groupname' => '', 'regex' => '', 'description' => '', 'msgcol' => 1]; switch ($_REQUEST['action'] ?? 'view') { case 'submit': if ($_POST['groupname'] === '') { - $error = 'Group must be a valid usenet group'; - break; + $error = 'Group must be a valid usenet group'; + break; } if ($_POST['regex'] === '') { - $error = 'Regex cannot be empty'; - break; + $error = 'Regex cannot be empty'; + break; } if ($_POST['id'] === '') { - $bin->addBlacklist($_POST); + $bin->addBlacklist($_POST); } else { - $bin->updateBlacklist($_POST); + $bin->updateBlacklist($_POST); } - header('Location:' . WWW_TOP . '/binaryblacklist-list.php'); + header('Location:'.WWW_TOP.'/binaryblacklist-list.php'); break; case 'addtest': if (isset($_GET['regex'], $_GET['groupname'])) { - $regex += [ + $regex += [ 'groupname' => $_GET['groupname'], 'regex' => $_GET['regex'], 'ordinal' => 1, - 'status' => 1 + 'status' => 1, ]; } break; @@ -44,14 +45,14 @@ switch ($_REQUEST['action'] ?? 'view') { case 'view': default: if (isset($_GET['id'])) { - $page->title = 'Binary Black/Whitelist Edit'; - $regex = $bin->getBlacklistByID($_GET['id']); + $page->title = 'Binary Black/Whitelist Edit'; + $regex = $bin->getBlacklistByID($_GET['id']); } else { - $page->title = 'Binary Black/Whitelist Add'; - $regex += [ + $page->title = 'Binary Black/Whitelist Add'; + $regex += [ 'status' => 1, 'optype' => 1, - 'msgcol' => 1 + 'msgcol' => 1, ]; } break; @@ -67,9 +68,9 @@ $page->smarty->assign([ 'msgcol_ids' => [ Binaries::BLACKLIST_FIELD_SUBJECT, Binaries::BLACKLIST_FIELD_FROM, - Binaries::BLACKLIST_FIELD_MESSAGEID + Binaries::BLACKLIST_FIELD_MESSAGEID, ], - 'msgcol_names' => ['Subject', 'Poster', 'MessageId'] + 'msgcol_names' => ['Subject', 'Poster', 'MessageId'], ] ); diff --git a/public/admin/binaryblacklist-list.php b/public/admin/binaryblacklist-list.php index 31bf85932..2023838f4 100644 --- a/public/admin/binaryblacklist-list.php +++ b/public/admin/binaryblacklist-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Binaries; @@ -8,7 +8,7 @@ $page = new AdminPage(); $bin = new Binaries(); -$page->title = "Binary Black/Whitelist List"; +$page->title = 'Binary Black/Whitelist List'; $binlist = $bin->getBlacklist(false); $page->smarty->assign('binlist', $binlist); diff --git a/public/admin/book-edit.php b/public/admin/book-edit.php index e280f3a81..729994450 100644 --- a/public/admin/book-edit.php +++ b/public/admin/book-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Books; use nntmux\Genres; @@ -13,40 +13,36 @@ $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 (isset($_REQUEST['id'])) { + $id = $_REQUEST['id']; + $b = $book->getBookInfo($id); - if (!$b) { - $page->show404(); - } + if (! $b) { + $page->show404(); + } - switch($action) - { + switch ($action) { case 'submit': - $coverLoc = WWW_DIR."covers/book/".$id.'.jpg'; + $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); - } + 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"]); + $_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"); + header('Location:'.WWW_TOP.'/book-list.php'); die(); break; case 'view': default: - $page->title = "Book Edit"; + $page->title = 'Book Edit'; $page->smarty->assign('book', $b); break; } diff --git a/public/admin/book-list.php b/public/admin/book-list.php index bc642176b..13af00f01 100644 --- a/public/admin/book-list.php +++ b/public/admin/book-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Books; use nntmux\utility\Utility; @@ -20,7 +20,7 @@ $page->smarty->assign([ 'pagerquerysuffix' => '#results', 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => WWW_TOP. '/book-list.php?offset=', + 'pagerquerybase' => WWW_TOP.'/book-list.php?offset=', ]); $pager = $page->smarty->fetch('pager.tpl'); @@ -28,7 +28,7 @@ $page->smarty->assign('pager', $pager); $bookList = Utility::getRange('bookinfo', $offset, ITEMS_PER_PAGE); -$page->smarty->assign('booklist',$bookList); +$page->smarty->assign('booklist', $bookList); $page->content = $page->smarty->fetch('book-list.tpl'); $page->render(); diff --git a/public/admin/category-edit.php b/public/admin/category-edit.php index e9a325afa..7596495e5 100644 --- a/public/admin/category-edit.php +++ b/public/admin/category-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Category; @@ -11,20 +11,19 @@ $id = 0; // set the current action $action = $_REQUEST['action'] ?? 'view'; -switch($action) -{ +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'); + 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); + $page->title = 'Category Edit'; + $id = $_GET['id']; + $cat = $category->getById($id); + $page->smarty->assign('category', $cat); } break; } diff --git a/public/admin/category-list.php b/public/admin/category-list.php index 053cc8180..35b21a23a 100644 --- a/public/admin/category-list.php +++ b/public/admin/category-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Category; @@ -12,8 +12,7 @@ $page->title = 'Category List'; $categorylist = $category->getFlat(); -$page->smarty->assign('categorylist',$categorylist); +$page->smarty->assign('categorylist', $categorylist); $page->content = $page->smarty->fetch('category-list.tpl'); $page->render(); - diff --git a/public/admin/category_regexes-edit.php b/public/admin/category_regexes-edit.php index 2ee86dc75..d5fe72647 100644 --- a/public/admin/category_regexes-edit.php +++ b/public/admin/category_regexes-edit.php @@ -1,5 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; + +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Regexes; use nntmux\Category; @@ -17,50 +18,50 @@ $regex = [ 'description' => '', 'ordinal' => '', 'categories_id' => '', - 'status' => 1]; + 'status' => 1, ]; $page->smarty->assign('regex', $regex); -switch($action) { +switch ($action) { case 'submit': if ($_POST['group_regex'] === '') { - $page->smarty->assign('error', 'Group regex must not be empty!'); - break; + $page->smarty->assign('error', 'Group regex must not be empty!'); + break; } if ($_POST['regex'] === '') { - $page->smarty->assign('error', 'Regex cannot be empty'); - break; + $page->smarty->assign('error', 'Regex cannot be empty'); + break; } - if (!is_numeric($_POST['ordinal']) || $_POST['ordinal'] < 0) { - $page->smarty->assign('error', 'Ordinal must be a number, 0 or higher.'); - break; + if (! is_numeric($_POST['ordinal']) || $_POST['ordinal'] < 0) { + $page->smarty->assign('error', 'Ordinal must be a number, 0 or higher.'); + break; } if ($_POST['id'] === '') { - $regexes->addRegex($_POST); + $regexes->addRegex($_POST); } else { - $regexes->updateRegex($_POST); + $regexes->updateRegex($_POST); } - header('Location:' .WWW_TOP. '/category_regexes-list.php'); + header('Location:'.WWW_TOP.'/category_regexes-list.php'); break; case 'view': default: if (isset($_GET['id'])) { - $page->title = 'Category Regex Edit'; - $id = $_GET['id']; - $regex = $regexes->getRegexByID($id); + $page->title = 'Category Regex Edit'; + $id = $_GET['id']; + $regex = $regexes->getRegexByID($id); } else { - $page->title = 'Category Regex Add'; + $page->title = 'Category Regex Add'; } $page->smarty->assign('regex', $regex); break; } -$page->smarty->assign('status_ids', [Category::STATUS_ACTIVE,Category::STATUS_INACTIVE]); +$page->smarty->assign('status_ids', [Category::STATUS_ACTIVE, Category::STATUS_INACTIVE]); $page->smarty->assign('status_names', ['Yes', 'No']); $categories_db = $page->settings->queryDirect( @@ -72,10 +73,10 @@ $categories_db = $page->settings->queryDirect( ); $categories = ['category_names', 'category_ids']; if ($categories_db) { - foreach($categories_db as $category_db) { - $categories['category_names'][] = $category_db['parent_title'] . ' ' . $category_db['title'] . ': ' . $category_db['id']; - $categories['category_ids'][] = $category_db['id']; - } + foreach ($categories_db as $category_db) { + $categories['category_names'][] = $category_db['parent_title'].' '.$category_db['title'].': '.$category_db['id']; + $categories['category_ids'][] = $category_db['id']; + } } $page->smarty->assign('category_names', $categories['category_names']); $page->smarty->assign('category_ids', $categories['category_ids']); diff --git a/public/admin/category_regexes-list.php b/public/admin/category_regexes-list.php index 9b09dd386..6dc44cb9f 100644 --- a/public/admin/category_regexes-list.php +++ b/public/admin/category_regexes-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Regexes; @@ -9,7 +9,7 @@ $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'category $page->title = 'Category Regex List'; -$group = isset($_REQUEST['group']) && !empty($_REQUEST['group']) ? $_REQUEST['group'] : ''; +$group = isset($_REQUEST['group']) && ! empty($_REQUEST['group']) ? $_REQUEST['group'] : ''; $offset = ($_REQUEST['offset'] ?? 0); $regex = $regexes->getRegex($group, ITEMS_PER_PAGE, $offset); @@ -20,7 +20,7 @@ $page->smarty->assign([ 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, 'regex' => $regex, - 'pagerquerybase' => WWW_TOP . '/category_regexes-list.php?' . $group . 'offset=', + 'pagerquerybase' => WWW_TOP.'/category_regexes-list.php?'.$group.'offset=', ] ); diff --git a/public/admin/collection_regexes-edit.php b/public/admin/collection_regexes-edit.php index 30850c4c7..931bf71d2 100644 --- a/public/admin/collection_regexes-edit.php +++ b/public/admin/collection_regexes-edit.php @@ -1,11 +1,11 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Regexes; use nntmux\Category; -$page = new AdminPage(); +$page = new AdminPage(); $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'collection_regexes']); $error = ''; $regex = ['id' => '', 'regex' => '', 'description' => '', 'group_regex' => '', 'ordinal' => '']; @@ -13,41 +13,41 @@ $regex = ['id' => '', 'regex' => '', 'description' => '', 'group_regex' => '', ' switch ($_REQUEST['action'] ?? 'view') { case 'submit': if ($_POST['group_regex'] === '') { - $error = 'Group regex must not be empty!'; - break; + $error = 'Group regex must not be empty!'; + break; } if ($_POST['regex'] === '') { - $error = 'Regex cannot be empty'; - break; + $error = 'Regex cannot be empty'; + break; } if ($_POST['description'] === '') { - $_POST['description'] = ''; + $_POST['description'] = ''; } - if (!is_numeric($_POST['ordinal']) || $_POST['ordinal'] < 0) { - $error = 'Ordinal must be a number, 0 or higher.'; - break; + if (! is_numeric($_POST['ordinal']) || $_POST['ordinal'] < 0) { + $error = 'Ordinal must be a number, 0 or higher.'; + break; } if ($_POST['id'] === '') { - $regexes->addRegex($_POST); + $regexes->addRegex($_POST); } else { - $regexes->updateRegex($_POST); + $regexes->updateRegex($_POST); } - header('Location:' . WWW_TOP . '/collection_regexes-list.php'); + header('Location:'.WWW_TOP.'/collection_regexes-list.php'); break; case 'view': default: if (isset($_GET['id'])) { - $page->title = 'Collections Regex Edit'; - $regex = $regexes->getRegexByID($_GET['id']); + $page->title = 'Collections Regex Edit'; + $regex = $regexes->getRegexByID($_GET['id']); } else { - $page->title = 'Collections Regex Add'; - $regex += ['status' => 1]; + $page->title = 'Collections Regex Add'; + $regex += ['status' => 1]; } break; } diff --git a/public/admin/collection_regexes-list.php b/public/admin/collection_regexes-list.php index b02289957..5b30c44a8 100644 --- a/public/admin/collection_regexes-list.php +++ b/public/admin/collection_regexes-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Regexes; @@ -9,17 +9,17 @@ $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'collecti $page->title = 'Collections Regex List'; -$group = (isset($_REQUEST['group']) && !empty($_REQUEST['group']) ? $_REQUEST['group'] : ''); +$group = (isset($_REQUEST['group']) && ! empty($_REQUEST['group']) ? $_REQUEST['group'] : ''); $offset = $_REQUEST['offset'] ?? 0; -$regex = $regexes->getRegex($group, ITEMS_PER_PAGE, $offset); +$regex = $regexes->getRegex($group, ITEMS_PER_PAGE, $offset); $page->smarty->assign([ 'group' => $group, 'regex' => $regex, 'pagertotalitems' => $regexes->getCount($group), 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => WWW_TOP . '/collection_regexes-list.php?' . $group . 'offset=', - 'pagerquerysuffix' => '' + 'pagerquerybase' => WWW_TOP.'/collection_regexes-list.php?'.$group.'offset=', + 'pagerquerysuffix' => '', ] ); diff --git a/public/admin/collection_regexes-test.php b/public/admin/collection_regexes-test.php index cb890129e..0a18bd4af 100644 --- a/public/admin/collection_regexes-test.php +++ b/public/admin/collection_regexes-test.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Regexes; @@ -8,15 +8,14 @@ $page = new AdminPage(); $page->title = 'Collections Regex Test'; -$group = trim(isset($_POST['group']) && !empty($_POST['group']) ? $_POST['group'] : ''); -$regex = trim(isset($_POST['regex']) && !empty($_POST['regex']) ? $_POST['regex'] : ''); +$group = trim(isset($_POST['group']) && ! empty($_POST['group']) ? $_POST['group'] : ''); +$regex = trim(isset($_POST['regex']) && ! empty($_POST['regex']) ? $_POST['regex'] : ''); $limit = (isset($_POST['limit']) && is_numeric($_POST['limit']) ? $_POST['limit'] : 50); $page->smarty->assign(['group' => $group, 'regex' => $regex, 'limit' => $limit]); if ($group && $regex) { - $page->smarty->assign('data', (new Regexes(['Settings' => $page->settings, 'Table_Name' => 'collection_regexes']))->testCollectionRegex($group, $regex, $limit)); + $page->smarty->assign('data', (new Regexes(['Settings' => $page->settings, 'Table_Name' => 'collection_regexes']))->testCollectionRegex($group, $regex, $limit)); } - $page->content = $page->smarty->fetch('collection_regexes-test.tpl'); $page->render(); diff --git a/public/admin/comments-delete.php b/public/admin/comments-delete.php index 1d8f4b520..681e2e6c2 100644 --- a/public/admin/comments-delete.php +++ b/public/admin/comments-delete.php @@ -1,15 +1,15 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\ReleaseComments; $page = new AdminPage(); if (isset($_GET['id'])) { - $rc = new ReleaseComments($page->settings); - $rc->deleteComment($_GET['id']); + $rc = new ReleaseComments($page->settings); + $rc->deleteComment($_GET['id']); } $referrer = $_SERVER['HTTP_REFERER']; -header("Location: " . $referrer); +header('Location: '.$referrer); diff --git a/public/admin/comments-list.php b/public/admin/comments-list.php index a785df8f3..9f66ee57f 100644 --- a/public/admin/comments-list.php +++ b/public/admin/comments-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\ReleaseComments; @@ -17,12 +17,12 @@ $page->smarty->assign([ 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, 'pagerquerybase' => WWW_TOP.'/comments-list.php?offset=', - 'pagerquerysuffix' => '']); + 'pagerquerysuffix' => '', ]); $pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); $commentslist = $releases->getCommentsRange($offset, ITEMS_PER_PAGE); -$page->smarty->assign('commentslist',$commentslist); +$page->smarty->assign('commentslist', $commentslist); $page->content = $page->smarty->fetch('comments-list.tpl'); $page->render(); diff --git a/public/admin/console-edit.php b/public/admin/console-edit.php index e52099c97..821d3eba6 100644 --- a/public/admin/console-edit.php +++ b/public/admin/console-edit.php @@ -1,9 +1,9 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; -use nntmux\Console; use nntmux\Genres; +use nntmux\Console; $page = new AdminPage(); $console = new Console(['Settings' => $page->settings]); @@ -13,42 +13,38 @@ $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 (isset($_REQUEST['id'])) { + $id = $_REQUEST['id']; + $con = $console->getConsoleInfo($id); - if (!$con) { - $page->show404(); - } + if (! $con) { + $page->show404(); + } - switch($action) - { + switch ($action) { case 'submit': - $coverLoc = WWW_DIR."covers/console/".$id.'.jpg'; + $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); - } + 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'])); + $_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"]); + $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"); + header('Location:'.WWW_TOP.'/console-list.php'); die(); break; case 'view': default: - $page->title = "Console Edit"; + $page->title = 'Console Edit'; $page->smarty->assign('console', $con); $page->smarty->assign('genres', $gen->getGenres(Genres::CONSOLE_TYPE)); break; diff --git a/public/admin/console-list.php b/public/admin/console-list.php index 86920a988..a2937a4bd 100644 --- a/public/admin/console-list.php +++ b/public/admin/console-list.php @@ -1,12 +1,12 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Console; use nntmux\utility\Utility; $page = new AdminPage(); -$con = new Console(['Settings' => $page->settings]); +$con = new Console(['Settings' => $page->settings]); $page->title = 'Console List'; @@ -19,7 +19,7 @@ $page->smarty->assign([ 'pagerquerysuffix' => '#results', 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => WWW_TOP. '/console-list.php?offset=', + 'pagerquerybase' => WWW_TOP.'/console-list.php?offset=', ]); $pager = $page->smarty->fetch('pager.tpl'); @@ -27,7 +27,7 @@ $page->smarty->assign('pager', $pager); $consoleList = Utility::getRange('consoleinfo', $offset, ITEMS_PER_PAGE); -$page->smarty->assign('consolelist',$consoleList); +$page->smarty->assign('consolelist', $consoleList); $page->content = $page->smarty->fetch('console-list.tpl'); $page->render(); diff --git a/public/admin/content-add.php b/public/admin/content-add.php index 1f2c72781..b1931216d 100644 --- a/public/admin/content-add.php +++ b/public/admin/content-add.php @@ -1,48 +1,48 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; -use nntmux\Contents; -use nntmux\Content; use nntmux\Users; +use nntmux\Content; +use nntmux\Contents; -$page = new AdminPage(); +$page = new AdminPage(); $contents = new Contents(['Settings' => $page->settings]); -$id = 0; +$id = 0; // Set the current action. $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; switch ($action) { case 'add': - $page->title = "Content Add"; - $content = new Content(); - $content->showinmenu = "1"; - $content->status = "1"; - $content->contenttype = "2"; + $page->title = 'Content Add'; + $content = new Content(); + $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); + if (! isset($_POST['id']) || $_POST['id'] == '') { + $returnid = $contents->add($_POST); } else { - $content = $contents->update($_POST); - $returnid = $content->id; + $content = $contents->update($_POST); + $returnid = $content->id; } - header("Location:content-add.php?id=" . $returnid); + header('Location:content-add.php?id='.$returnid); break; case 'view': default: - if (isset($_GET["id"])) { - $page->title = "Content Edit"; - $id = $_GET["id"]; + if (isset($_GET['id'])) { + $page->title = 'Content Edit'; + $id = $_GET['id']; - $content = $contents->getByID($id, Users::ROLE_ADMIN); - $page->smarty->assign('content', $content); + $content = $contents->getByID($id, Users::ROLE_ADMIN); + $page->smarty->assign('content', $content); } break; } @@ -53,10 +53,10 @@ $page->smarty->assign('status_names', ['Enabled', 'Disabled']); $page->smarty->assign('yesno_ids', [1, 0]); $page->smarty->assign('yesno_names', ['Yes', 'No']); -$contenttypelist = ["1" => "Useful Link", "2" => "Article", "3" => "Homepage"]; +$contenttypelist = ['1' => 'Useful Link', '2' => 'Article', '3' => 'Homepage']; $page->smarty->assign('contenttypelist', $contenttypelist); -$rolelist = ["0" => "Everyone", "1" => "Logged in Users", "2" => "Admins"]; +$rolelist = ['0' => 'Everyone', '1' => 'Logged in Users', '2' => 'Admins']; $page->smarty->assign('rolelist', $rolelist); $page->content = $page->smarty->fetch('content-add.tpl'); diff --git a/public/admin/content-delete.php b/public/admin/content-delete.php index ffcb949db..718da94a1 100644 --- a/public/admin/content-delete.php +++ b/public/admin/content-delete.php @@ -1,17 +1,15 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Contents; $page = new AdminPage(); -if (isset($_GET['id'])) -{ - $contents = new Contents(); - $contents->delete($_GET['id']); +if (isset($_GET['id'])) { + $contents = new Contents(); + $contents->delete($_GET['id']); } $referrer = $_SERVER['HTTP_REFERER']; -header("Location: " . $referrer); - +header('Location: '.$referrer); diff --git a/public/admin/content-list.php b/public/admin/content-list.php index 720492ac7..908d15b02 100644 --- a/public/admin/content-list.php +++ b/public/admin/content-list.php @@ -1,15 +1,15 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Contents; -$page = new AdminPage(); -$contents = new Contents(['Settings' => $page->settings]); +$page = new AdminPage(); +$contents = new Contents(['Settings' => $page->settings]); $contentlist = $contents->getAll(); $page->smarty->assign('contentlist', $contentlist); -$page->title = "Content List"; +$page->title = 'Content List'; $page->content = $page->smarty->fetch('content-list.tpl'); $page->render(); diff --git a/public/admin/failrel-list.php b/public/admin/failrel-list.php index f0d755569..64e9fc009 100644 --- a/public/admin/failrel-list.php +++ b/public/admin/failrel-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\DnzbFailures; @@ -18,7 +18,7 @@ $page->smarty->assign([ 'pagerquerysuffix' => '#results', 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => WWW_TOP . '/failrel-list.php?offset=', + 'pagerquerybase' => WWW_TOP.'/failrel-list.php?offset=', ] ); $pager = $page->smarty->fetch('pager.tpl'); @@ -29,4 +29,3 @@ $page->smarty->assign('releaselist', $frellist); $page->content = $page->smarty->fetch('failrel-list.tpl'); $page->render(); - diff --git a/public/admin/forum-delete.php b/public/admin/forum-delete.php index 7f1475ca4..36fb99f38 100644 --- a/public/admin/forum-delete.php +++ b/public/admin/forum-delete.php @@ -1,19 +1,19 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Forum; $page = new AdminPage(); -if (isset($_GET['id'])) -{ - $forum = new Forum(); - $forum->deletePost($_GET['id']); +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); +if (isset($_GET['from'])) { + $referrer = $_GET['from']; +} else { + $referrer = $_SERVER['HTTP_REFERER']; +} +header('Location: '.$referrer); diff --git a/public/admin/game-edit.php b/public/admin/game-edit.php index d12b1087d..2f4feda2d 100644 --- a/public/admin/game-edit.php +++ b/public/admin/game-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Games; use nntmux\Genres; @@ -13,38 +13,38 @@ $id = 0; // Set the current action. $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; -if (isset($_REQUEST["id"])) { - $id = $_REQUEST["id"]; - $game = $games->getGamesInfoById($id); +if (isset($_REQUEST['id'])) { + $id = $_REQUEST['id']; + $game = $games->getGamesInfoById($id); - if (!$game) { - $page->show404(); - } + if (! $game) { + $page->show404(); + } - switch($action) { + switch ($action) { case 'submit': - $coverLoc = NN_COVERS . "games/" . $id . '.jpg'; + $coverLoc = NN_COVERS.'games/'.$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); - } + 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['releasedate'] = (empty($_POST['releasedate']) || !strtotime($_POST['releasedate'])) ? $game['releasedate'] : date("Y-m-d H:i:s", strtotime($_POST['releasedate'])); + $_POST['releasedate'] = (empty($_POST['releasedate']) || ! strtotime($_POST['releasedate'])) ? $game['releasedate'] : date('Y-m-d H:i:s', strtotime($_POST['releasedate'])); - $games->update($id, $_POST["title"], $_POST['asin'], $_POST['url'], $_POST["publisher"], $_POST["releasedate"], $_POST["esrb"], $_POST["cover"], $_POST['trailerurl'], $_POST["genre"]); + $games->update($id, $_POST['title'], $_POST['asin'], $_POST['url'], $_POST['publisher'], $_POST['releasedate'], $_POST['esrb'], $_POST['cover'], $_POST['trailerurl'], $_POST['genre']); - header("Location:".WWW_TOP."/game-list.php"); + header('Location:'.WWW_TOP.'/game-list.php'); die(); break; case 'view': default: - $page->title = "Game Edit"; + $page->title = 'Game Edit'; $page->smarty->assign('game', $game); $page->smarty->assign('genres', $gen->getGenres(Genres::GAME_TYPE)); break; diff --git a/public/admin/game-list.php b/public/admin/game-list.php index 335462715..cb8f51d13 100644 --- a/public/admin/game-list.php +++ b/public/admin/game-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Games; @@ -18,7 +18,7 @@ $page->smarty->assign([ 'pagerquerysuffix' => '#results', 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => WWW_TOP. '/game-list.php?offset=', + 'pagerquerybase' => WWW_TOP.'/game-list.php?offset=', ]); $pager = $page->smarty->fetch('pager.tpl'); @@ -26,7 +26,7 @@ $page->smarty->assign('pager', $pager); $gamelist = $game->getRange($offset, ITEMS_PER_PAGE); -$page->smarty->assign('gamelist',$gamelist); +$page->smarty->assign('gamelist', $gamelist); $page->content = $page->smarty->fetch('game-list.tpl'); $page->render(); diff --git a/public/admin/group-bulk.php b/public/admin/group-bulk.php index 4e16f5a50..f649079b0 100644 --- a/public/admin/group-bulk.php +++ b/public/admin/group-bulk.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Groups; @@ -9,12 +9,11 @@ $page = new AdminPage(); // set the current action $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; -switch($action) -{ +switch ($action) { case 'submit': - if (isset($_POST['groupfilter']) && !empty($_POST['groupfilter'])) { - $groups = new Groups; - $msgs = $groups->addBulk($_POST['groupfilter'], $_POST['active'], $_POST['backfill']); + if (isset($_POST['groupfilter']) && ! empty($_POST['groupfilter'])) { + $groups = new Groups; + $msgs = $groups->addBulk($_POST['groupfilter'], $_POST['active'], $_POST['backfill']); } break; default: @@ -22,10 +21,10 @@ switch($action) break; } -$page->smarty->assign('groupmsglist',$msgs); -$page->smarty->assign('yesno_ids', array(1,0)); -$page->smarty->assign('yesno_names', array( 'Yes', 'No')); +$page->smarty->assign('groupmsglist', $msgs); +$page->smarty->assign('yesno_ids', [1, 0]); +$page->smarty->assign('yesno_names', ['Yes', 'No']); -$page->title = "Bulk Add Newsgroups"; +$page->title = 'Bulk Add Newsgroups'; $page->content = $page->smarty->fetch('group-bulk.tpl'); $page->render(); diff --git a/public/admin/group-edit.php b/public/admin/group-edit.php index f4079e8eb..1049627a8 100644 --- a/public/admin/group-edit.php +++ b/public/admin/group-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Groups; @@ -11,30 +11,30 @@ $id = 0; // Set the current action. $action = $_REQUEST['action'] ?? 'view'; -switch($action) { +switch ($action) { case 'submit': if ($_POST['id'] === '') { - // Add a new group. - $_POST['name'] = $groups->isValidGroup($_POST['name']); - if ($_POST['name'] !== false) { - $groups->add($_POST); - } + // Add a new group. + $_POST['name'] = $groups->isValidGroup($_POST['name']); + if ($_POST['name'] !== false) { + $groups->add($_POST); + } } else { - // Update an existing group. - $groups->update($_POST); + // Update an existing group. + $groups->update($_POST); } - header('Location:' . WWW_TOP . '/group-list.php'); + header('Location:'.WWW_TOP.'/group-list.php'); break; case 'view': default: if (isset($_GET['id'])) { - $page->title = 'Newsgroup Edit'; - $id = $_GET['id']; - $group = $groups->getByID($id); + $page->title = 'Newsgroup Edit'; + $id = $_GET['id']; + $group = $groups->getByID($id); } else { - $page->title = 'Newsgroup Add'; - $group = [ + $page->title = 'Newsgroup Add'; + $group = [ 'id' => '', 'name' => '', 'description' => '', @@ -44,14 +44,14 @@ switch($action) { 'minsizetoformrelease' => 0, 'first_record' => 0, 'last_record' => 0, - 'backfill_target' => 0 + 'backfill_target' => 0, ]; } $page->smarty->assign('group', $group); break; } -$page->smarty->assign('yesno_ids', [1,0]); +$page->smarty->assign('yesno_ids', [1, 0]); $page->smarty->assign('yesno_names', ['Yes', 'No']); $page->content = $page->smarty->fetch('group-edit.tpl'); diff --git a/public/admin/group-list-active.php b/public/admin/group-list-active.php index 57738609f..32037c661 100644 --- a/public/admin/group-list-active.php +++ b/public/admin/group-list-active.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Groups; @@ -8,19 +8,19 @@ $page = new AdminPage(); $groups = new Groups(['Settings' => $page->settings]); $gname = ''; -if (!empty($_REQUEST['groupname'])) { - $gname = $_REQUEST['groupname']; +if (! empty($_REQUEST['groupname'])) { + $gname = $_REQUEST['groupname']; } $groupcount = $groups->getCount($gname, 1); $offset = $_REQUEST['offset'] ?? 0; -$groupname = !empty($_REQUEST['groupname']) ? $_REQUEST['groupname'] : ''; +$groupname = ! empty($_REQUEST['groupname']) ? $_REQUEST['groupname'] : ''; -$page->smarty->assign('groupname',$groupname); -$page->smarty->assign('pagertotalitems',$groupcount); -$page->smarty->assign('pageroffset',$offset); -$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('groupname', $groupname); +$page->smarty->assign('pagertotalitems', $groupcount); +$page->smarty->assign('pageroffset', $offset); +$page->smarty->assign('pageritemsperpage', ITEMS_PER_PAGE); $page->smarty->assign('pagerquerysuffix', '#results'); $groupsearch = $gname != '' ? 'groupname='.$gname.'&' : ''; @@ -30,7 +30,7 @@ $page->smarty->assign('pager', $pager); $grouplist = $groups->getRange($offset, ITEMS_PER_PAGE, $gname, 1); -$page->smarty->assign('grouplist',$grouplist); +$page->smarty->assign('grouplist', $grouplist); $page->title = 'Group List'; diff --git a/public/admin/group-list-inactive.php b/public/admin/group-list-inactive.php index 3744852ce..82c40de29 100644 --- a/public/admin/group-list-inactive.php +++ b/public/admin/group-list-inactive.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Groups; @@ -8,19 +8,19 @@ $page = new AdminPage(); $groups = new Groups(['Settings' => $page->settings]); $gname = ''; -if (!empty($_REQUEST['groupname'])) { - $gname = $_REQUEST['groupname']; +if (! empty($_REQUEST['groupname'])) { + $gname = $_REQUEST['groupname']; } $groupcount = $groups->getCount($gname, 0); $offset = $_REQUEST['offset'] ?? 0; -$groupname = !empty($_REQUEST['groupname']) ? $_REQUEST['groupname'] : ''; +$groupname = ! empty($_REQUEST['groupname']) ? $_REQUEST['groupname'] : ''; -$page->smarty->assign('groupname',$groupname); -$page->smarty->assign('pagertotalitems',$groupcount); -$page->smarty->assign('pageroffset',$offset); -$page->smarty->assign('pageritemsperpage',ITEMS_PER_PAGE); +$page->smarty->assign('groupname', $groupname); +$page->smarty->assign('pagertotalitems', $groupcount); +$page->smarty->assign('pageroffset', $offset); +$page->smarty->assign('pageritemsperpage', ITEMS_PER_PAGE); $page->smarty->assign('pagerquerysuffix', '#results'); $groupsearch = $gname != '' ? 'groupname='.$gname.'&' : ''; @@ -30,7 +30,7 @@ $page->smarty->assign('pager', $pager); $grouplist = $groups->getRange($offset, ITEMS_PER_PAGE, $gname, 0); -$page->smarty->assign('grouplist',$grouplist); +$page->smarty->assign('grouplist', $grouplist); $page->title = 'Group List'; diff --git a/public/admin/group-list.php b/public/admin/group-list.php index 796a7aec4..ceea7081a 100644 --- a/public/admin/group-list.php +++ b/public/admin/group-list.php @@ -1,14 +1,14 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Groups; -$page = new AdminPage(); +$page = new AdminPage(); $groups = new Groups(['Settings' => $page->settings]); $groupName = $_REQUEST['groupname'] ?? ''; -$offset = $_REQUEST['offset'] ?? 0; +$offset = $_REQUEST['offset'] ?? 0; $page->smarty->assign( [ @@ -16,10 +16,9 @@ $page->smarty->assign( 'pagertotalitems' => $groups->getCount($groupName, -1), 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => - WWW_TOP . '/group-list.php?' . (($groupName !== '') ? "groupname=$groupName" : '') . '&offset=', + 'pagerquerybase' => WWW_TOP.'/group-list.php?'.(($groupName !== '') ? "groupname=$groupName" : '').'&offset=', 'pagerquerysuffix' => '', - 'grouplist' => $groups->getRange($offset, ITEMS_PER_PAGE, $groupName, -1) + 'grouplist' => $groups->getRange($offset, ITEMS_PER_PAGE, $groupName, -1), ] ); $page->smarty->assign('pager', $page->smarty->fetch('pager.tpl')); diff --git a/public/admin/index.php b/public/admin/index.php index 696f8458e..ba79a4983 100644 --- a/public/admin/index.php +++ b/public/admin/index.php @@ -1,10 +1,9 @@ <?php -require_once realpath(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'); + +require_once realpath(dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'); $page = new AdminPage(); -$page->title = "Admin Hangout"; +$page->title = 'Admin Hangout'; $page->content = $page->smarty->fetch('index.tpl'); $page->render(); - -?> diff --git a/public/admin/menu-delete.php b/public/admin/menu-delete.php index f54ba38f8..8875c74ff 100644 --- a/public/admin/menu-delete.php +++ b/public/admin/menu-delete.php @@ -1,17 +1,15 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Menu; $page = new AdminPage(); -if (isset($_GET['id'])) -{ - $menu = new Menu(); - $menu->delete($_GET['id']); +if (isset($_GET['id'])) { + $menu = new Menu(); + $menu->delete($_GET['id']); } $referrer = $_SERVER['HTTP_REFERER']; -header("Location: " . $referrer); - +header('Location: '.$referrer); diff --git a/public/admin/menu-edit.php b/public/admin/menu-edit.php index bddf4e735..f31b08881 100644 --- a/public/admin/menu-edit.php +++ b/public/admin/menu-edit.php @@ -1,18 +1,18 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Menu; $page = new AdminPage(); $menu = new Menu($page->settings); -$id = 0; +$id = 0; // Get the user roles. $userroles = $page->users->getRoles(); -$roles = []; +$roles = []; foreach ($userroles as $r) { - $roles[$r['id']] = $r['name']; + $roles[$r['id']] = $r['name']; } // set the current action @@ -20,27 +20,26 @@ $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; switch ($action) { case 'submit': - if ($_POST["id"] == "") { - $menu->add($_POST); + if ($_POST['id'] == '') { + $menu->add($_POST); } else { - $ret = $menu->update($_POST); + $ret = $menu->update($_POST); } - header("Location:" . WWW_TOP . "/menu-list.php"); + header('Location:'.WWW_TOP.'/menu-list.php'); break; case 'view': default: $menuRow = [ 'id' => '', 'title' => '', 'href' => '', 'tooltip' => '', - 'menueval' => '', 'role' => 0, 'ordinal' => 0, 'newwindow' => 0 + 'menueval' => '', 'role' => 0, 'ordinal' => 0, 'newwindow' => 0, ]; - if (isset($_GET["id"])) { - - $id = $_GET["id"]; - $menuRow = $menu->getByID($id); + if (isset($_GET['id'])) { + $id = $_GET['id']; + $menuRow = $menu->getByID($id); } - $page->title = "Menu Edit"; + $page->title = 'Menu Edit'; $page->smarty->assign('menu', $menuRow); break; } diff --git a/public/admin/menu-list.php b/public/admin/menu-list.php index 7929fd589..c6336e237 100644 --- a/public/admin/menu-list.php +++ b/public/admin/menu-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Menu; @@ -8,11 +8,10 @@ $page = new AdminPage(); $menu = new Menu(); -$page->title = "Menu List"; +$page->title = 'Menu List'; $menulist = $menu->getAll(); -$page->smarty->assign('menulist',$menulist); +$page->smarty->assign('menulist', $menulist); $page->content = $page->smarty->fetch('menu-list.tpl'); $page->render(); - diff --git a/public/admin/movie-add.php b/public/admin/movie-add.php index 172d0feed..0c1205b58 100644 --- a/public/admin/movie-add.php +++ b/public/admin/movie-add.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Movie; @@ -8,21 +8,19 @@ $page = new AdminPage(); $movie = new Movie(['Settings' => $page->settings]); $id = 0; -$page->title = "Movie Add"; +$page->title = 'Movie Add'; if (isset($_REQUEST['id']) && ctype_digit($_REQUEST['id']) && strlen($_REQUEST['id']) == 7) { - $id = $_REQUEST['id']; + $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(); - } - } + $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/public/admin/movie-edit.php b/public/admin/movie-edit.php index 08dbc27ff..42c1ccecf 100644 --- a/public/admin/movie-edit.php +++ b/public/admin/movie-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Movie; @@ -11,65 +11,59 @@ $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 (isset($_REQUEST['id'])) { + $id = $_REQUEST['id']; + $mov = $movie->getMovieInfo($id); - if (!$mov) { - $page->show404(); - } + if (! $mov) { + $page->show404(); + } - switch($action) - { + switch ($action) { case 'submit': - $coverLoc = WWW_DIR."covers/movies/".$id.'-cover.jpg'; - $backdropLoc = WWW_DIR."covers/movies/".$id.'-backdrop.jpg'; + $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['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); - } + 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([ - 'actors' => $_POST["actors"], + 'actors' => $_POST['actors'], 'backdrop' => $_POST['backdrop'], - 'cover' => $_POST["cover"], - 'director' => $_POST["director"], - 'genre' => $_POST["genre"], + 'cover' => $_POST['cover'], + 'director' => $_POST['director'], + 'genre' => $_POST['genre'], 'imdbid' => $id, - 'language' => $_POST["language"], - 'plot' => $_POST["plot"], - 'rating' => $_POST["rating"], + 'language' => $_POST['language'], + 'plot' => $_POST['plot'], + 'rating' => $_POST['rating'], 'tagline' => $_POST['tagline'], - 'title' => $_POST["title"], - 'year' => $_POST["year"] + 'title' => $_POST['title'], + 'year' => $_POST['year'], ]); - header("Location:".WWW_TOP."/movie-list.php"); + header('Location:'.WWW_TOP.'/movie-list.php'); die(); break; case 'view': default: - $page->title = "Movie Edit"; + $page->title = 'Movie Edit'; $page->smarty->assign('movie', $mov); break; } @@ -77,4 +71,3 @@ if (isset($_REQUEST["id"])) $page->content = $page->smarty->fetch('movie-edit.tpl'); $page->render(); - diff --git a/public/admin/movie-list.php b/public/admin/movie-list.php index 2c7fd6781..045e7e548 100644 --- a/public/admin/movie-list.php +++ b/public/admin/movie-list.php @@ -1,11 +1,11 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Movie; use nntmux\utility\Utility; -$page = new AdminPage(); +$page = new AdminPage(); $movie = new Movie(['Settings' => $page->settings]); $page->title = 'Movie List'; @@ -19,7 +19,7 @@ $page->smarty->assign([ 'pagerquerysuffix' => '#results', 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => WWW_TOP. '/movie-list.php?offset=', + 'pagerquerybase' => WWW_TOP.'/movie-list.php?offset=', ]); $pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); @@ -29,4 +29,3 @@ $page->smarty->assign('movielist', $movieList); $page->content = $page->smarty->fetch('movie-list.tpl'); $page->render(); - diff --git a/public/admin/music-edit.php b/public/admin/music-edit.php index 88ec27ee8..56ec0adf1 100644 --- a/public/admin/music-edit.php +++ b/public/admin/music-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Music; use nntmux\Genres; @@ -13,42 +13,38 @@ $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 (isset($_REQUEST['id'])) { + $id = $_REQUEST['id']; + $mus = $music->getMusicInfo($id); - if (!$mus) { - $page->show404(); - } + if (! $mus) { + $page->show404(); + } - switch($action) - { + switch ($action) { case 'submit': - $coverLoc = WWW_DIR."covers/music/".$id.'.jpg'; + $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); - } + 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'])); + $_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"]); + $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"); + header('Location:'.WWW_TOP.'/music-list.php'); die(); break; case 'view': default: - $page->title = "Music Edit"; + $page->title = 'Music Edit'; $page->smarty->assign('music', $mus); $page->smarty->assign('genres', $gen->getGenres(Genres::MUSIC_TYPE)); break; @@ -57,4 +53,3 @@ if (isset($_REQUEST["id"])) $page->content = $page->smarty->fetch('music-edit.tpl'); $page->render(); - diff --git a/public/admin/music-list.php b/public/admin/music-list.php index 2d235e227..77de7fe23 100644 --- a/public/admin/music-list.php +++ b/public/admin/music-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Music; use nntmux\utility\Utility; @@ -20,7 +20,7 @@ $page->smarty->assign([ 'pagerquerysuffix' => '#results', 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => WWW_TOP. '/music-list.php?offset=', + 'pagerquerybase' => WWW_TOP.'/music-list.php?offset=', ]); $pager = $page->smarty->fetch('pager.tpl'); @@ -28,8 +28,7 @@ $page->smarty->assign('pager', $pager); $musicList = Utility::getRange('musicinfo', $offset, ITEMS_PER_PAGE); -$page->smarty->assign('musiclist',$musicList); +$page->smarty->assign('musiclist', $musicList); $page->content = $page->smarty->fetch('music-list.tpl'); $page->render(); - diff --git a/public/admin/nzb-export.php b/public/admin/nzb-export.php index 12164e238..727546b53 100644 --- a/public/admin/nzb-export.php +++ b/public/admin/nzb-export.php @@ -1,69 +1,69 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Releases; use nntmux\NZBExport; if (\nntmux\utility\Utility::isCLI()) { - exit ('This script is only for exporting from the web, use the script in misc/testing' . + 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]); +$rel = new Releases(['Settings' => $page->settings]); if ($page->isPostBack()) { - $retVal = $path = ''; + $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); + $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([ + if ($path !== '') { + $NE = new NZBExport([ 'Browser' => true, 'Settings' => $page->settings, - 'Releases' => $rel + 'Releases' => $rel, ]); - $retVal = $NE->beginExport( + $retVal = $NE->beginExport( [ $path, $postFrom, $postTo, $group, - $gzip + $gzip, ] ); - } else { - $retVal = 'Error, a path is required!'; - } + } else { + $retVal = 'Error, a path is required!'; + } - $page->smarty->assign( + $page->smarty->assign( [ 'folder' => $path, 'output' => $retVal, 'fromdate' => $postFrom, 'todate' => $postTo, - 'group' => $_POST["group"], - 'gzip' => $_POST["gzip"] + 'group' => $_POST['group'], + 'gzip' => $_POST['gzip'], ] ); } else { - $page->smarty->assign( + $page->smarty->assign( [ 'fromdate' => $rel->getEarliestUsenetPostDate(), - 'todate' => $rel->getLatestUsenetPostDate() + 'todate' => $rel->getLatestUsenetPostDate(), ] ); } -$page->title = "Export Nzbs"; +$page->title = 'Export Nzbs'; $page->smarty->assign( [ 'gziplist' => [1 => 'True', 0 => 'False'], - 'grouplist' => $rel->getReleasedGroupsForSelect(true) + 'grouplist' => $rel->getReleasedGroupsForSelect(true), ] ); $page->content = $page->smarty->fetch('nzb-export.tpl'); diff --git a/public/admin/nzb-import.php b/public/admin/nzb-import.php index 3a68037d2..3df75bd93 100644 --- a/public/admin/nzb-import.php +++ b/public/admin/nzb-import.php @@ -1,11 +1,11 @@ <?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.'); + exit('This is a web only script, run misc/testing/nzb-import.php instead.'); } -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; - +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\NZBImport; @@ -13,46 +13,45 @@ $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 { + $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; + $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; + // 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 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"); - } + // Get the files from the user specified path. + $filesToProcess = glob($path.'*.nzb'); + } - if (count($filesToProcess) > 0) { + if (count($filesToProcess) > 0) { // Create a new instance of NZBImport and send it the file locations. - $NZBImport = new NZBImport(['Browser' => true, 'Settings' => $page->settings]); + $NZBImport = new NZBImport(['Browser' => true, 'Settings' => $page->settings]); - $page->smarty->assign('output', + $page->smarty->assign('output', $NZBImport->beginImport($filesToProcess, $useNzbName, $deleteNZB)); - } + } } -$page->title = "Import Nzbs"; +$page->title = 'Import Nzbs'; $page->content = $page->smarty->fetch('nzb-import.tpl'); $page->render(); diff --git a/public/admin/opcachestats.php b/public/admin/opcachestats.php index 837484088..9c4c1dfbf 100644 --- a/public/admin/opcachestats.php +++ b/public/admin/opcachestats.php @@ -2,14 +2,13 @@ // #newznab-tmux : Denotes modifications done for newznab-tmux integration. /* #newznab-tmux */ -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; - +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; $page = new AdminPage(); $NNURL = $page->serverurl; /* #newznab-tmux */ -/** +/* * OPcache GUI * * A simple but effective single-file GUI for the OPcache PHP extension. @@ -20,121 +19,125 @@ $NNURL = $page->serverurl; * @license MIT, http://acollington.mit-license.org/ */ -if (!extension_loaded('Zend OPcache')) { - die('The Zend OPcache extension does not appear to be installed'); +if (! extension_loaded('Zend OPcache')) { + die('The Zend OPcache extension does not appear to be installed'); } class OpCacheService { - protected $data; - protected $options = [ - 'allow_invalidate' => true + protected $data; + protected $options = [ + 'allow_invalidate' => true, ]; - private function __construct($options = []) - { - $this->data = $this->compileState(); - $this->options = array_merge($this->options, $options); - } + private function __construct($options = []) + { + $this->data = $this->compileState(); + $this->options = array_merge($this->options, $options); + } - public static function init($options = []) - { - $self = new self($options); - if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) + public static function init($options = []) + { + $self = new self($options); + if (! empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) { - if ((isset($_GET['reset']))) { - echo '{ "success": "' . ($self->resetCache() ? 'yes' : 'no') . '" }'; - } else if ((isset($_GET['invalidate']))) { - echo '{ "success": "' . ($self->resetCache($_GET['invalidate']) ? 'yes' : 'no') . '" }'; - } else { - echo json_encode($self->getData(@$_GET['section'] ?: null)); - } - exit; - } else if ((isset($_GET['reset']))) { - $self->resetCache(); - } else if ((isset($_GET['invalidate']))) { - $self->resetCache($_GET['invalidate']); - } - return $self; - } + if ((isset($_GET['reset']))) { + echo '{ "success": "'.($self->resetCache() ? 'yes' : 'no').'" }'; + } elseif ((isset($_GET['invalidate']))) { + echo '{ "success": "'.($self->resetCache($_GET['invalidate']) ? 'yes' : 'no').'" }'; + } else { + echo json_encode($self->getData(@$_GET['section'] ?: null)); + } + exit; + } elseif ((isset($_GET['reset']))) { + $self->resetCache(); + } elseif ((isset($_GET['invalidate']))) { + $self->resetCache($_GET['invalidate']); + } - public function getOption($name = null) - { - if ($name === null) { - return $this->options; - } - return (isset($this->options[$name]) + return $self; + } + + public function getOption($name = null) + { + if ($name === null) { + return $this->options; + } + + return isset($this->options[$name]) ? $this->options[$name] - : null - ); - } + : null; + } - public function getData($section = null, $property = null) - { - if ($section === null) { - return $this->data; - } - $section = strtolower($section); - if (isset($this->data[$section])) { - if ($property === null || !isset($this->data[$section][$property])) { - return $this->data[$section]; - } - return $this->data[$section][$property]; - } - return null; - } + public function getData($section = null, $property = null) + { + if ($section === null) { + return $this->data; + } + $section = strtolower($section); + if (isset($this->data[$section])) { + if ($property === null || ! isset($this->data[$section][$property])) { + return $this->data[$section]; + } - public function canInvalidate() - { - return ($this->getOption('allow_invalidate') && function_exists('opcache_invalidate')); - } + return $this->data[$section][$property]; + } - public function resetCache($file = null) - { - $success = false; - if ($file === null) { - $success = opcache_reset(); - } else if (function_exists('opcache_invalidate')) { - $success = opcache_invalidate(urldecode($file), true); - } - if ($success) { - $this->compileState(); - } - return $success; - } + return null; + } - protected function compileState() - { - $status = opcache_get_status(); - $config = opcache_get_configuration(); - $memsize = function($size, $precision = 3, $space = false) - { - $i = 0; - $val = array(' bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); - while (($size / 1024) > 1) { - $size /= 1024; - ++$i; - } - return sprintf("%.{$precision}f%s%s", $size, (($space && $i) ? ' ' : ''), $val[$i]); - }; + public function canInvalidate() + { + return $this->getOption('allow_invalidate') && function_exists('opcache_invalidate'); + } - $files = []; - if (!empty($status['scripts'])) { - uasort($status['scripts'], function($a, $b) { - return $a['hits'] < $b['hits']; - }); - foreach ($status['scripts'] as &$file) { - $file['full_path'] = str_replace('\\', '/', $file['full_path']); - $file['readable'] = [ + public function resetCache($file = null) + { + $success = false; + if ($file === null) { + $success = opcache_reset(); + } elseif (function_exists('opcache_invalidate')) { + $success = opcache_invalidate(urldecode($file), true); + } + if ($success) { + $this->compileState(); + } + + return $success; + } + + protected function compileState() + { + $status = opcache_get_status(); + $config = opcache_get_configuration(); + $memsize = function ($size, $precision = 3, $space = false) { + $i = 0; + $val = [' bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + while (($size / 1024) > 1) { + $size /= 1024; + ++$i; + } + + return sprintf("%.{$precision}f%s%s", $size, (($space && $i) ? ' ' : ''), $val[$i]); + }; + + $files = []; + if (! empty($status['scripts'])) { + uasort($status['scripts'], function ($a, $b) { + return $a['hits'] < $b['hits']; + }); + foreach ($status['scripts'] as &$file) { + $file['full_path'] = str_replace('\\', '/', $file['full_path']); + $file['readable'] = [ 'hits' => number_format($file['hits']), - 'memory_consumption' => $memsize($file['memory_consumption']) + 'memory_consumption' => $memsize($file['memory_consumption']), ]; - } - $files = array_values($status['scripts']); - } + } + $files = array_values($status['scripts']); + } - $overview = array_merge( + $overview = array_merge( $status['memory_usage'], $status['opcache_statistics'], [ 'used_memory_percentage' => round(100 * ( ($status['memory_usage']['used_memory'] + $status['memory_usage']['wasted_memory']) @@ -156,18 +159,18 @@ class OpCacheService 'last_restart_time' => ($status['opcache_statistics']['last_restart_time'] == 0 ? 'never' : date_format(date_create("@{$status['opcache_statistics']['last_restart_time']}"), 'Y-m-d H:i:s') - ) - ] + ), + ], ] ); - $directives = []; - ksort($config['directives']); - foreach ($config['directives'] as $k => $v) { - $directives[] = ['k' => $k, 'v' => $v]; - } + $directives = []; + ksort($config['directives']); + foreach ($config['directives'] as $k => $v) { + $directives[] = ['k' => $k, 'v' => $v]; + } - $version = array_merge( + $version = array_merge( $config['version'], [ 'php' => phpversion(), @@ -180,19 +183,19 @@ class OpCacheService : $_SERVER['SERVER_NAME'] ) ) - ) + ), ] ); - return [ + return [ 'version' => $version, 'overview' => $overview, 'files' => $files, 'directives' => $directives, 'blacklist' => $config['blacklist'], - 'functions' => get_extension_funcs('Zend OPcache') + 'functions' => get_extension_funcs('Zend OPcache'), ]; - } + } } $opcache = OpCacheService::init(); @@ -336,7 +339,7 @@ $opcache = OpCacheService::init(); <script type="text/javascript"> var realtime = false; var opstate = <?php echo json_encode($opcache->getData()); ?>; - var canInvalidate = <?php echo ($opcache->canInvalidate() ? 'true' : 'false'); ?>; + var canInvalidate = <?php echo $opcache->canInvalidate() ? 'true' : 'false'; ?>; $(function(){ function updateStatus() { diff --git a/public/admin/poster-delete.php b/public/admin/poster-delete.php index 28b93dddd..6a7003b11 100644 --- a/public/admin/poster-delete.php +++ b/public/admin/poster-delete.php @@ -1,19 +1,18 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use App\Models\MultigroupPosters; $page = new AdminPage(); -if (isset($_GET['id'])) -{ - MultigroupPosters::query()->where('id', '=', $_GET['id'])->delete(); +if (isset($_GET['id'])) { + MultigroupPosters::query()->where('id', '=', $_GET['id'])->delete(); } if (isset($_GET['from'])) { - $referrer = $_GET['from']; + $referrer = $_GET['from']; } else { - $referrer = $_SERVER['HTTP_REFERER']; + $referrer = $_SERVER['HTTP_REFERER']; } -header('Location: ' . $referrer); +header('Location: '.$referrer); diff --git a/public/admin/posters-edit.php b/public/admin/posters-edit.php index f2d45f672..683bc938c 100644 --- a/public/admin/posters-edit.php +++ b/public/admin/posters-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use App\Models\MultigroupPosters; use nntmux\processing\ProcessReleasesMultiGroup; @@ -14,24 +14,24 @@ $action = $_REQUEST['action'] ?? 'view'; switch ($action) { case 'submit': if ($_POST['id'] === '') { - // Add a new mg poster. - $poster = MultigroupPosters::query()->create(['poster' => $_POST['poster']]); + // Add a new mg poster. + $poster = MultigroupPosters::query()->create(['poster' => $_POST['poster']]); } else { - // Update an existing mg poster. - $poster = MultigroupPosters::query()->where('id', '=', $_POST['id'])->update(['poster' => $_POST['poster']]); + // Update an existing mg poster. + $poster = MultigroupPosters::query()->where('id', '=', $_POST['id'])->update(['poster' => $_POST['poster']]); } - header('Location:' . WWW_TOP . '/posters-list.php'); + header('Location:'.WWW_TOP.'/posters-list.php'); break; case 'view': default: - if (!empty($_GET['id'])) { - $page->title = 'MultiGroup Poster Edit'; - $poster = MultigroupPosters::query()->where('id', '=', $_GET['id'])->firstOrFail(); + if (! empty($_GET['id'])) { + $page->title = 'MultiGroup Poster Edit'; + $poster = MultigroupPosters::query()->where('id', '=', $_GET['id'])->firstOrFail(); } else { - $page->title = 'MultiGroup Poster Add'; - $poster = ''; + $page->title = 'MultiGroup Poster Add'; + $poster = ''; } $page->smarty->assign('poster', $poster); break; diff --git a/public/admin/posters-list.php b/public/admin/posters-list.php index 5c78d391d..a58033049 100644 --- a/public/admin/posters-list.php +++ b/public/admin/posters-list.php @@ -1,22 +1,22 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use App\Models\MultigroupPosters; -$page = new AdminPage(); +$page = new AdminPage(); $posters = MultigroupPosters::all('id', 'poster')->sortBy('poster'); $postersCheck = $posters->first(); -$poster = isset($_REQUEST['poster']) && !empty($_REQUEST['poster']) ? $_REQUEST['poster'] : ''; +$poster = isset($_REQUEST['poster']) && ! empty($_REQUEST['poster']) ? $_REQUEST['poster'] : ''; $page->smarty->assign( [ 'poster' => $poster, 'posters' => $posters, - 'check' => $postersCheck + 'check' => $postersCheck, ] ); diff --git a/public/admin/predb.php b/public/admin/predb.php index ee12f8de4..a9ddac2dd 100644 --- a/public/admin/predb.php +++ b/public/admin/predb.php @@ -1,37 +1,36 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\PreDb; $page = new AdminPage(); $predb = new PreDb(); -$offset = (isset($_REQUEST["offset"]) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST["offset"] : 0; +$offset = (isset($_REQUEST['offset']) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST['offset'] : 0; if (isset($_REQUEST['presearch'])) { - $lastSearch = $_REQUEST['presearch']; - $parr = $predb->getAll($offset, ITEMS_PER_PAGE, $_REQUEST['presearch']); + $lastSearch = $_REQUEST['presearch']; + $parr = $predb->getAll($offset, ITEMS_PER_PAGE, $_REQUEST['presearch']); } else { - $lastSearch = ''; - $parr = $predb->getAll($offset, ITEMS_PER_PAGE); + $lastSearch = ''; + $parr = $predb->getAll($offset, ITEMS_PER_PAGE); } $page->smarty->assign('pagertotalitems', $parr['count']); $page->smarty->assign('pageroffset', $offset); $page->smarty->assign('pageritemsperpage', ITEMS_PER_PAGE); -$page->smarty->assign('pagerquerybase', WWW_TOP . "/predb.php?offset="); -$page->smarty->assign('pagerquerysuffix', "#results"); +$page->smarty->assign('pagerquerybase', WWW_TOP.'/predb.php?offset='); +$page->smarty->assign('pagerquerysuffix', '#results'); $page->smarty->assign('lastSearch', $lastSearch); -$page->smarty->assign('pager', $page->smarty->fetch("pager.tpl")); +$page->smarty->assign('pager', $page->smarty->fetch('pager.tpl')); $page->smarty->assign('results', $parr['arr']); - -$page->title = "Browse PreDb"; -$page->meta_title = "View PreDb info"; -$page->meta_keywords = "view,predb,info,description,details"; -$page->meta_description = "View PreDb info"; +$page->title = 'Browse PreDb'; +$page->meta_title = 'View PreDb info'; +$page->meta_keywords = 'view,predb,info,description,details'; +$page->meta_description = 'View PreDb info'; $page->content = $page->smarty->fetch('predb.tpl'); $page->render(); diff --git a/public/admin/regex-edit.php b/public/admin/regex-edit.php index 3765ee2f9..15eca5794 100644 --- a/public/admin/regex-edit.php +++ b/public/admin/regex-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Category; use nntmux\ReleaseRegex; @@ -13,52 +13,44 @@ $id = 0; // set the current action $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; -switch($action) -{ +switch ($action) { case 'submit': - if ($_POST["id"] == "") - { - $reg->add($_POST); + if ($_POST['id'] == '') { + $reg->add($_POST); + } else { + $ret = $reg->update($_POST); } - else - { - $ret = $reg->update($_POST); - } - header("Location:".WWW_TOP."/regex-list.php"); + 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); + $r = ['groupname'=>$_GET['groupname'], 'regex'=>$_GET['regex'], 'ordinal'=>'1', 'status'=>'1']; + $page->smarty->assign('regex', $r); } break; case 'view': default: - $page->title = "Release Regex Add"; + $page->title = 'Release Regex Add'; - if (isset($_GET["id"])) - { - $page->title = "Release Regex Edit"; - $id = $_GET["id"]; + if (isset($_GET['id'])) { + $page->title = 'Release Regex Edit'; + $id = $_GET['id']; - $r = $reg->getByID($id); - - } - else - { - $r = []; - $r["status"] = 1; + $r = $reg->getByID($id); + } else { + $r = []; + $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('status_ids', [Category::STATUS_ACTIVE, Category::STATUS_INACTIVE]); +$page->smarty->assign('status_names', ['Yes', 'No']); -$page->smarty->assign('catlist',$category->getForSelect(true)); +$page->smarty->assign('catlist', $category->getForSelect(true)); $page->content = $page->smarty->fetch('regex-edit.tpl'); $page->render(); diff --git a/public/admin/regex-list.php b/public/admin/regex-list.php index 5eab3ec8d..610eddace 100644 --- a/public/admin/regex-list.php +++ b/public/admin/regex-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\ReleaseRegex; @@ -8,14 +8,15 @@ $page = new AdminPage(); $reg = new ReleaseRegex(); -$page->title = "Release Regex List"; +$page->title = 'Release Regex List'; $reggrouplist = $reg->getGroupsForSelect(); $page->smarty->assign('reggrouplist', $reggrouplist); -$group=".*"; -if (isset($_REQUEST["group"])) - $group = $_REQUEST["group"]; +$group = '.*'; +if (isset($_REQUEST['group'])) { + $group = $_REQUEST['group']; +} $page->smarty->assign('selectedgroup', $group); @@ -24,4 +25,3 @@ $page->smarty->assign('regexlist', $regexlist); $page->content = $page->smarty->fetch('regex-list.tpl'); $page->render(); - diff --git a/public/admin/regex-submit.php b/public/admin/regex-submit.php index f9cbda54a..c11dff809 100644 --- a/public/admin/regex-submit.php +++ b/public/admin/regex-submit.php @@ -1,59 +1,51 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\ReleaseRegex; $page = new AdminPage(); -$page->title = "Submit your regex expressions to newznab"; +$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'; +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); + // 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 = [ + 'regex' => $regexSerialize, + ]; + curl_setopt($ch, CURLOPT_POSTFIELDS, $post); + $response = curl_exec($ch); - curl_close($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); + 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 = ['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->content = $page->smarty->fetch('regex-submit.tpl'); $page->render(); - diff --git a/public/admin/regex-test.php b/public/admin/regex-test.php index 36c1f1a72..525a9c836 100644 --- a/public/admin/regex-test.php +++ b/public/admin/regex-test.php @@ -1,10 +1,10 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; -use nntmux\ReleaseRegex; use nntmux\Groups; use nntmux\Category; +use nntmux\ReleaseRegex; $page = new AdminPage(); $reg = new ReleaseRegex(); @@ -17,30 +17,29 @@ $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; $numarticlesdefault = 20000; $groupList = $groups->getAll(); -array_unshift($groupList, array('ID'=>0, 'name'=>'All Groups')); +array_unshift($groupList, ['ID'=>0, 'name'=>'All Groups']); $gid = $gnames = []; -$groupname = (isset($_REQUEST['groupname']) && !empty($_REQUEST['groupname'])) ? $_REQUEST['groupname'] : ''; +$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'] : ''; +$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; +$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"]; +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]; +if ($group == '') { + if ($groupID == 0) { + $group = 0; + } else { + $group = $gnames[$groupID]; + } } $page->smarty->assign('gid', $gid); @@ -54,25 +53,23 @@ $page->smarty->assign('unreleased', $unreleased); $page->smarty->assign('matchagainstbins', $matchagainstbins); $page->smarty->assign('numarticles', $numarticles); -switch($action) -{ +switch ($action) { case 'test': - if (isset($_REQUEST["regex"])) - { - $matches = $reg->testRegex($_REQUEST['regex'], $group, $poster, $unreleased, $matchagainstbins); + 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); + $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); + $matches = array_slice($matches, $offset, ITEMS_PER_PAGE); - $page->smarty->assign('matches', $matches); - } + $page->smarty->assign('matches', $matches); + } break; case 'fetch': $result = $reg->fetchTestBinaries($group, $numarticles, $clearexistingbins); @@ -82,7 +79,7 @@ switch($action) break; } -$page->title = "Release Regex Test"; +$page->title = 'Release Regex Test'; $page->content = $page->smarty->fetch('regex-test.tpl'); $page->render(); diff --git a/public/admin/release-delete.php b/public/admin/release-delete.php index c13a45fc8..ee3c15f08 100644 --- a/public/admin/release-delete.php +++ b/public/admin/release-delete.php @@ -1,20 +1,19 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Releases; $page = new AdminPage(); -if (isset($_GET['id'])) -{ - $releases = new Releases(['Settings' => $page->settings]); - $releases->deleteMultiple($_GET['id']); +if (isset($_GET['id'])) { + $releases = new Releases(['Settings' => $page->settings]); + $releases->deleteMultiple($_GET['id']); } -if (isset($_GET['from'])) - $referrer = $_GET['from']; -else - $referrer = $_SERVER['HTTP_REFERER']; -header("Location: " . $referrer); - +if (isset($_GET['from'])) { + $referrer = $_GET['from']; +} else { + $referrer = $_SERVER['HTTP_REFERER']; +} +header('Location: '.$referrer); diff --git a/public/admin/release-edit.php b/public/admin/release-edit.php index a01d6585c..409d1ced9 100644 --- a/public/admin/release-edit.php +++ b/public/admin/release-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Category; use nntmux\Releases; @@ -30,18 +30,18 @@ switch ($action) { $_POST['imdbid'], $_POST['anidbid']); - if (isset($_POST['from']) && !empty($_POST['from'])) { - header('Location:' . $_POST['from']); - exit; + if (isset($_POST['from']) && ! empty($_POST['from'])) { + header('Location:'.$_POST['from']); + exit; } - header('Location:' . WWW_TOP . '/release-list.php'); + header('Location:'.WWW_TOP.'/release-list.php'); break; case 'view': default: $page->title = 'Release Edit'; - $id = $_GET['id']; - $release = $releases->getById($id); + $id = $_GET['id']; + $release = $releases->getById($id); $page->smarty->assign('release', $release); break; } diff --git a/public/admin/release-files.php b/public/admin/release-files.php index c16f3ff7e..821a5ad81 100644 --- a/public/admin/release-files.php +++ b/public/admin/release-files.php @@ -1,11 +1,11 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; -use nntmux\Releases; -use nntmux\Users; use nntmux\NZB; use nntmux\db\DB; +use nntmux\Users; +use nntmux\Releases; $page = new AdminPage; $users = new Users; @@ -13,19 +13,21 @@ $releases = new Releases; $pdo = new DB(); $nzb = new NZB($pdo); -if (!$users->isLoggedIn()) - $page->show403(); +if (! $users->isLoggedIn()) { + $page->show403(); +} -if (isset($_GET["id"])) -{ - $rel = $releases->getByGuid($_GET["id"]); - if (!$rel) - $page->show404(); - - $nzbpath = $nzb->getNZBPath($_GET["id"], $page->getSettingValue('..nzbpath')); - - if (!file_exists($nzbpath)) +if (isset($_GET['id'])) { + $rel = $releases->getByGuid($_GET['id']); + if (! $rel) { $page->show404(); + } + + $nzbpath = $nzb->getNZBPath($_GET['id'], $page->getSettingValue('..nzbpath')); + + if (! file_exists($nzbpath)) { + $page->show404(); + } ob_start(); @readgzfile($nzbpath); @@ -37,12 +39,11 @@ if (isset($_GET["id"])) $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->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(); + $page->content = $page->smarty->fetch('release-files.tpl'); + $page->render(); } - diff --git a/public/admin/release-list.php b/public/admin/release-list.php index 92fa2c2aa..eece14cd2 100644 --- a/public/admin/release-list.php +++ b/public/admin/release-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Releases; @@ -19,15 +19,14 @@ $page->smarty->assign([ 'pagerquerysuffix' => '#results', 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => WWW_TOP. '/release-list.php?offset=', + '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->smarty->assign('releaselist', $releaselist); $page->content = $page->smarty->fetch('release-list.tpl'); $page->render(); - diff --git a/public/admin/release_naming_regexes-edit.php b/public/admin/release_naming_regexes-edit.php index 50a0fa59f..34ae1eeed 100644 --- a/public/admin/release_naming_regexes-edit.php +++ b/public/admin/release_naming_regexes-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Regexes; use nntmux\Category; @@ -11,52 +11,52 @@ $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'release_ // Set the current action. $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; -switch($action) { +switch ($action) { case 'submit': - if ($_POST["group_regex"] == "") { - $page->smarty->assign('error', "Group regex must not be empty!"); - break; + if ($_POST['group_regex'] == '') { + $page->smarty->assign('error', 'Group regex must not be empty!'); + break; } - if ($_POST["regex"] == "") { - $page->smarty->assign('error', "Regex cannot be empty"); - break; + if ($_POST['regex'] == '') { + $page->smarty->assign('error', 'Regex cannot be empty'); + break; } if ($_POST['description'] == '') { - $_POST['description'] = ''; + $_POST['description'] = ''; } - if (!is_numeric($_POST['ordinal']) || $_POST['ordinal'] < 0) { - $page->smarty->assign('error', "Ordinal must be a number, 0 or higher."); - break; + if (! is_numeric($_POST['ordinal']) || $_POST['ordinal'] < 0) { + $page->smarty->assign('error', 'Ordinal must be a number, 0 or higher.'); + break; } - if ($_POST["id"] == "") { - $regexes->addRegex($_POST); + if ($_POST['id'] == '') { + $regexes->addRegex($_POST); } else { - $regexes->updateRegex($_POST); + $regexes->updateRegex($_POST); } - header("Location:".WWW_TOP."/release_naming_regexes-list.php"); + header('Location:'.WWW_TOP.'/release_naming_regexes-list.php'); break; case 'view': default: - if (isset($_GET["id"])) { - $page->title = "Release Naming Regex Edit"; - $id = $_GET["id"]; - $r = $regexes->getRegexByID($id); + if (isset($_GET['id'])) { + $page->title = 'Release Naming Regex Edit'; + $id = $_GET['id']; + $r = $regexes->getRegexByID($id); } else { - $page->title = "Release Naming Regex Add"; - $r = ['status' => 1]; + $page->title = 'Release Naming Regex Add'; + $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('status_ids', [Category::STATUS_ACTIVE, Category::STATUS_INACTIVE]); +$page->smarty->assign('status_names', ['Yes', 'No']); $page->content = $page->smarty->fetch('release_naming_regexes-edit.tpl'); $page->render(); diff --git a/public/admin/release_naming_regexes-list.php b/public/admin/release_naming_regexes-list.php index 597373728..3317881d1 100644 --- a/public/admin/release_naming_regexes-list.php +++ b/public/admin/release_naming_regexes-list.php @@ -1,20 +1,20 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Regexes; $page = new AdminPage(); $regexes = new Regexes(['Settings' => $page->settings, 'Table_Name' => 'release_naming_regexes']); -$page->title = "Release Naming Regex List"; +$page->title = 'Release Naming Regex List'; $group = ''; -if (isset($_REQUEST['group']) && !empty($_REQUEST['group'])) { - $group = $_REQUEST['group']; +if (isset($_REQUEST['group']) && ! empty($_REQUEST['group'])) { + $group = $_REQUEST['group']; } -$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$offset = isset($_REQUEST['offset']) ? $_REQUEST['offset'] : 0; $regex = $regexes->getRegex($group, ITEMS_PER_PAGE, $offset); $page->smarty->assign('regex', $regex); @@ -24,8 +24,8 @@ $page->smarty->assign('pageroffset', $offset); $page->smarty->assign('pageritemsperpage', ITEMS_PER_PAGE); $page->smarty->assign('pagerquerysuffix', ''); -$page->smarty->assign('pagerquerybase', WWW_TOP . "/release_naming_regexes-list.php?" . $group . "offset="); -$page->smarty->assign('pager', $page->smarty->fetch("pager.tpl")); +$page->smarty->assign('pagerquerybase', WWW_TOP.'/release_naming_regexes-list.php?'.$group.'offset='); +$page->smarty->assign('pager', $page->smarty->fetch('pager.tpl')); $page->content = $page->smarty->fetch('release_naming_regexes-list.tpl'); $page->render(); diff --git a/public/admin/release_naming_regexes-test.php b/public/admin/release_naming_regexes-test.php index 164b0154d..dd053564a 100644 --- a/public/admin/release_naming_regexes-test.php +++ b/public/admin/release_naming_regexes-test.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Regexes; @@ -8,16 +8,15 @@ $page = new AdminPage(); $page->title = 'Release Naming Regex Test'; -$group = trim(isset($_POST['group']) && !empty($_POST['group']) ? $_POST['group'] : ''); -$regex = trim(isset($_POST['regex']) && !empty($_POST['regex']) ? $_POST['regex'] : ''); +$group = trim(isset($_POST['group']) && ! empty($_POST['group']) ? $_POST['group'] : ''); +$regex = trim(isset($_POST['regex']) && ! empty($_POST['regex']) ? $_POST['regex'] : ''); $showLimit = (isset($_POST['showlimit']) && is_numeric($_POST['showlimit']) ? $_POST['showlimit'] : 250); $queryLimit = (isset($_POST['querylimit']) && is_numeric($_POST['querylimit']) ? $_POST['querylimit'] : 100000); $page->smarty->assign(['group' => $group, 'regex' => $regex, 'showlimit' => $showLimit, 'querylimit' => $queryLimit]); if ($group && $regex) { - $page->smarty->assign('data', (new Regexes(['Settings' => $page->settings, 'Table_Name' => 'release_naming_regexes']))->testReleaseNamingRegex($group, $regex, $showLimit, $queryLimit)); + $page->smarty->assign('data', (new Regexes(['Settings' => $page->settings, 'Table_Name' => 'release_naming_regexes']))->testReleaseNamingRegex($group, $regex, $showLimit, $queryLimit)); } - $page->content = $page->smarty->fetch('release_naming_regexes-test.tpl'); $page->render(); diff --git a/public/admin/role-delete.php b/public/admin/role-delete.php index 5365032d9..995ea1222 100644 --- a/public/admin/role-delete.php +++ b/public/admin/role-delete.php @@ -1,17 +1,15 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Users; $page = new AdminPage(); -if (isset($_GET['id'])) -{ - $users = new Users(); - $users->deleteRole($_GET['id']); +if (isset($_GET['id'])) { + $users = new Users(); + $users->deleteRole($_GET['id']); } $referrer = $_SERVER['HTTP_REFERER']; -header("Location: " . $referrer); - +header('Location: '.$referrer); diff --git a/public/admin/role-edit.php b/public/admin/role-edit.php index d0442d8ec..1ceafaa44 100644 --- a/public/admin/role-edit.php +++ b/public/admin/role-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Category; @@ -11,12 +11,12 @@ $page = new AdminPage(); $userRoles = $page->users->getRoles(); $roles = []; foreach ($userRoles as $userRole) { - $roles[$userRole['id']] = $userRole['name']; + $roles[$userRole['id']] = $userRole['name']; } switch ($_REQUEST['action'] ?? 'view') { case 'add': - $page->title = 'User Roles Add'; + $page->title = 'User Roles Add'; $role = [ 'id' => '', 'name' => '', @@ -24,25 +24,25 @@ switch ($_REQUEST['action'] ?? 'view') { 'downloadrequests' => '', 'defaultinvites' => '', 'canpreview' => 0, - 'hideads' => 0 + 'hideads' => 0, ]; $page->smarty->assign('role', $role); break; case 'submit': if ($_POST['id'] === '') { - $role = $page->users->addRole($_POST['name'], $_POST['apirequests'], $_POST['downloadrequests'], + $role = $page->users->addRole($_POST['name'], $_POST['apirequests'], $_POST['downloadrequests'], $_POST['defaultinvites'], $_POST['canpreview'], $_POST['hideads'] ); - header('Location:' . WWW_TOP . '/role-list.php'); + header('Location:'.WWW_TOP.'/role-list.php'); } else { - $role = $page->users->updateRole($_POST['id'], $_POST['name'], $_POST['apirequests'], + $role = $page->users->updateRole($_POST['id'], $_POST['name'], $_POST['apirequests'], $_POST['downloadrequests'], $_POST['defaultinvites'], $_POST['isdefault'], $_POST['canpreview'], $_POST['hideads'] ); - header('Location:' . WWW_TOP . '/role-list.php'); + header('Location:'.WWW_TOP.'/role-list.php'); - $_POST['exccat'] = (!isset($_POST['exccat']) || !is_array($_POST['exccat'])) ? [] : $_POST['exccat']; - $page->users->addRoleCategoryExclusions($_POST['id'], $_POST['exccat']); + $_POST['exccat'] = (! isset($_POST['exccat']) || ! is_array($_POST['exccat'])) ? [] : $_POST['exccat']; + $page->users->addRoleCategoryExclusions($_POST['id'], $_POST['exccat']); } $page->smarty->assign('role', $role); break; @@ -50,17 +50,17 @@ switch ($_REQUEST['action'] ?? 'view') { case 'view': default: if (isset($_GET['id'])) { - $page->title = 'User Roles Edit'; - $role = $page->users->getRoleById($_GET['id']); - $page->smarty->assign('role', $role); - $page->smarty->assign('roleexccat', $page->users->getRoleCategoryExclusion($_GET['id'])); + $page->title = 'User Roles Edit'; + $role = $page->users->getRoleById($_GET['id']); + $page->smarty->assign('role', $role); + $page->smarty->assign('roleexccat', $page->users->getRoleCategoryExclusion($_GET['id'])); } break; } $page->smarty->assign('yesno_ids', [1, 0]); $page->smarty->assign('yesno_names', ['Yes', 'No']); -$page->smarty->assign('catlist',$category->getForSelect(false)); +$page->smarty->assign('catlist', $category->getForSelect(false)); $page->content = $page->smarty->fetch('role-edit.tpl'); $page->render(); diff --git a/public/admin/role-list.php b/public/admin/role-list.php index 19d8bafce..5c83d7c36 100644 --- a/public/admin/role-list.php +++ b/public/admin/role-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Users; @@ -13,8 +13,7 @@ $page->title = 'User Role List'; //get the user roles $userroles = $users->getRoles(); -$page->smarty->assign('userroles',$userroles); +$page->smarty->assign('userroles', $userroles); $page->content = $page->smarty->fetch('role-list.tpl'); $page->render(); - diff --git a/public/admin/sharing.php b/public/admin/sharing.php index 446d55f1e..3057e3436 100644 --- a/public/admin/sharing.php +++ b/public/admin/sharing.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\db\DB; @@ -13,40 +13,40 @@ $offset = $_GET['offset'] ?? 0; $allSites = $db->query(sprintf('SELECT * FROM sharing_sites ORDER BY id LIMIT %d OFFSET %d', 25, $offset)); if (count($allSites) === 0) { - $allSites = false; + $allSites = false; } $ourSite = $db->queryOneRow('SELECT * FROM sharing'); -if (!empty($_POST)) { - if (!empty($_POST['sharing_name']) && !preg_match('/\s+/', $_POST['sharing_name']) && strlen($_POST['sharing_name']) < 255) { - $site_name = trim($_POST['sharing_name']); - } else { - $site_name = $ourSite['site_name']; - } - if (!empty($_POST['sharing_maxpush']) && is_numeric($_POST['sharing_maxpush'])) { - $max_push = trim($_POST['sharing_maxpush']); - } else { - $max_push = $ourSite['max_push']; - } - if (!empty($_POST['sharing_maxpull']) && is_numeric($_POST['sharing_maxpush'])) { - $max_pull = trim($_POST['sharing_maxpull']); - } else { - $max_pull = $ourSite['max_pull']; - } - if (!empty($_POST['sharing_maxdownload']) && is_numeric($_POST['sharing_maxdownload'])) { - $max_download = trim($_POST['sharing_maxdownload']); - } else { - $max_download = $ourSite['max_download']; - } - $db->queryExec( +if (! empty($_POST)) { + if (! empty($_POST['sharing_name']) && ! preg_match('/\s+/', $_POST['sharing_name']) && strlen($_POST['sharing_name']) < 255) { + $site_name = trim($_POST['sharing_name']); + } else { + $site_name = $ourSite['site_name']; + } + if (! empty($_POST['sharing_maxpush']) && is_numeric($_POST['sharing_maxpush'])) { + $max_push = trim($_POST['sharing_maxpush']); + } else { + $max_push = $ourSite['max_push']; + } + if (! empty($_POST['sharing_maxpull']) && is_numeric($_POST['sharing_maxpush'])) { + $max_pull = trim($_POST['sharing_maxpull']); + } else { + $max_pull = $ourSite['max_pull']; + } + if (! empty($_POST['sharing_maxdownload']) && is_numeric($_POST['sharing_maxdownload'])) { + $max_download = trim($_POST['sharing_maxdownload']); + } else { + $max_download = $ourSite['max_download']; + } + $db->queryExec( sprintf(' UPDATE sharing SET site_name = %s, max_push = %d, max_pull = %d, max_download = %d', $db->escapeString($site_name), $max_push, $max_pull, $max_download ) ); - $ourSite = $db->queryOneRow('SELECT * FROM sharing'); + $ourSite = $db->queryOneRow('SELECT * FROM sharing'); } $total = $db->queryOneRow('SELECT COUNT(id) AS total FROM sharing_sites'); @@ -54,12 +54,12 @@ $total = $db->queryOneRow('SELECT COUNT(id) AS total FROM sharing_sites'); $page->smarty->assign('pagertotalitems', ($total === false ? 0 : $total['total'])); $page->smarty->assign('pageroffset', $offset); $page->smarty->assign('pageritemsperpage', 25); -$page->smarty->assign('pagerquerybase', WWW_TOP . '/sharing.php?offset='); +$page->smarty->assign('pagerquerybase', WWW_TOP.'/sharing.php?offset='); $pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); -$page->smarty->assign(array('local' => $ourSite, 'sites' => $allSites)); +$page->smarty->assign(['local' => $ourSite, 'sites' => $allSites]); $page->content = $page->smarty->fetch('sharing.tpl'); $page->render(); diff --git a/public/admin/show-delete.php b/public/admin/show-delete.php index 7a95e6492..d481b4d79 100755 --- a/public/admin/show-delete.php +++ b/public/admin/show-delete.php @@ -1,13 +1,13 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; -require_once NN_WWW . 'pages/smartyTV.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; +require_once NN_WWW.'pages/smartyTV.php'; $page = new AdminPage(); if (isset($_GET['id'])) { - (new smartyTV(['Settings' => $page->settings]))->delete($_GET['id']); + (new smartyTV(['Settings' => $page->settings]))->delete($_GET['id']); } $referrer = $_SERVER['HTTP_REFERER']; -header("Location: " . $referrer); +header('Location: '.$referrer); diff --git a/public/admin/show-edit.php b/public/admin/show-edit.php index 614a7a6c6..9c314e827 100755 --- a/public/admin/show-edit.php +++ b/public/admin/show-edit.php @@ -1,11 +1,11 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; -require_once NN_WWW . 'pages/smartyTV.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; +require_once NN_WWW.'pages/smartyTV.php'; use nntmux\Videos; -$page = new AdminPage(); +$page = new AdminPage(); $tv = new smartyTV(['Settings' => $page->settings]); $video = new Videos(['Settings' => $page->settings]); @@ -14,25 +14,25 @@ switch ($_REQUEST['action'] ?? 'view') { //TODO: Use a function that allows overwrites //$tv->update($_POST["id"], $_POST["title"],$_POST["summary"], $_POST['countries_id']); - if (isset($_POST['from']) && !empty($_POST['from'])) { - header('Location:' . $_POST['from']); - exit; + if (isset($_POST['from']) && ! empty($_POST['from'])) { + header('Location:'.$_POST['from']); + exit; } - header('Location:' . WWW_TOP . '/show-list.php'); + header('Location:'.WWW_TOP.'/show-list.php'); break; case 'view': default: if (isset($_GET['id'])) { - $page->title = 'TV Show Edit'; - $show = $video->getByVideoID($_GET['id']); + $page->title = 'TV Show Edit'; + $show = $video->getByVideoID($_GET['id']); } break; } $page->smarty->assign('show', $show); -$page->title = 'Edit TV Show Data'; +$page->title = 'Edit TV Show Data'; $page->content = $page->smarty->fetch('show-edit.tpl'); $page->render(); diff --git a/public/admin/show-list.php b/public/admin/show-list.php index 9fe9a5a70..5ca9be637 100755 --- a/public/admin/show-list.php +++ b/public/admin/show-list.php @@ -1,16 +1,16 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Videos; -$page = new AdminPage(); +$page = new AdminPage(); $tv = new Videos(['Settings' => $page->settings]); -$page->title = "TV Shows List"; +$page->title = 'TV Shows List'; -$tvshowname = (isset($_REQUEST['showname']) && !empty($_REQUEST['showname']) ? $_REQUEST['showname'] : ''); -$offset = isset($_REQUEST["offset"]) ? $_REQUEST["offset"] : 0; +$tvshowname = (isset($_REQUEST['showname']) && ! empty($_REQUEST['showname']) ? $_REQUEST['showname'] : ''); +$offset = isset($_REQUEST['offset']) ? $_REQUEST['offset'] : 0; $page->smarty->assign([ 'showname' => $tvshowname, @@ -19,12 +19,12 @@ $page->smarty->assign([ 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, 'pagerquerysuffix' => '', - 'pagerquerybase' => (WWW_TOP . "/show-list.php?" . - ($tvshowname != '' ? 'showname=' . $tvshowname . '&' : '') . "&offset=" - ) + 'pagerquerybase' => (WWW_TOP.'/show-list.php?'. + ($tvshowname != '' ? 'showname='.$tvshowname.'&' : '').'&offset=' + ), ] ); -$page->smarty->assign('pager', $page->smarty->fetch("pager.tpl")); +$page->smarty->assign('pager', $page->smarty->fetch('pager.tpl')); $page->content = $page->smarty->fetch('show-list.tpl'); $page->render(); diff --git a/public/admin/show-remove.php b/public/admin/show-remove.php index 6eb01b778..3fb4f91a0 100755 --- a/public/admin/show-remove.php +++ b/public/admin/show-remove.php @@ -1,21 +1,21 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Releases; -$page = new AdminPage(); +$page = new AdminPage(); $releases = new Releases(['Settings' => $page->settings]); $success = false; -if (isset($_GET["id"])) { - $success = $releases->removeVideoIdFromReleases($_GET["id"]); - $page->smarty->assign('videoid', $_GET["id"]); +if (isset($_GET['id'])) { + $success = $releases->removeVideoIdFromReleases($_GET['id']); + $page->smarty->assign('videoid', $_GET['id']); } $page->smarty->assign('success', $success); -$page->title = "Remove Video and Episode IDs from Releases"; +$page->title = 'Remove Video and Episode IDs from Releases'; $page->content = $page->smarty->fetch('show-remove.tpl'); $page->render(); diff --git a/public/admin/site-edit.php b/public/admin/site-edit.php index 74adfa5f9..1127f6a23 100644 --- a/public/admin/site-edit.php +++ b/public/admin/site-edit.php @@ -1,11 +1,11 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; -use App\Models\Settings; -use nntmux\Category; -use nntmux\SABnzbd; use nntmux\Sites; +use nntmux\SABnzbd; +use nntmux\Category; +use App\Models\Settings; use nntmux\utility\Utility; $category = new Category(); @@ -16,66 +16,62 @@ $id = 0; // set the current action $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; -switch($action) -{ +switch ($action) { case 'submit': - if (!empty($_POST['book_reqids'])) { - // book_reqids is an array it needs to be a comma separated string, make it so. - $_POST['book_reqids'] = is_array($_POST['book_reqids']) ? + if (! empty($_POST['book_reqids'])) { + // book_reqids is an array it needs to be a comma separated string, make it so. + $_POST['book_reqids'] = is_array($_POST['book_reqids']) ? implode(', ', $_POST['book_reqids']) : $_POST['book_reqids']; } - $error = ""; + $error = ''; $ret = $page->settings->settingsUpdate($_POST); - if (is_int($ret)) - { - if ($ret == Settings::ERR_BADUNRARPATH) - $error = "The unrar path does not point to a valid binary"; - elseif ($ret == Settings::ERR_BADFFMPEGPATH) - $error = "The ffmpeg path does not point to a valid binary"; - elseif ($ret == Settings::ERR_BADMEDIAINFOPATH) - $error = "The mediainfo path does not point to a valid binary"; - elseif ($ret == Settings::ERR_BADNZBPATH) - $error = "The nzb path does not point to a valid directory"; - elseif ($ret == Settings::ERR_DEEPNOUNRAR) - $error = "Deep password check requires a valid path to unrar binary"; - elseif ($ret == Settings::ERR_BADTMPUNRARPATH) - $error = "The temp unrar path is not a valid directory"; - elseif ($ret == Sites::ERR_BADLAMEPATH) - $error = "The lame path is not a valid directory"; - elseif ($ret == Sites::ERR_SABCOMPLETEPATH) - $error = "The sab complete path is not a valid directory"; + if (is_int($ret)) { + if ($ret == Settings::ERR_BADUNRARPATH) { + $error = 'The unrar path does not point to a valid binary'; + } elseif ($ret == Settings::ERR_BADFFMPEGPATH) { + $error = 'The ffmpeg path does not point to a valid binary'; + } elseif ($ret == Settings::ERR_BADMEDIAINFOPATH) { + $error = 'The mediainfo path does not point to a valid binary'; + } elseif ($ret == Settings::ERR_BADNZBPATH) { + $error = 'The nzb path does not point to a valid directory'; + } elseif ($ret == Settings::ERR_DEEPNOUNRAR) { + $error = 'Deep password check requires a valid path to unrar binary'; + } elseif ($ret == Settings::ERR_BADTMPUNRARPATH) { + $error = 'The temp unrar path is not a valid directory'; + } elseif ($ret == Sites::ERR_BADLAMEPATH) { + $error = 'The lame path is not a valid directory'; + } elseif ($ret == Sites::ERR_SABCOMPLETEPATH) { + $error = 'The sab complete path is not a valid directory'; + } } - if ($error == "") - { - $site = $ret; - $returnid = $site['id']; - header("Location:".WWW_TOP."/site-edit.php?id=".$returnid); - } - else - { - $page->smarty->assign('error', $error); - $site = $sites->row2Object($_POST); - $page->smarty->assign('site', $site); + if ($error == '') { + $site = $ret; + $returnid = $site['id']; + header('Location:'.WWW_TOP.'/site-edit.php?id='.$returnid); + } else { + $page->smarty->assign('error', $error); + $site = $sites->row2Object($_POST); + $page->smarty->assign('site', $site); } break; case 'view': default: - $page->title = "Site Edit"; - $site = $page->settings; + $page->title = 'Site Edit'; + $site = $page->settings; $page->smarty->assign('site', $site); $page->smarty->assign('settings', $site->getSettingsAsTree()); break; } -$page->smarty->assign('yesno_ids', array(1,0)); -$page->smarty->assign('yesno_names', array( 'Yes', 'No')); +$page->smarty->assign('yesno_ids', [1, 0]); +$page->smarty->assign('yesno_names', ['Yes', 'No']); -$page->smarty->assign('passwd_ids', array(1,0)); -$page->smarty->assign('passwd_names', array( 'Deep (requires unrar)', 'None')); +$page->smarty->assign('passwd_ids', [1, 0]); +$page->smarty->assign('passwd_names', ['Deep (requires unrar)', 'None']); /*0 = English, 2 = Danish, 3 = French, 1 = German*/ $page->smarty->assign('langlist_ids', [0, 2, 3, 1]); @@ -84,63 +80,63 @@ $page->smarty->assign('langlist_names', ['English', 'Danish', 'French', 'German' $page->smarty->assign('imdblang_ids', [ 'en', 'da', 'nl', 'fi', 'fr', 'de', 'it', 'tlh', 'no', 'po', 'ru', 'es', - 'sv' + 'sv', ]); $page->smarty->assign('imdblang_names', [ 'English', 'Danish', 'Dutch', 'Finnish', 'French', 'German', 'Italian', - 'Klingon', 'Norwegian', 'Polish', 'Russian', 'Spanish', 'Swedish' + 'Klingon', 'Norwegian', 'Polish', 'Russian', 'Spanish', 'Swedish', ]); -$page->smarty->assign('sabintegrationtype_ids', array(SABnzbd::INTEGRATION_TYPE_USER, SABnzbd::INTEGRATION_TYPE_SITEWIDE, SABnzbd::INTEGRATION_TYPE_NONE)); -$page->smarty->assign('sabintegrationtype_names', array( 'User', 'Site-wide', 'None (Off)')); +$page->smarty->assign('sabintegrationtype_ids', [SABnzbd::INTEGRATION_TYPE_USER, SABnzbd::INTEGRATION_TYPE_SITEWIDE, SABnzbd::INTEGRATION_TYPE_NONE]); +$page->smarty->assign('sabintegrationtype_names', ['User', 'Site-wide', 'None (Off)']); -$page->smarty->assign('sabapikeytype_ids', array(SABnzbd::API_TYPE_NZB,SABnzbd::API_TYPE_FULL)); -$page->smarty->assign('sabapikeytype_names', array( 'Nzb Api Key', 'Full Api Key')); +$page->smarty->assign('sabapikeytype_ids', [SABnzbd::API_TYPE_NZB, SABnzbd::API_TYPE_FULL]); +$page->smarty->assign('sabapikeytype_names', ['Nzb Api Key', 'Full Api Key']); -$page->smarty->assign('sabpriority_ids', array(SABnzbd::PRIORITY_FORCE, SABnzbd::PRIORITY_HIGH, SABnzbd::PRIORITY_NORMAL, SABnzbd::PRIORITY_LOW)); -$page->smarty->assign('sabpriority_names', array( 'Force', 'High', 'Normal', 'Low')); +$page->smarty->assign('sabpriority_ids', [SABnzbd::PRIORITY_FORCE, SABnzbd::PRIORITY_HIGH, SABnzbd::PRIORITY_NORMAL, SABnzbd::PRIORITY_LOW]); +$page->smarty->assign('sabpriority_names', ['Force', 'High', 'Normal', 'Low']); -$page->smarty->assign('curlproxytype_names', array( '', 'HTTP', 'SOCKS5')); +$page->smarty->assign('curlproxytype_names', ['', 'HTTP', 'SOCKS5']); -$page->smarty->assign('newgroupscan_names', array('Days','Posts')); +$page->smarty->assign('newgroupscan_names', ['Days', 'Posts']); -$page->smarty->assign('registerstatus_ids', array(Settings::REGISTER_STATUS_API_ONLY, Settings::REGISTER_STATUS_OPEN, Settings::REGISTER_STATUS_INVITE, Settings::REGISTER_STATUS_CLOSED)); -$page->smarty->assign('registerstatus_names', array('API Only', 'Open', 'Invite', 'Closed')); +$page->smarty->assign('registerstatus_ids', [Settings::REGISTER_STATUS_API_ONLY, Settings::REGISTER_STATUS_OPEN, Settings::REGISTER_STATUS_INVITE, Settings::REGISTER_STATUS_CLOSED]); +$page->smarty->assign('registerstatus_names', ['API Only', 'Open', 'Invite', 'Closed']); -$page->smarty->assign('passworded_ids', array(0,1,2)); +$page->smarty->assign('passworded_ids', [0, 1, 2]); $page->smarty->assign('passworded_names', [ 'Hide passworded or potentially passworded (*yes)', 'Hide passworded or potentially passworded (*no)', 'Show non-passworded and potentially passworded (*no)', - 'Show everything (*no)' + 'Show everything (*no)', ]); -$page->smarty->assign('sphinxrebuildfreqday_days', array('', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')); +$page->smarty->assign('sphinxrebuildfreqday_days', ['', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']); -$page->smarty->assign('lookuplanguage_iso', array('en', 'de', 'es', 'fr', 'it', 'nl', 'pt', 'sv')); -$page->smarty->assign('lookuplanguage_names', array('English', 'Deutsch', 'Español', 'Français', 'Italiano', 'Nederlands', 'Português', 'Svenska')); +$page->smarty->assign('lookuplanguage_iso', ['en', 'de', 'es', 'fr', 'it', 'nl', 'pt', 'sv']); +$page->smarty->assign('lookuplanguage_names', ['English', 'Deutsch', 'Español', 'Français', 'Italiano', 'Nederlands', 'Português', 'Svenska']); -$page->smarty->assign('imdb_urls', array(0,1)); -$page->smarty->assign('imdburl_names', array('imdb.com', 'akas.imdb.com')); +$page->smarty->assign('imdb_urls', [0, 1]); +$page->smarty->assign('imdburl_names', ['imdb.com', 'akas.imdb.com']); -$page->smarty->assign('lookupbooks_ids', [0,1,2]); +$page->smarty->assign('lookupbooks_ids', [0, 1, 2]); $page->smarty->assign('lookupbooks_names', ['Disabled', 'Lookup All Books', 'Lookup Renamed Books']); -$page->smarty->assign('lookupgames_ids', [0,1,2]); +$page->smarty->assign('lookupgames_ids', [0, 1, 2]); $page->smarty->assign('lookupgames_names', ['Disabled', 'Lookup All Consoles', 'Lookup Renamed Consoles']); -$page->smarty->assign('lookupmusic_ids', [0,1,2]); +$page->smarty->assign('lookupmusic_ids', [0, 1, 2]); $page->smarty->assign('lookupmusic_names', ['Disabled', 'Lookup All Music', 'Lookup Renamed Music']); -$page->smarty->assign('lookupmovies_ids', [0,1,2]); +$page->smarty->assign('lookupmovies_ids', [0, 1, 2]); $page->smarty->assign('lookupmovies_names', ['Disabled', 'Lookup All Movies', 'Lookup Renamed Movies']); -$page->smarty->assign('lookuptv_ids', [0,1,2]); +$page->smarty->assign('lookuptv_ids', [0, 1, 2]); $page->smarty->assign('lookuptv_names', ['Disabled', 'Lookup All TV', 'Lookup Renamed TV']); -$page->smarty->assign('lookup_reqids_ids', array(0,1,2)); -$page->smarty->assign('lookup_reqids_names', array('Disabled', 'Lookup Request IDs', 'Lookup Request IDs Threaded')); +$page->smarty->assign('lookup_reqids_ids', [0, 1, 2]); +$page->smarty->assign('lookup_reqids_names', ['Disabled', 'Lookup Request IDs', 'Lookup Request IDs Threaded']); $page->smarty->assign('coversPath', NN_COVERS); @@ -150,10 +146,9 @@ $result = $page->settings->query("SELECT id, title FROM categories WHERE id IN ( // setup the display lists for these categories, this could have been static, but then if names changed they would be wrong $book_reqids_ids = []; $book_reqids_names = []; -foreach ($result as $bookcategory) -{ - $book_reqids_ids[] = $bookcategory["id"]; - $book_reqids_names[] = $bookcategory["title"]; +foreach ($result as $bookcategory) { + $book_reqids_ids[] = $bookcategory['id']; + $book_reqids_names[] = $bookcategory['title']; } // convert from a string array to an int array as we want to use int @@ -162,7 +157,7 @@ $page->smarty->assign('book_reqids_ids', $book_reqids_ids); $page->smarty->assign('book_reqids_names', $book_reqids_names); // convert from a list to an array as we need to use an array, but teh Settings table only saves strings -$books_selected = explode(",", Settings::value('..book_reqids')); +$books_selected = explode(',', Settings::value('..book_reqids')); // convert from a string array to an int array $books_selected = array_map(create_function('$value', 'return (int)$value;'), $books_selected); @@ -170,8 +165,8 @@ $page->smarty->assign('book_reqids_selected', $books_selected); $page->smarty->assign('themelist', Utility::getThemesList()); -if (strpos(env('NNTP_SERVER'), "astra") === false) { - $page->smarty->assign('compress_headers_warning', "compress_headers_warning"); +if (strpos(env('NNTP_SERVER'), 'astra') === false) { + $page->smarty->assign('compress_headers_warning', 'compress_headers_warning'); } $page->content = $page->smarty->fetch('site-edit.tpl'); diff --git a/public/admin/site-stats.php b/public/admin/site-stats.php index 377e5f722..be6560cd3 100644 --- a/public/admin/site-stats.php +++ b/public/admin/site-stats.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Users; use nntmux\Releases; @@ -9,7 +9,7 @@ $page = new AdminPage(); $users = new Users(); $releases = new Releases(); -$page->title = "Site Stats"; +$page->title = 'Site Stats'; $topgrabs = $users->getTopGrabbers(); $page->smarty->assign('topgrabs', $topgrabs); @@ -39,4 +39,3 @@ $page->smarty->assign('loginsbymonth', $loginsbymonth); $page->content = $page->smarty->fetch('site-stats.tpl'); $page->render(); - diff --git a/public/admin/spotnab-delete.php b/public/admin/spotnab-delete.php index 0e7e346ce..13271aaea 100644 --- a/public/admin/spotnab-delete.php +++ b/public/admin/spotnab-delete.php @@ -1,17 +1,15 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\SpotNab; $page = new AdminPage(); -if (isset($_GET['id'])) -{ - $spotnab = new SpotNab(); - $spotnab->deleteSource($_GET['id']); +if (isset($_GET['id'])) { + $spotnab = new SpotNab(); + $spotnab->deleteSource($_GET['id']); } $referrer = $_SERVER['HTTP_REFERER']; -header("Location: " . $referrer); - +header('Location: '.$referrer); diff --git a/public/admin/spotnab-edit.php b/public/admin/spotnab-edit.php index 9d23090aa..37cb31c16 100644 --- a/public/admin/spotnab-edit.php +++ b/public/admin/spotnab-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\SpotNab; @@ -11,42 +11,37 @@ $id = 0; // set the current action $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'view'; -switch($action) -{ +switch ($action) { case 'add': - $page->title = "Spotnab Source Add"; + $page->title = 'Spotnab Source Add'; $source = []; - $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"] = ''; + $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"); + 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'); } - 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); + if (isset($_GET['id'])) { + $page->title = 'Spotnab Source Edit'; + $id = $_GET['id']; + $source = $spotnab->getSourceByID($id); + $page->smarty->assign('source', $source); } break; @@ -54,4 +49,3 @@ switch($action) $page->content = $page->smarty->fetch('spotnab-edit.tpl'); $page->render(); - diff --git a/public/admin/spotnab-list.php b/public/admin/spotnab-list.php index e9512060e..f2b343d0c 100644 --- a/public/admin/spotnab-list.php +++ b/public/admin/spotnab-list.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\SpotNab; @@ -11,15 +11,15 @@ $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"]); +if ((isset($_GET['toggle'])) && (isset($_GET['id']))) { + $spotnab->toggleSource($_GET['id'], $_GET['toggle']); } -$page->title = "Spotnab Sources List"; +$page->title = 'Spotnab Sources List'; //get the list of Sources $spotnab = $spotnab->getSources(); -$page->smarty->assign('spotnab',$spotnab); +$page->smarty->assign('spotnab', $spotnab); $page->content = $page->smarty->fetch('spotnab-list.tpl'); $page->render(); diff --git a/public/admin/tmux-edit.php b/public/admin/tmux-edit.php index b8e2746fe..d82fe43d0 100644 --- a/public/admin/tmux-edit.php +++ b/public/admin/tmux-edit.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Tmux; @@ -11,8 +11,7 @@ $id = 0; // Set the current action. $action = $_REQUEST['action'] ?? 'view'; -switch($action) -{ +switch ($action) { case 'submit': $error = ''; $ret = $tmux->update($_POST); @@ -29,36 +28,35 @@ switch($action) break; } -$page->smarty->assign('yesno_ids', array(1, 0)); -$page->smarty->assign('yesno_names', array('yes', 'no')); - -$page->smarty->assign('backfill_ids', array(0,4,1)); -$page->smarty->assign('backfill_names', array('Disabled', 'Safe', 'All')); -$page->smarty->assign('backfill_group_ids', array(1,2,3,4,5,6)); -$page->smarty->assign('backfill_group', array('Newest', 'Oldest', 'Alphabetical', 'Alphabetical - Reverse', 'Most Posts', 'Fewest Posts')); -$page->smarty->assign('backfill_days', array('Days per Group', 'Safe Backfill day')); -$page->smarty->assign('backfill_days_ids', array(1,2)); -$page->smarty->assign('dehash_ids', array(0,1,2,3)); -$page->smarty->assign('dehash_names', array('Disabled', 'Decrypt Hashes', 'Predb', 'All')); -$page->smarty->assign('import_ids', array(0,1,2)); -$page->smarty->assign('import_names', array('Disabled', 'Import - Do Not Use Filenames', 'Import - Use Filenames')); -$page->smarty->assign('releases_ids', array(0,1)); -$page->smarty->assign('releases_names', array('Disabled', 'Update Releases')); -$page->smarty->assign('post_ids', array(0,1,2,3)); -$page->smarty->assign('post_names', array('Disabled', 'PostProcess Additional', 'PostProcess NFOs', 'All')); -$page->smarty->assign('fix_crap_radio_ids', array('Disabled', 'All', 'Custom')); -$page->smarty->assign('fix_crap_radio_names', array('Disabled', 'All', 'Custom')); -$page->smarty->assign('fix_crap_check_ids', array('blacklist', 'blfiles', 'executable', 'gibberish', 'hashed', 'installbin', 'passworded', 'passwordurl', 'sample', 'scr', 'short', 'size', 'huge', 'nzb', 'codec')); -$page->smarty->assign('fix_crap_check_names', array('blacklist', 'blfiles', 'executable', 'gibberish', 'hashed', 'installbin', 'passworded', 'passwordurl', 'sample', 'scr', 'short', 'size', 'huge', 'nzb', 'codec')); -$page->smarty->assign('sequential_ids', array(0,1,2)); -$page->smarty->assign('sequential_names', array('Disabled', 'Basic Sequential', 'Complete Sequential')); -$page->smarty->assign('binaries_ids', array(0,1,2)); -$page->smarty->assign('binaries_names', array('Disabled', 'Simple Threaded Update', 'Complete Threaded Update')); -$page->smarty->assign('lookup_reqids_ids', array(0,1,2)); -$page->smarty->assign('lookup_reqids_names', array('Disabled', 'Lookup Request IDs', 'Lookup Request IDs Threaded')); -$page->smarty->assign('predb_ids', array(0,1)); -$page->smarty->assign('predb_names', array('Disabled', 'Enabled')); +$page->smarty->assign('yesno_ids', [1, 0]); +$page->smarty->assign('yesno_names', ['yes', 'no']); +$page->smarty->assign('backfill_ids', [0, 4, 1]); +$page->smarty->assign('backfill_names', ['Disabled', 'Safe', 'All']); +$page->smarty->assign('backfill_group_ids', [1, 2, 3, 4, 5, 6]); +$page->smarty->assign('backfill_group', ['Newest', 'Oldest', 'Alphabetical', 'Alphabetical - Reverse', 'Most Posts', 'Fewest Posts']); +$page->smarty->assign('backfill_days', ['Days per Group', 'Safe Backfill day']); +$page->smarty->assign('backfill_days_ids', [1, 2]); +$page->smarty->assign('dehash_ids', [0, 1, 2, 3]); +$page->smarty->assign('dehash_names', ['Disabled', 'Decrypt Hashes', 'Predb', 'All']); +$page->smarty->assign('import_ids', [0, 1, 2]); +$page->smarty->assign('import_names', ['Disabled', 'Import - Do Not Use Filenames', 'Import - Use Filenames']); +$page->smarty->assign('releases_ids', [0, 1]); +$page->smarty->assign('releases_names', ['Disabled', 'Update Releases']); +$page->smarty->assign('post_ids', [0, 1, 2, 3]); +$page->smarty->assign('post_names', ['Disabled', 'PostProcess Additional', 'PostProcess NFOs', 'All']); +$page->smarty->assign('fix_crap_radio_ids', ['Disabled', 'All', 'Custom']); +$page->smarty->assign('fix_crap_radio_names', ['Disabled', 'All', 'Custom']); +$page->smarty->assign('fix_crap_check_ids', ['blacklist', 'blfiles', 'executable', 'gibberish', 'hashed', 'installbin', 'passworded', 'passwordurl', 'sample', 'scr', 'short', 'size', 'huge', 'nzb', 'codec']); +$page->smarty->assign('fix_crap_check_names', ['blacklist', 'blfiles', 'executable', 'gibberish', 'hashed', 'installbin', 'passworded', 'passwordurl', 'sample', 'scr', 'short', 'size', 'huge', 'nzb', 'codec']); +$page->smarty->assign('sequential_ids', [0, 1, 2]); +$page->smarty->assign('sequential_names', ['Disabled', 'Basic Sequential', 'Complete Sequential']); +$page->smarty->assign('binaries_ids', [0, 1, 2]); +$page->smarty->assign('binaries_names', ['Disabled', 'Simple Threaded Update', 'Complete Threaded Update']); +$page->smarty->assign('lookup_reqids_ids', [0, 1, 2]); +$page->smarty->assign('lookup_reqids_names', ['Disabled', 'Lookup Request IDs', 'Lookup Request IDs Threaded']); +$page->smarty->assign('predb_ids', [0, 1]); +$page->smarty->assign('predb_names', ['Disabled', 'Enabled']); $page->content = $page->smarty->fetch('tmux-edit.tpl'); $page->render(); diff --git a/public/admin/user-delete.php b/public/admin/user-delete.php index a99115f7f..969964073 100644 --- a/public/admin/user-delete.php +++ b/public/admin/user-delete.php @@ -1,23 +1,19 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Users; $page = new AdminPage(); -if (isset($_GET['id'])) -{ - $users = new Users(); - $users->delete($_GET['id']); +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); +if (isset($_GET['redir'])) { + header('Location: '.$_GET['redir']); +} else { + $referrer = $_SERVER['HTTP_REFERER']; + header('Location: '.$referrer); } diff --git a/public/admin/user-edit.php b/public/admin/user-edit.php index 9d17330ae..b3370393c 100644 --- a/public/admin/user-edit.php +++ b/public/admin/user-edit.php @@ -1,10 +1,10 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; +use nntmux\Users; use App\Models\Settings; use App\Models\UserRole; -use nntmux\Users; use nntmux\utility\Utility; $page = new AdminPage(); @@ -16,7 +16,7 @@ $user = [ 'email' => '', 'password' => '', 'role' => Users::ROLE_USER, - 'notes' => '' + 'notes' => '', ]; // set the current action @@ -28,16 +28,16 @@ $roles = []; $defaultRole = Users::ROLE_USER; $defaultInvites = Users::DEFAULT_INVITES; foreach ($userRoles as $r) { - $roles[$r['id']] = $r['name']; - if ($r['isdefault'] === 1) { - $defaultrole = $r['id']; - $defaultinvites = $r['defaultinvites']; - } + $roles[$r['id']] = $r['name']; + if ($r['isdefault'] === 1) { + $defaultrole = $r['id']; + $defaultinvites = $r['defaultinvites']; + } } switch ($action) { case 'add': - $user += [ + $user += [ 'role' => $defaultRole, 'notes' => '', 'invites' => $defaultInvites, @@ -46,39 +46,39 @@ switch ($action) { 'musicview' => 0, 'consoleview' => 0, 'gameview' => 0, - 'bookview' => 0 + 'bookview' => 0, ]; $page->smarty->assign('user', $user); break; case 'submit': if (empty($_POST['id'])) { - $invites = $defaultInvites; - foreach ($userRoles as $role) { - if ($role['id'] === $_POST['role']) { - $invites = $role['defaultinvites']; - } - } - $ret = $users->signup($_POST['username'], $_POST['password'], $_POST['email'], '', $_POST['role'], $_POST['notes'], $invites, '', true); - $page->smarty->assign('role', $_POST['role']); + $invites = $defaultInvites; + foreach ($userRoles as $role) { + if ($role['id'] === $_POST['role']) { + $invites = $role['defaultinvites']; + } + } + $ret = $users->signup($_POST['username'], $_POST['password'], $_POST['email'], '', $_POST['role'], $_POST['notes'], $invites, '', true); + $page->smarty->assign('role', $_POST['role']); } else { - $ret = $users->update($_POST['id'], $_POST['username'], $_POST['email'], $_POST['grabs'], $_POST['role'], $_POST['notes'], $_POST['invites'], (isset($_POST['movieview']) ? 1 : 0), (isset($_POST['musicview']) ? 1 : 0), (isset($_POST['gameview']) ? 1 : 0), (isset($_POST['xxxview']) ? 1 : 0), (isset($_POST['consoleview']) ? 1 : 0), (isset($_POST['bookview']) ? 1 : 0)); - if ($_POST['password'] !== '') { - $users->updatePassword($_POST['id'], $_POST['password']); - } - if ($_POST['rolechangedate'] !== '') { - $users->updateUserRoleChangeDate($_POST['id'], $_POST['rolechangedate']); - } - if ($_POST['role'] !== '') { - $newRole = UserRole::query()->where('id', $_POST['role'])->value('name'); - $email = $_POST['email'] ?? $_GET['email']; - Utility::sendEmail($email, 'Account changed', 'Your account role has been changed to ' . $newRole, Settings::value('site.main.email')); - } + $ret = $users->update($_POST['id'], $_POST['username'], $_POST['email'], $_POST['grabs'], $_POST['role'], $_POST['notes'], $_POST['invites'], (isset($_POST['movieview']) ? 1 : 0), (isset($_POST['musicview']) ? 1 : 0), (isset($_POST['gameview']) ? 1 : 0), (isset($_POST['xxxview']) ? 1 : 0), (isset($_POST['consoleview']) ? 1 : 0), (isset($_POST['bookview']) ? 1 : 0)); + if ($_POST['password'] !== '') { + $users->updatePassword($_POST['id'], $_POST['password']); + } + if ($_POST['rolechangedate'] !== '') { + $users->updateUserRoleChangeDate($_POST['id'], $_POST['rolechangedate']); + } + if ($_POST['role'] !== '') { + $newRole = UserRole::query()->where('id', $_POST['role'])->value('name'); + $email = $_POST['email'] ?? $_GET['email']; + Utility::sendEmail($email, 'Account changed', 'Your account role has been changed to '.$newRole, Settings::value('site.main.email')); + } } if ($ret >= 0) { - header('Location:' . WWW_TOP . '/user-list.php'); + header('Location:'.WWW_TOP.'/user-list.php'); } else { - switch ($ret) { + switch ($ret) { case Users::ERR_SIGNUP_BADUNAME: $page->smarty->assign('error', 'Bad username. Try a better one.'); break; @@ -98,32 +98,32 @@ switch ($action) { $page->smarty->assign('error', 'Unknown save error.'); break; } - $user += [ + $user += [ 'id' => $_POST['id'], 'username' => $_POST['username'], 'email' => $_POST['email'], 'role' => $_POST['role'], - 'notes' => $_POST['notes'] + 'notes' => $_POST['notes'], ]; - $page->smarty->assign('user', $user); + $page->smarty->assign('user', $user); } break; case 'view': default: if (isset($_GET['id'])) { - $page->title = 'User Edit'; - $id = $_GET['id']; - $user = $users->getById($id); + $page->title = 'User Edit'; + $id = $_GET['id']; + $user = $users->getById($id); - $page->smarty->assign('user', $user); - } + $page->smarty->assign('user', $user); + } break; } -$page->smarty->assign('yesno_ids', array(1, 0)); -$page->smarty->assign('yesno_names', array('Yes', 'No')); +$page->smarty->assign('yesno_ids', [1, 0]); +$page->smarty->assign('yesno_names', ['Yes', 'No']); $page->smarty->assign('role_ids', array_keys($roles)); $page->smarty->assign('role_names', $roles); @@ -131,4 +131,3 @@ $page->smarty->assign('user', $user); $page->content = $page->smarty->fetch('user-edit.tpl'); $page->render(); - diff --git a/public/admin/user-list.php b/public/admin/user-list.php index 3ce7bcac8..d6ad4effe 100644 --- a/public/admin/user-list.php +++ b/public/admin/user-list.php @@ -1,5 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; + +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; $page = new AdminPage(); @@ -7,7 +8,7 @@ $page->title = 'User List'; $roles = []; foreach ($page->users->getRoles() as $userRole) { - $roles[$userRole['id']] = $userRole['name']; + $roles[$userRole['id']] = $userRole['name']; } $offset = $_REQUEST['offset'] ?? 0; @@ -17,7 +18,7 @@ $orderBy = isset($_REQUEST['ob']) && in_array($_REQUEST['ob'], $ordering, false) $variables = ['username' => '', 'email' => '', 'host' => '', 'role' => '']; $uSearch = ''; foreach ($variables as $key => $variable) { - checkREQUEST($key); + checkREQUEST($key); } $page->smarty->assign([ @@ -31,28 +32,29 @@ $page->smarty->assign([ 'pagertotalitems' => $page->users->getCount($variables['role']), 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => WWW_TOP . '/user-list.php?ob=' . $orderBy . $uSearch . '&offset=', + 'pagerquerybase' => WWW_TOP.'/user-list.php?ob='.$orderBy.$uSearch.'&offset=', 'userlist' => $page->users->getRange( $offset, ITEMS_PER_PAGE, $orderBy, $variables['username'], $variables['email'], $variables['host'], $variables['role'], true - ) + ), ] ); $page->users->updateExpiredRoles('Role changed', 'Your role has expired and has been downgraded to user'); foreach ($ordering as $orderType) { - $page->smarty->assign('orderby' . $orderType, WWW_TOP . '/user-list.php?ob=' . $orderType . '&offset=0'); + $page->smarty->assign('orderby'.$orderType, WWW_TOP.'/user-list.php?ob='.$orderType.'&offset=0'); } $page->smarty->assign('pager', $page->smarty->fetch('pager.tpl')); $page->content = $page->smarty->fetch('user-list.tpl'); $page->render(); -function checkREQUEST($param) { - global $uSearch, $variables; - if (isset($_REQUEST[$param])) { - $variables[$param] = $_REQUEST[$param]; - $uSearch .= "&$param=" . $_REQUEST[$param]; - } +function checkREQUEST($param) +{ + global $uSearch, $variables; + if (isset($_REQUEST[$param])) { + $variables[$param] = $_REQUEST[$param]; + $uSearch .= "&$param=".$_REQUEST[$param]; + } } diff --git a/public/admin/view-logs.php b/public/admin/view-logs.php index a369ff468..094869ffb 100644 --- a/public/admin/view-logs.php +++ b/public/admin/view-logs.php @@ -1,6 +1,6 @@ <?php -require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'smarty.php'; +require_once dirname(__DIR__).DIRECTORY_SEPARATOR.'smarty.php'; use nntmux\Logger; @@ -16,7 +16,7 @@ $logPath = $logPath['LogPath']; $regex = false; -switch($type) { +switch ($type) { case 'info': $regex = '/\[INFO\]/'; break; @@ -42,44 +42,44 @@ switch($type) { $data = $file = false; if (is_file($logPath)) { - $file = file($logPath); + $file = file($logPath); } $total = 0; if ($file !== false) { - rsort($file); - $data = []; - foreach ($file as $line) { - $line = str_replace(array('>', '<'), '', $line); - if ($regex !== false) { - if (preg_match($regex, $line)) { - $data[] = $line; - } - } else { - $data[] = $line; - } - } - if (count($data) === 0) { - $data = false; - } else { - $total = count($data); - $data = array_slice($data, $offset, ITEMS_PER_PAGE); - } + rsort($file); + $data = []; + foreach ($file as $line) { + $line = str_replace(['>', '<'], '', $line); + if ($regex !== false) { + if (preg_match($regex, $line)) { + $data[] = $line; + } + } else { + $data[] = $line; + } + } + if (count($data) === 0) { + $data = false; + } else { + $total = count($data); + $data = array_slice($data, $offset, ITEMS_PER_PAGE); + } } $page->smarty->assign( - array( + [ 'data' => $data, 'types' => ['all', 'info', 'notice', 'warning', 'error', 'fatal', 'sql'], - 'path' => NN_WWW . 'smarty.php' - ) + 'path' => NN_WWW.'smarty.php', + ] ); $page->smarty->assign('pagertotalitems', $total); $page->smarty->assign('pageroffset', $offset); $page->smarty->assign('pageritemsperpage', ITEMS_PER_PAGE); -$page->smarty->assign('pagerquerybase', WWW_TOP . "/view-logs.php?t=" . $type . "&offset="); +$page->smarty->assign('pagerquerybase', WWW_TOP.'/view-logs.php?t='.$type.'&offset='); -$pager = $page->smarty->fetch("pager.tpl"); +$pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); $page->content = $page->smarty->fetch('view-logs.tpl'); diff --git a/public/index.php b/public/index.php index e03860027..5c4501c07 100644 --- a/public/index.php +++ b/public/index.php @@ -1,12 +1,13 @@ <?php -require_once __DIR__ . DIRECTORY_SEPARATOR . 'smarty.php'; + +require_once __DIR__.DIRECTORY_SEPARATOR.'smarty.php'; use App\Models\Settings; $page = new Page; if ($app->isDownForMaintenance()) { - $page->showMaintenance(); + $page->showMaintenance(); } switch ($page->page) { @@ -64,16 +65,16 @@ switch ($page->page) { case 'xxx': case 'xxxmodal': // Don't show these pages if it's an API-only site. - if (!$page->users->isLoggedIn() && (int)Settings::value('..registerstatus') === Settings::REGISTER_STATUS_API_ONLY) { - header('Location: ' . Settings::value('site.main.code')); - break; + if (! $page->users->isLoggedIn() && (int) Settings::value('..registerstatus') === Settings::REGISTER_STATUS_API_ONLY) { + header('Location: '.Settings::value('site.main.code')); + break; } case 'api': case 'failed': case 'getnzb': case 'login': case 'rss': - include NN_WWW . 'pages/' . $page->page . '.php'; + include NN_WWW.'pages/'.$page->page.'.php'; break; default: $page->show404(); diff --git a/public/pages/AdminPage.php b/public/pages/AdminPage.php index a7050d937..719057e96 100644 --- a/public/pages/AdminPage.php +++ b/public/pages/AdminPage.php @@ -1,54 +1,53 @@ <?php -use nntmux\Category; use nntmux\Users; +use nntmux\Category; /** * All admin pages implement this class. Enforces admin role for requesting user. */ class AdminPage extends BasePage { - /** - * Default constructor. - * - * @throws \Exception - */ - public function __construct() - { - parent::__construct(); + /** + * Default constructor. + * + * @throws \Exception + */ + public function __construct() + { + parent::__construct(); - // Tell Smarty which directories to use for templates - $this->smarty->setTemplateDir( + // Tell Smarty which directories to use for templates + $this->smarty->setTemplateDir( [ - 'admin' => NN_THEMES . 'shared/templates/admin', - 'shared' => NN_THEMES . 'shared/templates', - 'default' => NN_THEMES . 'Omicron/templates' + 'admin' => NN_THEMES.'shared/templates/admin', + 'shared' => NN_THEMES.'shared/templates', + 'default' => NN_THEMES.'Omicron/templates', ] ); - if (!isset($this->userdata['role']) || (int)$this->userdata['role'] !== Users::ROLE_ADMIN || !$this->users->isLoggedIn()) { - $this->show403(true); - } + if (! isset($this->userdata['role']) || (int) $this->userdata['role'] !== Users::ROLE_ADMIN || ! $this->users->isLoggedIn()) { + $this->show403(true); + } - $category = new Category(); - $this->smarty->assign('catClass', $category); + $category = new Category(); + $this->smarty->assign('catClass', $category); + } - } + /** + * Output a page using the admin template. + * + * @throws \Exception + */ + public function render(): void + { + $this->smarty->assign('page', $this); - /** - * Output a page using the admin template. - * - * @throws \Exception - */ - public function render(): void - { - $this->smarty->assign('page',$this); + $admin_menu = $this->smarty->fetch('adminmenu.tpl'); + $this->smarty->assign('admin_menu', $admin_menu); - $admin_menu = $this->smarty->fetch('adminmenu.tpl'); - $this->smarty->assign('admin_menu',$admin_menu); + $this->page_template = 'baseadminpage.tpl'; - $this->page_template = 'baseadminpage.tpl'; - - parent::render(); - } + parent::render(); + } } diff --git a/public/pages/BasePage.php b/public/pages/BasePage.php index 78bbe6286..2deeb9fbe 100644 --- a/public/pages/BasePage.php +++ b/public/pages/BasePage.php @@ -1,310 +1,309 @@ <?php -require_once NN_LIB . 'utility' . DS . 'SmartyUtils.php'; +require_once NN_LIB.'utility'.DS.'SmartyUtils.php'; -use App\Models\Settings; use nntmux\db\DB; -use nntmux\SABnzbd; use nntmux\Users; +use nntmux\SABnzbd; +use App\Models\Settings; class BasePage { - /** - * @var DB - */ - public $settings = null; + /** + * @var DB + */ + public $settings = null; - /** - * @var Users - */ - public $users = null; + /** + * @var Users + */ + public $users = null; - /** - * @var Smarty - */ - public $smarty = null; + /** + * @var Smarty + */ + public $smarty = null; + public $title = ''; + public $content = ''; + public $head = ''; + public $body = ''; + public $meta_keywords = ''; + public $meta_title = ''; + public $meta_description = ''; + public $secure_connection = false; + public $show_desktop_mode = false; - public $title = ''; - public $content = ''; - public $head = ''; - public $body = ''; - public $meta_keywords = ''; - public $meta_title = ''; - public $meta_description = ''; - public $secure_connection = false; - public $show_desktop_mode = false; + /** + * Current page the user is browsing. ie browse. + * + * @var string + */ + public $page = ''; - /** - * Current page the user is browsing. ie browse - * - * @var string - */ - public $page = ''; + public $page_template = ''; - public $page_template = ''; + /** + * User settings from the MySQL DB. + * + * @var array|bool + */ + public $userdata = []; - /** - * User settings from the MySQL DB. - * - * @var array|bool - */ - public $userdata = []; + /** + * URL of the server. ie http://localhost/. + * + * @var string + */ + public $serverurl = ''; - /** - * URL of the server. ie http://localhost/ - * - * @var string - */ - public $serverurl = ''; + /** + * Whether to trim white space before rendering the page or not. + * + * @var bool + */ + public $trimWhiteSpace = true; - /** - * Whether to trim white space before rendering the page or not. - * - * @var bool - */ - public $trimWhiteSpace = true; + /** + * Is the current session HTTPS? + * + * @var bool + */ + public $https = false; - /** - * Is the current session HTTPS? - * - * @var bool - */ - public $https = false; + /** + * Public access to Captcha object for error checking. + * + * @var \nntmux\Captcha + */ + public $captcha; - /** - * Public access to Captcha object for error checking. - * - * @var \nntmux\Captcha - */ - public $captcha; + /** + * User's theme. + * + * @var string + */ + protected $theme = 'Gentele'; - /** - * User's theme - * - * @var string - */ - protected $theme = 'Gentele'; + /** + * @var string + */ + public $token; - /** - * @var string - */ - public $token; + /** + * Set up session / smarty / user variables. + * + * @throws \Exception + */ + public function __construct() + { + $this->https = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'; - /** - * Set up session / smarty / user variables. - * - * @throws \Exception - */ - public function __construct() - { - $this->https = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'; + if (session_id() === '') { + session_set_cookie_params(0, '/', '', $this->https, true); + session_start(); + if (empty($_SESSION['token'])) { + $_SESSION['token'] = bin2hex(random_bytes(32)); + } + $this->token = $_SESSION['token']; + } - if (session_id() === '') { - session_set_cookie_params(0, '/', '', $this->https, true); - session_start(); - if (empty($_SESSION['token'])) { - $_SESSION['token'] = bin2hex(random_bytes(32)); - } - $this->token = $_SESSION['token']; - } + if (NN_FLOOD_CHECK) { + $this->floodCheck(); + } - if (NN_FLOOD_CHECK) { - $this->floodCheck(); - } + // Buffer settings/DB connection. + $this->settings = new DB(); + $this->smarty = new Smarty(); - // Buffer settings/DB connection. - $this->settings = new DB(); - $this->smarty = new Smarty(); - - $this->smarty->setCompileDir(NN_SMARTY_TEMPLATES); - $this->smarty->setConfigDir(NN_SMARTY_CONFIGS); - $this->smarty->setCacheDir(NN_SMARTY_CACHE); - $this->smarty->setPluginsDir([ - NN_WWW . 'plugins/', - SMARTY_DIR . 'plugins/', + $this->smarty->setCompileDir(NN_SMARTY_TEMPLATES); + $this->smarty->setConfigDir(NN_SMARTY_CONFIGS); + $this->smarty->setCacheDir(NN_SMARTY_CACHE); + $this->smarty->setPluginsDir([ + NN_WWW.'plugins/', + SMARTY_DIR.'plugins/', ] ); - $this->smarty->error_reporting = (NN_DEBUG ? E_ALL : E_ALL - E_NOTICE); + $this->smarty->error_reporting = (NN_DEBUG ? E_ALL : E_ALL - E_NOTICE); - if (isset($_SERVER['SERVER_NAME'])) { - $this->serverurl = ( - ($this->https === true ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] . - (((int)$_SERVER['SERVER_PORT'] !== 80 && (int)$_SERVER['SERVER_PORT'] !== 443) ? ':' . $_SERVER['SERVER_PORT'] : '') . - WWW_TOP . '/' + if (isset($_SERVER['SERVER_NAME'])) { + $this->serverurl = ( + ($this->https === true ? 'https://' : 'http://').$_SERVER['SERVER_NAME']. + (((int) $_SERVER['SERVER_PORT'] !== 80 && (int) $_SERVER['SERVER_PORT'] !== 443) ? ':'.$_SERVER['SERVER_PORT'] : ''). + WWW_TOP.'/' ); - $this->smarty->assign('serverroot', $this->serverurl); - } + $this->smarty->assign('serverroot', $this->serverurl); + } - $this->page = $_GET['page'] ?? 'content'; + $this->page = $_GET['page'] ?? 'content'; - $this->users = new Users(['Settings' => $this->settings]); - if ($this->users->isLoggedIn()) { - $this->setUserPreferences(); - } else { - $this->theme = $this->getSettingValue('site.main.style'); + $this->users = new Users(['Settings' => $this->settings]); + if ($this->users->isLoggedIn()) { + $this->setUserPreferences(); + } else { + $this->theme = $this->getSettingValue('site.main.style'); - $this->smarty->assign('isadmin', 'false'); - $this->smarty->assign('ismod', 'false'); - $this->smarty->assign('loggedin', 'false'); - } - if ($this->theme === 'None') { - $this->theme = Settings::value('site.main.style'); - } + $this->smarty->assign('isadmin', 'false'); + $this->smarty->assign('ismod', 'false'); + $this->smarty->assign('loggedin', 'false'); + } + if ($this->theme === 'None') { + $this->theme = Settings::value('site.main.style'); + } - $this->smarty->assign('theme', $this->theme); - $this->smarty->assign('site', $this->settings); - $this->smarty->assign('page', $this); - } + $this->smarty->assign('theme', $this->theme); + $this->smarty->assign('site', $this->settings); + $this->smarty->assign('page', $this); + } - /** - * Unquotes quoted strings recursively in an array. - * - * @param $array - */ - private function stripSlashes(array &$array) - { - foreach ($array as $key => $value) { - $array[$key] = (is_array($value) ? array_map('stripslashes', $value) : stripslashes($value)); - } - } + /** + * Unquotes quoted strings recursively in an array. + * + * @param $array + */ + private function stripSlashes(array &$array) + { + foreach ($array as $key => $value) { + $array[$key] = (is_array($value) ? array_map('stripslashes', $value) : stripslashes($value)); + } + } - /** - * Check if the user is flooding. - */ - public function floodCheck(): void - { - $waitTime = (NN_FLOOD_WAIT_TIME < 1 ? 5 : NN_FLOOD_WAIT_TIME); - // Check if this is not from CLI. - if (empty($argc)) { - // If flood wait set, the user must wait x seconds until they can access a page. - if (isset($_SESSION['flood_wait_until']) && $_SESSION['flood_wait_until'] > microtime(true)) { - $this->showFloodWarning($waitTime); - } else { - // If user not an admin, they are allowed three requests in FLOOD_THREE_REQUESTS_WITHIN_X_SECONDS seconds. - if (!isset($_SESSION['flood_check_hits'])) { - $_SESSION['flood_check_hits'] = 1; - $_SESSION['flood_check_time'] = microtime(true); - } else { - if ($_SESSION['flood_check_hits'] >= (NN_FLOOD_MAX_REQUESTS_PER_SECOND < 1 ? 5 : NN_FLOOD_MAX_REQUESTS_PER_SECOND)) { - if ($_SESSION['flood_check_time'] + 1 > microtime(true)) { - $_SESSION['flood_wait_until'] = microtime(true) + $waitTime; - unset($_SESSION['flood_check_hits']); - $this->showFloodWarning($waitTime); - } else { - $_SESSION['flood_check_hits'] = 1; - $_SESSION['flood_check_time'] = microtime(true); - } - } else { - $_SESSION['flood_check_hits']++; - } - } - } - } - } + /** + * Check if the user is flooding. + */ + public function floodCheck(): void + { + $waitTime = (NN_FLOOD_WAIT_TIME < 1 ? 5 : NN_FLOOD_WAIT_TIME); + // Check if this is not from CLI. + if (empty($argc)) { + // If flood wait set, the user must wait x seconds until they can access a page. + if (isset($_SESSION['flood_wait_until']) && $_SESSION['flood_wait_until'] > microtime(true)) { + $this->showFloodWarning($waitTime); + } else { + // If user not an admin, they are allowed three requests in FLOOD_THREE_REQUESTS_WITHIN_X_SECONDS seconds. + if (! isset($_SESSION['flood_check_hits'])) { + $_SESSION['flood_check_hits'] = 1; + $_SESSION['flood_check_time'] = microtime(true); + } else { + if ($_SESSION['flood_check_hits'] >= (NN_FLOOD_MAX_REQUESTS_PER_SECOND < 1 ? 5 : NN_FLOOD_MAX_REQUESTS_PER_SECOND)) { + if ($_SESSION['flood_check_time'] + 1 > microtime(true)) { + $_SESSION['flood_wait_until'] = microtime(true) + $waitTime; + unset($_SESSION['flood_check_hits']); + $this->showFloodWarning($waitTime); + } else { + $_SESSION['flood_check_hits'] = 1; + $_SESSION['flood_check_time'] = microtime(true); + } + } else { + $_SESSION['flood_check_hits']++; + } + } + } + } + } - /** - * Done in html here to reduce any smarty processing burden if a large flood is underway. - * - * @param int $seconds - */ - public function showFloodWarning($seconds = 5): void - { - header('Retry-After: ' . $seconds); - $this->show503(); - } + /** + * Done in html here to reduce any smarty processing burden if a large flood is underway. + * + * @param int $seconds + */ + public function showFloodWarning($seconds = 5): void + { + header('Retry-After: '.$seconds); + $this->show503(); + } - /** - * Inject content into the html head - * - * @param $headcontent - */ - public function addToHead($headcontent): void - { - $this->head = $this->head . "\n" . $headcontent; - } + /** + * Inject content into the html head. + * + * @param $headcontent + */ + public function addToHead($headcontent): void + { + $this->head = $this->head."\n".$headcontent; + } - /** - * Inject js/attributes into the html body tag - * - * @param $attr - */ - public function addToBody($attr): void - { - $this->body = $this->body . ' ' . $attr; - } + /** + * Inject js/attributes into the html body tag. + * + * @param $attr + */ + public function addToBody($attr): void + { + $this->body = $this->body.' '.$attr; + } - /** - * @return bool - */ - public function isPostBack() - { - return (strtoupper($_SERVER['REQUEST_METHOD']) === 'POST'); - } + /** + * @return bool + */ + public function isPostBack() + { + return strtoupper($_SERVER['REQUEST_METHOD']) === 'POST'; + } - /** - * Show 404 page. - */ - public function show404(): void - { - header('HTTP/1.1 404 Not Found'); - die(view('errors.404')); - } + /** + * Show 404 page. + */ + public function show404(): void + { + header('HTTP/1.1 404 Not Found'); + die(view('errors.404')); + } - /** - * Show 403 page. - * - * @param bool $from_admin - */ - public function show403($from_admin = false): void - { - header( - 'Location: ' . - ($from_admin ? str_replace('/admin', '', WWW_TOP) : WWW_TOP) . - '/login?redirect=' . + /** + * Show 403 page. + * + * @param bool $from_admin + */ + public function show403($from_admin = false): void + { + header( + 'Location: '. + ($from_admin ? str_replace('/admin', '', WWW_TOP) : WWW_TOP). + '/login?redirect='. urlencode($_SERVER['REQUEST_URI']) ); - exit(); - } + exit(); + } - /** - * Show 503 page. - */ - public function show503(): void - { - header('HTTP/1.1 503 Service Temporarily Unavailable'); - die(view('errors.503')); - } + /** + * Show 503 page. + */ + public function show503(): void + { + header('HTTP/1.1 503 Service Temporarily Unavailable'); + die(view('errors.503')); + } - /** - * Show maintenance page. - * - */ - public function showMaintenance(): void - { - header('HTTP/1.1 503 Service Temporarily Unavailable'); - die(view('errors.maintenance')); - } + /** + * Show maintenance page. + */ + public function showMaintenance(): void + { + header('HTTP/1.1 503 Service Temporarily Unavailable'); + die(view('errors.maintenance')); + } - /** - * Show Security token mismatch page. - */ - public function showTokenError(): void - { - header('HTTP/1.1 503 Service Temporarily Unavailable'); - die(view('errors.tokenError')); - } + /** + * Show Security token mismatch page. + */ + public function showTokenError(): void + { + header('HTTP/1.1 503 Service Temporarily Unavailable'); + die(view('errors.tokenError')); + } - /** - * @param string $retry - */ - public function show429($retry = ''): void - { - header('HTTP/1.1 429 Too Many Requests'); - if ($retry !== '') - header('Retry-After: ' . $retry); + /** + * @param string $retry + */ + public function show429($retry = ''): void + { + header('HTTP/1.1 429 Too Many Requests'); + if ($retry !== '') { + header('Retry-After: '.$retry); + } - echo ' + echo ' <html> <head> <title>Too Many Requests @@ -313,99 +312,97 @@ class BasePage

Too Many Requests

-

Wait ' . (($retry !== '') ? ceil($retry / 60) . ' minutes ' : '') . 'or risk being temporarily banned.

+

Wait '.(($retry !== '') ? ceil($retry / 60).' minutes ' : '').'or risk being temporarily banned.

'; - die(); - } + die(); + } + public function render() + { + $this->smarty->display($this->page_template); + } - public function render() - { - $this->smarty->display($this->page_template); - } + protected function setUserPreferences(): void + { + $this->userdata = $this->users->getById($this->users->currentUserId()); + $this->userdata['categoryexclusions'] = $this->users->getCategoryExclusion($this->users->currentUserId()); + $this->userdata['rolecategoryexclusions'] = $this->users->getRoleCategoryExclusion($this->userdata['role']); - protected function setUserPreferences(): void - { - $this->userdata = $this->users->getById($this->users->currentUserId()); - $this->userdata['categoryexclusions'] = $this->users->getCategoryExclusion($this->users->currentUserId()); - $this->userdata['rolecategoryexclusions'] = $this->users->getRoleCategoryExclusion($this->userdata['role']); + // Change the theme to user's selected theme if they selected one, else use the admin one. + if ((int) Settings::value('site.main.userselstyle') === 1) { + $this->theme = $this->userdata['style'] ?? 'None'; + if ($this->theme === 'None') { + $this->theme = Settings::value('site.main.style'); + } + } else { + $this->theme = Settings::value('site.main.style'); + } - // Change the theme to user's selected theme if they selected one, else use the admin one. - if ((int)Settings::value('site.main.userselstyle') === 1) { - $this->theme = $this->userdata['style'] ?? 'None'; - if ($this->theme === 'None') { - $this->theme = Settings::value('site.main.style'); - } - } else { - $this->theme = Settings::value('site.main.style'); - } - - // Update last login every 15 mins. - if ((strtotime($this->userdata['now']) - 900) > + // Update last login every 15 mins. + if ((strtotime($this->userdata['now']) - 900) > strtotime($this->userdata['lastlogin']) ) { - $this->users->updateSiteAccessed($this->userdata['id']); - } + $this->users->updateSiteAccessed($this->userdata['id']); + } - $this->smarty->assign('userdata', $this->userdata); - $this->smarty->assign('loggedin', "true"); + $this->smarty->assign('userdata', $this->userdata); + $this->smarty->assign('loggedin', 'true'); - if ($this->userdata['nzbvortex_api_key'] !== '' && $this->userdata['nzbvortex_server_url'] !== '') { - $this->smarty->assign('weHasVortex', true); - } else { - $this->smarty->assign('weHasVortex', false); - } + if ($this->userdata['nzbvortex_api_key'] !== '' && $this->userdata['nzbvortex_server_url'] !== '') { + $this->smarty->assign('weHasVortex', true); + } else { + $this->smarty->assign('weHasVortex', false); + } - $sab = new SABnzbd($this); - $this->smarty->assign('sabintegrated', $sab->integratedBool); - if ($sab->integratedBool !== false && $sab->url !== '' && $sab->apikey !== '') { - $this->smarty->assign('sabapikeytype', $sab->apikeytype); - } - switch ((int)$this->userdata['role']) { + $sab = new SABnzbd($this); + $this->smarty->assign('sabintegrated', $sab->integratedBool); + if ($sab->integratedBool !== false && $sab->url !== '' && $sab->apikey !== '') { + $this->smarty->assign('sabapikeytype', $sab->apikeytype); + } + switch ((int) $this->userdata['role']) { case Users::ROLE_ADMIN: $this->smarty->assign('isadmin', 'true'); break; case Users::ROLE_MODERATOR: $this->smarty->assign('ismod', 'true'); } - } + } - /** - * Allows to fetch a value from the settings table. - * - * This method is deprecated, as the column it uses to select the data is due to be removed - * from the table *soon*. - * - * @param $setting - * - * @return array|bool|mixed|null|string - * @throws \Exception - */ - public function getSetting($setting) - { - if (strpos($setting, '.') === false) { - trigger_error( + /** + * Allows to fetch a value from the settings table. + * + * This method is deprecated, as the column it uses to select the data is due to be removed + * from the table *soon*. + * + * @param $setting + * + * @return array|bool|mixed|null|string + * @throws \Exception + */ + public function getSetting($setting) + { + if (strpos($setting, '.') === false) { + trigger_error( 'You should update your template to use the newer method "$page->getSettingValue()"" of fetching values from the "settings" table! This method *will* be removed in a future version.', E_USER_WARNING ); - } else { - return $this->getSettingValue($setting); - } + } else { + return $this->getSettingValue($setting); + } - return $this->settings->$setting; + return $this->settings->$setting; + } - } - - /** - * @param $setting - * - * @return null|string - * @throws \Exception - */ - public function getSettingValue($setting): ?string - { - return Settings::value($setting); - } + /** + * @param $setting + * + * @return null|string + * @throws \Exception + */ + public function getSettingValue($setting): ?string + { + return Settings::value($setting); + } } diff --git a/public/pages/InstallPage.php b/public/pages/InstallPage.php index 59399ceb3..05b3d6d57 100755 --- a/public/pages/InstallPage.php +++ b/public/pages/InstallPage.php @@ -3,48 +3,48 @@ class InstallPage { - public $title = ''; - public $content = ''; - public $head = ''; - public $page_template = ''; + public $title = ''; + public $content = ''; + public $head = ''; + public $page_template = ''; - /** - * @var Smarty - */ - public $smarty; + /** + * @var Smarty + */ + public $smarty; - public $error = false; + public $error = false; - public function __construct() - { - @session_start(); + public function __construct() + { + @session_start(); - $this->smarty = new Smarty(); + $this->smarty = new Smarty(); - $this->smarty->setTemplateDir(realpath('../install/templates/')); - $this->smarty->setCompileDir(NN_RES . 'smarty/templates_c/'); - $this->smarty->setConfigDir(NN_RES . 'smarty/configs/'); - $this->smarty->setCacheDir(NN_RES . 'smarty/cache/'); - } + $this->smarty->setTemplateDir(realpath('../install/templates/')); + $this->smarty->setCompileDir(NN_RES.'smarty/templates_c/'); + $this->smarty->setConfigDir(NN_RES.'smarty/configs/'); + $this->smarty->setCacheDir(NN_RES.'smarty/cache/'); + } - public function addToHead($headcontent) - { - $this->head = $this->head . "\n" . $headcontent; - } + public function addToHead($headcontent) + { + $this->head = $this->head."\n".$headcontent; + } - public function render() - { - $this->page_template = "installpage.tpl"; - $this->smarty->display($this->page_template); - } + public function render() + { + $this->page_template = 'installpage.tpl'; + $this->smarty->display($this->page_template); + } - public function isPostBack() - { - return (strtoupper($_SERVER["REQUEST_METHOD"]) === "POST"); - } + public function isPostBack() + { + return strtoupper($_SERVER['REQUEST_METHOD']) === 'POST'; + } - public function isSuccess() - { - return isset($_GET['success']); - } + public function isSuccess() + { + return isset($_GET['success']); + } } diff --git a/public/pages/Page.php b/public/pages/Page.php index da65cc8bf..4eddb95c1 100644 --- a/public/pages/Page.php +++ b/public/pages/Page.php @@ -1,82 +1,84 @@ smarty->setTemplateDir( + // Tell Smarty which directories to use for templates + $this->smarty->setTemplateDir( [ - 'user' => NN_THEMES . $this->theme . '/templates', - 'shared' => NN_THEMES . 'shared/templates', - 'default' => NN_THEMES . 'Gentele/templates' + 'user' => NN_THEMES.$this->theme.'/templates', + 'shared' => NN_THEMES.'shared/templates', + 'default' => NN_THEMES.'Gentele/templates', ] ); - $role = Users::ROLE_GUEST; - if ($this->userdata != null) - $role = $this->userdata["role"]; + $role = Users::ROLE_GUEST; + if ($this->userdata != null) { + $role = $this->userdata['role']; + } - $content = new Contents(['Settings' => $this->settings]); - $f = new Forum(); - $menu = new Menu($this->settings); - $this->smarty->assign('menulist',$menu->get($role, $this->serverurl)); - $this->smarty->assign('usefulcontentlist', $content->getForMenuByTypeAndRole(Contents::TYPEUSEFUL, $role)); - $this->smarty->assign('articlecontentlist', $content->getForMenuByTypeAndRole(Contents::TYPEARTICLE, $role)); - if ($this->userdata != null) - $this->smarty->assign('recentforumpostslist',$f->getPosts(Settings::value('..showrecentforumposts'))); + $content = new Contents(['Settings' => $this->settings]); + $f = new Forum(); + $menu = new Menu($this->settings); + $this->smarty->assign('menulist', $menu->get($role, $this->serverurl)); + $this->smarty->assign('usefulcontentlist', $content->getForMenuByTypeAndRole(Contents::TYPEUSEFUL, $role)); + $this->smarty->assign('articlecontentlist', $content->getForMenuByTypeAndRole(Contents::TYPEARTICLE, $role)); + if ($this->userdata != null) { + $this->smarty->assign('recentforumpostslist', $f->getPosts(Settings::value('..showrecentforumposts'))); + } - $this->smarty->assign('main_menu',$this->smarty->fetch('mainmenu.tpl')); - $this->smarty->assign('useful_menu',$this->smarty->fetch('usefullinksmenu.tpl')); - $this->smarty->assign('article_menu',$this->smarty->fetch('articlesmenu.tpl')); + $this->smarty->assign('main_menu', $this->smarty->fetch('mainmenu.tpl')); + $this->smarty->assign('useful_menu', $this->smarty->fetch('usefullinksmenu.tpl')); + $this->smarty->assign('article_menu', $this->smarty->fetch('articlesmenu.tpl')); - $category = new Category(['Settings' => $content->pdo]); - if (!empty($this->userdata)) { - $parentcatlist = $category->getForMenu($this->userdata['categoryexclusions'], $this->userdata['rolecategoryexclusions']); - } - else { - $parentcatlist = $category->getForMenu(); - } + $category = new Category(['Settings' => $content->pdo]); + if (! empty($this->userdata)) { + $parentcatlist = $category->getForMenu($this->userdata['categoryexclusions'], $this->userdata['rolecategoryexclusions']); + } else { + $parentcatlist = $category->getForMenu(); + } - $this->smarty->assign('parentcatlist',$parentcatlist); - $this->smarty->assign('catClass', $category); - $searchStr = ''; - if ($this->page == 'search' && isset($_REQUEST["id"])) - $searchStr = (string) $_REQUEST["id"]; - $this->smarty->assign('header_menu_search',$searchStr); + $this->smarty->assign('parentcatlist', $parentcatlist); + $this->smarty->assign('catClass', $category); + $searchStr = ''; + if ($this->page == 'search' && isset($_REQUEST['id'])) { + $searchStr = (string) $_REQUEST['id']; + } + $this->smarty->assign('header_menu_search', $searchStr); - if (isset($_REQUEST["t"])) { - $this->smarty->assign('header_menu_cat', $_REQUEST["t"]); - } else { - $this->smarty->assign('header_menu_cat', ''); - } - $header_menu = $this->smarty->fetch('headermenu.tpl'); - $this->smarty->assign('header_menu',$header_menu); - } + if (isset($_REQUEST['t'])) { + $this->smarty->assign('header_menu_cat', $_REQUEST['t']); + } else { + $this->smarty->assign('header_menu_cat', ''); + } + $header_menu = $this->smarty->fetch('headermenu.tpl'); + $this->smarty->assign('header_menu', $header_menu); + } - /** - * Output the page. - */ - public function render() - { - $this->smarty->assign('page',$this); - $this->page_template = "basepage.tpl"; + /** + * Output the page. + */ + public function render() + { + $this->smarty->assign('page', $this); + $this->page_template = 'basepage.tpl'; - parent::render(); - } + parent::render(); + } } diff --git a/public/pages/ajax_mediainfo.php b/public/pages/ajax_mediainfo.php index 55841ae0d..572e7bdcd 100644 --- a/public/pages/ajax_mediainfo.php +++ b/public/pages/ajax_mediainfo.php @@ -2,42 +2,42 @@ use nntmux\ReleaseExtra; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } -if (!isset($_REQUEST['id'])) { - $page->show404(); +if (! isset($_REQUEST['id'])) { + $page->show404(); } $re = new ReleaseExtra($page->settings); $redata = $re->getBriefByGuid($_REQUEST['id']); -if (!$redata) { - print 'No media info'; +if (! $redata) { + echo 'No media info'; } else { - print "
\n"; - if ($redata['videocodec'] !== '' && $redata['containerformat'] !== '') { - $redata['videocodec'] = $re->makeCodecPretty($redata['videocodec']); - print '\n"; - } - if ($redata['videoduration'] !== '') { - print '\n"; - } - if ($redata['size'] !== '') { - print '\n"; - } - if ($redata['videoaspect'] !== '') { - print '\n"; - } - if ($redata['audio'] !== '' && $redata['audio'] !== ', ') { - print '\n"; - } - if ($redata['audioformat'] !== '' && $redata['audioformat'] !== ', ') { - print '\n"; - } - if ($redata['subs'] !== '') { - print '\n"; - } - print '
Format:' . htmlentities($redata['videocodec'], ENT_QUOTES) . ' - ' . htmlentities($redata['containerformat'], ENT_QUOTES) . "
Duration:' . htmlentities($redata['videoduration'], ENT_QUOTES) . "
Resolution:' . htmlentities($redata['size'], ENT_QUOTES) . "
Aspect Ratio:' . htmlentities($redata['videoaspect'], ENT_QUOTES) . "
Audio Languages:' . htmlentities($redata['audio'], ENT_QUOTES) . "
Audio Format:' . htmlentities($redata['audioformat'], ENT_QUOTES) . "
Subtitles:' . htmlentities($redata['subs'], ENT_QUOTES) . "
'; + echo "\n"; + if ($redata['videocodec'] !== '' && $redata['containerformat'] !== '') { + $redata['videocodec'] = $re->makeCodecPretty($redata['videocodec']); + echo '\n"; + } + if ($redata['videoduration'] !== '') { + echo '\n"; + } + if ($redata['size'] !== '') { + echo '\n"; + } + if ($redata['videoaspect'] !== '') { + echo '\n"; + } + if ($redata['audio'] !== '' && $redata['audio'] !== ', ') { + echo '\n"; + } + if ($redata['audioformat'] !== '' && $redata['audioformat'] !== ', ') { + echo '\n"; + } + if ($redata['subs'] !== '') { + echo '\n"; + } + echo '
Format:'.htmlentities($redata['videocodec'], ENT_QUOTES).' - '.htmlentities($redata['containerformat'], ENT_QUOTES)."
Duration:'.htmlentities($redata['videoduration'], ENT_QUOTES)."
Resolution:'.htmlentities($redata['size'], ENT_QUOTES)."
Aspect Ratio:'.htmlentities($redata['videoaspect'], ENT_QUOTES)."
Audio Languages:'.htmlentities($redata['audio'], ENT_QUOTES)."
Audio Format:'.htmlentities($redata['audioformat'], ENT_QUOTES)."
Subtitles:'.htmlentities($redata['subs'], ENT_QUOTES)."
'; } diff --git a/public/pages/ajax_preinfo.php b/public/pages/ajax_preinfo.php index 06b6042c8..e7e0afb20 100644 --- a/public/pages/ajax_preinfo.php +++ b/public/pages/ajax_preinfo.php @@ -2,24 +2,24 @@ use nntmux\PreDb; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } -if (!isset($_REQUEST['id'])) { - $page->show404(); +if (! isset($_REQUEST['id'])) { + $page->show404(); } $pre = new PreDb(['Settings' => $page->settings]); $predata = $pre->getOne($_REQUEST['id']); -if (!$predata) { - print 'No pre info'; +if (! $predata) { + echo 'No pre info'; } else { - print "\n"; - if (isset($predata['nuked'])) { - $nuked = ''; - switch ($predata['nuked']) { + echo "
\n"; + if (isset($predata['nuked'])) { + $nuked = ''; + switch ($predata['nuked']) { case PreDb::PRE_NUKED: $nuked = 'NUKED'; break; @@ -36,23 +36,23 @@ if (!$predata) { $nuked = 'UNNUKED'; break; } - if ($nuked !== '') { - print '\n"; - } - } - print "\n"; - if (isset($predata['category']) && $predata['category'] !== '') { - print '\n"; - } - print '\n"; - if (isset($predata['size'])) { - if (isset($predata['size'][0]) && $predata['size'][0] > 0) { - print '\n"; - } - } - if (isset($predata['files'])) { - print '\n"; - } - print '\n"; - print '
' . $nuked . ':' . htmlentities($predata['nukereason'] ?? '', ENT_QUOTES) . "
Title:" . htmlentities($predata['title'], ENT_QUOTES) . "
Cat:' . htmlentities($predata['category'], ENT_QUOTES) . "
Source:' . htmlentities($predata['source'], ENT_QUOTES) . "
Size:' . htmlentities($predata['size'], ENT_QUOTES) . "
Files:' . htmlentities((preg_match('/F|B/', $predata['files'], $match) ? $predata['files'] : ($predata['files'] . 'MB')), ENT_QUOTES) . "
Pred:' . htmlentities($predata['predate'], ENT_QUOTES) . "
'; + if ($nuked !== '') { + echo ''.$nuked.':'.htmlentities($predata['nukereason'] ?? '', ENT_QUOTES)."\n"; + } + } + echo 'Title:'.htmlentities($predata['title'], ENT_QUOTES)."\n"; + if (isset($predata['category']) && $predata['category'] !== '') { + echo 'Cat:'.htmlentities($predata['category'], ENT_QUOTES)."\n"; + } + echo 'Source:'.htmlentities($predata['source'], ENT_QUOTES)."\n"; + if (isset($predata['size'])) { + if (isset($predata['size'][0]) && $predata['size'][0] > 0) { + echo 'Size:'.htmlentities($predata['size'], ENT_QUOTES)."\n"; + } + } + if (isset($predata['files'])) { + echo 'Files:'.htmlentities((preg_match('/F|B/', $predata['files'], $match) ? $predata['files'] : ($predata['files'].'MB')), ENT_QUOTES)."\n"; + } + echo 'Pred:'.htmlentities($predata['predate'], ENT_QUOTES)."\n"; + echo ''; } diff --git a/public/pages/ajax_profile.php b/public/pages/ajax_profile.php index 8615571eb..3f01a025b 100644 --- a/public/pages/ajax_profile.php +++ b/public/pages/ajax_profile.php @@ -2,18 +2,18 @@ use App\Models\Settings; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } -if (isset($_GET['action'], $_GET['emailto']) && (int)$_GET['action'] === 1) { - $emailto = $_GET['emailto']; - $ret = $page->users->sendInvite(Settings::value('site.main.title'), Settings::value('site.main.email'), $page->serverurl, $page->users->currentUserId(), $emailto); - if (!$ret) { - print 'Invite not sent.'; - } else { - print 'Invite sent. Alternatively paste them following link to register - ' . $ret; - } +if (isset($_GET['action'], $_GET['emailto']) && (int) $_GET['action'] === 1) { + $emailto = $_GET['emailto']; + $ret = $page->users->sendInvite(Settings::value('site.main.title'), Settings::value('site.main.email'), $page->serverurl, $page->users->currentUserId(), $emailto); + if (! $ret) { + echo 'Invite not sent.'; + } else { + echo 'Invite sent. Alternatively paste them following link to register - '.$ret; + } } else { - print 'Invite not sent.'; + echo 'Invite not sent.'; } diff --git a/public/pages/ajax_rarfilelist.php b/public/pages/ajax_rarfilelist.php index 06da916da..3891cdd2d 100644 --- a/public/pages/ajax_rarfilelist.php +++ b/public/pages/ajax_rarfilelist.php @@ -1,24 +1,25 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } -if (!isset($_REQUEST['id'])) { - $page->show404(); +if (! isset($_REQUEST['id'])) { + $page->show404(); } $rf = new ReleaseFiles(); $files = $rf->getByGuid($_REQUEST['id']); if (count($files) === 0) { - print 'No files'; + echo '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 '
'; + //print "

rar archive contains...

\n"; + echo "
    \n"; + foreach ($files as $f) { + echo '
  • '.htmlentities($f['name'], ENT_QUOTES).' '.($f['passworded'] === 1 ? '' : '')."
  • \n"; + } + echo '
'; } diff --git a/public/pages/ajax_release-admin.php b/public/pages/ajax_release-admin.php index f74aa5546..d6f6e4ed6 100644 --- a/public/pages/ajax_release-admin.php +++ b/public/pages/ajax_release-admin.php @@ -12,11 +12,11 @@ $action = $_REQUEST['action'] ?? ''; // Request is for id, but guid is actually being provided if (isset($_REQUEST['id']) && is_array($_REQUEST['id'])) { - $id = $_REQUEST['id']; - //Get info for first guid to populate form - $rel = $releases->getByGuid($_REQUEST['id'][0]); -} else { - $id = $rel = ''; + $id = $_REQUEST['id']; + //Get info for first guid to populate form + $rel = $releases->getByGuid($_REQUEST['id'][0]); +} else { + $id = $rel = ''; } $page->smarty->assign('action', $action); @@ -27,7 +27,7 @@ switch ($action) { case 'edit': $success = false; if ($action === 'doedit') { - $success = $releases->updateMulti( + $success = $releases->updateMulti( $_POST['id'], $_POST['category'], $_POST['grabs'], @@ -47,13 +47,13 @@ switch ($action) { case 'dodelete': $is_guid = true; if (is_array($_GET['id'])) { - if (is_numeric($_GET['id'][0])) { - $is_guid = false; - } + if (is_numeric($_GET['id'][0])) { + $is_guid = false; + } } else { - if (is_numeric($_GET['id'])) { - $is_guid = false; - } + if (is_numeric($_GET['id'])) { + $is_guid = false; + } } $releases->deleteMultiple($_GET['id'], $is_guid); break; diff --git a/public/pages/ajax_resetusergrabs-admin.php b/public/pages/ajax_resetusergrabs-admin.php index 4a6a94dcf..a0a8cd19f 100644 --- a/public/pages/ajax_resetusergrabs-admin.php +++ b/public/pages/ajax_resetusergrabs-admin.php @@ -8,8 +8,7 @@ $u = new Users(); $action = $_REQUEST['action'] ?? ''; $id = $_REQUEST['id'] ?? ''; -switch($action) -{ +switch ($action) { case 'grabs': $u->delDownloadRequests($id); break; @@ -20,4 +19,3 @@ switch($action) $page->show404(); break; } - diff --git a/public/pages/ajax_tvinfo.php b/public/pages/ajax_tvinfo.php index b91bb925f..758510091 100644 --- a/public/pages/ajax_tvinfo.php +++ b/public/pages/ajax_tvinfo.php @@ -1,32 +1,32 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } -if (!isset($_REQUEST['id'])) { - $page->show404(); +if (! isset($_REQUEST['id'])) { + $page->show404(); } $r = new Releases(); -$rel = $r->getByGuid($_REQUEST["id"]); +$rel = $r->getByGuid($_REQUEST['id']); -if (!$rel) { - print 'No tv info'; +if (! $rel) { + echo 'No tv info'; } else { - print "
    \n"; - print "
  • ".htmlentities($rel['title'], ENT_QUOTES)."
  • \n"; - print "
  • Aired on ".date('F j, Y', strtotime($rel['firstaired']))."
  • \n"; - print "
"; + echo "
    \n"; + echo '
  • '.htmlentities($rel['title'], ENT_QUOTES)."
  • \n"; + echo '
  • Aired on '.date('F j, Y', strtotime($rel['firstaired']))."
  • \n"; + echo '
'; - if (isset($rel['videos_id']) && $rel['videos_id'] > 0) { - $t = new Videos(); - $show = $t->getByVideoID($rel['videos_id']); - if (count($show) > 0 && (int)$show['image'] !== 0) { - print ""; - } - } + if (isset($rel['videos_id']) && $rel['videos_id'] > 0) { + $t = new Videos(); + $show = $t->getByVideoID($rel['videos_id']); + if (count($show) > 0 && (int) $show['image'] !== 0) { + echo ''; + } + } } diff --git a/public/pages/anime.php b/public/pages/anime.php index 68aff438e..2c39a0886 100755 --- a/public/pages/anime.php +++ b/public/pages/anime.php @@ -1,11 +1,11 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $releases = new Releases(['Settings' => $page->settings]); @@ -13,21 +13,20 @@ $aniDB = new AniDB(['Settings' => $page->settings]); if (isset($_GET['id']) && ctype_digit($_GET['id'])) { - # force the category to TV_ANIME as it should be for anime, as $catarray was NULL and we know the category for sure for anime - $aniDbReleases = $releases->searchbyAnidbId($_GET['id'], 0, 1000, '', [Category::TV_ANIME], -1); - $aniDbInfo = $aniDB->getAnimeInfo($_GET['id']); + // force the category to TV_ANIME as it should be for anime, as $catarray was NULL and we know the category for sure for anime + $aniDbReleases = $releases->searchbyAnidbId($_GET['id'], 0, 1000, '', [Category::TV_ANIME], -1); + $aniDbInfo = $aniDB->getAnimeInfo($_GET['id']); - if (!$releases && !$aniDbInfo) { - $page->show404(); - } else if (!$aniDbInfo) { - $page->smarty->assign('nodata', 'No AniDB information for this series.'); - } else if (!$aniDbReleases) { - $page->smarty->assign('nodata', 'No releases for this series.'); - } else { - - $page->smarty->assign('anidb', $aniDbInfo); - $page->smarty->assign('animeEpisodeTitles', $aniDbReleases); - $page->smarty->assign( + if (! $releases && ! $aniDbInfo) { + $page->show404(); + } elseif (! $aniDbInfo) { + $page->smarty->assign('nodata', 'No AniDB information for this series.'); + } elseif (! $aniDbReleases) { + $page->smarty->assign('nodata', 'No releases for this series.'); + } else { + $page->smarty->assign('anidb', $aniDbInfo); + $page->smarty->assign('animeEpisodeTitles', $aniDbReleases); + $page->smarty->assign( [ 'animeAnidbid' => $aniDbInfo['anidbid'], 'animeTitle' => $aniDbInfo['title'], @@ -41,58 +40,58 @@ if (isset($_GET['id']) && ctype_digit($_GET['id'])) { 'animeSimilar' => $aniDbInfo['similar'], 'animeCategories' => $aniDbInfo['categories'], 'animeCreators' => $aniDbInfo['creators'], - 'animeCharacters' => $aniDbInfo['characters'] + 'animeCharacters' => $aniDbInfo['characters'], ] ); - $page->smarty->assign('nodata', ''); + $page->smarty->assign('nodata', ''); - $page->title = $aniDbInfo['title']; - $page->meta_title = 'View Anime ' . $aniDbInfo['title']; - $page->meta_keywords = 'view,anime,anidb,description,details'; - $page->meta_description = 'View ' . $aniDbInfo['title'] . ' Anime'; - } - $page->content = $page->smarty->fetch('viewanime.tpl'); - $page->render(); + $page->title = $aniDbInfo['title']; + $page->meta_title = 'View Anime '.$aniDbInfo['title']; + $page->meta_keywords = 'view,anime,anidb,description,details'; + $page->meta_description = 'View '.$aniDbInfo['title'].' Anime'; + } + $page->content = $page->smarty->fetch('viewanime.tpl'); + $page->render(); } else { - $letter = (isset($_GET['id']) && preg_match('/^(0\-9|[A-Z])$/i', $_GET['id'])) ? + $letter = (isset($_GET['id']) && preg_match('/^(0\-9|[A-Z])$/i', $_GET['id'])) ? $_GET['id'] : '0-9'; - $animeTitle = (isset($_GET['title']) && !empty($_GET['title'])) ? + $animeTitle = (isset($_GET['title']) && ! empty($_GET['title'])) ? $_GET['title'] : ''; - if ($animeTitle !== '' && !isset($_GET['id'])) { - $letter = ''; - } + if ($animeTitle !== '' && ! isset($_GET['id'])) { + $letter = ''; + } - $masterserieslist = $aniDB->getAnimeList($letter, $animeTitle); + $masterserieslist = $aniDB->getAnimeList($letter, $animeTitle); - $page->title = 'Anime List'; - $page->meta_title = 'View Anime List'; - $page->meta_keywords = 'view,anime,series,description,details'; - $page->meta_description = 'View Anime List'; + $page->title = 'Anime List'; + $page->meta_title = 'View Anime List'; + $page->meta_keywords = 'view,anime,series,description,details'; + $page->meta_description = 'View Anime List'; - $animelist = []; - if ($masterserieslist instanceof \Traversable) { - foreach ($masterserieslist as $s) { - if (preg_match('/^[0-9]/', $s['title'])) { - $thisrange = '0-9'; - } else { - preg_match('/([A-Z]).*/i', $s['title'], $matches); - $thisrange = strtoupper($matches[1]); - } - $animelist[$thisrange][] = $s; - } - ksort($animelist); - } + $animelist = []; + if ($masterserieslist instanceof \Traversable) { + foreach ($masterserieslist as $s) { + if (preg_match('/^[0-9]/', $s['title'])) { + $thisrange = '0-9'; + } else { + preg_match('/([A-Z]).*/i', $s['title'], $matches); + $thisrange = strtoupper($matches[1]); + } + $animelist[$thisrange][] = $s; + } + ksort($animelist); + } - $page->smarty->assign('animelist', $animelist); - $page->smarty->assign('animerange', range('A', 'Z')); - $page->smarty->assign('animeletter', $letter); - $page->smarty->assign('animetitle', $animeTitle); + $page->smarty->assign('animelist', $animelist); + $page->smarty->assign('animerange', range('A', 'Z')); + $page->smarty->assign('animeletter', $letter); + $page->smarty->assign('animetitle', $animeTitle); - $page->content = $page->smarty->fetch('viewanimelist.tpl'); - $page->render(); + $page->content = $page->smarty->fetch('viewanimelist.tpl'); + $page->render(); } diff --git a/public/pages/api.php b/public/pages/api.php index a796b3610..3e7f52b90 100644 --- a/public/pages/api.php +++ b/public/pages/api.php @@ -1,14 +1,14 @@ users->isLoggedIn()) { - $uid = $page->userdata['id']; - $apiKey = $page->userdata['rsstoken']; - $catExclusions = $page->userdata['categoryexclusions']; - $maxRequests = $page->userdata['apirequests']; - if ($page->users->isDisabled($page->userdata['username'])) { - Utility::showApiError(101); - } + $uid = $page->userdata['id']; + $apiKey = $page->userdata['rsstoken']; + $catExclusions = $page->userdata['categoryexclusions']; + $maxRequests = $page->userdata['apirequests']; + if ($page->users->isDisabled($page->userdata['username'])) { + Utility::showApiError(101); + } } else { - if ($function !== 'c' && $function !== 'r') { - if (!isset($_GET['apikey'])) { - Utility::showApiError(200, 'Missing parameter (apikey)'); - } else { - $apiKey = $_GET['apikey']; - $res = $page->users->getByRssToken($apiKey); - if (!$res) { - Utility::showApiError(100, 'Incorrect user credentials (wrong API key)'); - } - } + if ($function !== 'c' && $function !== 'r') { + if (! isset($_GET['apikey'])) { + Utility::showApiError(200, 'Missing parameter (apikey)'); + } else { + $apiKey = $_GET['apikey']; + $res = $page->users->getByRssToken($apiKey); + if (! $res) { + Utility::showApiError(100, 'Incorrect user credentials (wrong API key)'); + } + } - if ($page->users->isDisabled($res['username'])) { - Utility::showApiError(101); - } + if ($page->users->isDisabled($res['username'])) { + Utility::showApiError(101); + } - $uid = $res['id']; - $catExclusions = $page->users->getCategoryExclusion($uid); - $maxRequests = $res['apirequests']; - } + $uid = $res['id']; + $catExclusions = $page->users->getCategoryExclusion($uid); + $maxRequests = $res['apirequests']; + } } // Record user access to the api, if its been called by a user (i.e. capabilities request do not require a user to be logged in or key provided). if ($uid !== '') { - $page->users->updateApiAccessed($uid); - $apiRequests = $page->users->getApiRequests($uid); - if ($apiRequests > $maxRequests) { - Utility::showApiError(500, 'Request limit reached (' . $apiRequests . '/' . $maxRequests . ')'); - } + $page->users->updateApiAccessed($uid); + $apiRequests = $page->users->getApiRequests($uid); + if ($apiRequests > $maxRequests) { + Utility::showApiError(500, 'Request limit reached ('.$apiRequests.'/'.$maxRequests.')'); + } } $releases = new Releases(['Settings' => $page->settings]); $api = new API(['Settings' => $page->settings, 'Request' => $_GET]); // Set Query Parameters based on Request objects -$outputXML = !(isset($_GET['o']) && $_GET['o'] === 'json'); +$outputXML = ! (isset($_GET['o']) && $_GET['o'] === 'json'); $minSize = (isset($_GET['minsize']) && $_GET['minsize'] > 0 ? $_GET['minsize'] : 0); $offset = $api->offset(); // Set API Parameters based on Request objects -$params['extended'] = (isset($_GET['extended']) && (int)$_GET['extended'] === 1 ? '1' : '0'); -$params['del'] = (isset($_GET['del']) && (int)$_GET['del'] === 1 ? '1' : '0'); +$params['extended'] = (isset($_GET['extended']) && (int) $_GET['extended'] === 1 ? '1' : '0'); +$params['del'] = (isset($_GET['del']) && (int) $_GET['del'] === 1 ? '1' : '0'); $params['uid'] = $uid; $params['token'] = $apiKey; @@ -119,12 +119,12 @@ switch ($function) { $limit = $api->limit(); if (isset($_GET['q'])) { - $relData = $releases->search( + $relData = $releases->search( $_GET['q'], -1, -1, -1, $groupName, -1, -1, 0, 0, -1, -1, $offset, $limit, '', $maxAge, $catExclusions, 'basic', $categoryID, $minSize ); } else { - $relData = $releases->getBrowseRange( + $relData = $releases->getBrowseRange( $categoryID, $offset, $limit, '', $maxAge, $catExclusions, $groupName, $minSize ); } @@ -152,20 +152,20 @@ switch ($function) { 'tvrage' => $_GET['rid'] ?? '0', 'tvmaze' => $_GET['tvmazeid'] ?? '0', 'imdb' => $_GET['imdbid'] ?? '0', - 'tmdb' => $_GET['tmdbid'] ?? '0' + 'tmdb' => $_GET['tmdbid'] ?? '0', ]; // Process season only queries or Season and Episode/Airdate queries - if (!empty($_GET['season']) && !empty($_GET['ep'])) { - if (preg_match('#^(19|20)\d{2}$#', $_GET['season'], $year) && strpos($_GET['ep'], '/') !== false) { - $airdate = str_replace('/', '-', $year[0] . '-' . $_GET['ep']); - } else { - $series = $_GET['season']; - $episode = $_GET['ep']; - } - } elseif (!empty($_GET['season'])) { - $series = $_GET['season']; - $episode = (!empty($_GET['ep']) ? $_GET['ep'] : ''); + if (! empty($_GET['season']) && ! empty($_GET['ep'])) { + if (preg_match('#^(19|20)\d{2}$#', $_GET['season'], $year) && strpos($_GET['ep'], '/') !== false) { + $airdate = str_replace('/', '-', $year[0].'-'.$_GET['ep']); + } else { + $series = $_GET['season']; + $episode = $_GET['ep']; + } + } elseif (! empty($_GET['season'])) { + $series = $_GET['season']; + $episode = (! empty($_GET['ep']) ? $_GET['ep'] : ''); } $relData = $releases->searchShows( @@ -205,8 +205,8 @@ switch ($function) { ); $api->addCoverURL($relData, - function($release) { - return Utility::getCoverURL(['type' => 'movies', 'id' => $release['imdbid']]); + function ($release) { + return Utility::getCoverURL(['type' => 'movies', 'id' => $release['imdbid']]); } ); @@ -220,26 +220,26 @@ switch ($function) { $page->users->addApiRequest($uid, $_SERVER['REQUEST_URI']); $relData = $releases->getByGuid($_GET['id']); if ($relData) { - header( - 'Location:' . - WWW_TOP . - '/getnzb?i=' . - $uid . - '&r=' . - $apiKey . - '&id=' . - $relData['guid'] . + header( + 'Location:'. + WWW_TOP. + '/getnzb?i='. + $uid. + '&r='. + $apiKey. + '&id='. + $relData['guid']. ((isset($_GET['del']) && $_GET['del'] === '1') ? '&del=1' : '') ); } else { - Utility::showApiError(300, 'No such item (the guid you provided has no release in our database)'); + Utility::showApiError(300, 'No such item (the guid you provided has no release in our database)'); } break; // Get individual NZB details. case 'd': - if (!isset($_GET['id'])) { - Utility::showApiError(200, 'Missing parameter (id is required for single release details)'); + if (! isset($_GET['id'])) { + Utility::showApiError(200, 'Missing parameter (id is required for single release details)'); } $page->users->addApiRequest($uid, $_SERVER['REQUEST_URI']); @@ -247,35 +247,35 @@ switch ($function) { $relData = []; if ($data) { - $relData[] = $data; + $relData[] = $data; } $api->output($relData, $params, $outputXML, $offset, 'api'); break; // Get an NFO file for an individual release. case 'n': - if (!isset($_GET['id'])) { - Utility::showApiError(200, 'Missing parameter (id is required for retrieving an NFO)'); + if (! isset($_GET['id'])) { + Utility::showApiError(200, 'Missing parameter (id is required for retrieving an NFO)'); } $page->users->addApiRequest($uid, $_SERVER['REQUEST_URI']); $rel = $releases->getByGuid($_GET['id']); $data = $releases->getReleaseNfo($rel['id']); - if ($rel !== false && !empty($rel)) { - if ($data !== false) { - if (isset($_GET['o']) && $_GET['o'] === 'file') { - header('Content-type: application/octet-stream'); - header("Content-disposition: attachment; filename={$rel['searchname']}.nfo"); - exit($data['nfo']); - } + if ($rel !== false && ! empty($rel)) { + if ($data !== false) { + if (isset($_GET['o']) && $_GET['o'] === 'file') { + header('Content-type: application/octet-stream'); + header("Content-disposition: attachment; filename={$rel['searchname']}.nfo"); + exit($data['nfo']); + } - echo nl2br(Utility::cp437toUTF($data['nfo'])); - } else { - Utility::showApiError(300, 'Release does not have an NFO file associated.'); - } + echo nl2br(Utility::cp437toUTF($data['nfo'])); + } else { + Utility::showApiError(300, 'Release does not have an NFO file associated.'); + } } else { - Utility::showApiError(300, 'Release does not exist.'); + Utility::showApiError(300, 'Release does not exist.'); } break; @@ -287,17 +287,17 @@ switch ($function) { case 'r': $api->verifyEmptyParameter('email'); - if (!in_array((int)Settings::value('..registerstatus'), [Settings::REGISTER_STATUS_OPEN, Settings::REGISTER_STATUS_API_ONLY], false)) { - Utility::showApiError(104); + if (! in_array((int) Settings::value('..registerstatus'), [Settings::REGISTER_STATUS_OPEN, Settings::REGISTER_STATUS_API_ONLY], false)) { + Utility::showApiError(104); } // Check email is valid format. - if (!$page->users->isValidEmail($_GET['email'])) { - Utility::showApiError(106); + if (! $page->users->isValidEmail($_GET['email'])) { + Utility::showApiError(106); } // Check email isn't taken. $ret = $page->users->getByEmail($_GET['email']); if (isset($ret['id'])) { - Utility::showApiError(105); + Utility::showApiError(105); } // Create username/pass and register. $username = $page->users->generateUsername($_GET['email']); @@ -310,7 +310,7 @@ switch ($function) { // Check if it succeeded. $userData = $page->users->getById($uid); if (empty($userData)) { - Utility::showApiError(107); + Utility::showApiError(107); } $params['username'] = $username; diff --git a/public/pages/apihelp.php b/public/pages/apihelp.php index 98f55836f..fa8697e14 100644 --- a/public/pages/apihelp.php +++ b/public/pages/apihelp.php @@ -7,4 +7,3 @@ $page->meta_description = 'View description of the site Nzb Api.'; $page->content = $page->smarty->fetch('apidesc.tpl'); $page->render(); - diff --git a/public/pages/bookmodal.php b/public/pages/bookmodal.php index 9554feced..93ee5cd04 100644 --- a/public/pages/bookmodal.php +++ b/public/pages/bookmodal.php @@ -4,36 +4,35 @@ use nntmux\Books; $b = new Books; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } if (isset($_GET['id']) && ctype_digit($_GET['id'])) { - $book = $b->getBookInfo($_GET['id']); - if (!$book) { - $page->show404(); - } + $book = $b->getBookInfo($_GET['id']); + if (! $book) { + $page->show404(); + } - $page->smarty->assign('book', $book); + $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'); + $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); - } + $modal = false; + if (isset($_GET['modal'])) { + $modal = true; + $page->smarty->assign('modal', true); + } - $page->content = $page->smarty->fetch('viewbook.tpl'); + $page->content = $page->smarty->fetch('viewbook.tpl'); - if ($modal) { - echo $page->content; - } else { - $page->render(); - } + if ($modal) { + echo $page->content; + } else { + $page->render(); + } } - diff --git a/public/pages/books.php b/public/pages/books.php index 61f5009b4..e0e291c5d 100644 --- a/public/pages/books.php +++ b/public/pages/books.php @@ -1,7 +1,7 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } use nntmux\Books; @@ -15,11 +15,11 @@ $fail = new DnzbFailures(['Settings' => $page->settings]); $boocats = $cat->getChildren(Category::BOOKS_ROOT); $btmp = []; foreach ($boocats as $bcat) { - $btmp[$bcat['id']] = $bcat; + $btmp[$bcat['id']] = $bcat; } $category = Category::BOOKS_ROOT; if (isset($_REQUEST['t']) && array_key_exists($_REQUEST['t'], $btmp)) { - $category = $_REQUEST['t'] + 0; + $category = $_REQUEST['t'] + 0; } $catarray = []; @@ -37,46 +37,46 @@ $results = $book->getBookRange($catarray, $offset, ITEMS_PER_COVER_PAGE, $orderb $maxwords = 50; foreach ($results as $result) { - if (!empty($result['overview'])) { - $words = explode(' ', $result['overview']); - if (count($words) > $maxwords) { - $newwords = array_slice($words, 0, $maxwords); - $result['overview'] = implode(' ', $newwords) . '...'; - } - } - $books[] = $result; + if (! empty($result['overview'])) { + $words = explode(' ', $result['overview']); + if (count($words) > $maxwords) { + $newwords = array_slice($words, 0, $maxwords); + $result['overview'] = implode(' ', $newwords).'...'; + } + } + $books[] = $result; } -$author = (isset($_REQUEST['author']) && !empty($_REQUEST['author'])) ? stripslashes($_REQUEST['author']) : ''; +$author = (isset($_REQUEST['author']) && ! empty($_REQUEST['author'])) ? stripslashes($_REQUEST['author']) : ''; $page->smarty->assign('author', $author); -$title = (isset($_REQUEST['title']) && !empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; +$title = (isset($_REQUEST['title']) && ! empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; $page->smarty->assign('title', $title); -$browseby_link = '&title=' . $title . '&author=' . $author; +$browseby_link = '&title='.$title.'&author='.$author; $page->smarty->assign('pagertotalitems', $results[0]['_totalcount'] ?? 0); $page->smarty->assign('pageroffset', $offset); $page->smarty->assign('pageritemsperpage', ITEMS_PER_COVER_PAGE); -$page->smarty->assign('pagerquerybase', WWW_TOP . '/books?t=' . $category . $browseby_link . '&ob=' . $orderby . '&offset='); +$page->smarty->assign('pagerquerybase', WWW_TOP.'/books?t='.$category.$browseby_link.'&ob='.$orderby.'&offset='); $page->smarty->assign('pagerquerysuffix', '#results'); $pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); -if ((int)$category === -1) { - $page->smarty->assign('catname', 'All'); +if ((int) $category === -1) { + $page->smarty->assign('catname', 'All'); } else { - $cdata = $cat->getById($category); - if ($cdata) { - $page->smarty->assign('catname', $cdata['title']); - } else { - $page->show404(); - } + $cdata = $cat->getById($category); + if ($cdata) { + $page->smarty->assign('catname', $cdata['title']); + } else { + $page->show404(); + } } foreach ($ordering as $ordertype) { - $page->smarty->assign('orderby' . $ordertype, WWW_TOP . '/books?t=' . $category . $browseby_link . '&ob=' . $ordertype . '&offset=0'); + $page->smarty->assign('orderby'.$ordertype, WWW_TOP.'/books?t='.$category.$browseby_link.'&ob='.$ordertype.'&offset=0'); } $page->smarty->assign('results', $books); diff --git a/public/pages/browse.php b/public/pages/browse.php index 69da479f1..b1517f1ba 100644 --- a/public/pages/browse.php +++ b/public/pages/browse.php @@ -1,22 +1,22 @@ $page->settings]); -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $category = -1; if (isset($_REQUEST['t'])) { - $category = $_REQUEST['t']; + $category = $_REQUEST['t']; } $grp = -1; if (isset($_REQUEST['g'])) { - $grp = is_numeric($_REQUEST['g']) ? -1 : $_REQUEST['g']; + $grp = is_numeric($_REQUEST['g']) ? -1 : $_REQUEST['g']; } $catarray = []; @@ -37,49 +37,49 @@ $page->smarty->assign( 'pagertotalitems' => $browsecount, 'pageroffset'=> $offset, 'pageritemsperpage'=> ITEMS_PER_PAGE, - 'pagerquerybase' => WWW_TOP . '/browse?t=' . $category . '&g=' . $grp . '&ob=' . $orderby . '&offset=', - 'pagerquerysuffix' => '#results' + 'pagerquerybase' => WWW_TOP.'/browse?t='.$category.'&g='.$grp.'&ob='.$orderby.'&offset=', + 'pagerquerysuffix' => '#results', ]); $pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); $covgroup = ''; -if ($category === -1 && (int)$grp === -1) { - $page->smarty->assign('catname', 'All'); -} elseif ((int)$category !== -1 && (int)$grp === -1) { - $cat = new Category(['Settings' => $releases->pdo]); - $cdata = $cat->getById($category); - if ($cdata) { - $page->smarty->assign('catname', $cdata['title']); - if ($cdata['parentid'] === Category::GAME_ROOT || $cdata['id'] === Category::GAME_ROOT) { - $covgroup = 'console'; - } elseif ($cdata['parentid'] === Category::MOVIE_ROOT || $cdata['id'] === Category::MOVIE_ROOT) { - $covgroup = 'movies'; - } elseif ($cdata['parentid'] === Category::XXX_ROOT || $cdata['id'] === Category::XXX_ROOT) { - $covgroup = 'xxx'; - } elseif ($cdata['parentid'] === Category::PC_ROOT || $cdata['id'] === Category::PC_GAMES) { - $covgroup = 'games'; - } elseif ($cdata['parentid'] === Category::MUSIC_ROOT || $cdata['id'] === Category::MUSIC_ROOT) { - $covgroup = 'music'; - } elseif ($cdata['parentid'] === Category::BOOKS_ROOT || $cdata['id'] === Category::BOOKS_ROOT) { - $covgroup = 'books'; - } - } else { - $page->show404(); - } -} elseif ((int)$grp !== -1) { - $page->smarty->assign('catname', $grp); +if ($category === -1 && (int) $grp === -1) { + $page->smarty->assign('catname', 'All'); +} elseif ((int) $category !== -1 && (int) $grp === -1) { + $cat = new Category(['Settings' => $releases->pdo]); + $cdata = $cat->getById($category); + if ($cdata) { + $page->smarty->assign('catname', $cdata['title']); + if ($cdata['parentid'] === Category::GAME_ROOT || $cdata['id'] === Category::GAME_ROOT) { + $covgroup = 'console'; + } elseif ($cdata['parentid'] === Category::MOVIE_ROOT || $cdata['id'] === Category::MOVIE_ROOT) { + $covgroup = 'movies'; + } elseif ($cdata['parentid'] === Category::XXX_ROOT || $cdata['id'] === Category::XXX_ROOT) { + $covgroup = 'xxx'; + } elseif ($cdata['parentid'] === Category::PC_ROOT || $cdata['id'] === Category::PC_GAMES) { + $covgroup = 'games'; + } elseif ($cdata['parentid'] === Category::MUSIC_ROOT || $cdata['id'] === Category::MUSIC_ROOT) { + $covgroup = 'music'; + } elseif ($cdata['parentid'] === Category::BOOKS_ROOT || $cdata['id'] === Category::BOOKS_ROOT) { + $covgroup = 'books'; + } + } else { + $page->show404(); + } +} elseif ((int) $grp !== -1) { + $page->smarty->assign('catname', $grp); } $page->smarty->assign('covgroup', $covgroup); foreach ($ordering as $ordertype) { - $page->smarty->assign('orderby' . $ordertype, WWW_TOP . '/browse?t=' . $category . '&g=' . $grp . '&ob=' . $ordertype . '&offset=0'); + $page->smarty->assign('orderby'.$ordertype, WWW_TOP.'/browse?t='.$category.'&g='.$grp.'&ob='.$ordertype.'&offset=0'); } -$page->smarty->assign('lastvisit',$page->userdata['lastlogin']); +$page->smarty->assign('lastvisit', $page->userdata['lastlogin']); -$page->smarty->assign('results',$results); +$page->smarty->assign('results', $results); $page->meta_title = 'Browse Nzbs'; $page->meta_keywords = 'browse,nzb,description,details'; diff --git a/public/pages/browsegroup.php b/public/pages/browsegroup.php index ecc6ce9d3..a54365007 100644 --- a/public/pages/browsegroup.php +++ b/public/pages/browsegroup.php @@ -1,6 +1,7 @@ users->isLoggedIn()) { - $page->show403(); + +if (! $page->users->isLoggedIn()) { + $page->show403(); } use nntmux\Groups; diff --git a/public/pages/cart.php b/public/pages/cart.php index ced5b866b..eee3741c1 100644 --- a/public/pages/cart.php +++ b/public/pages/cart.php @@ -1,47 +1,47 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } use nntmux\Releases; if (isset($_GET['add'])) { - $releases = new Releases(['Settings' => $page->settings]); - $guids = explode(',', $_GET['add']); - $data = $releases->getByGuid($guids); + $releases = new Releases(['Settings' => $page->settings]); + $guids = explode(',', $_GET['add']); + $data = $releases->getByGuid($guids); - if (!$data) { - $page->show404(); - } + if (! $data) { + $page->show404(); + } - foreach ($data as $d) { - $page->users->addCart($page->users->currentUserId(), $d['id']); - } + foreach ($data as $d) { + $page->users->addCart($page->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($_GET['delete']) && ! empty($_GET['delete'])) { + $ids = [$_GET['delete']]; + } elseif (isset($_POST['delete']) && is_array($_POST['delete'])) { + $ids = $_POST['delete']; + } - if ($ids !== null) { - $page->users->delCartByGuid($ids, $page->users->currentUserId()); - } + if ($ids !== null) { + $page->users->delCartByGuid($ids, $page->users->currentUserId()); + } - if (!isset($_POST['delete'])) { - header('Location: ' . WWW_TOP . '/cart'); - } + if (! isset($_POST['delete'])) { + header('Location: '.WWW_TOP.'/cart'); + } - exit(); + exit(); } else { - $page->meta_title = 'My Download Basket'; - $page->meta_keywords = 'search,add,to,cart,download,basket,nzb,description,details'; - $page->meta_description = 'Manage Your Download Basket'; + $page->meta_title = 'My Download Basket'; + $page->meta_keywords = 'search,add,to,cart,download,basket,nzb,description,details'; + $page->meta_description = 'Manage Your Download Basket'; - $results = $page->users->getCart($page->users->currentUserId()); - $page->smarty->assign('results', $results); + $results = $page->users->getCart($page->users->currentUserId()); + $page->smarty->assign('results', $results); - $page->content = $page->smarty->fetch('cart.tpl'); - $page->render(); + $page->content = $page->smarty->fetch('cart.tpl'); + $page->render(); } diff --git a/public/pages/console.php b/public/pages/console.php index 55c198305..34f0cd1a0 100644 --- a/public/pages/console.php +++ b/public/pages/console.php @@ -1,12 +1,12 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } +use nntmux\Genres; use nntmux\Console; use nntmux\Category; -use nntmux\Genres; use nntmux\DnzbFailures; $console = new Console(['Settings' => $page->settings]); @@ -17,11 +17,11 @@ $fail = new DnzbFailures(['Settings' => $page->settings]); $concats = $cat->getChildren(Category::GAME_ROOT); $ctmp = []; foreach ($concats as $ccat) { - $ctmp[$ccat['id']] = $ccat; + $ctmp[$ccat['id']] = $ccat; } $category = Category::GAME_ROOT; if (isset($_REQUEST['t']) && array_key_exists($_REQUEST['t'], $ctmp)) { - $category = $_REQUEST['t'] + 0; + $category = $_REQUEST['t'] + 0; } $catarray = []; @@ -39,55 +39,55 @@ $results = $console->getConsoleRange($catarray, $offset, ITEMS_PER_COVER_PAGE, $ $maxwords = 50; foreach ($results as $result) { - if (!empty($result['review'])) { - $words = explode(' ', $result['review']); - if (count($words) > $maxwords) { - $newwords = array_slice($words, 0, $maxwords); - $result['review'] = implode(' ', $newwords) . '...'; - } - } - $consoles[] = $result; + if (! empty($result['review'])) { + $words = explode(' ', $result['review']); + if (count($words) > $maxwords) { + $newwords = array_slice($words, 0, $maxwords); + $result['review'] = implode(' ', $newwords).'...'; + } + } + $consoles[] = $result; } -$platform = (isset($_REQUEST['platform']) && !empty($_REQUEST['platform'])) ? stripslashes($_REQUEST['platform']) : ''; +$platform = (isset($_REQUEST['platform']) && ! empty($_REQUEST['platform'])) ? stripslashes($_REQUEST['platform']) : ''; $page->smarty->assign('platform', $platform); -$title = (isset($_REQUEST['title']) && !empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; +$title = (isset($_REQUEST['title']) && ! empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; $page->smarty->assign('title', $title); $genres = $gen->getGenres(Genres::CONSOLE_TYPE, true); $tmpgnr = []; foreach ($genres as $gn) { - $tmpgnr[$gn['id']] = $gn['title']; + $tmpgnr[$gn['id']] = $gn['title']; } $genre = (isset($_REQUEST['genre']) && array_key_exists($_REQUEST['genre'], $tmpgnr)) ? $_REQUEST['genre'] : ''; $page->smarty->assign('genres', $genres); $page->smarty->assign('genre', $genre); -$browseby_link = '&title=' . $title . '&platform=' . $platform; +$browseby_link = '&title='.$title.'&platform='.$platform; $page->smarty->assign('pagertotalitems', $results[0]['_totalcount'] ?? 0); $page->smarty->assign('pageroffset', $offset); $page->smarty->assign('pageritemsperpage', ITEMS_PER_COVER_PAGE); -$page->smarty->assign('pagerquerybase', WWW_TOP . '/console?t=' . $category . $browseby_link . '&ob=' . $orderby . '&offset='); +$page->smarty->assign('pagerquerybase', WWW_TOP.'/console?t='.$category.$browseby_link.'&ob='.$orderby.'&offset='); $page->smarty->assign('pagerquerysuffix', '#results'); $pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); -if ((int)$category === -1) { - $page->smarty->assign('catname', 'All'); +if ((int) $category === -1) { + $page->smarty->assign('catname', 'All'); } else { - $cdata = $cat->getById($category); - if ($cdata) { - $page->smarty->assign('catname', $cdata['title']); - } else { - $page->show404(); - } + $cdata = $cat->getById($category); + if ($cdata) { + $page->smarty->assign('catname', $cdata['title']); + } else { + $page->show404(); + } } foreach ($ordering as $ordertype) { - $page->smarty->assign('orderby' . $ordertype, WWW_TOP . '/console?t=' . $category . $browseby_link . '&ob=' . $ordertype . '&offset=0'); + $page->smarty->assign('orderby'.$ordertype, WWW_TOP.'/console?t='.$category.$browseby_link.'&ob='.$ordertype.'&offset=0'); } $page->smarty->assign('results', $consoles); diff --git a/public/pages/consolemodal.php b/public/pages/consolemodal.php index 337917740..c0b4f2b5d 100644 --- a/public/pages/consolemodal.php +++ b/public/pages/consolemodal.php @@ -2,37 +2,36 @@ use nntmux\Console; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } if (isset($_GET['id']) && ctype_digit($_GET['id'])) { - $console = new Console(['Settings' => $page->settings]); - $con = $console->getConsoleInfo($_GET['id']); - if (!$con) { - $page->show404(); - } + $console = new Console(['Settings' => $page->settings]); + $con = $console->getConsoleInfo($_GET['id']); + if (! $con) { + $page->show404(); + } - $page->smarty->assign('console', $con); + $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'); + $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); - } + $modal = false; + if (isset($_GET['modal'])) { + $modal = true; + $page->smarty->assign('modal', true); + } - $page->content = $page->smarty->fetch('viewconsole.tpl'); + $page->content = $page->smarty->fetch('viewconsole.tpl'); - if ($modal) { - echo $page->content; - } - else { - $page->render(); - } + if ($modal) { + echo $page->content; + } else { + $page->render(); + } } diff --git a/public/pages/contact-us.php b/public/pages/contact-us.php index a40726158..6a92ca9ba 100644 --- a/public/pages/contact-us.php +++ b/public/pages/contact-us.php @@ -1,41 +1,41 @@ getError() === false) { - $email = $_POST['useremail']; - $mailto = Settings::value('site.main.email'); - $mailsubj = 'Contact Form Submitted'; - $mailhead = "From: $email\n"; - $mailbody = "Values submitted from contact form:\n"; + if ($captcha->getError() === false) { + $email = $_POST['useremail']; + $mailto = Settings::value('site.main.email'); + $mailsubj = 'Contact Form Submitted'; + $mailhead = "From: $email\n"; + $mailbody = "Values submitted from contact form:\n"; - foreach ($_POST as $key => $value) { - if ($key !== 'submit') { - $mailbody .= "$key : $value
\r\n"; - } - } + foreach ($_POST as $key => $value) { + if ($key !== 'submit') { + $mailbody .= "$key : $value
\r\n"; + } + } - if (!preg_match("/\n/i", $_POST['useremail'])) { - Utility::sendEmail($mailto, $mailsubj, $mailbody, $email); - } - $msg = "

Thank you for getting in touch with " . Settings::value('site.main.title') . '.

'; - } + if (! preg_match("/\n/i", $_POST['useremail'])) { + Utility::sendEmail($mailto, $mailsubj, $mailbody, $email); + } + $msg = "

Thank you for getting in touch with ".Settings::value('site.main.title').'.

'; + } } $page->smarty->assign('msg', $msg); $page->title = 'Contact '.Settings::value('site.main.title'); $page->meta_title = 'Contact '.Settings::value('site.main.title'); $page->meta_keywords = 'contact us,contact,get in touch,email'; -$page->meta_description = 'Contact us at ' . Settings::value('site.main.title') . ' and submit your feedback'; +$page->meta_description = 'Contact us at '.Settings::value('site.main.title').' and submit your feedback'; $page->content = $page->smarty->fetch('contact.tpl'); diff --git a/public/pages/content.php b/public/pages/content.php index a5b403206..75d125dd3 100644 --- a/public/pages/content.php +++ b/public/pages/content.php @@ -5,8 +5,8 @@ use nntmux\Contents; $contents = new Contents(['Settings' => $page->settings]); $role = 0; -if (!empty($page->userdata) && $page->users->isLoggedIn()) { - $role = $page->userdata['role']; +if (! empty($page->userdata) && $page->users->isLoggedIn()) { + $role = $page->userdata['role']; } /* The role column in the content table values are : @@ -26,42 +26,41 @@ if (!empty($page->userdata) && $page->users->isLoggedIn()) { $page->smarty->assign('admin', (($role === 2 || $role === 4) ? 'true' : 'false')); $contentId = 0; -if (!empty($_GET['id'])) { - $contentId = $_GET['id']; +if (! empty($_GET['id'])) { + $contentId = $_GET['id']; } $request = false; -if (!empty($_REQUEST['page'])) { - $request = $_REQUEST['page']; +if (! empty($_REQUEST['page'])) { + $request = $_REQUEST['page']; } if ($contentId === 0 && $request === 'content') { - $content = $contents->getAllButFront(); - $page->smarty->assign('front', false); - $page->meta_title = 'Contents page'; - $page->meta_keywords = 'contents'; - $page->meta_description = 'This is the contents page.'; -} else if ($contentId !== 0 && $request !== false) { - $content = [$contents->getByID($contentId, $role)]; - $page->smarty->assign('front', false); - $page->meta_title = 'Contents page'; - $page->meta_keywords = 'contents'; - $page->meta_description = 'This is the contents page.'; + $content = $contents->getAllButFront(); + $page->smarty->assign('front', false); + $page->meta_title = 'Contents page'; + $page->meta_keywords = 'contents'; + $page->meta_description = 'This is the contents page.'; +} elseif ($contentId !== 0 && $request !== false) { + $content = [$contents->getByID($contentId, $role)]; + $page->smarty->assign('front', false); + $page->meta_title = 'Contents page'; + $page->meta_keywords = 'contents'; + $page->meta_description = 'This is the contents page.'; } else { - $content = $contents->getFrontPage(); - $index = $contents->getIndex(); - $page->smarty->assign('front', true); - $page->meta_title = $index->title; - $page->meta_keywords = $index->metakeywords; - $page->meta_description = $index->metadescription; + $content = $contents->getFrontPage(); + $index = $contents->getIndex(); + $page->smarty->assign('front', true); + $page->meta_title = $index->title; + $page->meta_keywords = $index->metakeywords; + $page->meta_description = $index->metadescription; } if (empty($content)) { - $page->show404(); + $page->show404(); } $page->smarty->assign('content', $content); - $page->content = $page->smarty->fetch('content.tpl'); $page->render(); diff --git a/public/pages/details.php b/public/pages/details.php index 1084d2f39..0719d445a 100644 --- a/public/pages/details.php +++ b/public/pages/details.php @@ -1,167 +1,167 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } if (isset($_GET['id'])) { - $releases = new Releases(['Settings' => $page->settings]); - $rc = new ReleaseComments; - $re = new ReleaseExtra; - $df = new DnzbFailures(['Settings' => $page->settings]); - $data = $releases->getByGuid($_GET['id']); - $user = $page->users->getById($page->users->currentUserId()); - $cpapi = $user['cp_api']; - $cpurl = $user['cp_url']; - $releaseRegex = ReleaseRegexes::query()->where('releases_id', '=', $data['id'])->first(); + $releases = new Releases(['Settings' => $page->settings]); + $rc = new ReleaseComments; + $re = new ReleaseExtra; + $df = new DnzbFailures(['Settings' => $page->settings]); + $data = $releases->getByGuid($_GET['id']); + $user = $page->users->getById($page->users->currentUserId()); + $cpapi = $user['cp_api']; + $cpurl = $user['cp_url']; + $releaseRegex = ReleaseRegexes::query()->where('releases_id', '=', $data['id'])->first(); - if (!$data) { - $page->show404(); - } + if (! $data) { + $page->show404(); + } - if ($page->isPostBack()) { - $rc->addComment($data['id'], $data['gid'], $_POST['txtAddComment'], $page->users->currentUserId(), $_SERVER['REMOTE_ADDR']); - } + if ($page->isPostBack()) { + $rc->addComment($data['id'], $data['gid'], $_POST['txtAddComment'], $page->users->currentUserId(), $_SERVER['REMOTE_ADDR']); + } - $nfo = $releases->getReleaseNfo($data['id']); - $reVideo = $re->getVideo($data['id']); - $reAudio = $re->getAudio($data['id']); - $reSubs = $re->getSubs($data['id']); - $comments = $rc->getCommentsByGid($data['gid']); - $similars = $releases->searchSimilar($data['id'], + $nfo = $releases->getReleaseNfo($data['id']); + $reVideo = $re->getVideo($data['id']); + $reAudio = $re->getAudio($data['id']); + $reSubs = $re->getSubs($data['id']); + $comments = $rc->getCommentsByGid($data['gid']); + $similars = $releases->searchSimilar($data['id'], $data['searchname'], 6, $page->userdata['categoryexclusions']); - $failed = $df->getFailedCount($data['id']); + $failed = $df->getFailedCount($data['id']); - $showInfo = ''; - if ($data['videos_id'] > 0) { - $showInfo = (new Videos(['Settings' => $page->settings]))->getByVideoID($data['videos_id']); - } + $showInfo = ''; + if ($data['videos_id'] > 0) { + $showInfo = (new Videos(['Settings' => $page->settings]))->getByVideoID($data['videos_id']); + } - $mov = ''; - if ($data['imdbid'] !== '' && $data['imdbid'] !== 0000000) { - $movie = new Movie(['Settings' => $page->settings]); - $mov = $movie->getMovieInfo($data['imdbid']); - if (!empty($mov['title'])) { - $mov['title'] = str_replace(['/', '\\'], '', $mov['title']); - $mov['actors'] = $movie->makeFieldLinks($mov, 'actors'); - $mov['genre'] = $movie->makeFieldLinks($mov, 'genre'); - $mov['director'] = $movie->makeFieldLinks($mov, 'director'); - if (Settings::value('site.trailers.trailers_display')) { - $trailer = empty($mov['trailer']) || $mov['trailer'] === '' ? $movie->getTrailer($data['imdbid']) : $mov['trailer']; - if ($trailer) { - $mov['trailer'] = sprintf( + $mov = ''; + if ($data['imdbid'] !== '' && $data['imdbid'] !== 0000000) { + $movie = new Movie(['Settings' => $page->settings]); + $mov = $movie->getMovieInfo($data['imdbid']); + if (! empty($mov['title'])) { + $mov['title'] = str_replace(['/', '\\'], '', $mov['title']); + $mov['actors'] = $movie->makeFieldLinks($mov, 'actors'); + $mov['genre'] = $movie->makeFieldLinks($mov, 'genre'); + $mov['director'] = $movie->makeFieldLinks($mov, 'director'); + if (Settings::value('site.trailers.trailers_display')) { + $trailer = empty($mov['trailer']) || $mov['trailer'] === '' ? $movie->getTrailer($data['imdbid']) : $mov['trailer']; + if ($trailer) { + $mov['trailer'] = sprintf( '', Settings::value('site.trailers.trailers_size_x'), Settings::value('site.trailers.trailers_size_y'), $trailer ); - } - } - } - } + } + } + } + } - $xxx = ''; - if ($data['xxxinfo_id'] !== '' && $data['xxxinfo_id'] !== 0) { - $x = new XXX(); - $xxx = $x->getXXXInfo($data['xxxinfo_id']); + $xxx = ''; + if ($data['xxxinfo_id'] !== '' && $data['xxxinfo_id'] !== 0) { + $x = new XXX(); + $xxx = $x->getXXXInfo($data['xxxinfo_id']); - if (isset($xxx['trailers'])) { - $xxx['trailers'] = $x->insertSwf($xxx['classused'], $xxx['trailers']); - } + if (isset($xxx['trailers'])) { + $xxx['trailers'] = $x->insertSwf($xxx['classused'], $xxx['trailers']); + } - if ($xxx && isset($xxx['title'])) { - $xxx['title'] = str_replace(array('/', '\\'), '', $xxx['title']); - $xxx['actors'] = $x->makeFieldLinks($xxx, 'actors'); - $xxx['genre'] = $x->makeFieldLinks($xxx, 'genre'); - $xxx['director'] = $x->makeFieldLinks($xxx, 'director'); - } else { - $xxx = false; - } - } + if ($xxx && isset($xxx['title'])) { + $xxx['title'] = str_replace(['/', '\\'], '', $xxx['title']); + $xxx['actors'] = $x->makeFieldLinks($xxx, 'actors'); + $xxx['genre'] = $x->makeFieldLinks($xxx, 'genre'); + $xxx['director'] = $x->makeFieldLinks($xxx, 'director'); + } else { + $xxx = false; + } + } - $game = ''; - if ($data['gamesinfo_id'] !== '') { - $g = new Games(); - $game = $g->getGamesInfoById($data['gamesinfo_id']); - } + $game = ''; + if ($data['gamesinfo_id'] !== '') { + $g = new Games(); + $game = $g->getGamesInfoById($data['gamesinfo_id']); + } - $mus = ''; - if ($data['musicinfo_id'] !== '') { - $music = new Music(['Settings' => $page->settings]); - $mus = $music->getMusicInfo($data['musicinfo_id']); - } + $mus = ''; + if ($data['musicinfo_id'] !== '') { + $music = new Music(['Settings' => $page->settings]); + $mus = $music->getMusicInfo($data['musicinfo_id']); + } - $book = ''; - if ($data['bookinfo_id'] !== '') { - $b = new Books(); - $book = $b->getBookInfo($data['bookinfo_id']); - } + $book = ''; + if ($data['bookinfo_id'] !== '') { + $b = new Books(); + $book = $b->getBookInfo($data['bookinfo_id']); + } - $con = ''; - if ($data['consoleinfo_id'] !== '') { - $c = new Console(); - $con = $c->getConsoleInfo($data['consoleinfo_id']); - } + $con = ''; + if ($data['consoleinfo_id'] !== '') { + $c = new Console(); + $con = $c->getConsoleInfo($data['consoleinfo_id']); + } - $AniDBAPIArray = ''; - if ($data['anidbid'] > 0) { - $AniDB = new AniDB(['Settings' => $releases->pdo]); - $AniDBAPIArray = $AniDB->getAnimeInfo($data['anidbid']); - } + $AniDBAPIArray = ''; + if ($data['anidbid'] > 0) { + $AniDB = new AniDB(['Settings' => $releases->pdo]); + $AniDBAPIArray = $AniDB->getAnimeInfo($data['anidbid']); + } - $prehash = new PreDb(); - $pre = $prehash->getForRelease($data['predb_id']); + $prehash = new PreDb(); + $pre = $prehash->getForRelease($data['predb_id']); - $rf = new ReleaseFiles; - $releasefiles = $rf->get($data['id']); + $rf = new ReleaseFiles; + $releasefiles = $rf->get($data['id']); - $page->smarty->assign('releasefiles',$releasefiles); - $page->smarty->assign('release',$data); - $page->smarty->assign('reVideo',$reVideo); - $page->smarty->assign('reAudio',$reAudio); - $page->smarty->assign('reSubs',$reSubs); - $page->smarty->assign('nfo',$nfo); - $page->smarty->assign('show',$showInfo); - $page->smarty->assign('movie',$mov); - $page->smarty->assign('xxx', $xxx); - $page->smarty->assign('anidb',$AniDBAPIArray); - $page->smarty->assign('music',$mus); - $page->smarty->assign('con',$con); - $page->smarty->assign('game', $game); - $page->smarty->assign('book',$book); - $page->smarty->assign('predb', $pre); - $page->smarty->assign('comments',$comments); - $page->smarty->assign('searchname',$releases->getSimilarName($data['searchname'])); - $page->smarty->assign('similars', $similars); - $page->smarty->assign('privateprofiles', (int)Settings::value('..privateprofiles') === 1); - $page->smarty->assign('failed', $failed); - $page->smarty->assign('cpapi', $cpapi); - $page->smarty->assign('cpurl', $cpurl); - $page->smarty->assign('regex', $releaseRegex); + $page->smarty->assign('releasefiles', $releasefiles); + $page->smarty->assign('release', $data); + $page->smarty->assign('reVideo', $reVideo); + $page->smarty->assign('reAudio', $reAudio); + $page->smarty->assign('reSubs', $reSubs); + $page->smarty->assign('nfo', $nfo); + $page->smarty->assign('show', $showInfo); + $page->smarty->assign('movie', $mov); + $page->smarty->assign('xxx', $xxx); + $page->smarty->assign('anidb', $AniDBAPIArray); + $page->smarty->assign('music', $mus); + $page->smarty->assign('con', $con); + $page->smarty->assign('game', $game); + $page->smarty->assign('book', $book); + $page->smarty->assign('predb', $pre); + $page->smarty->assign('comments', $comments); + $page->smarty->assign('searchname', $releases->getSimilarName($data['searchname'])); + $page->smarty->assign('similars', $similars); + $page->smarty->assign('privateprofiles', (int) Settings::value('..privateprofiles') === 1); + $page->smarty->assign('failed', $failed); + $page->smarty->assign('cpapi', $cpapi); + $page->smarty->assign('cpurl', $cpurl); + $page->smarty->assign('regex', $releaseRegex); - $page->meta_title = 'View NZB'; - $page->meta_keywords = 'view,nzb,description,details'; - $page->meta_description = 'View NZB for'.$data['searchname'] ; + $page->meta_title = 'View NZB'; + $page->meta_keywords = 'view,nzb,description,details'; + $page->meta_description = 'View NZB for'.$data['searchname']; - $page->content = $page->smarty->fetch('viewnzb.tpl'); - $page->render(); + $page->content = $page->smarty->fetch('viewnzb.tpl'); + $page->render(); } diff --git a/public/pages/failed.php b/public/pages/failed.php index 31db49dbb..3dc8fab6d 100644 --- a/public/pages/failed.php +++ b/public/pages/failed.php @@ -5,44 +5,43 @@ use nntmux\DnzbFailures; // Page is accessible only by the rss token, or logged in users. if ($page->users->isLoggedIn()) { - $uid = $page->users->currentUserId(); - $rssToken = $page->userdata['rsstoken']; + $uid = $page->users->currentUserId(); + $rssToken = $page->userdata['rsstoken']; } else { - if ((int)Settings::value('..registerstatus') === Settings::REGISTER_STATUS_API_ONLY) { - if (!isset($_GET['rsstoken'])) { - header('X-DNZB-RCode: 400'); - header('X-DNZB-RText: Bad request, please supply all parameters!'); - $page->show403(); - } else { - $res = $page->users->getByRssToken($_GET['rsstoken']); - } - } else { - if (!isset($_GET['userid']) || !isset($_GET['rsstoken'])) { - header('X-DNZB-RCode: 400'); - header('X-DNZB-RText: Bad request, please supply all parameters!'); - $page->show403(); - } else { - $res = $page->users->getByIdAndRssToken($_GET['userid'], $_GET['rsstoken']); - } - } - if (!isset($res)) { - header('X-DNZB-RCode: 401'); - header('X-DNZB-RText: Unauthorised, wrong user ID or rss key!'); - $page->show403(); - } else { - $uid = $res['id']; - $rssToken = $res['rsstoken']; - } + if ((int) Settings::value('..registerstatus') === Settings::REGISTER_STATUS_API_ONLY) { + if (! isset($_GET['rsstoken'])) { + header('X-DNZB-RCode: 400'); + header('X-DNZB-RText: Bad request, please supply all parameters!'); + $page->show403(); + } else { + $res = $page->users->getByRssToken($_GET['rsstoken']); + } + } else { + if (! isset($_GET['userid']) || ! isset($_GET['rsstoken'])) { + header('X-DNZB-RCode: 400'); + header('X-DNZB-RText: Bad request, please supply all parameters!'); + $page->show403(); + } else { + $res = $page->users->getByIdAndRssToken($_GET['userid'], $_GET['rsstoken']); + } + } + if (! isset($res)) { + header('X-DNZB-RCode: 401'); + header('X-DNZB-RText: Unauthorised, wrong user ID or rss key!'); + $page->show403(); + } else { + $uid = $res['id']; + $rssToken = $res['rsstoken']; + } } if (isset($_GET['guid'], $uid, $rssToken) && is_numeric($uid)) { - - $alt = (new DnzbFailures(['Settings' => $page->settings]))->getAlternate($_GET['guid'], $uid); - if ($alt === false) { - header('X-DNZB-RCode: 404'); - header('X-DNZB-RText: No NZB found for alternate match.'); - $page->show404(); - } else { - header('Location: ' . $page->serverurl . 'getnzb/' . $alt['guid'] . '&i=' . $uid . '&r=' . $rssToken); - } + $alt = (new DnzbFailures(['Settings' => $page->settings]))->getAlternate($_GET['guid'], $uid); + if ($alt === false) { + header('X-DNZB-RCode: 404'); + header('X-DNZB-RText: No NZB found for alternate match.'); + $page->show404(); + } else { + header('Location: '.$page->serverurl.'getnzb/'.$alt['guid'].'&i='.$uid.'&r='.$rssToken); + } } diff --git a/public/pages/filelist.php b/public/pages/filelist.php index af8ca9ae9..a4424caf1 100644 --- a/public/pages/filelist.php +++ b/public/pages/filelist.php @@ -1,56 +1,55 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } if (isset($_GET['id'])) { - $rel = $releases->getByGuid($_GET['id']); - if (!$rel) { - $page->show404(); - } + $rel = $releases->getByGuid($_GET['id']); + if (! $rel) { + $page->show404(); + } - $nzbpath = $nzb->NZBPath($_GET['id']); + $nzbpath = $nzb->NZBPath($_GET['id']); - if (!file_exists($nzbpath)) { - $page->show404(); - } + if (! file_exists($nzbpath)) { + $page->show404(); + } - ob_start(); - @readgzfile($nzbpath); - $nzbfile = ob_get_contents(); - ob_end_clean(); + ob_start(); + @readgzfile($nzbpath); + $nzbfile = ob_get_contents(); + ob_end_clean(); - $ret = $nzb->nzbFileList($nzbfile); + $ret = $nzb->nzbFileList($nzbfile); - $page->smarty->assign('rel', $rel); - $page->smarty->assign('files', $ret); + $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->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'; - $modal = false; - if (isset($_GET['modal'])) { - $modal = true; - $page->smarty->assign('modal', true); - } + $modal = false; + if (isset($_GET['modal'])) { + $modal = true; + $page->smarty->assign('modal', true); + } - $page->content = $page->smarty->fetch('viewfilelist.tpl'); + $page->content = $page->smarty->fetch('viewfilelist.tpl'); - if ($modal) { - echo $page->content; - } else { - $page->render(); - } + if ($modal) { + echo $page->content; + } else { + $page->render(); + } } - diff --git a/public/pages/forgottenpassword.php b/public/pages/forgottenpassword.php index 181eb3014..123c83088 100644 --- a/public/pages/forgottenpassword.php +++ b/public/pages/forgottenpassword.php @@ -1,11 +1,11 @@ users->isLoggedIn()) { - header('Location: ' . WWW_TOP . '/'); + header('Location: '.WWW_TOP.'/'); } $action = $_REQUEST['action'] ?? 'view'; @@ -13,76 +13,76 @@ $action = $_REQUEST['action'] ?? 'view'; $captcha = new Captcha($page); $email = $sent = $confirmed = ''; -switch($action) { +switch ($action) { case 'reset': - if (!isset($_REQUEST['guid'])) { - $page->smarty->assign('error', 'No reset code provided.'); - break; + if (! isset($_REQUEST['guid'])) { + $page->smarty->assign('error', 'No reset code provided.'); + break; } $ret = $page->users->getByPassResetGuid($_REQUEST['guid']); - if (!$ret) { - $page->smarty->assign('error', 'Bad reset code provided.'); - break; + if (! $ret) { + $page->smarty->assign('error', 'Bad reset code provided.'); + break; } else { - // - // reset the password, inform the user, send out the email - // - $page->users->updatePassResetGuid($ret['id'], ''); - $newpass = $page->users->generatePassword(); - $page->users->updatePassword($ret['id'], $newpass); + // + // reset the password, inform the user, send out the email + // + $page->users->updatePassResetGuid($ret['id'], ''); + $newpass = $page->users->generatePassword(); + $page->users->updatePassword($ret['id'], $newpass); - $to = $ret['email']; - $subject = Settings::value('site.main.title') . ' Password Reset'; - $contents = 'Your password has been reset to ' . $newpass; - $onscreen = 'Your password has been reset to ' . $newpass .' and sent to your e-mail address.'; - Utility::sendEmail($to, $subject, $contents, Settings::value('site.main.email')); - $page->smarty->assign('notice', $onscreen); - $confirmed = true; - break; + $to = $ret['email']; + $subject = Settings::value('site.main.title').' Password Reset'; + $contents = 'Your password has been reset to '.$newpass; + $onscreen = 'Your password has been reset to '.$newpass.' and sent to your e-mail address.'; + Utility::sendEmail($to, $subject, $contents, Settings::value('site.main.email')); + $page->smarty->assign('notice', $onscreen); + $confirmed = true; + break; } break; case 'submit': if ($captcha->getError() === false) { - $email = $_POST['email'] ?? ''; - if (empty($email)) { - $page->smarty->assign('error', 'Missing Email'); - } else { - // - // Check users exists and send an email - // - $ret = $page->users->getByEmail($email); - if (!$ret) { - $page->smarty->assign('error', 'The email address is not recognised.'); - $sent = true; - break; - } else { - // - // Generate a forgottenpassword guid, store it in the user table - // - $guid = md5(uniqid('', false)); - $page->users->updatePassResetGuid($ret['id'], $guid); + $email = $_POST['email'] ?? ''; + if (empty($email)) { + $page->smarty->assign('error', 'Missing Email'); + } else { + // + // Check users exists and send an email + // + $ret = $page->users->getByEmail($email); + if (! $ret) { + $page->smarty->assign('error', 'The email address is not recognised.'); + $sent = true; + break; + } else { + // + // Generate a forgottenpassword guid, store it in the user table + // + $guid = md5(uniqid('', false)); + $page->users->updatePassResetGuid($ret['id'], $guid); - // - // Send the email - // - $to = $ret['email']; - $subject = Settings::value('site.main.title') . ' Forgotten Password Request'; - $contents = 'Someone has requested a password reset for this email address. To reset the password use the following link. ' . PHP_EOL . PHP_EOL . $page->serverurl . 'forgottenpassword?action=reset&guid=' . $guid; - Utility::sendEmail($to, $subject, $contents, Settings::value('site.main.email')); - $sent = true; - break; - } - } - break; + // + // Send the email + // + $to = $ret['email']; + $subject = Settings::value('site.main.title').' Forgotten Password Request'; + $contents = 'Someone has requested a password reset for this email address. To reset the password use the following link. '.PHP_EOL.PHP_EOL.$page->serverurl.'forgottenpassword?action=reset&guid='.$guid; + Utility::sendEmail($to, $subject, $contents, Settings::value('site.main.email')); + $sent = true; + break; + } + } + break; } } $page->smarty->assign([ 'email' => $email, 'confirmed' => $confirmed, - 'sent' => $sent + 'sent' => $sent, ] ); diff --git a/public/pages/forum.php b/public/pages/forum.php index 7a2480517..f350ac4f8 100644 --- a/public/pages/forum.php +++ b/public/pages/forum.php @@ -1,59 +1,58 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } -if (!empty($_POST['addMessage']) && !empty($_POST['addSubject']) && $page->isPostBack()) { - $forum->add(0, $page->users->currentUserId(), $_POST['addSubject'], $_POST['addMessage']); - header('Location:'.WWW_TOP.'/forum'); - die(); +if (! empty($_POST['addMessage']) && ! empty($_POST['addSubject']) && $page->isPostBack()) { + $forum->add(0, $page->users->currentUserId(), $_POST['addSubject'], $_POST['addMessage']); + header('Location:'.WWW_TOP.'/forum'); + die(); } $lock = $unlock = null; -if (!empty($_GET['lock'])) { - $lock = $_GET['lock']; +if (! empty($_GET['lock'])) { + $lock = $_GET['lock']; } -if (!empty($_GET['unlock'])) { - $unlock = $_GET['unlock']; +if (! empty($_GET['unlock'])) { + $unlock = $_GET['unlock']; } if ($lock !== null) { - $forum->lockUnlockTopic($lock, 1); - header('Location:' . WWW_TOP . '/forum'); - die(); + $forum->lockUnlockTopic($lock, 1); + header('Location:'.WWW_TOP.'/forum'); + die(); } -if($unlock !== null) { - $forum->lockUnlockTopic($unlock, 0); - header('Location:' . WWW_TOP . '/forum'); - die(); +if ($unlock !== null) { + $forum->lockUnlockTopic($unlock, 0); + header('Location:'.WWW_TOP.'/forum'); + die(); } - $browsecount = $forum->getBrowseCount(); $offset = isset($_REQUEST['offset']) && ctype_digit($_REQUEST['offset']) ? $_REQUEST['offset'] : 0; $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('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'); -$page->smarty->assign('privateprofiles', (int)Settings::value('..privateprofiles') === 1); +$page->smarty->assign('privateprofiles', (int) Settings::value('..privateprofiles') === 1); $pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); -$page->smarty->assign('results',$results); +$page->smarty->assign('results', $results); $page->meta_title = 'Forum'; $page->meta_keywords = 'forum,chat,posts'; diff --git a/public/pages/forumpost.php b/public/pages/forumpost.php index afa91bbc5..cae7c190e 100644 --- a/public/pages/forumpost.php +++ b/public/pages/forumpost.php @@ -1,25 +1,25 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $id = $_GET['id'] + 0; $forum = new Forum(); -if (!empty($_POST['addMessage']) && $page->isPostBack()) { - $forum->add($id, $page->users->currentUserId(), '', $_POST['addMessage']); - header('Location:' . WWW_TOP . '/forumpost/' . $id . '#last'); - die(); +if (! empty($_POST['addMessage']) && $page->isPostBack()) { + $forum->add($id, $page->users->currentUserId(), '', $_POST['addMessage']); + header('Location:'.WWW_TOP.'/forumpost/'.$id.'#last'); + die(); } $results = $forum->getPosts($id); if (count($results) === 0) { - header('Location:' . WWW_TOP . '/forum'); - die(); + header('Location:'.WWW_TOP.'/forum'); + die(); } $page->meta_title = 'Forum Post'; @@ -27,9 +27,7 @@ $page->meta_keywords = 'view,forum,post,thread'; $page->meta_description = 'View forum post'; $page->smarty->assign('results', $results); -$page->smarty->assign('privateprofiles', (int)Settings::value('..privateprofiles') === 1); +$page->smarty->assign('privateprofiles', (int) Settings::value('..privateprofiles') === 1); $page->content = $page->smarty->fetch('forumpost.tpl'); $page->render(); - - diff --git a/public/pages/games.php b/public/pages/games.php index 4de38f61e..c280c9cfa 100644 --- a/public/pages/games.php +++ b/public/pages/games.php @@ -1,12 +1,12 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $games = new Games(['Settings' => $page->settings]); @@ -17,11 +17,11 @@ $fail = new DnzbFailures(['Settings' => $page->settings]); $concats = $cat->getChildren(Category::PC_ROOT); $ctmp = []; foreach ($concats as $ccat) { - $ctmp[$ccat['id']] = $ccat; + $ctmp[$ccat['id']] = $ccat; } $category = Category::PC_GAMES; if (isset($_REQUEST['t']) && array_key_exists($_REQUEST['t'], $ctmp)) { - $category = $_REQUEST['t'] + 0; + $category = $_REQUEST['t'] + 0; } $catarray = []; @@ -39,27 +39,27 @@ $results = $games2 = []; $results = $games->getGamesRange($catarray, $offset, ITEMS_PER_COVER_PAGE, $orderby, '', $page->userdata['categoryexclusions']); $maxwords = 50; foreach ($results as $result) { - if (!empty($result['review'])) { - // remove "Overview" from start of review if present - if (0 === strpos($result['review'], 'Overview')) { - $result['review'] = substr($result['review'], 8); - } - $words = explode(' ', $result['review']); - if (count($words) > $maxwords) { - $newwords = array_slice($words, 0, $maxwords); - $result['review'] = implode(' ', $newwords) . '...'; - } - } - $games2[] = $result; + if (! empty($result['review'])) { + // remove "Overview" from start of review if present + if (0 === strpos($result['review'], 'Overview')) { + $result['review'] = substr($result['review'], 8); + } + $words = explode(' ', $result['review']); + if (count($words) > $maxwords) { + $newwords = array_slice($words, 0, $maxwords); + $result['review'] = implode(' ', $newwords).'...'; + } + } + $games2[] = $result; } -$title = (isset($_REQUEST['title']) && !empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; +$title = (isset($_REQUEST['title']) && ! empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; $page->smarty->assign('title', $title); $genres = $gen->getGenres(Genres::GAME_TYPE, true); $tmpgnr = []; foreach ($genres as $gn) { - $tmpgnr[$gn['id']] = $gn['title']; + $tmpgnr[$gn['id']] = $gn['title']; } $years = range(1903, date('Y') + 1); @@ -72,30 +72,30 @@ $genre = (isset($_REQUEST['genre']) && array_key_exists($_REQUEST['genre'], $tmp $page->smarty->assign('genres', $genres); $page->smarty->assign('genre', $genre); -$browseby_link = '&title=' . $title . '&year=' . $year; +$browseby_link = '&title='.$title.'&year='.$year; $page->smarty->assign('pagertotalitems', $results[0]['_totalcount'] ?? 0); $page->smarty->assign('pageroffset', $offset); $page->smarty->assign('pageritemsperpage', ITEMS_PER_COVER_PAGE); -$page->smarty->assign('pagerquerybase', WWW_TOP . '/games?t=' . $category . $browseby_link . '&ob=' . $orderby . '&offset='); +$page->smarty->assign('pagerquerybase', WWW_TOP.'/games?t='.$category.$browseby_link.'&ob='.$orderby.'&offset='); $page->smarty->assign('pagerquerysuffix', '#results'); $pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); if ($category == -1) { - $page->smarty->assign('catname', 'All'); + $page->smarty->assign('catname', 'All'); } else { - $cdata = $cat->getById($category); - if ($cdata) { - $page->smarty->assign('catname', $cdata['title']); - } else { - $page->show404(); - } + $cdata = $cat->getById($category); + if ($cdata) { + $page->smarty->assign('catname', $cdata['title']); + } else { + $page->show404(); + } } foreach ($ordering as $ordertype) { - $page->smarty->assign('orderby' . $ordertype, WWW_TOP . '/games?t=' . $category . $browseby_link . '&ob=' . $ordertype . '&offset=0'); + $page->smarty->assign('orderby'.$ordertype, WWW_TOP.'/games?t='.$category.$browseby_link.'&ob='.$ordertype.'&offset=0'); } $page->smarty->assign('results', $games2); diff --git a/public/pages/getnzb.php b/public/pages/getnzb.php index 1480ee9af..f8e71495b 100644 --- a/public/pages/getnzb.php +++ b/public/pages/getnzb.php @@ -1,61 +1,61 @@ users->isLoggedIn()) { - $uid = $page->users->currentUserId(); - $maxDownloads = $page->userdata["downloadrequests"]; - $rssToken = $page->userdata['rsstoken']; - if ($page->users->isDisabled($page->userdata['username'])) { - Utility::showApiError(101); - } + $uid = $page->users->currentUserId(); + $maxDownloads = $page->userdata['downloadrequests']; + $rssToken = $page->userdata['rsstoken']; + if ($page->users->isDisabled($page->userdata['username'])) { + Utility::showApiError(101); + } } else { - if (Settings::value('..registerstatus') == Settings::REGISTER_STATUS_API_ONLY) { - $res = $page->users->getById(0); - } else { - if ((!isset($_GET["i"]) || !isset($_GET["r"]))) { - Utility::showApiError(200); - } + if (Settings::value('..registerstatus') == Settings::REGISTER_STATUS_API_ONLY) { + $res = $page->users->getById(0); + } else { + if ((! isset($_GET['i']) || ! isset($_GET['r']))) { + Utility::showApiError(200); + } - $res = $page->users->getByIdAndRssToken($_GET["i"], $_GET["r"]); - if (!$res) { - Utility::showApiError(100); - } - } - $uid = $res["id"]; - $rssToken = $res['rsstoken']; - $maxDownloads = $res["downloadrequests"]; - if ($page->users->isDisabled($res['username'])) { - Utility::showApiError(101); - } + $res = $page->users->getByIdAndRssToken($_GET['i'], $_GET['r']); + if (! $res) { + Utility::showApiError(100); + } + } + $uid = $res['id']; + $rssToken = $res['rsstoken']; + $maxDownloads = $res['downloadrequests']; + if ($page->users->isDisabled($res['username'])) { + Utility::showApiError(101); + } } // Remove any suffixed id with .nzb which is added to help weblogging programs see nzb traffic. if (isset($_GET['id'])) { - $_GET['id'] = str_ireplace('.nzb','', $_GET['id']); + $_GET['id'] = str_ireplace('.nzb', '', $_GET['id']); } // // A hash of the users ip to record against the download // -$hosthash = ""; +$hosthash = ''; if (Settings::value('..storeuserips') == 1) { - $hosthash = $page->users->getHostHash($_SERVER["REMOTE_ADDR"], Settings::value('..siteseed')); + $hosthash = $page->users->getHostHash($_SERVER['REMOTE_ADDR'], Settings::value('..siteseed')); } // Check download limit on user role. $requests = $page->users->getDownloadRequests($uid); if ($requests > $maxDownloads) { - Utility::showApiError(501); + Utility::showApiError(501); } -if (!isset($_GET['id'])) { - Utility::showApiError(200, 'parameter id is required'); +if (! isset($_GET['id'])) { + Utility::showApiError(200, 'parameter id is required'); } // Remove any suffixed id with .nzb which is added to help weblogging programs see nzb traffic. @@ -63,47 +63,47 @@ $_GET['id'] = str_ireplace('.nzb', '', $_GET['id']); $rel = new Releases(['Settings' => $page->settings]); // User requested a zip of guid,guid,guid releases. -if (isset($_GET["zip"]) && $_GET["zip"] == "1") { - $guids = explode(",", $_GET["id"]); - if ($requests['num'] + sizeof($guids) > $maxDownloads) { - Utility::showApiError(501); - } +if (isset($_GET['zip']) && $_GET['zip'] == '1') { + $guids = explode(',', $_GET['id']); + if ($requests['num'] + sizeof($guids) > $maxDownloads) { + Utility::showApiError(501); + } - $zip = $rel->getZipped($guids); - if (strlen($zip) > 0) { - $page->users->incrementGrabs($uid, count($guids)); - foreach ($guids as $guid) { - $rel->updateGrab($guid); - $page->users->addDownloadRequest($uid, $guid); + $zip = $rel->getZipped($guids); + if (strlen($zip) > 0) { + $page->users->incrementGrabs($uid, count($guids)); + foreach ($guids as $guid) { + $rel->updateGrab($guid); + $page->users->addDownloadRequest($uid, $guid); - if (isset($_GET["del"]) && $_GET["del"] == 1) { - $page->users->delCartByUserAndRelease($guid, $uid); - } - } + if (isset($_GET['del']) && $_GET['del'] == 1) { + $page->users->delCartByUserAndRelease($guid, $uid); + } + } - header("Content-type: application/octet-stream"); - header("Content-disposition: attachment; filename=" . date("Ymdhis") . ".nzb.zip"); - exit($zip); - } else { - $page->show404(); - } + header('Content-type: application/octet-stream'); + header('Content-disposition: attachment; filename='.date('Ymdhis').'.nzb.zip'); + exit($zip); + } else { + $page->show404(); + } } -$nzbPath = (new NZB($page->settings))->getNZBPath($_GET["id"]); -if (!file_exists($nzbPath)) { - Utility::showApiError(300, 'NZB file not found!'); +$nzbPath = (new NZB($page->settings))->getNZBPath($_GET['id']); +if (! file_exists($nzbPath)) { + Utility::showApiError(300, 'NZB file not found!'); } -$relData = $rel->getByGuid($_GET["id"]); +$relData = $rel->getByGuid($_GET['id']); if ($relData) { - $rel->updateGrab($_GET["id"]); - $page->users->addDownloadRequest($uid, $relData['id']); - $page->users->incrementGrabs($uid); - if (isset($_GET["del"]) && $_GET["del"] == 1) { - $page->users->delCartByUserAndRelease($_GET["id"], $uid); - } + $rel->updateGrab($_GET['id']); + $page->users->addDownloadRequest($uid, $relData['id']); + $page->users->incrementGrabs($uid); + if (isset($_GET['del']) && $_GET['del'] == 1) { + $page->users->delCartByUserAndRelease($_GET['id'], $uid); + } } else { - Utility::showApiError(300, 'Release not found!'); + Utility::showApiError(300, 'Release not found!'); } // Start reading output buffer. @@ -111,29 +111,29 @@ ob_start(); // De-gzip the NZB and store it in the output buffer. readgzfile($nzbPath); -$cleanName = str_replace(array(',', ' ', '/'), '_', $relData["searchname"]); +$cleanName = str_replace([',', ' ', '/'], '_', $relData['searchname']); // Set the NZB file name. -header("Content-Disposition: attachment; filename=" . $cleanName . ".nzb"); +header('Content-Disposition: attachment; filename='.$cleanName.'.nzb'); // Get the size of the NZB file. -header("Content-Length: " . ob_get_length()); -header("Content-Type: application/x-nzb"); -header("Expires: " . date('r', time() + 31536000)); +header('Content-Length: '.ob_get_length()); +header('Content-Type: application/x-nzb'); +header('Expires: '.date('r', time() + 31536000)); // Set X-DNZB header data. -header("X-DNZB-Failure: " . $page->serverurl . 'failed/' . '?guid=' . $_GET['id'] . '&userid=' . $uid . '&rsstoken=' . $rssToken); -header("X-DNZB-Category: " . $relData["category_name"]); -header("X-DNZB-Details: " . $page->serverurl . 'details/' . $_GET["id"]); -if (!empty($relData['imdbid']) && $relData['imdbid'] > 0) { - header("X-DNZB-MoreInfo: http://www.imdb.com/title/tt" . $relData['imdbid']); -} else if (!empty($relData['tvdb']) && $relData['tvdb'] > 0) { - header("X-DNZB-MoreInfo: http://www.thetvdb.com/?tab=series&id=" . $relData['tvdb']); +header('X-DNZB-Failure: '.$page->serverurl.'failed/'.'?guid='.$_GET['id'].'&userid='.$uid.'&rsstoken='.$rssToken); +header('X-DNZB-Category: '.$relData['category_name']); +header('X-DNZB-Details: '.$page->serverurl.'details/'.$_GET['id']); +if (! empty($relData['imdbid']) && $relData['imdbid'] > 0) { + header('X-DNZB-MoreInfo: http://www.imdb.com/title/tt'.$relData['imdbid']); +} elseif (! empty($relData['tvdb']) && $relData['tvdb'] > 0) { + header('X-DNZB-MoreInfo: http://www.thetvdb.com/?tab=series&id='.$relData['tvdb']); } -header("X-DNZB-Name: " . $cleanName); +header('X-DNZB-Name: '.$cleanName); if ($relData['nfostatus'] == 1) { - header("X-DNZB-NFO: " . $page->serverurl . 'nfo/' . $_GET["id"]); + header('X-DNZB-NFO: '.$page->serverurl.'nfo/'.$_GET['id']); } -header("X-DNZB-RCode: 200"); -header("X-DNZB-RText: OK, NZB content follows."); +header('X-DNZB-RCode: 200'); +header('X-DNZB-RText: OK, NZB content follows.'); // Print buffer and flush it. ob_end_flush(); diff --git a/public/pages/login.php b/public/pages/login.php index 43473ea25..2963102c6 100644 --- a/public/pages/login.php +++ b/public/pages/login.php @@ -8,44 +8,44 @@ $page->smarty->assign(['error' => '', 'username' => '', 'rememberme' => '']); $captcha = new Captcha($page); -if (!$page->users->isLoggedIn()) { - if (!isset($_POST['username']) || !isset($_POST['password'])) { - $page->smarty->assign('error', 'Please enter your username and password.'); - } elseif ($captcha->getError() === false) { - $username = htmlspecialchars($_POST['username']); - $page->smarty->assign('username', $username); - if (Utility::checkCsrfToken() === true) { - $logging = new Logging(['Settings' => $page->settings]); - $res = $page->users->getByUsername($username); +if (! $page->users->isLoggedIn()) { + if (! isset($_POST['username']) || ! isset($_POST['password'])) { + $page->smarty->assign('error', 'Please enter your username and password.'); + } elseif ($captcha->getError() === false) { + $username = htmlspecialchars($_POST['username']); + $page->smarty->assign('username', $username); + if (Utility::checkCsrfToken() === true) { + $logging = new Logging(['Settings' => $page->settings]); + $res = $page->users->getByUsername($username); - if ($res) { - $dis = $page->users->isDisabled($username); - if ($dis) { - $page->smarty->assign('error', 'Your account has been disabled.'); - } else if ($page->users->checkPassword($_POST['password'], $res['password'], $res['id'])) { - $rememberMe = (isset($_POST['rememberme']) && $_POST['rememberme'] === 'on'); - $page->users->login($res['id'], $_SERVER['REMOTE_ADDR'], $rememberMe); + if ($res) { + $dis = $page->users->isDisabled($username); + if ($dis) { + $page->smarty->assign('error', 'Your account has been disabled.'); + } elseif ($page->users->checkPassword($_POST['password'], $res['password'], $res['id'])) { + $rememberMe = (isset($_POST['rememberme']) && $_POST['rememberme'] === 'on'); + $page->users->login($res['id'], $_SERVER['REMOTE_ADDR'], $rememberMe); - if (isset($_POST['redirect']) && $_POST['redirect'] !== '') { - header('Location: ' . $_POST['redirect']); - } else { - header('Location: ' . WWW_TOP . $page->settings->home_link); - } - die(); - } else { - $page->smarty->assign('error', 'Incorrect username or password.'); - $logging->LogBadPasswd($username, $_SERVER['REMOTE_ADDR']); - } - } else { - $page->smarty->assign('error', 'Incorrect username or password.'); - $logging->LogBadPasswd($username, $_SERVER['REMOTE_ADDR']); - } - } else { - $page->showTokenError(); - } - } + if (isset($_POST['redirect']) && $_POST['redirect'] !== '') { + header('Location: '.$_POST['redirect']); + } else { + header('Location: '.WWW_TOP.$page->settings->home_link); + } + die(); + } else { + $page->smarty->assign('error', 'Incorrect username or password.'); + $logging->LogBadPasswd($username, $_SERVER['REMOTE_ADDR']); + } + } else { + $page->smarty->assign('error', 'Incorrect username or password.'); + $logging->LogBadPasswd($username, $_SERVER['REMOTE_ADDR']); + } + } else { + $page->showTokenError(); + } + } } else { - header('Location: ' . WWW_TOP . $page->settings->home_link); + header('Location: '.WWW_TOP.$page->settings->home_link); } $page->smarty->assign('redirect', $_GET['redirect'] ?? ''); diff --git a/public/pages/logout.php b/public/pages/logout.php index 0103baedb..46c6eea50 100644 --- a/public/pages/logout.php +++ b/public/pages/logout.php @@ -1,4 +1,5 @@ users->logout(); -header("Location: ".WWW_TOP."/login"); +header('Location: '.WWW_TOP.'/login'); diff --git a/public/pages/movie.php b/public/pages/movie.php index 72bafef10..a3042779c 100644 --- a/public/pages/movie.php +++ b/public/pages/movie.php @@ -2,38 +2,38 @@ use nntmux\Movie; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } if (isset($_GET['modal'], $_GET['id']) && ctype_digit($_GET['id'])) { - $movie = new Movie(['Settings' => $page->settings]); - $mov = $movie->getMovieInfo($_GET['id']); + $movie = new Movie(['Settings' => $page->settings]); + $mov = $movie->getMovieInfo($_GET['id']); - if (!$mov) { - $page->show404(); - } + if (! $mov) { + $page->show404(); + } - $mov['actors'] = $movie->makeFieldLinks($mov, 'actors'); - $mov['genre'] = $movie->makeFieldLinks($mov, 'genre'); - $mov['director'] = $movie->makeFieldLinks($mov, 'director'); + $mov['actors'] = $movie->makeFieldLinks($mov, 'actors'); + $mov['genre'] = $movie->makeFieldLinks($mov, 'genre'); + $mov['director'] = $movie->makeFieldLinks($mov, 'director'); - $page->smarty->assign(['movie' => $mov, 'modal' => true]); + $page->smarty->assign(['movie' => $mov, 'modal' => true]); - $page->title = 'Info for ' . $mov['title']; - $page->meta_title = ''; - $page->meta_keywords = ''; - $page->meta_description = ''; - $page->smarty->registerPlugin('modifier', 'ss', 'stripslashes'); + $page->title = 'Info for '.$mov['title']; + $page->meta_title = ''; + $page->meta_keywords = ''; + $page->meta_description = ''; + $page->smarty->registerPlugin('modifier', 'ss', 'stripslashes'); - if (isset($_GET['modal'])) { - $page->content = $page->smarty->fetch('viewmovie.tpl'); - $page->smarty->assign('modal', true); - echo $page->content; - } else { - $page->content = $page->smarty->fetch('viewmoviefull.tpl'); - $page->render(); - } + if (isset($_GET['modal'])) { + $page->content = $page->smarty->fetch('viewmovie.tpl'); + $page->smarty->assign('modal', true); + echo $page->content; + } else { + $page->content = $page->smarty->fetch('viewmoviefull.tpl'); + $page->render(); + } } else { - $page->render(); + $page->render(); } diff --git a/public/pages/movies.php b/public/pages/movies.php index 13d767dc0..6a2849415 100644 --- a/public/pages/movies.php +++ b/public/pages/movies.php @@ -1,27 +1,26 @@ $page->settings]); $cat = new Category(['Settings' => $page->settings]); $fail = new DnzbFailures(['Settings' => $page->settings]); -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } - $moviecats = $cat->getChildren(Category::MOVIE_ROOT); $mtmp = []; -foreach($moviecats as $mcat) { - $mtmp[$mcat['id']] = $mcat; +foreach ($moviecats as $mcat) { + $mtmp[$mcat['id']] = $mcat; } $category = (isset($_GET['imdb']) ? -1 : Category::MOVIE_ROOT); if (isset($_REQUEST['t']) && array_key_exists($_REQUEST['t'], $mtmp)) { - $category = $_REQUEST['t'] + 0; + $category = $_REQUEST['t'] + 0; } $user = $page->users->getById($page->users->currentUserId()); @@ -32,7 +31,7 @@ $page->smarty->assign('cpurl', $cpurl); $catarray = []; if ($category != -1) { - $catarray[] = $category; + $catarray[] = $category; } $page->smarty->assign('catlist', $mtmp); @@ -45,21 +44,21 @@ $orderby = isset($_REQUEST['ob']) && in_array($_REQUEST['ob'], $ordering) ? $_RE $results = $movies = []; $results = $movie->getMovieRange($catarray, $offset, ITEMS_PER_COVER_PAGE, $orderby, -1, $page->userdata['categoryexclusions']); foreach ($results as $result) { - $result['genre'] = $movie->makeFieldLinks($result, 'genre'); - $result['actors'] = $movie->makeFieldLinks($result, 'actors'); - $result['director'] = $movie->makeFieldLinks($result, 'director'); - $result['languages'] = explode(', ', $result['language']); + $result['genre'] = $movie->makeFieldLinks($result, 'genre'); + $result['actors'] = $movie->makeFieldLinks($result, 'actors'); + $result['director'] = $movie->makeFieldLinks($result, 'director'); + $result['languages'] = explode(', ', $result['language']); - $movies[] = $result; + $movies[] = $result; } -$title = (isset($_REQUEST['title']) && !empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; +$title = (isset($_REQUEST['title']) && ! empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; $page->smarty->assign('title', $title); -$actors = (isset($_REQUEST['actors']) && !empty($_REQUEST['actors'])) ? stripslashes($_REQUEST['actors']) : ''; +$actors = (isset($_REQUEST['actors']) && ! empty($_REQUEST['actors'])) ? stripslashes($_REQUEST['actors']) : ''; $page->smarty->assign('actors', $actors); -$director = (isset($_REQUEST['director']) && !empty($_REQUEST['director'])) ? stripslashes($_REQUEST['director']) : ''; +$director = (isset($_REQUEST['director']) && ! empty($_REQUEST['director'])) ? stripslashes($_REQUEST['director']) : ''; $page->smarty->assign('director', $director); $ratings = range(1, 9); @@ -72,7 +71,7 @@ $genre = (isset($_REQUEST['genre']) && in_array($_REQUEST['genre'], $genres, fal $page->smarty->assign('genres', $genres); $page->smarty->assign('genre', $genre); -$years = range(1903, (date('Y')+1)); +$years = range(1903, (date('Y') + 1)); rsort($years); $year = (isset($_REQUEST['year']) && in_array($_REQUEST['year'], $years, false)) ? $_REQUEST['year'] : ''; $page->smarty->assign('years', $years); @@ -81,8 +80,8 @@ $page->smarty->assign('year', $year); $browseby_link = '&title='.$title.'&actors='.$actors.'&director='.$director.'&rating='.$rating.'&genre='.$genre.'&year='.$year; $page->smarty->assign('pagertotalitems', $results[0]['_totalcount'] ?? 0); -$page->smarty->assign('pageroffset',$offset); -$page->smarty->assign('pageritemsperpage',ITEMS_PER_COVER_PAGE); +$page->smarty->assign('pageroffset', $offset); +$page->smarty->assign('pageritemsperpage', ITEMS_PER_COVER_PAGE); $page->smarty->assign('pagerquerybase', WWW_TOP.'/movies?t='.$category.$browseby_link.'&ob='.$orderby.'&offset='); $page->smarty->assign('pagerquerysuffix', '#results'); @@ -90,30 +89,30 @@ $pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); if ($category == -1) { - $page->smarty->assign('catname', 'All'); + $page->smarty->assign('catname', 'All'); } else { - $cat = new Category(); - $cdata = $cat->getById($category); - if ($cdata) { - $page->smarty->assign('catname', $cdata['title']); - } else { - $page->show404(); - } + $cat = new Category(); + $cdata = $cat->getById($category); + if ($cdata) { + $page->smarty->assign('catname', $cdata['title']); + } else { + $page->show404(); + } } -foreach($ordering as $ordertype) { - $page->smarty->assign('orderby' . $ordertype, WWW_TOP . '/movies?t=' . $category . $browseby_link . '&ob=' . $ordertype . '&offset=0'); +foreach ($ordering as $ordertype) { + $page->smarty->assign('orderby'.$ordertype, WWW_TOP.'/movies?t='.$category.$browseby_link.'&ob='.$ordertype.'&offset=0'); } -$page->smarty->assign('results',$movies); +$page->smarty->assign('results', $movies); $page->meta_title = 'Browse Nzbs'; $page->meta_keywords = 'browse,nzb,description,details'; $page->meta_description = 'Browse for Nzbs'; if (isset($_GET['imdb'])) { - $page->content = $page->smarty->fetch('viewmoviefull.tpl'); + $page->content = $page->smarty->fetch('viewmoviefull.tpl'); } else { - $page->content = $page->smarty->fetch('movies.tpl'); + $page->content = $page->smarty->fetch('movies.tpl'); } $page->render(); diff --git a/public/pages/movietrailer.php b/public/pages/movietrailer.php index f58a1e37a..69a0bf809 100644 --- a/public/pages/movietrailer.php +++ b/public/pages/movietrailer.php @@ -4,36 +4,36 @@ use nntmux\Movie; $movie = new Movie; -if (!$page->users->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(); +if (! $page->users->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/public/pages/music.php b/public/pages/music.php index 13cf55e49..7424d28ba 100644 --- a/public/pages/music.php +++ b/public/pages/music.php @@ -1,12 +1,12 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $music = new Music(['Settings' => $page->settings]); @@ -17,11 +17,11 @@ $fail = new DnzbFailures(['Settings' => $page->settings]); $musiccats = $cat->getChildren(Category::MUSIC_ROOT); $mtmp = []; foreach ($musiccats as $mcat) { - $mtmp[$mcat['id']] = $mcat; + $mtmp[$mcat['id']] = $mcat; } $category = Category::MUSIC_ROOT; if (isset($_REQUEST['t']) && array_key_exists($_REQUEST['t'], $mtmp)) { - $category = $_REQUEST['t'] + 0; + $category = $_REQUEST['t'] + 0; } $catarray = []; @@ -37,64 +37,64 @@ $orderby = isset($_REQUEST['ob']) && in_array($_REQUEST['ob'], $ordering) ? $_RE $results = $musics = []; $results = $music->getMusicRange($catarray, $offset, ITEMS_PER_COVER_PAGE, $orderby, $page->userdata['categoryexclusions']); -$artist = (isset($_REQUEST['artist']) && !empty($_REQUEST['artist'])) ? stripslashes($_REQUEST['artist']) : ''; +$artist = (isset($_REQUEST['artist']) && ! empty($_REQUEST['artist'])) ? stripslashes($_REQUEST['artist']) : ''; $page->smarty->assign('artist', $artist); -$title = (isset($_REQUEST['title']) && !empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; +$title = (isset($_REQUEST['title']) && ! empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; $page->smarty->assign('title', $title); $genres = $gen->getGenres(Genres::MUSIC_TYPE, true); $tmpgnr = []; foreach ($genres as $gn) { - $tmpgnr[$gn['id']] = $gn['title']; + $tmpgnr[$gn['id']] = $gn['title']; } foreach ($results as $result) { - $result['genre'] = $tmpgnr[$result["genres_id"]]; - $musics[] = $result; + $result['genre'] = $tmpgnr[$result['genres_id']]; + $musics[] = $result; } $genre = (isset($_REQUEST['genre']) && array_key_exists($_REQUEST['genre'], $tmpgnr)) ? $_REQUEST['genre'] : ''; $page->smarty->assign('genres', $genres); $page->smarty->assign('genre', $genre); -$years = range(1950, (date("Y") + 1)); +$years = range(1950, (date('Y') + 1)); rsort($years); $year = (isset($_REQUEST['year']) && in_array($_REQUEST['year'], $years)) ? $_REQUEST['year'] : ''; $page->smarty->assign('years', $years); $page->smarty->assign('year', $year); -$browseby_link = '&title=' . $title . '&artist=' . $artist . '&genre=' . $genre . '&year=' . $year; +$browseby_link = '&title='.$title.'&artist='.$artist.'&genre='.$genre.'&year='.$year; $page->smarty->assign('pagertotalitems', isset($results[0]['_totalcount']) ? $results[0]['_totalcount'] : 0); $page->smarty->assign('pageroffset', $offset); $page->smarty->assign('pageritemsperpage', ITEMS_PER_COVER_PAGE); -$page->smarty->assign('pagerquerybase', WWW_TOP . "/music?t=" . $category . $browseby_link . "&ob=" . $orderby . "&offset="); -$page->smarty->assign('pagerquerysuffix', "#results"); +$page->smarty->assign('pagerquerybase', WWW_TOP.'/music?t='.$category.$browseby_link.'&ob='.$orderby.'&offset='); +$page->smarty->assign('pagerquerysuffix', '#results'); -$pager = $page->smarty->fetch("pager.tpl"); +$pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); if ($category == -1) { - $page->smarty->assign("catname", "All"); + $page->smarty->assign('catname', 'All'); } else { - $cdata = $cat->getById($category); - if ($cdata) { - $page->smarty->assign('catname', $cdata['title']); - } else { - $page->show404(); - } + $cdata = $cat->getById($category); + if ($cdata) { + $page->smarty->assign('catname', $cdata['title']); + } else { + $page->show404(); + } } foreach ($ordering as $ordertype) { - $page->smarty->assign('orderby' . $ordertype, WWW_TOP . "/music?t=" . $category . $browseby_link . "&ob=" . $ordertype . "&offset=0"); + $page->smarty->assign('orderby'.$ordertype, WWW_TOP.'/music?t='.$category.$browseby_link.'&ob='.$ordertype.'&offset=0'); } $page->smarty->assign('results', $musics); -$page->meta_title = "Browse Albums"; -$page->meta_keywords = "browse,nzb,albums,description,details"; -$page->meta_description = "Browse for Albums"; +$page->meta_title = 'Browse Albums'; +$page->meta_keywords = 'browse,nzb,albums,description,details'; +$page->meta_description = 'Browse for Albums'; $page->content = $page->smarty->fetch('music.tpl'); $page->render(); diff --git a/public/pages/musicmodal.php b/public/pages/musicmodal.php index 3fefc2963..63936b3e7 100644 --- a/public/pages/musicmodal.php +++ b/public/pages/musicmodal.php @@ -4,36 +4,36 @@ use nntmux\Music; $music = new Music; -if (!$page->users->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(); +if (! $page->users->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/public/pages/mymovies.php b/public/pages/mymovies.php index 964aec2a9..300031a9b 100755 --- a/public/pages/mymovies.php +++ b/public/pages/mymovies.php @@ -1,13 +1,13 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $um = new UserMovies(['Settings' => $page->settings]); @@ -17,23 +17,23 @@ $action = isset($_REQUEST['id']) ? $_REQUEST['id'] : ''; $imdbid = isset($_REQUEST['subpage']) ? $_REQUEST['subpage'] : ''; if (isset($_REQUEST['from'])) { - $page->smarty->assign('from', WWW_TOP . $_REQUEST['from']); + $page->smarty->assign('from', WWW_TOP.$_REQUEST['from']); } else { - $page->smarty->assign('from', WWW_TOP . '/mymovies'); + $page->smarty->assign('from', WWW_TOP.'/mymovies'); } switch ($action) { case 'delete': $movie = $um->getMovie($page->users->currentUserId(), $imdbid); if (isset($_REQUEST['from'])) { - header("Location:" . WWW_TOP . $_REQUEST['from']); + header('Location:'.WWW_TOP.$_REQUEST['from']); } else { - header("Location:" . WWW_TOP . "/mymovies"); + header('Location:'.WWW_TOP.'/mymovies'); } - if (!$movie) { - $page->show404('Not subscribed'); + if (! $movie) { + $page->show404('Not subscribed'); } else { - $um->delMovie($page->users->currentUserId(), $imdbid); + $um->delMovie($page->users->currentUserId(), $imdbid); } break; @@ -41,109 +41,109 @@ switch ($action) { case 'doadd': $movie = $um->getMovie($page->users->currentUserId(), $imdbid); if ($movie) { - $page->show404('Already subscribed'); + $page->show404('Already subscribed'); } else { - $movie = $mv->getMovieInfo($imdbid); - if (!$movie) { - $page->show404('No matching movie.'); - } + $movie = $mv->getMovieInfo($imdbid); + if (! $movie) { + $page->show404('No matching movie.'); + } } if ($action == 'doadd') { - $category = (isset($_REQUEST['category']) && is_array($_REQUEST['category']) && !empty($_REQUEST['category'])) ? $_REQUEST['category'] : []; - $um->addMovie($page->users->currentUserId(), $imdbid, $category); - if (isset($_REQUEST['from'])) { - header("Location:" . WWW_TOP . $_REQUEST['from']); - } else { - header("Location:" . WWW_TOP . "/mymovies"); - } + $category = (isset($_REQUEST['category']) && is_array($_REQUEST['category']) && ! empty($_REQUEST['category'])) ? $_REQUEST['category'] : []; + $um->addMovie($page->users->currentUserId(), $imdbid, $category); + if (isset($_REQUEST['from'])) { + header('Location:'.WWW_TOP.$_REQUEST['from']); + } else { + header('Location:'.WWW_TOP.'/mymovies'); + } } else { - $cat = new Category(['Settings' => $page->settings]); - $tmpcats = $cat->getChildren(Category::MOVIE_ROOT); - $categories = []; - foreach ($tmpcats as $c) { - // If MOVIE WEB-DL categorization is disabled, don't include it as an option - if (Settings::value('indexer.categorise.catwebdl') == 0 && $c['id'] == Category::MOVIE_WEBDL) { - continue; - } - $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', []); - $page->smarty->assign('imdbid', $imdbid); - $page->smarty->assign('movie', $movie); - $page->content = $page->smarty->fetch('mymovies-add.tpl'); - $page->render(); + $cat = new Category(['Settings' => $page->settings]); + $tmpcats = $cat->getChildren(Category::MOVIE_ROOT); + $categories = []; + foreach ($tmpcats as $c) { + // If MOVIE WEB-DL categorization is disabled, don't include it as an option + if (Settings::value('indexer.categorise.catwebdl') == 0 && $c['id'] == Category::MOVIE_WEBDL) { + continue; + } + $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', []); + $page->smarty->assign('imdbid', $imdbid); + $page->smarty->assign('movie', $movie); + $page->content = $page->smarty->fetch('mymovies-add.tpl'); + $page->render(); } break; case 'edit': case 'doedit': $movie = $um->getMovie($page->users->currentUserId(), $imdbid); - if (!$movie) { - $page->show404(); + if (! $movie) { + $page->show404(); } if ($action == 'doedit') { - $category = (isset($_REQUEST['category']) && is_array($_REQUEST['category']) && !empty($_REQUEST['category'])) ? $_REQUEST['category'] : []; - $um->updateMovie($page->users->currentUserId(), $imdbid, $category); - if (isset($_REQUEST['from'])) { - header("Location:" . WWW_TOP . $_REQUEST['from']); - } else { - header("Location:" . WWW_TOP . "/mymovies"); - } + $category = (isset($_REQUEST['category']) && is_array($_REQUEST['category']) && ! empty($_REQUEST['category'])) ? $_REQUEST['category'] : []; + $um->updateMovie($page->users->currentUserId(), $imdbid, $category); + if (isset($_REQUEST['from'])) { + header('Location:'.WWW_TOP.$_REQUEST['from']); + } else { + header('Location:'.WWW_TOP.'/mymovies'); + } } else { - $cat = new Category(['Settings' => $page->settings]); + $cat = new Category(['Settings' => $page->settings]); - $tmpcats = $cat->getChildren(Category::MOVIE_ROOT); - $categories = []; - foreach ($tmpcats as $c) { - $categories[$c['id']] = $c['title']; - } + $tmpcats = $cat->getChildren(Category::MOVIE_ROOT); + $categories = []; + 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('|', $movie['categories'])); - $page->smarty->assign('imdbid', $imdbid); - $page->smarty->assign('movie', $movie); - $page->content = $page->smarty->fetch('mymovies-add.tpl'); - $page->render(); + $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('|', $movie['categories'])); + $page->smarty->assign('imdbid', $imdbid); + $page->smarty->assign('movie', $movie); + $page->content = $page->smarty->fetch('mymovies-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"; + $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'; $movies = $um->getMovies($page->users->currentUserId()); $releases = new Releases(['Settings' => $page->settings]); - $browsecount = $releases->getMovieCount($movies, -1, $page->userdata["categoryexclusions"]); + $browsecount = $releases->getMovieCount($movies, -1, $page->userdata['categoryexclusions']); - $offset = (isset($_REQUEST["offset"]) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST["offset"] : 0; + $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"] : ''; + $orderby = isset($_REQUEST['ob']) && in_array($_REQUEST['ob'], $ordering) ? $_REQUEST['ob'] : ''; $results = []; - $results = $mv->getMovieRange($movies, $offset, ITEMS_PER_PAGE, $orderby, -1, $page->userdata["categoryexclusions"]); + $results = $mv->getMovieRange($movies, $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 . "/mymovies/browse?ob=" . $orderby . "&offset="); - $page->smarty->assign('pagerquerysuffix', "#results"); + $page->smarty->assign('pagerquerybase', WWW_TOP.'/mymovies/browse?ob='.$orderby.'&offset='); + $page->smarty->assign('pagerquerysuffix', '#results'); $page->smarty->assign('covgroup', ''); - $pager = $page->smarty->fetch("pager.tpl"); + $pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); foreach ($ordering as $ordertype) { - $page->smarty->assign('orderby' . $ordertype, WWW_TOP . "/mymovies/browse?ob=" . $ordertype . "&offset=0"); + $page->smarty->assign('orderby'.$ordertype, WWW_TOP.'/mymovies/browse?ob='.$ordertype.'&offset=0'); } $page->smarty->assign('lastvisit', $page->userdata['lastlogin']); @@ -157,35 +157,35 @@ switch ($action) { break; default: - $page->title = "My Movies"; - $page->meta_title = "My Movies"; - $page->meta_keywords = "search,add,to,cart,nzb,description,details"; - $page->meta_description = "Manage Your Movies"; + $page->title = 'My Movies'; + $page->meta_title = 'My Movies'; + $page->meta_keywords = 'search,add,to,cart,nzb,description,details'; + $page->meta_description = 'Manage Your Movies'; $cat = new Category(['Settings' => $page->settings]); $tmpcats = $cat->getChildren(Category::MOVIE_ROOT); $categories = []; foreach ($tmpcats as $c) { - $categories[$c['id']] = $c['title']; + $categories[$c['id']] = $c['title']; } $movies = $um->getMovies($page->users->currentUserId()); $results = []; foreach ($movies as $moviek => $movie) { - $showcats = explode('|', $movie['categories']); - if (is_array($showcats) && sizeof($showcats) > 0) { - $catarr = []; - foreach ($showcats as $scat) { - if (!empty($scat)) { - $catarr[] = $categories[$scat]; - } - } - $movie['categoryNames'] = implode(', ', $catarr); - } else { - $movie['categoryNames'] = ''; - } + $showcats = explode('|', $movie['categories']); + if (is_array($showcats) && sizeof($showcats) > 0) { + $catarr = []; + foreach ($showcats as $scat) { + if (! empty($scat)) { + $catarr[] = $categories[$scat]; + } + } + $movie['categoryNames'] = implode(', ', $catarr); + } else { + $movie['categoryNames'] = ''; + } - $results[$moviek] = $movie; + $results[$moviek] = $movie; } $page->smarty->assign('movies', $results); diff --git a/public/pages/myshows.php b/public/pages/myshows.php index 2f709169e..d706e36c0 100755 --- a/public/pages/myshows.php +++ b/public/pages/myshows.php @@ -1,13 +1,13 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $us = new UserSeries(['Settings' => $page->settings]); @@ -17,23 +17,23 @@ $action = isset($_REQUEST['id']) ? $_REQUEST['id'] : ''; $videoId = isset($_REQUEST['subpage']) ? $_REQUEST['subpage'] : ''; if (isset($_REQUEST['from'])) { - $page->smarty->assign('from', WWW_TOP . $_REQUEST['from']); + $page->smarty->assign('from', WWW_TOP.$_REQUEST['from']); } else { - $page->smarty->assign('from', WWW_TOP . '/myshows'); + $page->smarty->assign('from', WWW_TOP.'/myshows'); } switch ($action) { case 'delete': $show = $us->getShow($page->users->currentUserId(), $videoId); if (isset($_REQUEST['from'])) { - header("Location:" . WWW_TOP . $_REQUEST['from']); + header('Location:'.WWW_TOP.$_REQUEST['from']); } else { - header("Location:" . WWW_TOP . "/myshows"); + header('Location:'.WWW_TOP.'/myshows'); } - if (!$show) { - $page->show404('Not subscribed'); + if (! $show) { + $page->show404('Not subscribed'); } else { - $us->delShow($page->users->currentUserId(), $videoId); + $us->delShow($page->users->currentUserId(), $videoId); } break; @@ -41,109 +41,109 @@ switch ($action) { case 'doadd': $show = $us->getShow($page->users->currentUserId(), $videoId); if ($show) { - $page->show404('Already subscribed'); + $page->show404('Already subscribed'); } else { - $show = $tv->getByVideoID($videoId); - if (!$show) { - $page->show404('No matching show.'); - } + $show = $tv->getByVideoID($videoId); + if (! $show) { + $page->show404('No matching show.'); + } } if ($action == 'doadd') { - $category = (isset($_REQUEST['category']) && is_array($_REQUEST['category']) && !empty($_REQUEST['category'])) ? $_REQUEST['category'] : []; - $us->addShow($page->users->currentUserId(), $videoId, $category); - if (isset($_REQUEST['from'])) { - header("Location:" . WWW_TOP . $_REQUEST['from']); - } else { - header("Location:" . WWW_TOP . "/myshows"); - } + $category = (isset($_REQUEST['category']) && is_array($_REQUEST['category']) && ! empty($_REQUEST['category'])) ? $_REQUEST['category'] : []; + $us->addShow($page->users->currentUserId(), $videoId, $category); + if (isset($_REQUEST['from'])) { + header('Location:'.WWW_TOP.$_REQUEST['from']); + } else { + header('Location:'.WWW_TOP.'/myshows'); + } } else { - $cat = new Category(['Settings' => $page->settings]); - $tmpcats = $cat->getChildren(Category::TV_ROOT); - $categories = []; - foreach ($tmpcats as $c) { - // If TV WEB-DL categorization is disabled, don't include it as an option - if (Settings::value('indexer.categorise.catwebdl') == 0 && $c['id'] == Category::TV_WEBDL) { - continue; - } - $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('video', $videoId); - $page->smarty->assign('show', $show); - $page->content = $page->smarty->fetch('myshows-add.tpl'); - $page->render(); + $cat = new Category(['Settings' => $page->settings]); + $tmpcats = $cat->getChildren(Category::TV_ROOT); + $categories = []; + foreach ($tmpcats as $c) { + // If TV WEB-DL categorization is disabled, don't include it as an option + if (Settings::value('indexer.categorise.catwebdl') == 0 && $c['id'] == Category::TV_WEBDL) { + continue; + } + $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', []); + $page->smarty->assign('video', $videoId); + $page->smarty->assign('show', $show); + $page->content = $page->smarty->fetch('myshows-add.tpl'); + $page->render(); } break; case 'edit': case 'doedit': $show = $us->getShow($page->users->currentUserId(), $videoId); - if (!$show) { - $page->show404(); + if (! $show) { + $page->show404(); } if ($action == 'doedit') { - $category = (isset($_REQUEST['category']) && is_array($_REQUEST['category']) && !empty($_REQUEST['category'])) ? $_REQUEST['category'] : []; - $us->updateShow($page->users->currentUserId(), $videoId, $category); - if (isset($_REQUEST['from'])) { - header("Location:" . WWW_TOP . $_REQUEST['from']); - } else { - header("Location:" . WWW_TOP . "/myshows"); - } + $category = (isset($_REQUEST['category']) && is_array($_REQUEST['category']) && ! empty($_REQUEST['category'])) ? $_REQUEST['category'] : []; + $us->updateShow($page->users->currentUserId(), $videoId, $category); + if (isset($_REQUEST['from'])) { + header('Location:'.WWW_TOP.$_REQUEST['from']); + } else { + header('Location:'.WWW_TOP.'/myshows'); + } } else { - $cat = new Category(['Settings' => $page->settings]); + $cat = new Category(['Settings' => $page->settings]); - $tmpcats = $cat->getChildren(Category::TV_ROOT); - $categories = []; - foreach ($tmpcats as $c) { - $categories[$c['id']] = $c['title']; - } + $tmpcats = $cat->getChildren(Category::TV_ROOT); + $categories = []; + 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['categories'])); - $page->smarty->assign('video', $videoId); - $page->smarty->assign('show', $show); - $page->content = $page->smarty->fetch('myshows-add.tpl'); - $page->render(); + $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['categories'])); + $page->smarty->assign('video', $videoId); + $page->smarty->assign('show', $show); + $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"; + $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($page->users->currentUserId()); $releases = new Releases(['Settings' => $page->settings]); - $browsecount = $releases->getShowsCount($shows, -1, $page->userdata["categoryexclusions"]); + $browsecount = $releases->getShowsCount($shows, -1, $page->userdata['categoryexclusions']); - $offset = (isset($_REQUEST["offset"]) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST["offset"] : 0; + $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"] : ''; + $orderby = isset($_REQUEST['ob']) && in_array($_REQUEST['ob'], $ordering) ? $_REQUEST['ob'] : ''; $results = []; - $results = $releases->getShowsRange($shows, $offset, ITEMS_PER_PAGE, $orderby, -1, $page->userdata["categoryexclusions"]); + $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"); + $page->smarty->assign('pagerquerybase', WWW_TOP.'/myshows/browse?ob='.$orderby.'&offset='); + $page->smarty->assign('pagerquerysuffix', '#results'); $page->smarty->assign('covgroup', ''); - $pager = $page->smarty->fetch("pager.tpl"); + $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('orderby'.$ordertype, WWW_TOP.'/myshows/browse?ob='.$ordertype.'&offset=0'); } $page->smarty->assign('lastvisit', $page->userdata['lastlogin']); @@ -157,35 +157,35 @@ switch ($action) { 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"; + $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(['Settings' => $page->settings]); $tmpcats = $cat->getChildren(Category::TV_ROOT); $categories = []; foreach ($tmpcats as $c) { - $categories[$c['id']] = $c['title']; + $categories[$c['id']] = $c['title']; } $shows = $us->getShows($page->users->currentUserId()); $results = []; foreach ($shows as $showk => $show) { - $showcats = explode('|', $show['categories']); - if (is_array($showcats) && sizeof($showcats) > 0) { - $catarr = []; - foreach ($showcats as $scat) { - if (!empty($scat)) { - $catarr[] = $categories[$scat]; - } - } - $show['categoryNames'] = implode(', ', $catarr); - } else { - $show['categoryNames'] = ''; - } + $showcats = explode('|', $show['categories']); + if (is_array($showcats) && sizeof($showcats) > 0) { + $catarr = []; + foreach ($showcats as $scat) { + if (! empty($scat)) { + $catarr[] = $categories[$scat]; + } + } + $show['categoryNames'] = implode(', ', $catarr); + } else { + $show['categoryNames'] = ''; + } - $results[$showk] = $show; + $results[$showk] = $show; } $page->smarty->assign('shows', $results); diff --git a/public/pages/newposterwall.php b/public/pages/newposterwall.php index e965b5cbb..e4464ca92 100644 --- a/public/pages/newposterwall.php +++ b/public/pages/newposterwall.php @@ -1,58 +1,58 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } -use nntmux\Releases; -use nntmux\Contents; use nntmux\Category; +use nntmux\Contents; +use nntmux\Releases; $releases = new Releases(['Settings' => $page->settings]); $contents = new Contents(['Settings' => $page->settings]); $category = new Category(['Settings' => $page->settings]); -$error = false; +$error = false; // Array with all the possible poster wall types. -$startTypes = array('Books', 'Console', 'Movies', 'XXX', 'Audio', 'PC', 'TV', 'Anime'/*, 'Recent'*/); +$startTypes = ['Books', 'Console', 'Movies', 'XXX', 'Audio', 'PC', 'TV', 'Anime'/*, 'Recent'*/]; // Array that will contain the poster wall types (the above array minus whatever they have disabled in admin). $types = []; // Get the names of all enabled parent categories. $categories = $category->getEnabledParentNames(); // Loop through our possible ones and check if they are in the enabled categories. if (count($categories) > 0) { - foreach ($categories as $pType) { - if (in_array($pType['title'], $startTypes)) { - $types[] = $pType['title']; - if ($pType['title'] == 'TV') { - $types[] = 'Anime'; - } - } - } + foreach ($categories as $pType) { + if (in_array($pType['title'], $startTypes)) { + $types[] = $pType['title']; + if ($pType['title'] == 'TV') { + $types[] = 'Anime'; + } + } + } } else { - $error = "No categories are enabled!"; + $error = 'No categories are enabled!'; } if (count($types) === 0) { - $error = 'No categories enabled for the new poster wall. Possible choices are: ' . implode(', ', $startTypes) . '.'; + $error = 'No categories enabled for the new poster wall. Possible choices are: '.implode(', ', $startTypes).'.'; } -if (!$error) { +if (! $error) { // Check if the user did not pass the required t parameter, set it to the first type. - if (!isset($_REQUEST['t'])) { - $_REQUEST['t'] = $types[0]; - } + if (! isset($_REQUEST['t'])) { + $_REQUEST['t'] = $types[0]; + } - // Check if the user passed an invalid t parameter. - if (!in_array($_REQUEST['t'], $types)) { - $_REQUEST['t'] = $types[0]; - } + // Check if the user passed an invalid t parameter. + if (! in_array($_REQUEST['t'], $types)) { + $_REQUEST['t'] = $types[0]; + } - $page->smarty->assign('types', $types); - $page->smarty->assign('type', $_REQUEST['t']); + $page->smarty->assign('types', $types); + $page->smarty->assign('type', $_REQUEST['t']); - switch ($_REQUEST['t']) { + switch ($_REQUEST['t']) { case 'Movies': $getnewestmovies = $releases->getNewestMovies(); $page->smarty->assign('newest', $getnewestmovies); @@ -112,13 +112,13 @@ if (!$error) { break; default: - $error = "ERROR: Invalid ?t parameter (" . $_REQUEST['t'] . ")."; + $error = 'ERROR: Invalid ?t parameter ('.$_REQUEST['t'].').'; } } -$page->title = 'New ' . $_REQUEST['t'] . ' Releases'; -$page->meta_title = $_REQUEST['t'] . ' Poster Wall'; -$page->meta_keywords = "view,new,releases,posters,wall"; -$page->meta_description = "The newest " . $_REQUEST['t'] . ' releases'; +$page->title = 'New '.$_REQUEST['t'].' Releases'; +$page->meta_title = $_REQUEST['t'].' Poster Wall'; +$page->meta_keywords = 'view,new,releases,posters,wall'; +$page->meta_description = 'The newest '.$_REQUEST['t'].' releases'; $page->smarty->assign('error', $error); $page->content = $page->smarty->fetch('newposterwall.tpl'); $page->render(); diff --git a/public/pages/nfo.php b/public/pages/nfo.php index ec8d6b1d3..edafcc967 100644 --- a/public/pages/nfo.php +++ b/public/pages/nfo.php @@ -1,40 +1,43 @@ users->isLoggedIn()) - $page->show403(); - -if (isset($_GET["id"])) { - $rel = $releases->getByGuid($_GET["id"]); - - if (!$rel) - $page->show404(); - - $nfo = $releases->getReleaseNfo($rel['id']); - $nfo['nfoUTF'] = Utility::cp437toUTF($nfo['nfo']); - - $page->smarty->assign('rel', $rel); - $page->smarty->assign('nfo', $nfo); - - $page->title = "NFO File"; - $page->meta_title = "View Nfo"; - $page->meta_keywords = "view,nzb,nfo,description,details"; - $page->meta_description = "View Nfo File"; - - $modal = false; - if (isset($_GET['modal'])) { - $modal = true; - $page->smarty->assign('modal', true); - } - - $page->content = $page->smarty->fetch('viewnfo.tpl'); - - if ($modal) - echo $page->content; - else - $page->render(); +if (! $page->users->isLoggedIn()) { + $page->show403(); +} + +if (isset($_GET['id'])) { + $rel = $releases->getByGuid($_GET['id']); + + if (! $rel) { + $page->show404(); + } + + $nfo = $releases->getReleaseNfo($rel['id']); + $nfo['nfoUTF'] = Utility::cp437toUTF($nfo['nfo']); + + $page->smarty->assign('rel', $rel); + $page->smarty->assign('nfo', $nfo); + + $page->title = 'NFO File'; + $page->meta_title = 'View Nfo'; + $page->meta_keywords = 'view,nzb,nfo,description,details'; + $page->meta_description = 'View Nfo File'; + + $modal = false; + if (isset($_GET['modal'])) { + $modal = true; + $page->smarty->assign('modal', true); + } + + $page->content = $page->smarty->fetch('viewnfo.tpl'); + + if ($modal) { + echo $page->content; + } else { + $page->render(); + } } diff --git a/public/pages/nzbgetqueuedata.php b/public/pages/nzbgetqueuedata.php index 527d48f88..9a7cc4623 100644 --- a/public/pages/nzbgetqueuedata.php +++ b/public/pages/nzbgetqueuedata.php @@ -1,36 +1,35 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $nzbget = new NZBGet($page); -$output = ""; +$output = ''; $data = $nzbget->getQueue(); if ($data !== false) { - if (count($data > 0)) { + if (count($data > 0)) { + $status = $nzbget->status(); - $status = $nzbget->status(); - - if ($status !== false) { - $output .= + if ($status !== false) { + $output .= "
-
Avg Speed:
" . Utility::bytesToSizeString($status['AverageDownloadRate'], 2) . "/s
-
Speed:
" . Utility::bytesToSizeString($status['DownloadRate'], 2) . "/s
-
Limit:
" . Utility::bytesToSizeString($status['DownloadLimit'], 2) . "/s
-
Queue Left(no pars):
" . Utility::bytesToSizeString($status['RemainingSizeLo'], 2) . "
-
Free Space:
" . Utility::bytesToSizeString($status['FreeDiskSpaceMB'] * 1024000, 2) . "
-
Status:
" . ($status['Download2Paused'] == 1 ? 'Paused' : 'Downloading') . "
-
"; - } +
Avg Speed:
".Utility::bytesToSizeString($status['AverageDownloadRate'], 2)."/s
+
Speed:
".Utility::bytesToSizeString($status['DownloadRate'], 2)."/s
+
Limit:
".Utility::bytesToSizeString($status['DownloadLimit'], 2)."/s
+
Queue Left(no pars):
".Utility::bytesToSizeString($status['RemainingSizeLo'], 2)."
+
Free Space:
".Utility::bytesToSizeString($status['FreeDiskSpaceMB'] * 1024000, 2)."
+
Status:
".($status['Download2Paused'] == 1 ? 'Paused' : 'Downloading').'
+ '; + } - $count = 1; - $output .= + $count = 1; + $output .= " @@ -47,29 +46,29 @@ if ($data !== false) { "; - foreach ($data as $item) { - $output .= - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - ""; - $count++; - } - $output .= - " -
" . $count . "" . $item['NZBName'] . "" . $item['FileSizeMB'] . " MB" . $item['RemainingSizeMB'] . " MB" . ($item['FileSizeMB'] == 0 ? 0 : round(100 - ($item['RemainingSizeMB'] / $item['FileSizeMB']) * 100)) . "%" . ($item['ActiveDownloads'] > 0 ? 'Downloading' : 'Paused') . "DeletePauseResume
"; - } else { - $output .= "

The queue is currently empty.

"; - } + foreach ($data as $item) { + $output .= + ''. + "".$count.''. + "".$item['NZBName'].''. + "".$item['FileSizeMB'].' MB'. + "".$item['RemainingSizeMB'].' MB'. + "".($item['FileSizeMB'] == 0 ? 0 : round(100 - ($item['RemainingSizeMB'] / $item['FileSizeMB']) * 100)).'%'. + "".($item['ActiveDownloads'] > 0 ? 'Downloading' : 'Paused').''. + "Delete". + "Pause". + "Resume". + ''; + $count++; + } + $output .= + ' + '; + } else { + $output .= "

The queue is currently empty.

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

Error retreiving queue.

"; + $output .= "

Error retreiving queue.

"; } -print $output; +echo $output; diff --git a/public/pages/nzbvortex.php b/public/pages/nzbvortex.php index e89d73352..8751ba00d 100644 --- a/public/pages/nzbvortex.php +++ b/public/pages/nzbvortex.php @@ -1,18 +1,16 @@ users->isLoggedIn()) +if (! $page->users->isLoggedIn()) { $page->show403(); +} use nntmux\NZBVortex; -try -{ - if (isset($_GET['isAjax'])) - { +try { + if (isset($_GET['isAjax'])) { $vortex = new NZBVortex; // I guess we Ajax this way. - if (isset($_GET['getOverview'])) - { + if (isset($_GET['getOverview'])) { $overview = $vortex->getOverview(); $page->smarty->assign('overview', $overview); $content = $page->smarty->fetch('nzbvortex-ajax.tpl'); @@ -20,65 +18,54 @@ try exit; } - if (isset($_GET['addQueue'])) - { + if (isset($_GET['addQueue'])) { $nzb = $_GET['addQueue']; $vortex->addQueue($nzb); exit; } - if (isset($_GET['resume'])) - { - $vortex->resume((int)$_GET['resume']); + if (isset($_GET['resume'])) { + $vortex->resume((int) $_GET['resume']); exit; } - if (isset($_GET['pause'])) - { - $vortex->pause((int)$_GET['pause']); + if (isset($_GET['pause'])) { + $vortex->pause((int) $_GET['pause']); exit; } - if (isset($_GET['moveup'])) - { - $vortex->moveUp((int)$_GET['moveup']); + if (isset($_GET['moveup'])) { + $vortex->moveUp((int) $_GET['moveup']); exit; } - if (isset($_GET['movedown'])) - { - $vortex->moveDown((int)$_GET['movedown']); + if (isset($_GET['movedown'])) { + $vortex->moveDown((int) $_GET['movedown']); exit; } - if (isset($_GET['movetop'])) - { - $vortex->moveTop((int)$_GET['movetop']); + if (isset($_GET['movetop'])) { + $vortex->moveTop((int) $_GET['movetop']); exit; } - if (isset($_GET['movebottom'])) - { - $vortex->moveBottom((int)$_GET['movebottom']); + if (isset($_GET['movebottom'])) { + $vortex->moveBottom((int) $_GET['movebottom']); exit; } - if (isset($_GET['delete'])) - { - $vortex->delete((int)$_GET['delete']); + if (isset($_GET['delete'])) { + $vortex->delete((int) $_GET['delete']); exit; } - if (isset($_GET['filelist'])) - { - $response = $vortex->getFilelist((int)$_GET['filelist']); + if (isset($_GET['filelist'])) { + $response = $vortex->getFilelist((int) $_GET['filelist']); echo json_encode($response); exit; } } -} -catch (Exception $e) -{ +} catch (Exception $e) { header('HTTP/1.1 500 Internal Server Error'); printf($e->getMessage()); exit; diff --git a/public/pages/opensearch.php b/public/pages/opensearch.php index 2fe06c81f..08706ab1b 100644 --- a/public/pages/opensearch.php +++ b/public/pages/opensearch.php @@ -1,4 +1,3 @@ smarty->fetch('opensearch.tpl'); - +echo $page->smarty->fetch('opensearch.tpl'); diff --git a/public/pages/post_edit.php b/public/pages/post_edit.php index f1569fdd9..b5578b3c5 100644 --- a/public/pages/post_edit.php +++ b/public/pages/post_edit.php @@ -2,28 +2,27 @@ use nntmux\Forum; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $forum = new Forum(); $id = $_GET['id'] + 0; - -if (isset($id) && !empty($_POST['addMessage'])) { - $parent = $forum->getPost($id); - $forum->editPost($id, $_POST['addMessage'], $page->users->currentUserId()); - if($parent['parentid'] != 0) { - header("Location:" . WWW_TOP . "/forumpost/" . $parent['parentid'] . "#last"); - } else { - header("Location:" . WWW_TOP . "/forumpost/" . $id); - } +if (isset($id) && ! empty($_POST['addMessage'])) { + $parent = $forum->getPost($id); + $forum->editPost($id, $_POST['addMessage'], $page->users->currentUserId()); + if ($parent['parentid'] != 0) { + header('Location:'.WWW_TOP.'/forumpost/'.$parent['parentid'].'#last'); + } else { + header('Location:'.WWW_TOP.'/forumpost/'.$id); + } } $result = $forum->getPost($id); -$page->meta_title = "Edit forum Post"; -$page->meta_keywords = "edit, view,forum,post,thread"; -$page->meta_description = "Edit forum post"; +$page->meta_title = 'Edit forum Post'; +$page->meta_keywords = 'edit, view,forum,post,thread'; +$page->meta_description = 'Edit forum post'; $page->smarty->assign('result', $result); diff --git a/public/pages/profile.php b/public/pages/profile.php index 46067274a..f63eaf862 100644 --- a/public/pages/profile.php +++ b/public/pages/profile.php @@ -1,12 +1,13 @@ users->isLoggedIn()) - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); +} $rc = new ReleaseComments; $sab = new SABnzbd($page); @@ -14,38 +15,37 @@ $nzbget = new NZBGet($page); $userID = $page->users->currentUserId(); $privileged = $page->users->isAdmin($userID) || $page->users->isModerator($userID); -$privateProfiles = (int)Settings::value('..privateprofiles') === 1; +$privateProfiles = (int) Settings::value('..privateprofiles') === 1; $publicView = false; -if ($privileged || !$privateProfiles) { +if ($privileged || ! $privateProfiles) { + $altID = (isset($_GET['id']) && (int) $_GET['id'] >= 0) ? (int) $_GET['id'] : false; + $altUsername = (isset($_GET['name']) && strlen($_GET['name']) > 0) ? $_GET['name'] : false; - $altID = (isset($_GET['id']) && (int)$_GET['id'] >= 0) ? (int)$_GET['id'] : false; - $altUsername = (isset($_GET['name']) && strlen($_GET['name']) > 0) ? $_GET['name'] : false; - - // If both 'id' and 'name' are specified, 'id' should take precedence. - if ($altID === false && $altUsername !== false) { - $user = $page->users->getByUsername($altUsername); - if ($user) { - $altID = $user['id']; - $userID = $altID; - } - } else if ($altID !== false) { - $userID = $altID; - $publicView = true; - } + // If both 'id' and 'name' are specified, 'id' should take precedence. + if ($altID === false && $altUsername !== false) { + $user = $page->users->getByUsername($altUsername); + if ($user) { + $altID = $user['id']; + $userID = $altID; + } + } elseif ($altID !== false) { + $userID = $altID; + $publicView = true; + } } $downloadlist = $page->users->getDownloadRequestsForUser($userID); -$page->smarty->assign('downloadlist',$downloadlist); +$page->smarty->assign('downloadlist', $downloadlist); $data = $page->users->getById($userID); -if (!$data) { - $page->show404(); +if (! $data) { + $page->show404(); } // Check if the user selected a theme. -if (!isset($data['style']) || $data['style'] === 'None') { - $data['style'] = 'Using the admin selected theme.'; +if (! isset($data['style']) || $data['style'] === 'None') { + $data['style'] = 'Using the admin selected theme.'; } $offset = $_REQUEST['offset'] ?? 0; @@ -60,18 +60,18 @@ $page->smarty->assign([ 'pagertotalitems' => $rc->getCommentCountForUser($userID), 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, - 'pagerquerybase' => '/profile?id=' . $userID . '&offset=', - 'pagerquerysuffix' => '#comments' + 'pagerquerybase' => '/profile?id='.$userID.'&offset=', + 'pagerquerysuffix' => '#comments', ] ); $sabApiKeyTypes = [ SABnzbd::API_TYPE_NZB => 'Nzb Api Key', - SABnzbd::API_TYPE_FULL => 'Full Api Key' + SABnzbd::API_TYPE_FULL => 'Full Api Key', ]; $sabPriorities = [ SABnzbd::PRIORITY_FORCE => 'Force', SABnzbd::PRIORITY_HIGH => 'High', - SABnzbd::PRIORITY_NORMAL => 'Normal', SABnzbd::PRIORITY_LOW => 'Low' + SABnzbd::PRIORITY_NORMAL => 'Normal', SABnzbd::PRIORITY_LOW => 'Low', ]; $sabSettings = [1 => 'Site', 2 => 'Cookie']; @@ -84,13 +84,13 @@ $page->smarty->assign([ 'sabapikey' => $sab->apikey, 'sabapikeytype' => $sab->apikeytype !== '' ? $sabApiKeyTypes[$sab->apikeytype] : '', 'sabpriority' => $sab->priority !== '' ? $sabPriorities[$sab->priority] : '', - 'sabsetting' => $sabSettings[$sab->checkCookie() === true ? 2 : 1] + '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->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/public/pages/profileedit.php b/public/pages/profileedit.php index d9ed7bf6c..816465536 100644 --- a/public/pages/profileedit.php +++ b/public/pages/profileedit.php @@ -1,26 +1,28 @@ users = new Users(); -if (!$page->users->isLoggedIn()) - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); +} $action = $_REQUEST['action'] ?? 'view'; $userid = $page->users->currentUserId(); $data = $page->users->getById($userid); -if (!$data) - $page->show404(); +if (! $data) { + $page->show404(); +} $errorStr = ''; @@ -36,30 +38,31 @@ switch ($action) { case 'submit': $data['email'] = $_POST['email']; - if (isset($_POST['saburl']) && !Utility::endsWith($_POST['saburl'], '/') &&strlen(trim($_POST['saburl'])) > 0) - $_POST['saburl'] .= '/'; + if (isset($_POST['saburl']) && ! Utility::endsWith($_POST['saburl'], '/') && strlen(trim($_POST['saburl'])) > 0) { + $_POST['saburl'] .= '/'; + } if ($_POST['password'] !== '' && $_POST['password'] !== $_POST['confirmpassword']) { - $errorStr = 'Password Mismatch'; - } else if ($_POST['password'] !== '' && !$page->users->isValidPassword($_POST['password'])) { - $errorStr = 'Your password must be longer than five characters.'; - } else if (!empty($_POST['nzbgeturl']) && $nzbGet->verifyURL($_POST['nzbgeturl']) === false) { - $errorStr = 'The NZBGet URL you entered is invalid!'; - } else if (!$page->users->isValidEmail($_POST['email'])) { - $errorStr = 'Your email is not a valid format.'; + $errorStr = 'Password Mismatch'; + } elseif ($_POST['password'] !== '' && ! $page->users->isValidPassword($_POST['password'])) { + $errorStr = 'Your password must be longer than five characters.'; + } elseif (! empty($_POST['nzbgeturl']) && $nzbGet->verifyURL($_POST['nzbgeturl']) === false) { + $errorStr = 'The NZBGet URL you entered is invalid!'; + } elseif (! $page->users->isValidEmail($_POST['email'])) { + $errorStr = 'Your email is not a valid format.'; } else { - $res = $page->users->getByEmail($_POST['email']); - if ($res && (int)$res['id'] !== (int)$userid) { - $errorStr = 'Sorry, the email is already in use.'; - } elseif ((empty($_POST['saburl']) && !empty($_POST['sabapikey'])) || (!empty($_POST['saburl']) && empty($_POST['sabapikey']))) { - $errorStr = 'Insert a SABnzdb URL and API key.'; - } else { - if (isset($_POST['sabsetting']) && $_POST['sabsetting'] == 2) { - $sab->setCookie($_POST['saburl'], $_POST['sabapikey'], $_POST['sabpriority'], $_POST['sabapikeytype']); - $_POST['saburl'] = $_POST['sabapikey'] = $_POST['sabpriority'] = $_POST['sabapikeytype'] = false; - } + $res = $page->users->getByEmail($_POST['email']); + if ($res && (int) $res['id'] !== (int) $userid) { + $errorStr = 'Sorry, the email is already in use.'; + } elseif ((empty($_POST['saburl']) && ! empty($_POST['sabapikey'])) || (! empty($_POST['saburl']) && empty($_POST['sabapikey']))) { + $errorStr = 'Insert a SABnzdb URL and API key.'; + } else { + if (isset($_POST['sabsetting']) && $_POST['sabsetting'] == 2) { + $sab->setCookie($_POST['saburl'], $_POST['sabapikey'], $_POST['sabpriority'], $_POST['sabapikeytype']); + $_POST['saburl'] = $_POST['sabapikey'] = $_POST['sabpriority'] = $_POST['sabapikeytype'] = false; + } - $page->users->update( + $page->users->update( $userid, $data['username'], $_POST['email'], @@ -88,15 +91,16 @@ switch ($action) { $_POST['style'] ); - $_POST['exccat'] = (!isset($_POST['exccat']) || !is_array($_POST['exccat'])) ? [] : $_POST['exccat']; - $page->users->addCategoryExclusions($userid, $_POST['exccat']); + $_POST['exccat'] = (! isset($_POST['exccat']) || ! is_array($_POST['exccat'])) ? [] : $_POST['exccat']; + $page->users->addCategoryExclusions($userid, $_POST['exccat']); - if ($_POST['password'] !== '') - $page->users->updatePassword($userid, $_POST['password']); + if ($_POST['password'] !== '') { + $page->users->updatePassword($userid, $_POST['password']); + } - header('Location:' . WWW_TOP . '/profile'); - die(); - } + header('Location:'.WWW_TOP.'/profile'); + die(); + } } break; @@ -104,9 +108,9 @@ switch ($action) { default: break; } -if ((int)Settings::value('site.main.userselstyle') === 1) { -// Get the list of themes. - $page->smarty->assign('themelist', Utility::getThemesList()); +if ((int) Settings::value('site.main.userselstyle') === 1) { + // Get the list of themes. + $page->smarty->assign('themelist', Utility::getThemesList()); } $page->smarty->assign('error', $errorStr); @@ -142,13 +146,13 @@ switch ($sab->integrated) { $page->smarty->assign([ 'queuetypes' => $queueTypes, - 'queuetypeids' => $queueTypeIDs + 'queuetypeids' => $queueTypeIDs, ] ); $page->meta_title = 'Edit User Profile'; $page->meta_keywords = 'edit,profile,user,details'; -$page->meta_description = 'Edit User Profile for ' . $data['username']; +$page->meta_description = 'Edit User Profile for '.$data['username']; $page->smarty->assign('cp_url_selected', $data['cp_url']); $page->smarty->assign('cp_api_selected', $data['cp_api']); diff --git a/public/pages/queue.php b/public/pages/queue.php index e6dee9e43..0118ce92b 100644 --- a/public/pages/queue.php +++ b/public/pages/queue.php @@ -1,26 +1,26 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $userData = $page->users->getById($page->users->currentUserId()); -if (!$userData) { - $page->show404(); +if (! $userData) { + $page->show404(); } $page->smarty->assign('user', $userData); $queueType = $error = ''; $queue = null; -switch(Settings::value('apps.sabnzbplus.integrationtype')) { +switch (Settings::value('apps.sabnzbplus.integrationtype')) { case SABnzbd::INTEGRATION_TYPE_NONE: if ($userData['queuetype'] === 2) { - $queueType = 'NZBGet'; - $queue = new NZBGet($page); + $queueType = 'NZBGet'; + $queue = new NZBGet($page); } break; case SABnzbd::INTEGRATION_TYPE_SITEWIDE: @@ -28,7 +28,7 @@ switch(Settings::value('apps.sabnzbplus.integrationtype')) { $queue = new SABnzbd($page); break; case SABnzbd::INTEGRATION_TYPE_USER: - switch((int)$userData['queuetype']) { + switch ((int) $userData['queuetype']) { case 1: $queueType = 'Sabnzbd'; $queue = new SABnzbd($page); @@ -42,50 +42,49 @@ switch(Settings::value('apps.sabnzbplus.integrationtype')) { } if ($queue !== null) { + if ($queueType === 'Sabnzbd') { + if (empty($queue->url)) { + $error = 'ERROR: The Sabnzbd URL is missing!'; + } - if ($queueType === 'Sabnzbd') { - if (empty($queue->url)) { - $error = 'ERROR: The Sabnzbd URL is missing!'; - } + if (empty($queue->apikey)) { + if ($error === '') { + $error = 'ERROR: The Sabnzbd API key is missing!'; + } else { + $error .= ' The Sabnzbd API key is missing!'; + } + } + } - if (empty($queue->apikey)) { - if ($error === '') { - $error = 'ERROR: The Sabnzbd API key is missing!'; - } else { - $error .= ' The Sabnzbd API key is missing!'; - } - } - } + if ($error === '') { + if (isset($_REQUEST['del'])) { + $queue->delFromQueue($_REQUEST['del']); + } - if ($error === '') { - if (isset($_REQUEST['del'])) { - $queue->delFromQueue($_REQUEST['del']); - } + if (isset($_REQUEST['pause'])) { + $queue->pauseFromQueue($_REQUEST['pause']); + } - if (isset($_REQUEST['pause'])) { - $queue->pauseFromQueue($_REQUEST['pause']); - } + if (isset($_REQUEST['resume'])) { + $queue->resumeFromQueue($_REQUEST['resume']); + } - if (isset($_REQUEST['resume'])) { - $queue->resumeFromQueue($_REQUEST['resume']); - } + if (isset($_REQUEST['pall'])) { + $queue->pauseAll(); + } - if (isset($_REQUEST['pall'])) { - $queue->pauseAll(); - } + if (isset($_REQUEST['rall'])) { + $queue->resumeAll(); + } - if (isset($_REQUEST['rall'])) { - $queue->resumeAll(); - } - - $page->smarty->assign('serverURL', $queue->url); - } + $page->smarty->assign('serverURL', $queue->url); + } } -$page->smarty->assign(array('queueType' => $queueType, 'error' => $error, 'user', $page->users)); -$page->title = 'Your ' . $queueType . ' Download Queue'; -$page->meta_title = 'View' . $queueType . ' Queue'; -$page->meta_keywords = 'view,' . strtolower($queueType) . ',queue'; -$page->meta_description = 'View' . $queueType . ' Queue'; +$page->smarty->assign(['queueType' => $queueType, 'error' => $error, 'user', $page->users]); +$page->title = 'Your '.$queueType.' Download Queue'; +$page->meta_title = 'View'.$queueType.' Queue'; +$page->meta_keywords = 'view,'.strtolower($queueType).',queue'; +$page->meta_description = 'View'.$queueType.' Queue'; $page->content = $page->smarty->fetch('viewqueue.tpl'); $page->render(); diff --git a/public/pages/register.php b/public/pages/register.php index e68e729e4..ca6077db3 100644 --- a/public/pages/register.php +++ b/public/pages/register.php @@ -1,64 +1,63 @@ users->isLoggedIn()) { - header('Location: ' . WWW_TOP . '/'); + header('Location: '.WWW_TOP.'/'); } $error = $userName = $password = $confirmPassword = $email = $inviteCode = $inviteCodeQuery = ''; $showRegister = 1; -if ((int)Settings::value('..registerstatus') === Settings::REGISTER_STATUS_CLOSED || (int)Settings::value('..registerstatus') === Settings::REGISTER_STATUS_API_ONLY) { - $error = 'Registrations are currently disabled.'; - $showRegister = 0; -} elseif (Settings::value('..registerstatus') === Settings::REGISTER_STATUS_INVITE && (!isset($_REQUEST['invitecode']) || empty($_REQUEST['invitecode']))) { - $error = 'Registrations are currently invite only.'; - $showRegister = 0; +if ((int) Settings::value('..registerstatus') === Settings::REGISTER_STATUS_CLOSED || (int) Settings::value('..registerstatus') === Settings::REGISTER_STATUS_API_ONLY) { + $error = 'Registrations are currently disabled.'; + $showRegister = 0; +} elseif (Settings::value('..registerstatus') === Settings::REGISTER_STATUS_INVITE && (! isset($_REQUEST['invitecode']) || empty($_REQUEST['invitecode']))) { + $error = 'Registrations are currently invite only.'; + $showRegister = 0; } if ($showRegister === 1) { - $action = $_REQUEST['action'] ?? 'view'; + $action = $_REQUEST['action'] ?? 'view'; - //Be sure to persist the invite code in the event of multiple form submissions. (errors) - if (isset($_REQUEST['invitecode'])) { - $inviteCodeQuery = '&invitecode=' . $_REQUEST['invitecode']; - } + //Be sure to persist the invite code in the event of multiple form submissions. (errors) + if (isset($_REQUEST['invitecode'])) { + $inviteCodeQuery = '&invitecode='.$_REQUEST['invitecode']; + } - $captcha = new Captcha($page); + $captcha = new Captcha($page); - switch ($action) { + switch ($action) { case 'submit': if ($captcha->getError() === false) { - if (Utility::checkCsrfToken() === true) { - $userName = $_POST['username']; - $password = $_POST['password']; - $confirmPassword = $_POST['confirmpassword']; - $email = $_POST['email']; - if (!empty($_REQUEST['invitecode'])) { - $inviteCode = $_REQUEST['invitecode']; - } + if (Utility::checkCsrfToken() === true) { + $userName = $_POST['username']; + $password = $_POST['password']; + $confirmPassword = $_POST['confirmpassword']; + $email = $_POST['email']; + if (! empty($_REQUEST['invitecode'])) { + $inviteCode = $_REQUEST['invitecode']; + } - // Check uname/email isn't in use, password valid. If all good create new user account and redirect back to home page. - if ($password !== $confirmPassword) { - $error = 'Password Mismatch'; - } else { - // Get the default user role. - $userDefault = $page->users->getDefaultRole(); + // Check uname/email isn't in use, password valid. If all good create new user account and redirect back to home page. + if ($password !== $confirmPassword) { + $error = 'Password Mismatch'; + } else { + // Get the default user role. + $userDefault = $page->users->getDefaultRole(); - $ret = $page->users->signup($userName, $password, $email, + $ret = $page->users->signup($userName, $password, $email, $_SERVER['REMOTE_ADDR'], $userDefault['id'], '', $userDefault['defaultinvites'], $inviteCode ); - if ($ret > 0) { - $page->users->login($ret, $_SERVER['REMOTE_ADDR']); - header('Location: ' . WWW_TOP . '/'); - } else { - switch ($ret) { + if ($ret > 0) { + $page->users->login($ret, $_SERVER['REMOTE_ADDR']); + header('Location: '.WWW_TOP.'/'); + } else { + switch ($ret) { case Users::ERR_SIGNUP_BADUNAME: $error = 'Your username must be at least five characters.'; break; @@ -81,24 +80,24 @@ if ($showRegister === 1) { $error = 'Failed to register.'; break; } - } - } - } else { - $page->showTokenError(); - } + } + } + } else { + $page->showTokenError(); + } } break; case 'view': { $inviteCode = $_GET['invitecode'] ?? null; if (isset($inviteCode)) { - // See if it is a valid invite. - $invite = $page->users->getInvite($inviteCode); - if (!$invite) { - $error = sprintf('Bad or invite code older than %d days.', Users::DEFAULT_INVITE_EXPIRY_DAYS); - $showRegister = 0; - } else { - $inviteCode = $invite['guid']; - } + // See if it is a valid invite. + $invite = $page->users->getInvite($inviteCode); + if (! $invite) { + $error = sprintf('Bad or invite code older than %d days.', Users::DEFAULT_INVITE_EXPIRY_DAYS); + $showRegister = 0; + } else { + $inviteCode = $invite['guid']; + } } break; } @@ -113,7 +112,7 @@ $page->smarty->assign([ 'invite_code_query' => Utility::htmlfmt($inviteCodeQuery), 'showregister' => $showRegister, 'error' => $error, - 'csrf_token' => $page->token + 'csrf_token' => $page->token, ] ); $page->meta_title = 'Register'; diff --git a/public/pages/rss-info.php b/public/pages/rss-info.php index e461de036..049e52aa7 100755 --- a/public/pages/rss-info.php +++ b/public/pages/rss-info.php @@ -4,25 +4,25 @@ use nntmux\http\RSS; $rss = new RSS(['Settings' => $page->settings]); -$page->title = "RSS Info"; -$page->meta_title = "RSS Help Topics"; -$page->meta_keywords = "view,nzb,api,details,help,json,rss,atom"; -$page->meta_description = "View description of the site Nzb RSS."; +$page->title = 'RSS Info'; +$page->meta_title = 'RSS Help Topics'; +$page->meta_keywords = 'view,nzb,api,details,help,json,rss,atom'; +$page->meta_description = 'View description of the site Nzb RSS.'; $firstShow = $rss->getFirstInstance('videos_id', 'releases', 'id'); $firstAni = $rss->getFirstInstance('anidbid', 'releases', 'id'); if (isset($firstShow['videos_id'])) { - $page->smarty->assign('show', $firstShow['videos_id']); + $page->smarty->assign('show', $firstShow['videos_id']); } else { - $page->smarty->assign('show', -1); + $page->smarty->assign('show', -1); } if (isset($firstAni['anidbid'])) { - $page->smarty->assign('anidb', $firstAni['anidbid']); + $page->smarty->assign('anidb', $firstAni['anidbid']); } else { - $page->smarty->assign('anidb', -1); + $page->smarty->assign('anidb', -1); } $page->content = $page->smarty->fetch('rssdesc.tpl'); -$page->render(); \ No newline at end of file +$page->render(); diff --git a/public/pages/rss.php b/public/pages/rss.php index a19adfa11..d61ef7065 100755 --- a/public/pages/rss.php +++ b/public/pages/rss.php @@ -1,8 +1,8 @@ $page->settings]); @@ -10,111 +10,111 @@ $rss = new RSS(['Settings' => $page->settings]); $offset = 0; // If no content id provided then show user the rss selection page. -if (!isset($_GET["t"]) && !isset($_GET["show"]) && !isset($_GET["anidb"])) { - // User has to either be logged in, or using rsskey. - if (!$page->users->isLoggedIn()) { - if (Settings::value('..registerstatus') != Settings::REGISTER_STATUS_API_ONLY) { - Utility::showApiError(100); - } else { - header("Location: " . Settings::value('site.main.code')); - } - } +if (! isset($_GET['t']) && ! isset($_GET['show']) && ! isset($_GET['anidb'])) { + // User has to either be logged in, or using rsskey. + if (! $page->users->isLoggedIn()) { + if (Settings::value('..registerstatus') != Settings::REGISTER_STATUS_API_ONLY) { + Utility::showApiError(100); + } else { + header('Location: '.Settings::value('site.main.code')); + } + } - $page->title = "Rss Info"; - $page->meta_title = "Rss Nzb Info"; - $page->meta_keywords = "view,nzb,description,details,rss,atom"; - $page->meta_description = "View information about Newznab Tmux RSS Feeds."; + $page->title = 'Rss Info'; + $page->meta_title = 'Rss Nzb Info'; + $page->meta_keywords = 'view,nzb,description,details,rss,atom'; + $page->meta_description = 'View information about Newznab Tmux RSS Feeds.'; - $firstShow = $rss->getFirstInstance('videos_id', 'releases', 'id'); - $firstAni = $rss->getFirstInstance('anidbid', 'releases', 'id'); + $firstShow = $rss->getFirstInstance('videos_id', 'releases', 'id'); + $firstAni = $rss->getFirstInstance('anidbid', 'releases', 'id'); - if (isset($firstShow['videos_id'])) { - $page->smarty->assign('show', $firstShow['videos_id']); - } else { - $page->smarty->assign('show', 1); - } + if (isset($firstShow['videos_id'])) { + $page->smarty->assign('show', $firstShow['videos_id']); + } else { + $page->smarty->assign('show', 1); + } - if (isset($firstAni['anidbid'])) { - $page->smarty->assign('anidb', $firstAni['anidbid']); - } else { - $page->smarty->assign('anidb', 1); - } + if (isset($firstAni['anidbid'])) { + $page->smarty->assign('anidb', $firstAni['anidbid']); + } else { + $page->smarty->assign('anidb', 1); + } - $page->smarty->assign([ - 'categorylist' => $category->getCategories(true, $page->userdata["categoryexclusions"]), - 'parentcategorylist' => $category->getForMenu($page->userdata["categoryexclusions"]) + $page->smarty->assign([ + 'categorylist' => $category->getCategories(true, $page->userdata['categoryexclusions']), + 'parentcategorylist' => $category->getForMenu($page->userdata['categoryexclusions']), ] ); - $page->content = $page->smarty->fetch('rssdesc.tpl'); - $page->render(); + $page->content = $page->smarty->fetch('rssdesc.tpl'); + $page->render(); } else { - $rssToken = $uid = -1; - // User requested a feed, ensure either logged in or passing a valid token. - if ($page->users->isLoggedIn()) { - $uid = $page->userdata["id"]; - $rssToken = $page->userdata["rsstoken"]; - $maxRequests = $page->userdata['apirequests']; - } else { - if (Settings::value('..registerstatus') == Settings::REGISTER_STATUS_API_ONLY) { - $res = $page->users->getById(0); - } else { - if (!isset($_GET["i"]) || !isset($_GET["r"])) { - Utility::showApiError(100, 'Both the User ID and API key are required for viewing the RSS!'); - } + $rssToken = $uid = -1; + // User requested a feed, ensure either logged in or passing a valid token. + if ($page->users->isLoggedIn()) { + $uid = $page->userdata['id']; + $rssToken = $page->userdata['rsstoken']; + $maxRequests = $page->userdata['apirequests']; + } else { + if (Settings::value('..registerstatus') == Settings::REGISTER_STATUS_API_ONLY) { + $res = $page->users->getById(0); + } else { + if (! isset($_GET['i']) || ! isset($_GET['r'])) { + Utility::showApiError(100, 'Both the User ID and API key are required for viewing the RSS!'); + } - $res = $page->users->getByIdAndRssToken($_GET["i"], $_GET["r"]); - } + $res = $page->users->getByIdAndRssToken($_GET['i'], $_GET['r']); + } - if (!$res) { - Utility::showApiError(100); - } + if (! $res) { + Utility::showApiError(100); + } - $uid = $res["id"]; - $rssToken = $res['rsstoken']; - $maxRequests = $res['apirequests']; - $username = $res['username']; + $uid = $res['id']; + $rssToken = $res['rsstoken']; + $maxRequests = $res['apirequests']; + $username = $res['username']; - if ($page->users->isDisabled($username)) { - Utility::showApiError(101); - } - } + if ($page->users->isDisabled($username)) { + Utility::showApiError(101); + } + } - if ($page->users->getApiRequests($uid) > $maxRequests) { - Utility::showApiError(500, 'You have reached your daily limit for API requests!'); - } else { - $page->users->addApiRequest($uid, $_SERVER['REQUEST_URI']); - } + if ($page->users->getApiRequests($uid) > $maxRequests) { + Utility::showApiError(500, 'You have reached your daily limit for API requests!'); + } else { + $page->users->addApiRequest($uid, $_SERVER['REQUEST_URI']); + } - // Valid or logged in user, get them the requested feed. - $userShow = $userAnidb = -1; - if (isset($_GET["show"])) { - $userShow = ($_GET["show"] == 0 ? -1 : $_GET["show"] + 0); - } elseif (isset($_GET["anidb"])) { - $userAnidb = ($_GET["anidb"] == 0 ? -1 : $_GET["anidb"] + 0); - } + // Valid or logged in user, get them the requested feed. + $userShow = $userAnidb = -1; + if (isset($_GET['show'])) { + $userShow = ($_GET['show'] == 0 ? -1 : $_GET['show'] + 0); + } elseif (isset($_GET['anidb'])) { + $userAnidb = ($_GET['anidb'] == 0 ? -1 : $_GET['anidb'] + 0); + } - $outputXML = (isset($_GET['o']) && $_GET['o'] == 'json' ? false : true); + $outputXML = (isset($_GET['o']) && $_GET['o'] == 'json' ? false : true); - $userCat = (isset($_GET['t']) ? ($_GET['t'] == 0 ? -1 : $_GET['t']) : -1); - $userNum = (isset($_GET["num"]) && is_numeric($_GET['num']) ? abs($_GET['num']) : 100); - $userAirDate = (isset($_GET["airdate"]) && is_numeric($_GET['airdate']) ? abs($_GET["airdate"]) : -1); + $userCat = (isset($_GET['t']) ? ($_GET['t'] == 0 ? -1 : $_GET['t']) : -1); + $userNum = (isset($_GET['num']) && is_numeric($_GET['num']) ? abs($_GET['num']) : 100); + $userAirDate = (isset($_GET['airdate']) && is_numeric($_GET['airdate']) ? abs($_GET['airdate']) : -1); - $params = + $params = [ 'dl' => (isset($_GET['dl']) && $_GET['dl'] == '1' ? '1' : '0'), 'del' => (isset($_GET['del']) && $_GET['del'] == '1' ? '1' : '0'), 'extended' => 1, 'uid' => $uid, - 'token' => $rssToken + 'token' => $rssToken, ]; - if ($userCat == -3) { - $relData = $rss->getShowsRss($userNum, $uid, $page->users->getCategoryExclusion($uid), $userAirDate); - } elseif ($userCat == -4) { - $relData = $rss->getMyMoviesRss($userNum, $uid, $page->users->getCategoryExclusion($uid)); - } else { - $relData = $rss->getRss(explode(',', $userCat), $userNum, $userShow, $userAnidb, $uid, $userAirDate); - } - $rss->output($relData, $params, $outputXML, $offset, 'rss'); + if ($userCat == -3) { + $relData = $rss->getShowsRss($userNum, $uid, $page->users->getCategoryExclusion($uid), $userAirDate); + } elseif ($userCat == -4) { + $relData = $rss->getMyMoviesRss($userNum, $uid, $page->users->getCategoryExclusion($uid)); + } else { + $relData = $rss->getRss(explode(',', $userCat), $userNum, $userShow, $userAnidb, $uid, $userAirDate); + } + $rss->output($relData, $params, $outputXML, $offset, 'rss'); } diff --git a/public/pages/sabqueuedata.php b/public/pages/sabqueuedata.php index e31853fc6..dff15bc51 100644 --- a/public/pages/sabqueuedata.php +++ b/public/pages/sabqueuedata.php @@ -2,8 +2,8 @@ use nntmux\SABnzbd; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $sab = new SABnzbd($page); @@ -13,22 +13,22 @@ $output = ''; $json = $sab->getAdvQueue(); if ($json !== false) { - $obj = json_decode($json); - $queue = $obj->{'queue'}; - $count = 1; + $obj = json_decode($json); + $queue = $obj->{'queue'}; + $count = 1; - $output .= + $output .= "
-
Speed:
" . $obj->{'speed'} . "B/s
-
Queued:
" . round($obj->{'mbleft'}, 2) . "MB / " . round($obj->{'mb'}, 2) . "MB" . "
-
Status:
" . ucwords(strtolower($obj->{'state'})) . "
-
Free (temp):
" . round($obj->{'diskspace1'}) . "GB
-
Free Space:
" . round($obj->{'diskspace2'}) . "GB
-
Stats:
" . preg_replace('/\s+\|\s+| /', ',', $obj->{'loadavg'}) . '
+
Speed:
".$obj->{'speed'}."B/s
+
Queued:
".round($obj->{'mbleft'}, 2).'MB / '.round($obj->{'mb'}, 2).'MB'."
+
Status:
".ucwords(strtolower($obj->{'state'}))."
+
Free (temp):
".round($obj->{'diskspace1'})."GB
+
Free Space:
".round($obj->{'diskspace2'})."GB
+
Stats:
".preg_replace('/\s+\|\s+| /', ',', $obj->{'loadavg'}).'
'; - if (count($queue) > 0) { - $output .= + if (count($queue) > 0) { + $output .= " @@ -45,31 +45,31 @@ if ($json !== false) { "; - foreach ($queue->{'slots'} as $item) { - if (strpos($item->{'filename'}, 'fetch NZB') === false) { - $output .= - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - ""; - $count++; - } - } - $output .= - " -
" . $count . "" . $item->{'filename'} . "" . round($item->{'mb'}, 2) . " MB" . round($item->{'mbleft'}, 2) . " MB" . ($item->{'mb'} === 0 ? 0 : round(100 - ($item->{'mbleft'} / $item->{'mb'}) * 100)) . "%" . $item->{'timeleft'} . "DeletePauseResume
"; - } else { - $output .= "

The queue is currently empty.

"; - } + foreach ($queue->{'slots'} as $item) { + if (strpos($item->{'filename'}, 'fetch NZB') === false) { + $output .= + ''. + "".$count.''. + "".$item->{'filename'}.''. + "".round($item->{'mb'}, 2).' MB'. + "".round($item->{'mbleft'}, 2).' MB'. + "".($item->{'mb'} === 0 ? 0 : round(100 - ($item->{'mbleft'} / $item->{'mb'}) * 100)).'%'. + "".$item->{'timeleft'}.''. + "Delete". + "Pause". + "Resume". + ''; + $count++; + } + } + $output .= + ' + '; + } else { + $output .= "

The queue is currently empty.

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

Error retrieving queue.

"; + $output .= "

Error retrieving queue.

"; } -print $output; +echo $output; diff --git a/public/pages/search.php b/public/pages/search.php index 1fb638911..a63659dfe 100644 --- a/public/pages/search.php +++ b/public/pages/search.php @@ -1,120 +1,116 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } -$groups = new Groups(['Settings' => $page->settings]); +$groups = new Groups(['Settings' => $page->settings]); $releases = new Releases(['Groups' => $groups, 'Settings' => $page->settings]); -$page->meta_title = 'Search Nzbs'; -$page->meta_keywords = 'search,nzb,description,details'; +$page->meta_title = 'Search Nzbs'; +$page->meta_keywords = 'search,nzb,description,details'; $page->meta_description = 'Search for Nzbs'; -$results = []; +$results = []; $searchType = 'basic'; if (isset($_REQUEST['search_type']) && $_REQUEST['search_type'] === 'adv') { - $searchType = 'advanced'; + $searchType = 'advanced'; } $ordering = $releases->getBrowseOrdering(); -$orderBy = (isset($_REQUEST['ob']) && in_array($_REQUEST['ob'], $ordering, false) ? $_REQUEST['ob'] : ''); -$offset = (isset($_REQUEST['offset']) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST['offset'] : 0; +$orderBy = (isset($_REQUEST['ob']) && in_array($_REQUEST['ob'], $ordering, false) ? $_REQUEST['ob'] : ''); +$offset = (isset($_REQUEST['offset']) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST['offset'] : 0; $page->smarty->assign( [ 'subject' => '', 'search' => '', 'category' => [0], 'pagertotalitems' => 0, - 'pageritemsperpage' => 1, 'pageroffset' => 1, 'covgroup' => '' + 'pageritemsperpage' => 1, 'pageroffset' => 1, 'covgroup' => '', ] ); -if ((isset($_REQUEST['id']) || isset($_REQUEST['subject'])) && !isset($_REQUEST['searchadvr']) && $searchType === 'basic') { - - $searchString = ''; - switch (true) { +if ((isset($_REQUEST['id']) || isset($_REQUEST['subject'])) && ! isset($_REQUEST['searchadvr']) && $searchType === 'basic') { + $searchString = ''; + switch (true) { case isset($_REQUEST['subject']): $searchString = (string) $_REQUEST['subject']; $page->smarty->assign('subject', $searchString); break; case isset($_REQUEST['id']): - $searchString =(string) $_REQUEST['id']; + $searchString = (string) $_REQUEST['id']; $page->smarty->assign('search', $searchString); break; } - $categoryID[] = -1; - if (isset($_REQUEST['t'])) { - $categoryID = explode(',', $_REQUEST['t']); - } - foreach ($releases->getBrowseOrdering() as $orderType) { - $page->smarty->assign( - 'orderby' . $orderType, - WWW_TOP . '/search/' . htmlentities($searchString) . '?t=' . implode(',', $categoryID) . '&ob='. $orderType + $categoryID[] = -1; + if (isset($_REQUEST['t'])) { + $categoryID = explode(',', $_REQUEST['t']); + } + foreach ($releases->getBrowseOrdering() as $orderType) { + $page->smarty->assign( + 'orderby'.$orderType, + WWW_TOP.'/search/'.htmlentities($searchString).'?t='.implode(',', $categoryID).'&ob='.$orderType ); - } + } - $results = $releases->search( + $results = $releases->search( $searchString, -1, -1, -1, -1, -1, -1, 0, 0, -1, -1, $offset, ITEMS_PER_PAGE, $orderBy, -1, $page->userdata['categoryexclusions'], 'basic', $categoryID ); - $page->smarty->assign( + $page->smarty->assign( [ 'lastvisit' => $page->userdata['lastlogin'], 'pagertotalitems' => (count($results) > 0 ? $results[0]['_totalrows'] : 0), 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, 'pagerquerysuffix' => '#results', - 'pagerquerybase' => - WWW_TOP . '/search/' . htmlentities($searchString) . '?t=' . - implode(',', $categoryID) . '&ob=' . $orderBy . '&offset=', - 'category' => $categoryID + 'pagerquerybase' => WWW_TOP.'/search/'.htmlentities($searchString).'?t='. + implode(',', $categoryID).'&ob='.$orderBy.'&offset=', + 'category' => $categoryID, ] ); - } $searchVars = [ 'searchadvr' => '', 'searchadvsubject' => '', 'searchadvposter' => '', 'searchadvfilename' => '', 'searchadvdaysnew' => '', 'searchadvdaysold' => '', 'searchadvgroups' => '', 'searchadvcat' => '', 'searchadvsizefrom' => '', - 'searchadvsizeto' => '', 'searchadvhasnfo' => '', 'searchadvhascomments' => '' + 'searchadvsizeto' => '', 'searchadvhasnfo' => '', 'searchadvhascomments' => '', ]; -foreach($searchVars as $searchVarKey => $searchVar) { - $searchVars[$searchVarKey] = (isset($_REQUEST[$searchVarKey]) ? (string) $_REQUEST[$searchVarKey] : ''); +foreach ($searchVars as $searchVarKey => $searchVar) { + $searchVars[$searchVarKey] = (isset($_REQUEST[$searchVarKey]) ? (string) $_REQUEST[$searchVarKey] : ''); } $searchVars['selectedgroup'] = $searchVars['searchadvgroups']; $searchVars['selectedcat'] = $searchVars['searchadvcat']; $searchVars['selectedsizefrom'] = $searchVars['searchadvsizefrom']; $searchVars['selectedsizeto'] = $searchVars['searchadvsizeto']; -foreach($searchVars as $searchVarKey => $searchVar) { - $page->smarty->assign($searchVarKey, $searchVars[$searchVarKey]); +foreach ($searchVars as $searchVarKey => $searchVar) { + $page->smarty->assign($searchVarKey, $searchVars[$searchVarKey]); } -if (isset($_REQUEST['searchadvr']) && !isset($_REQUEST['id']) && !isset($_REQUEST['subject']) && $searchType !== 'basic') { +if (isset($_REQUEST['searchadvr']) && ! isset($_REQUEST['id']) && ! isset($_REQUEST['subject']) && $searchType !== 'basic') { + $orderByString = ''; + foreach ($searchVars as $searchVarKey => $searchVar) { + $orderByString .= "&$searchVarKey=".htmlentities($searchVar); + } + $orderByString = ltrim($orderByString, '&'); - $orderByString = ''; - foreach ($searchVars as $searchVarKey => $searchVar) { - $orderByString .= "&$searchVarKey=" . htmlentities($searchVar); - } - $orderByString = ltrim($orderByString, '&'); - - foreach ($ordering as $orderType) { - $page->smarty->assign( - 'orderby' . $orderType, - WWW_TOP . '/search?' . $orderByString . '&search_type=adv&ob=' . $orderType + foreach ($ordering as $orderType) { + $page->smarty->assign( + 'orderby'.$orderType, + WWW_TOP.'/search?'.$orderByString.'&search_type=adv&ob='.$orderType ); - } + } - $results = $releases->search( + $results = $releases->search( ($searchVars['searchadvr'] === '' ? -1 : $searchVars['searchadvr']), ($searchVars['searchadvsubject'] === '' ? -1 : $searchVars['searchadvsubject']), ($searchVars['searchadvposter'] === '' ? -1 : $searchVars['searchadvposter']), @@ -127,14 +123,14 @@ if (isset($_REQUEST['searchadvr']) && !isset($_REQUEST['id']) && !isset($_REQUES [$searchVars['searchadvcat'] === '' ? -1 : $searchVars['searchadvcat']] ); - $page->smarty->assign( + $page->smarty->assign( [ 'lastvisit' => $page->userdata['lastlogin'], 'pagertotalitems' => count($results) > 0 ? $results[0]['_totalrows'] : 0, 'pageroffset' => $offset, 'pageritemsperpage' => ITEMS_PER_PAGE, 'pagerquerysuffix' => '#results', - 'pagerquerybase' => WWW_TOP . '/search?' . $orderByString . '&search_type=adv&ob=' . $orderBy . '&offset=' + 'pagerquerybase' => WWW_TOP.'/search?'.$orderByString.'&search_type=adv&ob='.$orderBy.'&offset=', ] ); } @@ -178,13 +174,13 @@ $page->smarty->assign( [ 'sizelist' => [ -1 => '--Select--', 1 => '100MB', 2 => '250MB', 3 => '500MB', 4 => '1GB', 5 => '2GB', - 6 => '3GB', 7 => '4GB', 8 => '8GB', 9 => '16GB', 10 => '32GB', 11 => '64GB' + 6 => '3GB', 7 => '4GB', 8 => '8GB', 9 => '16GB', 10 => '32GB', 11 => '64GB', ], 'results' => $results, 'sadvanced' => $searchType !== 'basic', 'grouplist' => $groups->getGroupsForSelect(), 'catlist' => (new Category(['Settings' => $page->settings]))->getForSelect(), 'search_description' => $search_description, - 'pager' => $page->smarty->fetch('pager.tpl') + 'pager' => $page->smarty->fetch('pager.tpl'), ] ); diff --git a/public/pages/sendtocouch.php b/public/pages/sendtocouch.php index 9d1e24b45..e12a47d3b 100644 --- a/public/pages/sendtocouch.php +++ b/public/pages/sendtocouch.php @@ -2,22 +2,22 @@ use nntmux\CouchPotato; -if (!$page->users->isLoggedIn()){ - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } -if (empty($_GET["id"])) { - $page->show404(); +if (empty($_GET['id'])) { + $page->show404(); } else { - $cp = new CouchPotato($page); + $cp = new CouchPotato($page); - if (empty($cp->cpurl)) { - $page->show404(); - } + if (empty($cp->cpurl)) { + $page->show404(); + } - if (empty($cp->cpapi)) { - $page->show404(); - } - $id = $_GET["id"]; - $cp->sendToCouchPotato($id); + if (empty($cp->cpapi)) { + $page->show404(); + } + $id = $_GET['id']; + $cp->sendToCouchPotato($id); } diff --git a/public/pages/sendtonzbget.php b/public/pages/sendtonzbget.php index 2499d6aab..d405083b9 100644 --- a/public/pages/sendtonzbget.php +++ b/public/pages/sendtonzbget.php @@ -2,24 +2,28 @@ use nntmux\NZBGet; -if (!$page->users->isLoggedIn()) - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); +} -if (empty($_GET["id"])) - $page->show404(); +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)) +if (empty($nzbget->url)) { $page->show404(); +} -$guid = $_GET["id"]; +if (empty($nzbget->username)) { + $page->show404(); +} + +if (empty($nzbget->password)) { + $page->show404(); +} + +$guid = $_GET['id']; $nzbget->sendURLToNZBGet($guid); - diff --git a/public/pages/sendtoqueue.php b/public/pages/sendtoqueue.php index 28d059302..d9970a1ed 100644 --- a/public/pages/sendtoqueue.php +++ b/public/pages/sendtoqueue.php @@ -1,28 +1,27 @@ users->isLoggedIn()) { - $page->show403(); +use nntmux\NZBGet; +use nntmux\SABnzbd; + +if (! $page->users->isLoggedIn()) { + $page->show403(); } -if (empty($_GET["id"])) { - $page->show404(); +if (empty($_GET['id'])) { + $page->show404(); } $user = $page->users->getById($page->users->currentUserId()); if ($user['queuetype'] != 2) { - - $sab = new SABnzbd($page); - if (empty($sab->url)) { - $page->show404(); - } - if (empty($sab->apikey)) { - $page->show404(); - } - $sab->sendToSab($_GET["id"]); - + $sab = new SABnzbd($page); + if (empty($sab->url)) { + $page->show404(); + } + if (empty($sab->apikey)) { + $page->show404(); + } + $sab->sendToSab($_GET['id']); } elseif ($user['queuetype'] == 2) { - $nzbget = new NZBGet($page); - $nzbget->sendURLToNZBGet($_GET['id']); + $nzbget = new NZBGet($page); + $nzbget->sendURLToNZBGet($_GET['id']); } diff --git a/public/pages/sendtosab.php b/public/pages/sendtosab.php index ac38a2d10..4ad4b3205 100644 --- a/public/pages/sendtosab.php +++ b/public/pages/sendtosab.php @@ -2,21 +2,24 @@ use nntmux\SABnzbd; -if (!$page->users->isLoggedIn()) - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); +} -if (empty($_GET["id"])) - $page->show404(); +if (empty($_GET['id'])) { + $page->show404(); +} $sab = new SABnzbd($page); -if (empty($sab->url)) - $page->show404(); +if (empty($sab->url)) { + $page->show404(); +} -if (empty($sab->apikey)) - $page->show404(); +if (empty($sab->apikey)) { + $page->show404(); +} -$guid = $_GET["id"]; +$guid = $_GET['id']; $sab->sendToSab($guid); - diff --git a/public/pages/series.php b/public/pages/series.php index 3b2d6ac08..fc5396fc0 100644 --- a/public/pages/series.php +++ b/public/pages/series.php @@ -1,12 +1,12 @@ users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $releases = new Releases(['Settings' => $page->settings]); @@ -15,110 +15,110 @@ $cat = new Category(['Settings' => $page->settings]); $us = new UserSeries(['Settings' => $page->settings]); if (isset($_GET['id']) && ctype_digit($_GET['id'])) { - $category = -1; - if (isset($_REQUEST['t']) && ctype_digit($_REQUEST['t'])) { - $category = $_REQUEST['t']; - } + $category = -1; + if (isset($_REQUEST['t']) && ctype_digit($_REQUEST['t'])) { + $category = $_REQUEST['t']; + } - $catarray = []; - $catarray[] = $category; + $catarray = []; + $catarray[] = $category; - $rel = $releases->searchShows(['id' => $_GET['id']], '', '', '', 0, 1000, '', $catarray, -1); - $show = $tvshow->getByVideoID($_GET['id']); + $rel = $releases->searchShows(['id' => $_GET['id']], '', '', '', 0, 1000, '', $catarray, -1); + $show = $tvshow->getByVideoID($_GET['id']); - if (!$show) { - $page->smarty->assign('nodata', 'No video information for this series.'); - } elseif (!$rel) { - $page->smarty->assign('nodata', 'No releases for this series.'); - } else { - $myshows = $us->getShow($page->users->currentUserId(), $show['id']); + if (! $show) { + $page->smarty->assign('nodata', 'No video information for this series.'); + } elseif (! $rel) { + $page->smarty->assign('nodata', 'No releases for this series.'); + } else { + $myshows = $us->getShow($page->users->currentUserId(), $show['id']); - // Sort releases by season, episode, date posted. - $series = $episode = $posted = []; - foreach ($rel as $rlk => $rlv) { - $series[$rlk] = $rlv['series']; - $episode[$rlk] = $rlv['episode']; - $posted[$rlk] = $rlv['postdate']; - } - array_multisort($series, SORT_DESC, $episode, SORT_DESC, $posted, SORT_DESC, $rel); + // Sort releases by season, episode, date posted. + $series = $episode = $posted = []; + foreach ($rel as $rlk => $rlv) { + $series[$rlk] = $rlv['series']; + $episode[$rlk] = $rlv['episode']; + $posted[$rlk] = $rlv['postdate']; + } + array_multisort($series, SORT_DESC, $episode, SORT_DESC, $posted, SORT_DESC, $rel); - $series = []; - foreach ($rel as $r) { - $series[$r['series']][$r['episode']][] = $r; - } + $series = []; + foreach ($rel as $r) { + $series[$r['series']][$r['episode']][] = $r; + } - $page->smarty->assign('seasons', $series); - $page->smarty->assign('show', $show); - $page->smarty->assign('myshows', $myshows); + $page->smarty->assign('seasons', $series); + $page->smarty->assign('show', $show); + $page->smarty->assign('myshows', $myshows); - //get series name(s), description, country and genre - $seriestitles = $seriesdescription = $seriescountry = []; - $seriestitles[] = $show['title']; + //get series name(s), description, country and genre + $seriestitles = $seriesdescription = $seriescountry = []; + $seriestitles[] = $show['title']; - if (!empty($show['summary'])) { - $seriessummary[] = $show['summary']; - } + if (! empty($show['summary'])) { + $seriessummary[] = $show['summary']; + } - if (!empty($show['countries_id'])) { - $seriescountry[] = $show['countries_id']; - } + if (! empty($show['countries_id'])) { + $seriescountry[] = $show['countries_id']; + } - $seriestitles = implode('/', array_map('trim', $seriestitles)); - $page->smarty->assign('seriestitles', $seriestitles); - $page->smarty->assign('seriessummary', array_shift($seriessummary)); - $page->smarty->assign('seriescountry', array_shift($seriescountry)); + $seriestitles = implode('/', array_map('trim', $seriestitles)); + $page->smarty->assign('seriestitles', $seriestitles); + $page->smarty->assign('seriessummary', array_shift($seriessummary)); + $page->smarty->assign('seriescountry', array_shift($seriescountry)); - $page->title = 'Series'; - $page->meta_title = 'View TV Series'; - $page->meta_keywords = 'view,series,tv,show,description,details'; - $page->meta_description = 'View TV Series'; + $page->title = 'Series'; + $page->meta_title = 'View TV Series'; + $page->meta_keywords = 'view,series,tv,show,description,details'; + $page->meta_description = 'View TV Series'; - if ($category !== -1) { - $cdata = $cat->getById($category); - $catid = $category; - } else { - $cdata = ['title' => '']; - $catid = ''; - } - $page->smarty->assign('catname', $cdata['title']); - $page->smarty->assign('category', $catid); - $page->smarty->assign('nodata', ''); - } - $page->content = $page->smarty->fetch('viewseries.tpl'); - $page->render(); + if ($category !== -1) { + $cdata = $cat->getById($category); + $catid = $category; + } else { + $cdata = ['title' => '']; + $catid = ''; + } + $page->smarty->assign('catname', $cdata['title']); + $page->smarty->assign('category', $catid); + $page->smarty->assign('nodata', ''); + } + $page->content = $page->smarty->fetch('viewseries.tpl'); + $page->render(); } else { - $letter = (isset($_GET['id']) && preg_match('/^(0\-9|[A-Z])$/i', $_GET['id'])) ? $_GET['id'] : '0-9'; + $letter = (isset($_GET['id']) && preg_match('/^(0\-9|[A-Z])$/i', $_GET['id'])) ? $_GET['id'] : '0-9'; - $showname = (isset($_GET['title']) && !empty($_GET['title'])) ? $_GET['title'] : ''; + $showname = (isset($_GET['title']) && ! empty($_GET['title'])) ? $_GET['title'] : ''; - if ($showname !== '' && !isset($_GET['id'])) { - $letter = ''; - } + if ($showname !== '' && ! isset($_GET['id'])) { + $letter = ''; + } - $masterserieslist = $tvshow->getSeriesList($page->users->currentUserId(), $letter, $showname); + $masterserieslist = $tvshow->getSeriesList($page->users->currentUserId(), $letter, $showname); - $page->title = 'Series List'; - $page->meta_title = 'View Series List'; - $page->meta_keywords = 'view,series,tv,show,description,details'; - $page->meta_description = 'View Series List'; + $page->title = 'Series List'; + $page->meta_title = 'View Series List'; + $page->meta_keywords = 'view,series,tv,show,description,details'; + $page->meta_description = 'View Series List'; - $serieslist = []; - foreach ($masterserieslist as $s) { - if (preg_match('/^[0-9]/', $s['title'])) { - $thisrange = '0-9'; - } else { - preg_match('/([A-Z]).*/i', $s['title'], $matches); - $thisrange = strtoupper($matches[1]); - } - $serieslist[$thisrange][] = $s; - } - ksort($serieslist); + $serieslist = []; + foreach ($masterserieslist as $s) { + if (preg_match('/^[0-9]/', $s['title'])) { + $thisrange = '0-9'; + } else { + preg_match('/([A-Z]).*/i', $s['title'], $matches); + $thisrange = strtoupper($matches[1]); + } + $serieslist[$thisrange][] = $s; + } + ksort($serieslist); - $page->smarty->assign('serieslist', $serieslist); - $page->smarty->assign('seriesrange', range('A', 'Z')); - $page->smarty->assign('seriesletter', $letter); - $page->smarty->assign('showname', $showname); + $page->smarty->assign('serieslist', $serieslist); + $page->smarty->assign('seriesrange', range('A', 'Z')); + $page->smarty->assign('seriesletter', $letter); + $page->smarty->assign('showname', $showname); - $page->content = $page->smarty->fetch('viewserieslist.tpl'); - $page->render(); + $page->content = $page->smarty->fetch('viewserieslist.tpl'); + $page->render(); } diff --git a/public/pages/sitemap.php b/public/pages/sitemap.php index 06e639f5c..1916c7990 100644 --- a/public/pages/sitemap.php +++ b/public/pages/sitemap.php @@ -1,64 +1,61 @@ smarty; -$arPages = array(); +$arPages = []; -$arPages[] = buildURL("Home", "Home Page", "/", 'daily', '1.0'); +$arPages[] = buildURL('Home', 'Home Page', '/', 'daily', '1.0'); - -$role=0; -if ($page->userdata != null) - $role = $page->userdata["role"]; +$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'); +$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'); +$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'); +$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'); +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('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('Forum', 'Forum', '/forum', 'daily', '0.80'); - $arPages[] = buildURL("User", "Cart", "/cart", 'weekly', '0.50'); - $arPages[] = buildURL("User", "Profile", "/profile", 'weekly', '0.50'); + $arPages[] = buildURL('User', 'Cart', '/cart', 'weekly', '0.50'); + $arPages[] = buildURL('User', 'Profile', '/profile', 'weekly', '0.50'); } // @@ -67,27 +64,24 @@ if ($page->userdata != null) asort($arPages); $page->smarty->assign([ 'sitemaps' => $arPages, - 'last_type' => '' + 'last_type' => '', ] ); -if (isset($_GET["type"]) && $_GET["type"] == "xml") -{ - echo $page->smarty->fetch('sitemap-xml.tpl'); -} -else -{ - $page->title = Settings::value('site.main.title'). " site map"; - $page->meta_title = Settings::value('site.main.title'). " site map"; - $page->meta_keywords = "sitemap,site,map"; - $page->meta_description = Settings::value('site.main.title')." site map shows all our pages."; - $page->content = $page->smarty->fetch('sitemap.tpl'); - $page->render(); +if (isset($_GET['type']) && $_GET['type'] == 'xml') { + echo $page->smarty->fetch('sitemap-xml.tpl'); +} else { + $page->title = Settings::value('site.main.title').' site map'; + $page->meta_title = Settings::value('site.main.title').' site map'; + $page->meta_keywords = 'sitemap,site,map'; + $page->meta_description = Settings::value('site.main.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') +function buildURL($type, $name, $url, $freq = 'daily', $p = '1.0') { - $s = new Sitemap($type, $name, $url, $freq, $p); - return $s; -} + $s = new Sitemap($type, $name, $url, $freq, $p); + return $s; +} diff --git a/public/pages/smartyTV.php b/public/pages/smartyTV.php index 4b42eb553..86b66fd58 100644 --- a/public/pages/smartyTV.php +++ b/public/pages/smartyTV.php @@ -24,89 +24,80 @@ use nntmux\processing\tv\TV; class smartyTV extends TV { - /** - * Main processing director function for scrapers - * Calls work query function and initiates processing - * - * @param $groupID - * @param $guidChar - * @param $process - * @param bool $local - */ - protected function processSite($groupID, $guidChar, $process, $local = false) - { - ; - } + /** + * Main processing director function for scrapers + * Calls work query function and initiates processing. + * + * @param $groupID + * @param $guidChar + * @param $process + * @param bool $local + */ + protected function processSite($groupID, $guidChar, $process, $local = false) + { + } - protected function getBanner($videoID, $siteId) - { - ; - } + protected function getBanner($videoID, $siteId) + { + } - /** - * Retrieve info of TV episode from site using its API. - * - * @param integer $siteId - * @param integer $series - * @param integer $episode - * - * @return array|false False on failure, an array of information fields otherwise. - */ - protected function getEpisodeInfo($siteId, $series, $episode) - { - ; - } + /** + * Retrieve info of TV episode from site using its API. + * + * @param int $siteId + * @param int $series + * @param int $episode + * + * @return array|false False on failure, an array of information fields otherwise. + */ + protected function getEpisodeInfo($siteId, $series, $episode) + { + } - /** - * Retrieve poster image for TV episode from site using its API. - * - * @param integer $videoId ID from videos table. - * @param integer $siteId ID that this site uses for the programme. - * - * @return null - */ - protected function getPoster($videoId, $siteId) - { - ; - } + /** + * Retrieve poster image for TV episode from site using its API. + * + * @param int $videoId ID from videos table. + * @param int $siteId ID that this site uses for the programme. + * + * @return null + */ + protected function getPoster($videoId, $siteId) + { + } - /** - * Retrieve info of TV programme from site using it's API. - * - * @param string $name Title of programme to look up. Usually a cleaned up version from releases table. - * - * @return array|false False on failure, an array of information fields otherwise. - */ - protected function getShowInfo($name) - { - ; - } + /** + * Retrieve info of TV programme from site using it's API. + * + * @param string $name Title of programme to look up. Usually a cleaned up version from releases table. + * + * @return array|false False on failure, an array of information fields otherwise. + */ + protected function getShowInfo($name) + { + } - /** - * Assigns API show response values to a formatted array for insertion - * Returns the formatted array - * - * @param $show - * - * @return array - */ - protected function formatShowInfo($show) - { - ; - } + /** + * Assigns API show response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $show + * + * @return array + */ + protected function formatShowInfo($show) + { + } - /** - * Assigns API episode response values to a formatted array for insertion - * Returns the formatted array - * - * @param $episode - * - * @return array - */ - protected function formatEpisodeInfo($episode) - { - ; - } + /** + * Assigns API episode response values to a formatted array for insertion + * Returns the formatted array. + * + * @param $episode + * + * @return array + */ + protected function formatEpisodeInfo($episode) + { + } } - -?> diff --git a/public/pages/terms-and-conditions.php b/public/pages/terms-and-conditions.php index f996b6992..952e267af 100644 --- a/public/pages/terms-and-conditions.php +++ b/public/pages/terms-and-conditions.php @@ -2,12 +2,11 @@ use App\Models\Settings; -$page->title = "Terms and Conditions"; -$page->meta_title = Settings::value('site.main.title')." - Terms and conditions"; -$page->meta_keywords = "terms,conditions"; -$page->meta_description = "Terms and Conditions for ".Settings::value('site.main.title'); +$page->title = 'Terms and Conditions'; +$page->meta_title = Settings::value('site.main.title').' - Terms and conditions'; +$page->meta_keywords = 'terms,conditions'; +$page->meta_description = 'Terms and Conditions for '.Settings::value('site.main.title'); $page->content = $page->smarty->fetch('terms.tpl'); $page->render(); - diff --git a/public/pages/topic_delete.php b/public/pages/topic_delete.php index f7de82f1d..31bb4c1c2 100644 --- a/public/pages/topic_delete.php +++ b/public/pages/topic_delete.php @@ -2,14 +2,13 @@ use nntmux\Forum; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $forum = new Forum(); $id = $_GET['id'] + 0; -if (isset($id)) -{ - $forum->deleteParent($id); - header("Location:" . WWW_TOP . "/forum"); +if (isset($id)) { + $forum->deleteParent($id); + header('Location:'.WWW_TOP.'/forum'); } diff --git a/public/pages/xxx.php b/public/pages/xxx.php index d8c9eb560..5859dc0ed 100644 --- a/public/pages/xxx.php +++ b/public/pages/xxx.php @@ -4,8 +4,8 @@ use nntmux\XXX; use nntmux\Category; use nntmux\DnzbFailures; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } $movie = new XXX(); @@ -15,11 +15,11 @@ $fail = new DnzbFailures(['Settings' => $page->settings]); $moviecats = $cat->getChildren(Category::XXX_ROOT); $mtmp = []; foreach ($moviecats as $mcat) { - $mtmp[$mcat['id']] = $mcat; + $mtmp[$mcat['id']] = $mcat; } $category = Category::XXX_ROOT; if (isset($_REQUEST['t']) && array_key_exists($_REQUEST['t'], $mtmp)) { - $category = $_REQUEST['t'] + 0; + $category = $_REQUEST['t'] + 0; } $catarray = []; $catarray[] = $category; @@ -27,67 +27,67 @@ $catarray[] = $category; $page->smarty->assign('catlist', $mtmp); $page->smarty->assign('category', $category); -$offset = (isset($_REQUEST['offset']) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST["offset"] : 0; +$offset = (isset($_REQUEST['offset']) && ctype_digit($_REQUEST['offset'])) ? $_REQUEST['offset'] : 0; $ordering = $movie->getXXXOrdering(); $orderby = isset($_REQUEST['ob']) && in_array($_REQUEST['ob'], $ordering, false) ? $_REQUEST['ob'] : ''; $results = $movies = []; $results = $movie->getXXXRange($catarray, $offset, ITEMS_PER_COVER_PAGE, $orderby, -1, $page->userdata['categoryexclusions']); foreach ($results as $result) { - $result['genre'] = $movie->makeFieldLinks($result, 'genre'); - $result['actors'] = $movie->makeFieldLinks($result, 'actors'); - $result['director'] = $movie->makeFieldLinks($result, 'director'); - $movies[] = $result; + $result['genre'] = $movie->makeFieldLinks($result, 'genre'); + $result['actors'] = $movie->makeFieldLinks($result, 'actors'); + $result['director'] = $movie->makeFieldLinks($result, 'director'); + $movies[] = $result; } -$title = (isset($_REQUEST['title']) && !empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; +$title = (isset($_REQUEST['title']) && ! empty($_REQUEST['title'])) ? stripslashes($_REQUEST['title']) : ''; $page->smarty->assign('title', stripslashes($title)); -$actors = (isset($_REQUEST['actors']) && !empty($_REQUEST['actors'])) ? stripslashes($_REQUEST['actors']) : ''; +$actors = (isset($_REQUEST['actors']) && ! empty($_REQUEST['actors'])) ? stripslashes($_REQUEST['actors']) : ''; $page->smarty->assign('actors', $actors); -$director = (isset($_REQUEST['director']) && !empty($_REQUEST['director'])) ? stripslashes($_REQUEST['director']) : ''; +$director = (isset($_REQUEST['director']) && ! empty($_REQUEST['director'])) ? stripslashes($_REQUEST['director']) : ''; $page->smarty->assign('director', $director); -$genres = (array)$movie->getAllGenres(true); +$genres = (array) $movie->getAllGenres(true); $genre = (isset($_REQUEST['genre']) && in_array($_REQUEST['genre'], $genres, false)) ? $_REQUEST['genre'] : ''; $page->smarty->assign('genres', $genres); $page->smarty->assign('genre', $genre); -$browseby_link = '&title=' . $title . '&actors=' . $actors . '&director=' . $director . '&genre=' . $genre; +$browseby_link = '&title='.$title.'&actors='.$actors.'&director='.$director.'&genre='.$genre; $page->smarty->assign('pagertotalitems', $results[0]['_totalcount'] ?? 0); $page->smarty->assign('pageroffset', $offset); $page->smarty->assign('pageritemsperpage', ITEMS_PER_COVER_PAGE); -$page->smarty->assign('pagerquerybase', WWW_TOP . "/xxx?t=" . $category . $browseby_link . "&ob=" . $orderby . "&offset="); -$page->smarty->assign('pagerquerysuffix', "#results"); +$page->smarty->assign('pagerquerybase', WWW_TOP.'/xxx?t='.$category.$browseby_link.'&ob='.$orderby.'&offset='); +$page->smarty->assign('pagerquerysuffix', '#results'); -$pager = $page->smarty->fetch("pager.tpl"); +$pager = $page->smarty->fetch('pager.tpl'); $page->smarty->assign('pager', $pager); if ($category == -1) { - $page->smarty->assign("catname", "All"); + $page->smarty->assign('catname', 'All'); } else { - $cdata = $cat->getById($category); - if ($cdata) { - $page->smarty->assign('catname', $cdata['title']); - } else { - $page->show404(); - } + $cdata = $cat->getById($category); + if ($cdata) { + $page->smarty->assign('catname', $cdata['title']); + } else { + $page->show404(); + } } foreach ($ordering as $ordertype) { - $page->smarty->assign('orderby' . $ordertype, WWW_TOP . "/xxx?t=" . $category . $browseby_link . "&ob=" . $ordertype . "&offset=0"); + $page->smarty->assign('orderby'.$ordertype, WWW_TOP.'/xxx?t='.$category.$browseby_link.'&ob='.$ordertype.'&offset=0'); } $page->smarty->assign('results', $movies); -$page->meta_title = "Browse XXX"; -$page->meta_keywords = "browse,xxx,nzb,description,details"; -$page->meta_description = "Browse for XXX Movies"; +$page->meta_title = 'Browse XXX'; +$page->meta_keywords = 'browse,xxx,nzb,description,details'; +$page->meta_description = 'Browse for XXX Movies'; -if (isset($_GET["id"])) { - $page->content = $page->smarty->fetch('viewxxxfull.tpl'); +if (isset($_GET['id'])) { + $page->content = $page->smarty->fetch('viewxxxfull.tpl'); } else { - $page->content = $page->smarty->fetch('xxx.tpl'); + $page->content = $page->smarty->fetch('xxx.tpl'); } $page->render(); diff --git a/public/pages/xxxmodal.php b/public/pages/xxxmodal.php index f4f94d280..f64883b96 100644 --- a/public/pages/xxxmodal.php +++ b/public/pages/xxxmodal.php @@ -2,41 +2,38 @@ use nntmux\XXX; -if (!$page->users->isLoggedIn()) { - $page->show403(); +if (! $page->users->isLoggedIn()) { + $page->show403(); } -if (isset($_GET['modal']) && isset($_GET["id"]) && ctype_digit($_GET["id"])) { - $movie = new XXX(['Settings' => $page->settings]); - $mov = $movie->getXXXInfo($_GET['id']); +if (isset($_GET['modal']) && isset($_GET['id']) && ctype_digit($_GET['id'])) { + $movie = new XXX(['Settings' => $page->settings]); + $mov = $movie->getXXXInfo($_GET['id']); - if (!$mov) { - $page->show404(); - } + if (! $mov) { + $page->show404(); + } - $mov['actors'] = $movie->makeFieldLinks($mov, 'actors'); - $mov['genre'] = $movie->makeFieldLinks($mov, 'genre'); - $mov['director'] = $movie->makeFieldLinks($mov, 'director'); + $mov['actors'] = $movie->makeFieldLinks($mov, 'actors'); + $mov['genre'] = $movie->makeFieldLinks($mov, 'genre'); + $mov['director'] = $movie->makeFieldLinks($mov, 'director'); - $page->smarty->assign(['movie' => $mov, 'modal' => true]); + $page->smarty->assign(['movie' => $mov, 'modal' => true]); - $page->title = "Info for " . $mov['title']; - $page->meta_title = ""; - $page->meta_keywords = ""; - $page->meta_description = ""; - $page->smarty->registerPlugin('modifier', 'ss', 'stripslashes'); + $page->title = 'Info for '.$mov['title']; + $page->meta_title = ''; + $page->meta_keywords = ''; + $page->meta_description = ''; + $page->smarty->registerPlugin('modifier', 'ss', 'stripslashes'); - if (isset($_GET['modal'])) - { - $page->content = $page->smarty->fetch('viewxxx.tpl'); - $page->smarty->assign('modal', true); - echo $page->content; - } - else - { - $page->content = $page->smarty->fetch('viewxxxfull.tpl'); - $page->render(); - } + if (isset($_GET['modal'])) { + $page->content = $page->smarty->fetch('viewxxx.tpl'); + $page->smarty->assign('modal', true); + echo $page->content; + } else { + $page->content = $page->smarty->fetch('viewxxxfull.tpl'); + $page->render(); + } } else { - $page->render(); + $page->render(); } diff --git a/public/plugins/block.php.php b/public/plugins/block.php.php index 4a0aa3dd7..b0c7ce457 100755 --- a/public/plugins/block.php.php +++ b/public/plugins/block.php.php @@ -1,25 +1,23 @@ allow_php_tag) { - throw new SmartyException("{php} is deprecated, set allow_php_tag = true to enable"); - } - eval($content); - return ''; + if (! $template->allow_php_tag) { + throw new SmartyException('{php} is deprecated, set allow_php_tag = true to enable'); + } + eval($content); + + return ''; } -?> \ No newline at end of file diff --git a/public/plugins/function.getcatval.php b/public/plugins/function.getcatval.php index 04e88e39a..09e37c1e7 100755 --- a/public/plugins/function.getcatval.php +++ b/public/plugins/function.getcatval.php @@ -10,13 +10,12 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program (see LICENSE.txt in the base directory. If - * not, see: + * not, see:. * * @link . * @author niel * @copyright 2016 nZEDb */ - use nntmux\Category; /** @@ -29,7 +28,5 @@ use nntmux\Category; */ function smarty_function_getcatval($params) { - return Category::getCategoryValue($params['category']); + return Category::getCategoryValue($params['category']); } - -?> diff --git a/public/plugins/function.html_options_multiple.php b/public/plugins/function.html_options_multiple.php index 240a584e4..b89306c19 100755 --- a/public/plugins/function.html_options_multiple.php +++ b/public/plugins/function.html_options_multiple.php @@ -1,9 +1,6 @@ * Name: html_options_multiple
@@ -39,17 +36,17 @@ require_once 'load_plugin_dependency.php'; */ function smarty_function_html_options_multiple($params, $template) { - load_plugin_dependency('shared.escape_special_chars.php'); - $name = null; - $values = null; - $options = null; - $selected = null; - $output = null; - $id = null; - $class = null; - $extra = ''; - foreach ($params as $_key => $_val) { - switch ($_key) { + load_plugin_dependency('shared.escape_special_chars.php'); + $name = null; + $values = null; + $options = null; + $selected = null; + $output = null; + $id = null; + $class = null; + $extra = ''; + foreach ($params as $_key => $_val) { + switch ($_key) { case 'name': case 'class': case 'id': @@ -64,116 +61,119 @@ function smarty_function_html_options_multiple($params, $template) break; case 'selected': if (is_array($_val)) { - $selected = array(); - foreach ($_val as $_sel) { - if (is_object($_sel)) { - if (method_exists($_sel, "__toString")) { - $_sel = smarty_function_escape_special_chars((string) $_sel->__toString()); - } else { - trigger_error("html_options_multiple: selected attribute contains an object of class '". get_class($_sel) ."' without __toString() method", E_USER_NOTICE); - continue; - } - } else { - $_sel = smarty_function_escape_special_chars((string) $_sel); - } - $selected[$_sel] = true; - } + $selected = []; + foreach ($_val as $_sel) { + if (is_object($_sel)) { + if (method_exists($_sel, '__toString')) { + $_sel = smarty_function_escape_special_chars((string) $_sel->__toString()); + } else { + trigger_error("html_options_multiple: selected attribute contains an object of class '".get_class($_sel)."' without __toString() method", E_USER_NOTICE); + continue; + } + } else { + $_sel = smarty_function_escape_special_chars((string) $_sel); + } + $selected[$_sel] = true; + } } elseif (is_object($_val)) { - if (method_exists($_val, "__toString")) { - $selected = smarty_function_escape_special_chars((string) $_val->__toString()); - } else { - trigger_error("html_options_multiple: selected attribute is an object of class '". get_class($_val) ."' without __toString() method", E_USER_NOTICE); - } + if (method_exists($_val, '__toString')) { + $selected = smarty_function_escape_special_chars((string) $_val->__toString()); + } else { + trigger_error("html_options_multiple: selected attribute is an object of class '".get_class($_val)."' without __toString() method", E_USER_NOTICE); + } } else { - $selected = smarty_function_escape_special_chars((string) $_val); + $selected = smarty_function_escape_special_chars((string) $_val); } break; case 'strict': break; case 'disabled': case 'readonly': - if (!empty($params['strict'])) { - if (!is_scalar($_val)) { - trigger_error("html_options_multiple: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute", E_USER_NOTICE); - } - if ($_val === true || $_val === $_key) { - $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"'; - } - break; + if (! empty($params['strict'])) { + if (! is_scalar($_val)) { + trigger_error("html_options_multiple: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute", E_USER_NOTICE); + } + if ($_val === true || $_val === $_key) { + $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_key).'"'; + } + break; } // omit break; to fall through! default: - if (!is_array($_val)) { - $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"'; + if (! is_array($_val)) { + $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"'; } else { - trigger_error("html_options_multiple: extra attribute '$_key' cannot be an array", E_USER_NOTICE); + trigger_error("html_options_multiple: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } - } - if (!isset($options) && !isset($values)) { - /* raise error here? */ - return ''; - } - $_html_result = ''; - $_idx = 0; - if (isset($options)) { - foreach ($options as $_key => $_val) { - $_html_result .= smarty_function_html_options_multiple_optoutput($_key, $_val, $selected, $id, $class, $_idx); - } - } else { - foreach ($values as $_i => $_key) { - $_val = isset($output[$_i]) ? $output[$_i] : ''; - $_html_result .= smarty_function_html_options_multiple_optoutput($_key, $_val, $selected, $id, $class, $_idx); - } - } - if (!empty($name)) { - $_html_class = !empty($class) ? ' class="'.$class.'"' : ''; - $_html_id = !empty($id) ? ' id="'.$id.'"' : ''; - // the name needs to have [] added (this is html text [] not PHP, so that the return for the multiselect is an array - $_html_result = '' . "\n"; - } - return $_html_result; + } + if (! isset($options) && ! isset($values)) { + /* raise error here? */ + return ''; + } + $_html_result = ''; + $_idx = 0; + if (isset($options)) { + foreach ($options as $_key => $_val) { + $_html_result .= smarty_function_html_options_multiple_optoutput($_key, $_val, $selected, $id, $class, $_idx); + } + } else { + foreach ($values as $_i => $_key) { + $_val = isset($output[$_i]) ? $output[$_i] : ''; + $_html_result .= smarty_function_html_options_multiple_optoutput($_key, $_val, $selected, $id, $class, $_idx); + } + } + if (! empty($name)) { + $_html_class = ! empty($class) ? ' class="'.$class.'"' : ''; + $_html_id = ! empty($id) ? ' id="'.$id.'"' : ''; + // the name needs to have [] added (this is html text [] not PHP, so that the return for the multiselect is an array + $_html_result = ''."\n"; + } + + return $_html_result; } function smarty_function_html_options_multiple_optoutput($key, $value, $selected, $id, $class, &$idx) { - if (!is_array($value)) { - $_key = smarty_function_escape_special_chars($key); - $_html_result = '' . "\n"; - $idx++; - } else { - $_idx = 0; - $_html_result = smarty_function_html_options_multiple_optgroup($key, $value, $selected, !empty($id) ? ($id.'-'.$idx) : null, $class, $_idx); - $idx++; - } - return $_html_result; + if (! is_array($value)) { + $_key = smarty_function_escape_special_chars($key); + $_html_result = ''."\n"; + $idx++; + } else { + $_idx = 0; + $_html_result = smarty_function_html_options_multiple_optgroup($key, $value, $selected, ! empty($id) ? ($id.'-'.$idx) : null, $class, $_idx); + $idx++; + } + + return $_html_result; } function smarty_function_html_options_multiple_optgroup($key, $values, $selected, $id, $class, &$idx) { - $optgroup_html = '' . "\n"; - foreach ($values as $key => $value) { - $optgroup_html .= smarty_function_html_options_multiple_optoutput($key, $value, $selected, $id, $class, $idx); - } - $optgroup_html .= "\n"; - return $optgroup_html; + $optgroup_html = ''."\n"; + foreach ($values as $key => $value) { + $optgroup_html .= smarty_function_html_options_multiple_optoutput($key, $value, $selected, $id, $class, $idx); + } + $optgroup_html .= "\n"; + + return $optgroup_html; } -?> diff --git a/public/plugins/load_plugin_dependency.php b/public/plugins/load_plugin_dependency.php index 4a610b6a9..040fc5d2f 100644 --- a/public/plugins/load_plugin_dependency.php +++ b/public/plugins/load_plugin_dependency.php @@ -2,37 +2,35 @@ function load_plugin_dependency($filename) { - global $smarty; + global $smarty; - if (!isset($smarty)) { - $smarty = new Smarty(); - } + if (! isset($smarty)) { + $smarty = new Smarty(); + } - switch (true) { + switch (true) { case is_string($smarty->plugins_dir) && is_dir($smarty->plugins_dir): $plugins_dir = $smarty->plugins_dir; - require_once $plugins_dir . DIRECTORY_SEPARATOR . $filename; + require_once $plugins_dir.DIRECTORY_SEPARATOR.$filename; break; case is_array($smarty->plugins_dir): $plugins_dir = ''; foreach ($smarty->plugins_dir as $dir) { - if (is_string($dir) && is_dir($dir)) { - $file = $dir . DIRECTORY_SEPARATOR . $filename; - if (file_exists($file) && is_readable($file)) { - $plugins_dir = $dir; - require_once $file; - break; - } - } + if (is_string($dir) && is_dir($dir)) { + $file = $dir.DIRECTORY_SEPARATOR.$filename; + if (file_exists($file) && is_readable($file)) { + $plugins_dir = $dir; + require_once $file; + break; + } + } } break; default: $plugins_dir = ''; } - if (!is_dir($plugins_dir)) { - exit('Fatal: Unable to find smarty plugins directory.' . PHP_EOL); - } + if (! is_dir($plugins_dir)) { + exit('Fatal: Unable to find smarty plugins directory.'.PHP_EOL); + } } - -?> diff --git a/public/plugins/modifier.daysago.php b/public/plugins/modifier.daysago.php index 00053525f..4a8653d5f 100755 --- a/public/plugins/modifier.daysago.php +++ b/public/plugins/modifier.daysago.php @@ -1,41 +1,37 @@ - * Name: daysAgo
+ * Name: daysAgo
. * @author Stephan Otto * @param string * @return string */ function smarty_modifier_daysAgo($date) { - if ($date == "") - return "n/a"; - $sec = mktime(0,0,0,date("m"), date("d"), date("Y")) - (( strtotime($date)) ? strtotime(date("Y-m-d", strtotime($date))) : strtotime(date("Y-m-d", $date))); - $min = $sec / 60; - $hrs = $min / 60; - $days = $sec/60/60/24; - if ( $hrs <= 24) return ' Today'; - if ($days >= 365) - { - $years = round(($days/365), 1); - return $years.' Yr'.($years!=1?"s":"").' ago'; - } - else if ($days >= 90) - { - return round($days/7).' Wks ago'; - } - else if ($days <= 2) - return 'Yesterday'; - else - { - return round($days, 0).'d ago'; - } + if ($date == '') { + return 'n/a'; + } + $sec = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - ((strtotime($date)) ? strtotime(date('Y-m-d', strtotime($date))) : strtotime(date('Y-m-d', $date))); + $min = $sec / 60; + $hrs = $min / 60; + $days = $sec / 60 / 60 / 24; + if ($hrs <= 24) { + return ' Today'; + } + if ($days >= 365) { + $years = round(($days / 365), 1); + + return $years.' Yr'.($years != 1 ? 's' : '').' ago'; + } elseif ($days >= 90) { + return round($days / 7).' Wks ago'; + } elseif ($days <= 2) { + return 'Yesterday'; + } else { + return round($days, 0).'d ago'; + } } -?> \ No newline at end of file diff --git a/public/plugins/modifier.fsize_format.php b/public/plugins/modifier.fsize_format.php index 78a7a5e42..926dc3374 100755 --- a/public/plugins/modifier.fsize_format.php +++ b/public/plugins/modifier.fsize_format.php @@ -29,29 +29,28 @@ * 2003-02-21 Version 0.1 - initial release * ------------------------------------------------------------- */ -function smarty_modifier_fsize_format($size,$format = '',$precision = 2, $dec_point = ".", $thousands_sep = ",") +function smarty_modifier_fsize_format($size, $format = '', $precision = 2, $dec_point = '.', $thousands_sep = ',') { - $format = strtoupper($format); - static $sizes = array(); - if(!count($sizes)) { - $b = 1024; - $sizes["B"] = 1; - $sizes["KB"] = $sizes["B"] * $b; - $sizes["MB"] = $sizes["KB"] * $b; - $sizes["GB"] = $sizes["MB"] * $b; - $sizes["TB"] = $sizes["GB"] * $b; - $sizes["PB"] = $sizes["TB"] * $b; - $sizes["EB"] = $sizes["PB"] * $b; - $sizes["ZB"] = $sizes["EB"] * $b; - $sizes["YB"] = $sizes["ZB"] * $b; - $sizes = array_reverse($sizes,true); - } - //~ get "human" filesize - foreach($sizes AS $unit => $bytes) { - if($size > $bytes || $unit == $format) { - //~ return formatted size - return number_format($size / $bytes,$precision,$dec_point,$thousands_sep)." ".$unit; - } //~ end if - } //~ end foreach + $format = strtoupper($format); + static $sizes = []; + if (! count($sizes)) { + $b = 1024; + $sizes['B'] = 1; + $sizes['KB'] = $sizes['B'] * $b; + $sizes['MB'] = $sizes['KB'] * $b; + $sizes['GB'] = $sizes['MB'] * $b; + $sizes['TB'] = $sizes['GB'] * $b; + $sizes['PB'] = $sizes['TB'] * $b; + $sizes['EB'] = $sizes['PB'] * $b; + $sizes['ZB'] = $sizes['EB'] * $b; + $sizes['YB'] = $sizes['ZB'] * $b; + $sizes = array_reverse($sizes, true); + } + //~ get "human" filesize + foreach ($sizes as $unit => $bytes) { + if ($size > $bytes || $unit == $format) { + //~ return formatted size + return number_format($size / $bytes, $precision, $dec_point, $thousands_sep).' '.$unit; + } //~ end if + } //~ end foreach } //~ end function -?> \ No newline at end of file diff --git a/public/plugins/modifier.magicurl.php b/public/plugins/modifier.magicurl.php index 9b815c597..9feb397ae 100755 --- a/public/plugins/modifier.magicurl.php +++ b/public/plugins/modifier.magicurl.php @@ -1,11 +1,9 @@ * Name: magicurl
@@ -14,7 +12,7 @@ * @param string * @return string */ -function smarty_modifier_magicurl($str, $dereferrer="") { - return preg_replace('/(https?):\/\/([A-Za-z0-9\._\-\/\?=&;%]+)/is', '$1://$2', $str); +function smarty_modifier_magicurl($str, $dereferrer = '') +{ + return preg_replace('/(https?):\/\/([A-Za-z0-9\._\-\/\?=&;%]+)/is', '$1://$2', $str); } -?> \ No newline at end of file diff --git a/public/plugins/modifier.nl2br.php b/public/plugins/modifier.nl2br.php index d6dc55ca7..24ef525f6 100755 --- a/public/plugins/modifier.nl2br.php +++ b/public/plugins/modifier.nl2br.php @@ -1,11 +1,9 @@ * Name: nl2br
@@ -25,7 +23,6 @@ */ function smarty_modifier_nl2br($string) { - return nl2br($string); + return nl2br($string); } /* vim: set expandtab: */ -?> \ No newline at end of file diff --git a/public/plugins/modifier.parray.php b/public/plugins/modifier.parray.php index 285a4e98d..b0640c812 100755 --- a/public/plugins/modifier.parray.php +++ b/public/plugins/modifier.parray.php @@ -1,9 +1,10 @@ \ No newline at end of file diff --git a/public/plugins/modifier.phpdate_format.php b/public/plugins/modifier.phpdate_format.php index 1aea14c97..17942550d 100755 --- a/public/plugins/modifier.phpdate_format.php +++ b/public/plugins/modifier.phpdate_format.php @@ -4,14 +4,14 @@ * phpdate_format plugin * Sam Easterby-Smith * Does exactly what the normal date_format plugin does - only it uses date() rather than strftime() - * It also supports the various php date constants for doing things like rfc822 dates + * It also supports the various php date constants for doing things like rfc822 dates. */ /** - * Include the {@link shared.make_timestamp.php} plugin + * Include the {@link shared.make_timestamp.php} plugin. */ // Fix by nZEDb -if (!isset($smarty)) { - $smarty = new Smarty(); +if (! isset($smarty)) { + $smarty = new Smarty(); } switch (true) { case is_string($smarty->plugins_dir) && is_dir($smarty->plugins_dir): @@ -20,22 +20,22 @@ switch (true) { case is_array($smarty->plugins_dir): $plugins_dir = ''; foreach ($smarty->plugins_dir as $dir) { - if (is_string($dir) && is_dir($dir)) { - $plugins_dir = $dir; - break; - } + if (is_string($dir) && is_dir($dir)) { + $plugins_dir = $dir; + break; + } } break; default: $plugins_dir = ''; } -if (!is_dir($plugins_dir)) { - exit('Fatal: Unable to find smarty plugins directory.' . PHP_EOL); +if (! is_dir($plugins_dir)) { + exit('Fatal: Unable to find smarty plugins directory.'.PHP_EOL); } // End fix by nZEDb. -require_once ($plugins_dir . 'shared.make_timestamp.php'); +require_once $plugins_dir.'shared.make_timestamp.php'; /** - * Smarty phpdate_format modifier plugin + * Smarty phpdate_format modifier plugin. * * Type: modifier
* Name: date_format
@@ -52,37 +52,36 @@ require_once ($plugins_dir . 'shared.make_timestamp.php'); * @return string|void * @uses smarty_make_timestamp() */ -function smarty_modifier_phpdate_format($string, $format="Y/m/d H:i:s", $default_date=null) +function smarty_modifier_phpdate_format($string, $format = 'Y/m/d H:i:s', $default_date = null) { - /* if (substr(PHP_OS,0,3) == 'WIN') { + /* if (substr(PHP_OS,0,3) == 'WIN') { $_win_from = array ('%e', '%T', '%D'); $_win_to = array ('%#d', '%H:%M:%S', '%m/%d/%y'); $format = str_replace($_win_from, $_win_to, $format); }*/ - if (substr($format,0,5)=='DATE_'){ - switch ($format){ - case 'DATE_ATOM': $nformat=DATE_ATOM; break; - case 'DATE_COOKIE': $nformat=DATE_COOKIE; break; - case 'DATE_ISO8601': $nformat=DATE_ISO8601; break; - case 'DATE_RFC822': $nformat="D, d M y H:i:s O"; break; //The php constant is not quite right - as the time-zone comes out with invalid values like "UTC"... - case 'DATE_RFC850': $nformat=DATE_RFC850; break; - case 'DATE_RFC1036': $nformat=DATE_RFC1036; break; - case 'DATE_RFC1123': $nformat=DATE_RFC1123; break; - case 'DATE_RFC2822': $nformat=DATE_RFC2822; break; - case 'DATE_RFC3339': $nformat=DATE_RFC3339; break; - case 'DATE_RSS': $nformat="D, d M Y H:i:s O"; break; //as rfc822 ... - case 'DATE_W3C': $nformat=DATE_W3C; break; + if (substr($format, 0, 5) == 'DATE_') { + switch ($format) { + case 'DATE_ATOM': $nformat = DATE_ATOM; break; + case 'DATE_COOKIE': $nformat = DATE_COOKIE; break; + case 'DATE_ISO8601': $nformat = DATE_ISO8601; break; + case 'DATE_RFC822': $nformat = 'D, d M y H:i:s O'; break; //The php constant is not quite right - as the time-zone comes out with invalid values like "UTC"... + case 'DATE_RFC850': $nformat = DATE_RFC850; break; + case 'DATE_RFC1036': $nformat = DATE_RFC1036; break; + case 'DATE_RFC1123': $nformat = DATE_RFC1123; break; + case 'DATE_RFC2822': $nformat = DATE_RFC2822; break; + case 'DATE_RFC3339': $nformat = DATE_RFC3339; break; + case 'DATE_RSS': $nformat = 'D, d M Y H:i:s O'; break; //as rfc822 ... + case 'DATE_W3C': $nformat = DATE_W3C; break; } - } else { - $nformat=$format; - } - if($string != '') { - return date($nformat, smarty_make_timestamp($string)); - } elseif (isset($default_date) && $default_date != '') { - return date($nformat, smarty_make_timestamp($default_date)); - } else { - return; - } + } else { + $nformat = $format; + } + if ($string != '') { + return date($nformat, smarty_make_timestamp($string)); + } elseif (isset($default_date) && $default_date != '') { + return date($nformat, smarty_make_timestamp($default_date)); + } else { + return; + } } /* vim: set expandtab: */ -?> \ No newline at end of file diff --git a/public/plugins/modifier.strtotime.php b/public/plugins/modifier.strtotime.php index 16c9c39c4..804a785a1 100755 --- a/public/plugins/modifier.strtotime.php +++ b/public/plugins/modifier.strtotime.php @@ -1,6 +1,6 @@ \ No newline at end of file diff --git a/public/plugins/modifier.timeago.php b/public/plugins/modifier.timeago.php index 686b1b0e7..2d90f9f1e 100755 --- a/public/plugins/modifier.timeago.php +++ b/public/plugins/modifier.timeago.php @@ -1,49 +1,56 @@ - * Name: timeAgo
+ * Name: timeAgo
. * @author Stephan Otto * @param string * @return string */ -function smarty_modifier_timeAgo( $date) +function smarty_modifier_timeAgo($date) { - if ($date == "") - return "n/a"; - $timeStrings = array( 'now', // 0 + if ($date == '') { + return 'n/a'; + } + $timeStrings = ['now', // 0 'Sec', 'Secs', // 1,1 - 'Min','Mins', // 3,3 + 'Min', 'Mins', // 3,3 'Hour', 'Hrs', // 5,5 - 'Day', 'Days'); - $sec = time() - (( !is_numeric($date) && strtotime($date)) ? strtotime($date) : $date); - if ( $sec <= 0) return $timeStrings[0]; - if ( $sec < 2) return $sec." ".$timeStrings[1]; - if ( $sec < 60) return $sec." ".$timeStrings[2]; - $min = $sec / 60; - if ( floor($min+0.5) < 2) return floor($min+0.5)." ".$timeStrings[3]; - if ( $min < 60) return floor($min+0.5)." ".$timeStrings[4]; - $hrs = $min / 60; - if ( floor($hrs+0.5) < 2) return floor($hrs+0.5)." ".$timeStrings[5]; - if ( $hrs < 24) return floor($hrs+0.5)." ".$timeStrings[6]; - $days = $sec/60/60/24; - if ($days > 365) - { - return round(($days/365), 1).' Yrs'; - } - else if ($days > 90) - { - return round($days/7).' Wks'; - } - else - { - return round($days, 1).'d'; - } + 'Day', 'Days', ]; + $sec = time() - ((! is_numeric($date) && strtotime($date)) ? strtotime($date) : $date); + if ($sec <= 0) { + return $timeStrings[0]; + } + if ($sec < 2) { + return $sec.' '.$timeStrings[1]; + } + if ($sec < 60) { + return $sec.' '.$timeStrings[2]; + } + $min = $sec / 60; + if (floor($min + 0.5) < 2) { + return floor($min + 0.5).' '.$timeStrings[3]; + } + if ($min < 60) { + return floor($min + 0.5).' '.$timeStrings[4]; + } + $hrs = $min / 60; + if (floor($hrs + 0.5) < 2) { + return floor($hrs + 0.5).' '.$timeStrings[5]; + } + if ($hrs < 24) { + return floor($hrs + 0.5).' '.$timeStrings[6]; + } + $days = $sec / 60 / 60 / 24; + if ($days > 365) { + return round(($days / 365), 1).' Yrs'; + } elseif ($days > 90) { + return round($days / 7).' Wks'; + } else { + return round($days, 1).'d'; + } } -?> \ No newline at end of file diff --git a/public/plugins/shared.make_timestamp.php b/public/plugins/shared.make_timestamp.php index f87d40c7e..f3dfc86c1 100644 --- a/public/plugins/shared.make_timestamp.php +++ b/public/plugins/shared.make_timestamp.php @@ -1,9 +1,6 @@ getCode() === 1) { - if (is_dir('install')) { - header('Location: install'); - exit(); - } - } + if ((int) $e->getCode() === 1) { + if (is_dir('install')) { + header('Location: install'); + exit(); + } + } } if (function_exists('ini_set') && function_exists('ini_get')) { - ini_set('include_path', NN_WWW . PATH_SEPARATOR . ini_get('include_path')); + ini_set('include_path', NN_WWW.PATH_SEPARATOR.ini_get('include_path')); } -$www_top = str_replace("\\", '/', dirname($_SERVER['PHP_SELF'])); +$www_top = str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])); if (strlen($www_top) === 1) { - $www_top = ''; + $www_top = ''; } // Used everywhere an href is output, includes the full path to the NNTmux install. diff --git a/server.php b/server.php index 5fb6379e7..20bc389f0 100644 --- a/server.php +++ b/server.php @@ -1,12 +1,10 @@ */ - $uri = urldecode( parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) );