/** * @param Settings $pdo */ public function __construct(Settings $pdo = null) { parent::__construct($pdo); $this->_git = new \nzedb\utility\Git(); $this->_vers = \nzedb\utility\Utility::getValidVersionsFile(); $this->_setColourMasks(); }
/** * @param Settings $pdo */ public function __construct(Settings $pdo = null) { parent::__construct($pdo); $this->_git = new \nzedb\utility\Git(); // Do not remove the full namespace/ PHP gets confused for some reason without it. $this->_vers = Utility::getValidVersionsFile(); $this->_setColourMasks(); }
/** * 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 bool $array Return the full array or just the IMDB id. * * @return bool|mixed * * @access public */ public function traktMoviesummary($movie = '', $array = false) { if (!empty($this->APIKEY)) { $MovieJson = Utility::getUrl(['url' => 'http://api.trakt.tv/movie/summary.json/' . $this->APIKEY . '/' . str_replace([' ', '_', '.'], '-', str_replace(['(', ')'], '', $movie))]); if ($MovieJson !== false) { $MovieJson = json_decode($MovieJson, true); if (isset($MovieJson['status']) && $MovieJson['status'] === 'failure') { return false; } if ($array) { return $MovieJson; } elseif (isset($MovieJson["imdb_id"])) { return $MovieJson["imdb_id"]; } } } return false; }
/** * Check the Admin settings for yEnc and process them accordingly. * * @void * * @access protected */ protected function _initiateYEncSettings() { // Check if the user wants to use yyDecode or the simple_php_yenc_decode extension. $this->_yyDecoderPath = $this->pdo->getSetting('yydecoderpath') != '' ? (string) $this->pdo->getSetting('yydecoderpath') : false; if (strpos((string) $this->_yyDecoderPath, 'simple_php_yenc_decode') !== false) { if (extension_loaded('simple_php_yenc_decode')) { $this->_yEncExtension = true; } else { $this->_yyDecoderPath = false; } } else { if ($this->_yyDecoderPath !== false) { $this->_yEncSilence = Utility::isWin() ? '' : ' > /dev/null 2>&1'; $this->_yEncTempInput = nZEDb_TMP . 'yEnc' . DS; $this->_yEncTempOutput = $this->_yEncTempInput . 'output'; $this->_yEncTempInput .= 'input'; // Test if the user can read/write to the yEnc path. if (!is_file($this->_yEncTempInput)) { @file_put_contents($this->_yEncTempInput, 'x'); } if (!is_file($this->_yEncTempInput) || !is_readable($this->_yEncTempInput) || !is_writable($this->_yEncTempInput)) { $this->_yyDecoderPath = false; } if (is_file($this->_yEncTempInput)) { @unlink($this->_yEncTempInput); } } } }
/** * Cleans file names for PreDB Match */ protected function _cleanMatchFiles($fileName = '') { // first strip all non-printing chars from filename $this->_fileName = $this->utility->stripNonPrintingChars($fileName); if (strlen($this->_fileName) !== false && 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 $this->_fileName = $this->utility->cutStringUsingLast('.', $this->_fileName, "left", false); continue; //if filename has a .part001, send it back to the function to cut the next period //if filename has a .part001, send it back to the function to cut the next period case preg_match('/\\.part\\d+$/', $this->_fileName): $this->_fileName = $this->utility->cutStringUsingLast('.', $this->_fileName, "left", false); continue; //if filename has a .vol001, send it back to the function to cut the next period //if filename has a .vol001, send it back to the function to cut the next period case preg_match('/\\.vol\\d+(\\+\\d+)?$/', $this->_fileName): $this->_fileName = $this->utility->cutStringUsingLast('.', $this->_fileName, "left", false); continue; //if filename contains a slash, cut the string and keep string to the right of the last slash to remove dir //if filename contains a slash, cut the string and keep string to the right of the last slash to remove dir case strpos($this->_fileName, '\\') !== false: $this->_fileName = $this->utility->cutStringUsingLast('\\', $this->_fileName, "right", false); continue; // A lot of obscured releases have one NFO file properly named with a track number (Audio) at the front of it // This will strip out the track and match it to its pre title // A lot of obscured releases have one NFO file properly named with a track number (Audio) at the front of it // This will strip out the track and match it to its pre title case preg_match('/^\\d{2}-/', $this->_fileName): $this->_fileName = preg_replace('/^\\d{2}-/', '', $this->_fileName); } return trim($this->_fileName); } }
/** * 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 = array('data' => nZEDb_RES . 'db' . DS . 'schema' . DS . 'data' . DS, 'ext' => 'sql', 'path' => nZEDb_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); $last = preg_match($options['regex'], end($files), $matches) ? (int) $matches['patch'] : false; if ($update) { if ($last !== false && $this->_vers->sql->file->__toString() != $last) { echo $this->out->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; }
<?php require_once dirname(__FILE__) . '/../../../www/config.php'; use nzedb\db\Settings; use nzedb\utility\Utility; $pdo = new Settings(); $covers = $updated = $deleted = 0; if ($argc == 1 || $argv[1] != 'true') { exit($pdo->log->error("\nThis script will check all images in covers/xxx and compare to db->xxxinfo.\nTo run:\nphp {$argv['0']} true\n")); } $row = $pdo->queryOneRow("SELECT value FROM settings WHERE setting = 'coverspath'"); if ($row !== false) { Utility::setCoversConstant($row['value']); } else { die("Unable to set Covers' constant!\n"); } $path2covers = nZEDb_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 $pdo->log->info($filePath . " not found in db."); }
/** * Export to user specified folder. * * @param array $params * * @return bool * * @access public */ public function beginExport($params) { $gzip = false; if ($params[4] === true) { $gzip = true; } $fromDate = $toDate = ''; $path = $params[0]; // Check if the path ends with dir separator. if (substr($path, -1) !== DS) { $path .= DS; } // Check if it's a directory. if (!is_dir($path)) { $this->echoOut('Folder does not exist: ' . $path); return $this->returnValue(); } // Check if we can write to it. if (!is_writable($path)) { $this->echoOut('Folder is not writable: ' . $path); return $this->returnValue(); } // Check if the from date is the proper format. if (isset($params[1]) && $params[1] !== '') { if (!$this->checkDate($params[1])) { return $this->returnValue(); } $fromDate = $params[1]; } // Check if the to date is the proper format. if (isset($params[2]) && $params[2] !== '') { if (!$this->checkDate($params[2])) { return $this->returnValue(); } $toDate = $params[2]; } // Check if the group_id exists. if (isset($params[3]) && $params[3] !== 0) { if (!is_numeric($params[3])) { $this->echoOut('The group ID is not a number: ' . $params[3]); return $this->returnValue(); } $groups = $this->pdo->query('SELECT id, name FROM groups WHERE id = ' . $params[3]); if (count($groups) === 0) { $this->echoOut('The group ID is not in the DB: ' . $params[3]); return $this->returnValue(); } } else { $groups = $this->pdo->query('SELECT id, name FROM groups'); } $exported = 0; // Loop over groups to take less RAM. foreach ($groups as $group) { $currentExport = 0; // Get all the releases based on the parameters. $releases = $this->releases->getForExport($fromDate, $toDate, $group['id']); $totalFound = count($releases); if ($totalFound === 0) { if ($this->echoCLI) { echo 'No releases found to export for group: ' . $group['name'] . PHP_EOL; } continue; } if ($this->echoCLI) { echo 'Found ' . $totalFound . ' releases to export for group: ' . $group['name'] . PHP_EOL; } // Create a path to store the new NZB files. $currentPath = $path . $this->safeFilename($group['name']) . DS; if (!is_dir($currentPath)) { mkdir($currentPath); } foreach ($releases as $release) { // Get path to the NZB file. $nzbFile = $this->nzb->NZBPath($release["guid"]); // Check if it exists. if ($nzbFile === false) { if ($this->echoCLI) { echo 'Unable to find NZB for release with GUID: ' . $release['guid']; } continue; } // Create path to current file. $currentFile = $currentPath . $this->safeFilename($release['searchname']); // Check if the user wants them in gzip, copy it if so. if ($gzip) { if (!copy($nzbFile, $currentFile . '.nzb.gz')) { if ($this->echoCLI) { echo 'Unable to export NZB with GUID: ' . $release['guid']; } continue; } // If not, decompress it and create a file to store it in. } else { $nzbContents = Utility::unzipGzipFile($nzbFile); if (!$nzbContents) { if ($this->echoCLI) { echo 'Unable to export NZB with GUID: ' . $release['guid']; } continue; } $fh = fopen($currentFile . '.nzb', 'w'); fwrite($fh, $nzbContents); fclose($fh); } $currentExport++; if ($this->echoCLI && $currentExport % 10 === 0) { echo 'Exported ' . $currentExport . ' of ' . $totalFound . ' nzbs for group: ' . $group['name'] . "\r"; } } if ($this->echoCLI && $currentExport > 0) { echo 'Exported ' . $currentExport . ' of ' . $totalFound . ' nzbs for group: ' . $group['name'] . PHP_EOL; } $exported += $currentExport; } if ($exported > 0) { $this->echoOut('Exported total of ' . $exported . ' NZB files to ' . $path); } return $this->returnValue(); }
/** * Gets Raw Html * * @param string $fetchURL * @param bool $usePost * * @return bool */ private function getUrl($fetchURL, $usePost = false) { if (isset($fetchURL)) { $this->_ch = curl_init($fetchURL); } if ($usePost === true) { curl_setopt($this->_ch, CURLOPT_POST, 1); curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $this->_postParams); } curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($this->_ch, CURLOPT_HEADER, 0); curl_setopt($this->_ch, CURLOPT_VERBOSE, 0); curl_setopt($this->_ch, CURLOPT_USERAGENT, "Firefox/2.0.0.1"); curl_setopt($this->_ch, CURLOPT_FAILONERROR, 1); if (isset($this->cookie)) { curl_setopt($this->_ch, CURLOPT_COOKIEJAR, $this->cookie); curl_setopt($this->_ch, CURLOPT_COOKIEFILE, $this->cookie); } curl_setopt_array($this->_ch, Utility::curlSslContextOptions()); $this->_response = curl_exec($this->_ch); if (!$this->_response) { curl_close($this->_ch); return false; } curl_close($this->_ch); $this->_html->load($this->_response); return true; }
/** * Get Raw html of webpage * * @param bool $usepost * * @return bool */ private function getUrl($usepost = false) { if (isset($this->_trailUrl)) { $ch = curl_init(self::POPURL . $this->_trailUrl); } else { $ch = curl_init(self::IF18); } if ($usepost === true) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postParams); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_USERAGENT, "Firefox/2.0.0.1"); curl_setopt($ch, CURLOPT_FAILONERROR, 1); if (isset($this->cookie)) { curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie); curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie); } curl_setopt_array($ch, Utility::curlSslContextOptions()); $this->_response = curl_exec($ch); if (!$this->_response) { curl_close($ch); return false; } curl_close($ch); $this->_html->load($this->_response); return true; }
function create_guids($live, $delete = false) { $pdo = new Settings(); $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 = array(); 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); $pdo->queryExec("UPDATE releases set nzb_guid = " . $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.")); } }
/** * 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'); // The nzb was not located. decrement the password status. $this->pdo->queryExec(sprintf('UPDATE releases SET passwordstatus = passwordstatus - 1 WHERE id = %d', $this->_release['id'])); return false; } $nzbContents = \nzedb\utility\Utility::unzipGzipFile($nzbPath); // Get a list of files in the nzb. $this->_nzbContents = $this->_nzb->nzbFileList($nzbContents); if (count($this->_nzbContents) === 0) { $this->_echo('NZB is empty or broken for GUID: ' . $this->_release['guid'], 'warning'); // There does not appear to be any files in the nzb, decrement password status. $this->pdo->queryExec(sprintf('UPDATE releases SET passwordstatus = passwordstatus - 1 WHERE id = %d', $this->_release['id'])); return false; } // Sort the files inside the NZB. usort($this->_nzbContents, ['\\nzedb\\processing\\post\\ProcessAdditional', '_sortNZB']); return true; }
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; break; case $fields['ffmpegpath'] != "" && !is_file($fields['ffmpegpath']): $error = Settings::ERR_BADFFMPEGPATH; break; case $fields['unrarpath'] != "" && !is_file($fields['unrarpath']): $error = Settings::ERR_BADUNRARPATH; break; case empty($fields['nzbpath']): $error = Settings::ERR_BADNZBPATH_UNSET; break; case !file_exists($fields['nzbpath']) || !is_dir($fields['nzbpath']): $error = Settings::ERR_BADNZBPATH; break; case !is_readable($fields['nzbpath']): $error = Settings::ERR_BADNZBPATH_UNREADABLE; break; case $fields['checkpasswordedrar'] == 1 && !is_file($fields['unrarpath']): $error = Settings::ERR_DEEPNOUNRAR; break; case $fields['tmpunrarpath'] != "" && !file_exists($fields['tmpunrarpath']): $error = Settings::ERR_BADTMPUNRARPATH; break; case $fields['yydecoderpath'] != "" && $fields['yydecoderpath'] !== 'simple_php_yenc_decode' && !file_exists($fields['yydecoderpath']): $error = Settings::ERR_BAD_YYDECODER_PATH; } return $error; }
private static function check_bin($binPath = null) { if (!empty(self::$bin)) { return; } if (empty($binPath)) { $binPath = '/usr/bin/git'; if (\nzedb\utility\Utility::hasWhich()) { exec('which git', $output, $error); if (!$error) { $binPath = $output[0]; } } } self::set_bin($binPath); }
/** * @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; } } $start = date('Y-m-d H:i:s'); $nzbsImported = $nzbsSkipped = 0; // Loop over the file names. foreach ($filesToProcess as $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 ($nzbString === false) { $this->echoOut('ERROR: Unable to read: ' . $nzbFile); 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); 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); if ($inserted) { // Try to copy the NZB to the NZB folder. $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); if (!is_file($path)) { $this->echoOut('ERROR: Problem compressing NZB file to: ' . $path); // Remove the release. $this->pdo->queryExec(sprintf("DELETE FROM releases WHERE guid = %s", $this->pdo->escapeString($this->relGuid))); if ($deleteFailed) { @unlink($nzbFile); } $nzbsSkipped++; continue; } else { if ($delete) { // Remove the nzb file. @unlink($nzbFile); } $nzbsImported++; continue; } } else { 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; } }
public function getRageMatch($showInfo) { $title = $showInfo['cleanname']; // Full search gives us the akas. $xml = Utility::getUrl(['url' => $this->xmlFullSearchUrl . urlencode(strtolower($title))]); if ($xml !== false) { $arrXml = @Utility::objectsIntoArray(simplexml_load_string($xml)); if (isset($arrXml['show']) && is_array($arrXml)) { // We got a valid xml response $titleMatches = $urlMatches = $akaMatches = []; if (isset($arrXml['show']['showid'])) { // We got exactly 1 match so lets convert it to an array so we can use it in the logic below. $newArr = []; $newArr[] = $arrXml['show']; unset($arrXml); $arrXml['show'] = $newArr; } foreach ($arrXml['show'] as $arr) { $tvrlink = ''; // Get a match percentage based on our name and the name returned from tvr. $titlepct = $this->checkMatch($title, $arr['name']); if ($titlepct !== false) { $titleMatches[$titlepct][] = ['title' => $arr['name'], 'showid' => $arr['showid'], 'country' => $this->countryCode($arr['country']), 'genres' => $arr['genres'], 'tvr' => $arr]; } // Get a match percentage based on our name and the url returned from tvr. if (isset($arr['link']) && preg_match('/tvrage\\.com\\/((?!shows)[^\\/]*)$/i', $arr['link'], $tvrlink)) { $urltitle = str_replace('_', ' ', $tvrlink[1]); $urlpct = $this->checkMatch($title, $urltitle); if ($urlpct !== false) { $urlMatches[$urlpct][] = ['title' => $urltitle, 'showid' => $arr['showid'], 'country' => $this->countryCode($arr['country']), 'genres' => $arr['genres'], 'tvr' => $arr]; } } // Check if there are any akas for this result and get a match percentage for them too. if (isset($arr['akas']['aka'])) { if (is_array($arr['akas']['aka'])) { // Multuple akas. foreach ($arr['akas']['aka'] as $aka) { $akapct = $this->checkMatch($title, $aka); if ($akapct !== false) { $akaMatches[$akapct][] = ['title' => $aka, 'showid' => $arr['showid'], 'country' => $this->countryCode($arr['country']), 'genres' => $arr['genres'], 'tvr' => $arr]; } } } else { // One aka. $akapct = $this->checkMatch($title, $arr['akas']['aka']); if ($akapct !== false) { $akaMatches[$akapct][] = ['title' => $arr['akas']['aka'], 'showid' => $arr['showid'], 'country' => $this->countryCode($arr['country']), 'genres' => $arr['genres'], 'tvr' => $arr]; } } } } // Reverse sort our matches so highest matches are first. krsort($titleMatches); krsort($urlMatches); krsort($akaMatches); // Look for 100% title matches first. if (isset($titleMatches[100])) { if ($this->echooutput) { echo $this->pdo->log->primary('Found 100% match: "' . $titleMatches[100][0]['title'] . '"'); } return $titleMatches[100][0]; } // Look for 100% url matches next. if (isset($urlMatches[100])) { if ($this->echooutput) { echo $this->pdo->log->primary('Found 100% url match: "' . $urlMatches[100][0]['title'] . '"'); } return $urlMatches[100][0]; } // Look for 100% aka matches next. if (isset($akaMatches[100])) { if ($this->echooutput) { echo $this->pdo->log->primary('Found 100% aka match: "' . $akaMatches[100][0]['title'] . '"'); } return $akaMatches[100][0]; } // No 100% matches, loop through what we got and if our next closest match is more than TvRage::MATCH_PROBABILITY % of the title lets take it. foreach ($titleMatches as $mk => $mv) { // Since its not 100 match if we have country info lets use that to make sure we get the right show. if (isset($showInfo['country']) && !empty($showInfo['country']) && !empty($mv[0]['country'])) { if (strtolower($showInfo['country']) != strtolower($mv[0]['country'])) { continue; } } if ($this->echooutput) { echo $this->pdo->log->primary('Found ' . $mk . '% match: "' . $titleMatches[$mk][0]['title'] . '"'); } return $titleMatches[$mk][0]; } // Same as above but for akas. foreach ($akaMatches as $ak => $av) { if (isset($showInfo['country']) && !empty($showInfo['country']) && !empty($av[0]['country'])) { if (strtolower($showInfo['country']) != strtolower($av[0]['country'])) { continue; } } if ($this->echooutput) { echo $this->pdo->log->primary('Found ' . $ak . '% aka match: "' . $akaMatches[$ak][0]['title'] . '"'); } return $akaMatches[$ak][0]; } if ($this->echooutput) { echo $this->pdo->log->primary('No match found on TVRage trying Trakt.'); } return false; } else { if ($this->echooutput) { echo $this->pdo->log->primary('Nothing returned from tvrage.'); } return false; } } else { return -1; } }
use nzedb\utility\Utility; if (!$page->users->isLoggedIn()) { $page->show403(); } if (isset($_GET["id"])) { $releases = new Releases(['Settings' => $page->settings]); $rel = $releases->getByGuid($_GET["id"]); if (!$rel) { $page->show404(); } $nzb = new NZB($page->settings); $nzbpath = $nzb->getNZBPath($_GET["id"]); if (!file_exists($nzbpath)) { $page->show404(); } $nzbfile = Utility::unzipGzipFile($nzbpath); $ret = $nzb->nzbFileList($nzbfile); $offset = isset($_REQUEST["offset"]) && ctype_digit($_REQUEST['offset']) ? $_REQUEST["offset"] : 0; $page->smarty->assign('pagertotalitems', sizeof($ret)); $page->smarty->assign('pageroffset', $offset); $page->smarty->assign('pageritemsperpage', ITEMS_PER_PAGE); $page->smarty->assign('pagerquerybase', WWW_TOP . "/filelist/" . $_GET["id"] . "/&offset="); $page->smarty->assign('pagerquerysuffix', "#results"); $pager = $page->smarty->fetch("pager.tpl"); $page->smarty->assign('pager', $pager); $page->smarty->assign('rel', $rel); $page->smarty->assign('files', array_slice($ret, $offset, ITEMS_PER_PAGE)); $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";
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * 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: * * @link <http://www.gnu.org/licenses/>. * @author niel * @copyright 2015 nZEDb */ require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'config.php'; use nzedb\db\DbUpdate; use nzedb\utility\Git; use nzedb\utility\Utility; if (!Utility::isCLI()) { exit; } $error = false; $git = new Git(); $branch = $git->active_branch(); if (in_array($branch, $git->mainBranches())) { // 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!\n"; echo $e->getMessage() . "\n";
$runVar['commands']['_phpn'] = "nice -n{$tmux_niceness} {$PHP}"; $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 $tRun->runPane('scraper', $runVar); //get list of panes by name $runVar['panes'] = $tRun->getListOfPanes($runVar['constants']); //totals per category in db, results by parentID $catcntqry = "SELECT c.parentid AS parentid, COUNT(r.id) AS count FROM category c, releases r WHERE r.categoryid = c.id GROUP BY c.parentid"; //create timers and set to now $runVar['timers']['timer1'] = $runVar['timers']['timer2'] = $runVar['timers']['timer3'] = $runVar['timers']['timer4'] = $runVar['timers']['timer5'] = time(); $runVar['timers']['query']['tmux_time'] = $runVar['timers']['query']['split_time'] = $runVar['timers']['query']['init_time'] = $runVar['timers']['query']['proc1_time'] = $runVar['timers']['query']['proc2_time'] = $runVar['timers']['query']['proc3_time'] = $runVar['timers']['query']['split1_time'] = $runVar['timers']['query']['init1_time'] = $runVar['timers']['query']['proc11_time'] = $runVar['timers']['query']['proc21_time'] = $runVar['timers']['query']['proc31_time'] = $runVar['timers']['query']['tpg_time'] = $runVar['timers']['query']['tpg1_time'] = 0; // Analyze tables printf($pdo->log->info("\nAnalyzing your tables to refresh your indexes.")); $pdo->optimise(false, 'analyze', false, ['releases']); Utility::clearScreen(); $runVar['settings']['monitor'] = 0; $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); $psTableRowCount = $pdo->Prepare($tblCount); while ($runVar['counts']['iterations'] > 0) { //check the db connection if ($pdo->ping(true) == false) { unset($pdo); $pdo = new Settings(); } $timer01 = time(); // These queries are very fast, run every loop -- tmux and site settings $runVar['settings'] = $pdo->queryOneRow($tRun->getMonitorSettings(), false);
/** * @param string $pathname full path to file for saving. Will be overwritten. * * @return bool|int */ protected function saveSourceFile($pathname) { $result = false; $file = Utility::getUrl(['url' => $this->sourceURL]); if ($file !== false) { $result = file_put_contents($pathname, $file); } return $result; }
use nzedb\utility\Utility; $pdo = new Settings(); if (isset($argv[1]) && ($argv[1] === "true" || $argv[1] === "delete")) { $releases = new Releases(['Settings' => $pdo]); $nzb = new NZB($pdo); $releaseImage = new ReleaseImage($pdo); $consoletools = new ConsoleTools(['ColorCLI' => $pdo->log]); $timestart = time(); $checked = $deleted = 0; $couldbe = $argv[1] === "true" ? $couldbe = "could be " : "were "; echo $pdo->log->header('Getting List of nzbs to check against db.'); $dirItr = new \RecursiveDirectoryIterator($pdo->getSetting('nzbpath')); $itr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::LEAVES_ONLY); foreach ($itr as $filePath) { if (is_file($filePath) && preg_match('/([a-f-0-9]+)\\.nzb\\.gz/', $filePath, $guid)) { $nzbfile = Utility::unzipGzipFile($filePath); if ($nzbfile) { $nzbfile = @simplexml_load_string($nzbfile); } if ($nzbfile) { $res = $pdo->queryOneRow(sprintf("SELECT id, guid FROM releases WHERE guid = %s", $pdo->escapeString(stristr($filePath->getFilename(), '.nzb.gz', true)))); if ($res === false) { if ($argv[1] === "delete") { @copy($filePath, nZEDb_ROOT . "pooped/" . $guid[1] . ".nzb.gz"); $releases->deleteSingle(['g' => $guid[1], 'i' => false], $nzb, $releaseImage); $deleted++; } } else { if (isset($res)) { $pdo->queryExec(sprintf("UPDATE releases SET nzbstatus = 1 WHERE id = %s", $res['id'])); }
} else { $genre = $tvrShow['genres']['genre']; } } $country = ''; if (isset($tvrShow['country']) && !empty($tvrShow['country'])) { $country = $tvrage->countryCode($tvrShow['country']); } $rInfo = $tvrage->getRageInfoFromPage($rageid); $desc = ''; if (isset($rInfo['desc']) && !empty($rInfo['desc'])) { $desc = $rInfo['desc']; } $imgbytes = ''; if (isset($rInfo['imgurl']) && !empty($rInfo['imgurl'])) { $img = Utility::getUrl(['url' => $rInfo['imgurl']]); if ($img !== false) { $im = @imagecreatefromstring($img); if ($im !== false) { $imgbytes = $img; } } } $pdo->queryDirect(sprintf("UPDATE tvrage_titles SET description = %s, genre = %s, country = %s, imgdata = %s WHERE rageid = %d", $pdo->escapeString(substr($desc, 0, 10000)), $pdo->escapeString(substr($genre, 0, 64)), $pdo->escapeString($country), $pdo->escapeString($imgbytes), $rageid)); $name = $pdo->query("Select releasetitle from tvrage_titles where rageid = " . $rageid); echo $pdo->log->primary("Updated: " . $name[0]['releasetitle']); $diff = floor((microtime(true) - $starttime) * 1000000); if (1000000 - $diff > 0) { echo $pdo->log->alternate("Sleeping"); usleep(1000000 - $diff); }
/** * 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.' . 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 $nzbFile; }
/** * 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 . $this->pdo->getSetting('mediainfopath') . '" --Output=XML "' . $fileLocation . '"'); // Check if we got it. if (is_array($xmlArray)) { // Convert it to string. $xmlArray = implode("\n", $xmlArray); 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); if ($this->_echoCLI) { $this->_echo('m', 'primaryOver', false); } return true; } } return false; }
/** * @param $guids * * @return string */ public function getZipped($guids) { $nzb = new NZB($this->pdo); $zipFile = new \ZipFile(); foreach ($guids as $guid) { $nzbPath = $nzb->NZBPath($guid); 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(); }
protected function _backupDb() { if (Utility::hasCommand("php5")) { $PHP = "php5"; } else { $PHP = "php"; } system("{$PHP} " . nZEDb_MISC . 'testing' . DS . 'DB' . DS . $this->_DbSystem . 'dump_tables.php db dump'); $this->backedup = true; }
/** * Resume all NZB's in the SAB queue. * * @return bool|mixed */ public function resumeAll() { return Utility::getUrl(['url' => $this->url . "api?mode=resume" . "&apikey=" . $this->apikey, 'verifycert' => 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) { $img = Utility::getUrl(['url' => $imgLoc]); } else { if (is_file($imgLoc)) { $img = @file_get_contents($imgLoc); } } if ($img !== false) { $im = @imagecreatefromstring($img); if ($im !== false) { imagedestroy($im); return $img; } } return false; }
<?php require_once dirname(__FILE__) . '/../../../www/config.php'; use nzedb\db\Settings; $pdo = new Settings(); $covers = $updated = $deleted = 0; if ($argc == 1 || $argv[1] != 'true') { exit($pdo->log->error("\nThis script will check all images in covers/xxx and compare to db->xxxinfo.\nTo run:\nphp {$argv['0']} true\n")); } $row = $pdo->queryOneRow("SELECT value FROM settings WHERE setting = 'coverspath'"); if ($row !== false) { \nzedb\utility\Utility::setCoversConstant($row['value']); } else { die("Unable to set Covers' constant!\n"); } $path2covers = nZEDb_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 $pdo->log->info($filePath . " not found in db."); } }
/** * Request for current status (summary) information. Parts of informations returned by this method can be printed by command "nzbget -L". * * @return array The status. * * @access public */ public function status() { $data = Utility::getUrl(['url' => $this->fullURL . 'status', 'verifycert' => false]); $retVal = false; if ($data) { $xml = simplexml_load_string($data); if ($xml) { foreach ($xml->params->param->value->struct->member as $member) { $value = (array) $member->value; $value = array_shift($value); if (!is_object($value)) { $retVal[(string) $member->name] = $value; } } } } return $retVal; }