Пример #1
0
 /**
  * @param newznab\db\Settings $pdo
  */
 public function __construct(Settings $pdo = null)
 {
     parent::__construct($pdo);
     $this->_git = new \newznab\utility\Git();
     // Do not remove the full namespace/ PHP gets confused for some reason without it.
     $this->_vers = Utility::getValidVersionsFile();
     $this->_setColourMasks();
 }
Пример #2
0
 /**
  * Runs a Sphinx command.  This suppresses various lines of output from the
  * Sphinx binaries.
  *
  * @param   string  $cmd    The command to run.
  * @param   boolean $stdout If ``true`` (default), print to stdout.
  * @return  array   An array of lines returned from the popen process.
  */
 public function runCmd($cmd, $stdout = true)
 {
     $output = [];
     $handle = popen($cmd, "r");
     while ($line = fgets($handle)) {
         if (\newznab\utility\Utility::startsWith($line, "Sphinx") || \newznab\utility\Utility::startsWith($line, "Copyright") || \newznab\utility\Utility::startsWith($line, "\n") || startsWith($line, "using config")) {
             continue;
         }
         $output[] = $line;
         if ($stdout) {
             printf("%s", $line);
         }
     }
     return $output;
 }
Пример #3
0
function BackupDatabase()
{
    $db = new DB();
    $c = new ColorCLI();
    $DIR = dirname(__FILE__);
    if (Utility::hasCommand("php5")) {
        $PHP = "php5";
    } else {
        $PHP = "php";
    }
    //Backup based on database system
    if ($db->dbSystem() == "mysql") {
        system("{$PHP} {$DIR}mysqldump_tables.php db dump ../../");
    } else {
        if ($db->dbSystem() == "pgsql") {
            exit($c->error("Currently not supported on this platform."));
        }
    }
}
Пример #4
0
 /**
  * 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) {
         $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;
 }
Пример #5
0
 /**
  * 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;
 }
Пример #6
0
 /**
  * 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;
 }
Пример #7
0
 /**
  * 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->getNZBPath($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;
 }
Пример #8
0
 /**
  * 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 (empty($query)) {
         return false;
     }
     if (NN_QUERY_STRIP_WHITESPACE) {
         $query = Utility::collapseWhiteSpace($query);
     }
     try {
         $result = $this->pdo->query($query);
     } catch (\PDOException $e) {
         // Check if we lost connection to MySQL.
         if ($this->_checkGoneAway($e->getMessage()) !== false) {
             // Reconnect to MySQL.
             if ($this->_reconnect() === true) {
                 // If we reconnected, retry the 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(get_class(), __FUNCTION__, $query, \Logger::LOG_SQL);
                 }
             }
             $result = false;
         }
     }
     return $result;
 }
Пример #9
0
 /**
  * Try to find a IMDB id on yahoo.com
  *
  * @return bool
  */
 protected function yahooSearch()
 {
     $buffer = Utility::getUrl(['url' => "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=intitle:" . urlencode('intitle:' . implode(' intitle:', explode(' ', preg_replace('/\\s+/', ' ', preg_replace('/\\W/', ' ', $this->currentTitle)))) . ' intitle:' . $this->currentYear) . '&vs=' . urlencode('www.imdb.com/title/')]);
     if ($buffer !== false) {
         $this->yahooLimit++;
         if ($this->doMovieUpdate($buffer, 'Yahoo.com', $this->currentRelID) !== false) {
             return true;
         }
     }
     return false;
 }
Пример #10
0
 /**
  * @param $url
  * @param $nnid
  * @param $groupname
  * @param $reqid
  *
  * @return string
  */
 public function getReleaseNameForReqId($url, $nnid, $groupname, $reqid)
 {
     if ($reqid == " null " || $reqid == "0" || $reqid == "") {
         return "";
     }
     $url = str_ireplace("[GROUP]", urlencode($groupname), $url);
     $url = str_ireplace("[REQID]", urlencode($reqid), $url);
     if ($nnid != "") {
         $url = $url . "&newznabID=" . $nnid;
     }
     $xml = Utility::getUrl([$url]);
     if ($xml === false || preg_match('/no feed/i', $xml)) {
         return "no feed";
     } else {
         if ($xml != "") {
             $xmlObj = @simplexml_load_string($xml);
             $arrXml = objectsIntoArray($xmlObj);
             if (isset($arrXml["item"]) && is_array($arrXml["item"])) {
                 foreach ($arrXml["item"] as $item) {
                     $title = array_key_exists("@attributes", $item) ? $item["@attributes"]["title"] : $item["title"];
                     return $title;
                 }
             }
         }
     }
     return "";
 }
Пример #11
0
 /**
  * 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 bool|mixed
  */
 private function getJsonArray($URI, $extended = 'min')
 {
     if (!empty($this->clientID)) {
         $json = Utility::getUrl(['url' => $URI . "?extended={$extended}", 'requestheaders' => $this->requestHeaders]);
         if ($json !== false) {
             $json = json_decode($json, true);
             if (!is_array($json) || isset($json['status']) && $json['status'] === 'failure') {
                 return false;
             }
             return $json;
         }
     }
     return false;
 }
Пример #12
0
 /**
  * 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(phpversion(), "5.2") !== false) {
         $command = "\"" . $command . "\"";
     }
     if ($debug) {
         echo '-Running Command: ' . $nl . '   ' . $command . $nl;
     }
     $output = [];
     $status = 1;
     @exec($command, $output, $status);
     if ($debug) {
         echo '-Command Output: ' . $nl . '   ' . implode($nl . '  ', $output) . $nl;
     }
     return $output;
 }
Пример #13
0
 /**
  * Make a request to RT.
  *
  * @param string  $function The type of request.
  * @param array   $params   Extra HTTP parameters.
  *
  * @return string JSON data from RT.
  */
 private function _makeCall($function, $params = [])
 {
     return trim(Utility::getUrl(['url' => RottenTomato::API_URL . $function . '?limit=' . mt_rand(15, 20) . '&apikey=' . $this->_apikey . (!empty($params) ? '&' . http_build_query($params) : '')]));
 }
Пример #14
0
     } 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 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 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);
 }
Пример #15
0
 /**
  * Has to be performed after mediainfo, as lame strips id3 tags.
  */
 public function lameAudioSample($lameinfo, $releaseguid)
 {
     $returnval = false;
     $minacceptableencodefilesize = 10000;
     $samplefile = $this->mp3SavePath . $releaseguid . '.mp3';
     $samplefileogg = $this->mp3SavePath . $releaseguid . '.ogg';
     $ffmpeginfo = $this->pdo->getSetting('ffmpegpath');
     if (file_exists($samplefile)) {
         $outfile = $this->mp3SavePath . $releaseguid . '_l.mp3';
         $outfileogg = $this->mp3SavePath . $releaseguid . '_l.ogg';
         //
         // lame the sample down to 96kb and replace it. alternatives could be
         // V8 for low quality variable.
         //
         $execstring = '"' . $lameinfo . '" -b 96 "' . $samplefile . '" "' . $outfile . '"';
         $execstringogg = '"' . $ffmpeginfo . '" -i "' . $samplefile . '" -acodec libvorbis "' . $outfileogg . '"';
         $output = Utility::runCmd($execstring, false, true);
         $output = Utility::runCmd($execstringogg, false, true);
         //
         // lame can create bad/small files if the source was corrupt
         // if it creates a file thats surprisingly small, then ignore it and retain
         // original
         //
         if (file_exists($outfile)) {
             if (filesize($outfile) < $minacceptableencodefilesize) {
                 unlink($outfile);
             } else {
                 unlink($samplefile);
                 rename($outfile, $samplefile);
                 $returnval = true;
             }
         }
         if (file_exists($outfileogg)) {
             if (filesize($outfileogg) < $minacceptableencodefilesize) {
                 unlink($outfileogg);
             } else {
                 rename($outfileogg, $samplefileogg);
                 $returnval = true;
             }
         }
     }
     return $returnval;
 }
Пример #16
0
 protected function _backupDb()
 {
     if (Utility::hasCommand("php5")) {
         $PHP = "php5";
     } else {
         $PHP = "php";
     }
     system("{$PHP} " . NN_MISC . 'testing' . DS . 'DB' . DS . $this->_DbSystem . 'dump_tables.php db dump');
     $this->backedup = true;
 }
Пример #17
0
 /**
  * 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->getNZBPath($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();
 }
Пример #18
0
 /**
  * Get Raw html of webpage
  *
  * @param bool $usepost
  *
  * @return bool
  */
 private function getUrl($usepost = false)
 {
     if (isset($this->_trailUrl)) {
         $ch = curl_init(self::ADMURL . $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;
 }
Пример #19
0
$pdo = new Settings();
$DIR = NN_TMUX;
$c = new ColorCLI();
$t = new Tmux();
$tmux = $t->get();
$import = isset($tmux->import) ? $tmux->import : 0;
$tmux_session = isset($tmux->tmux_session) ? $tmux->tmux_session : 0;
$seq = isset($tmux->sequential) ? $tmux->sequential : 0;
$powerline = isset($tmux->powerline) ? $tmux->powerline : 0;
$colors = isset($tmux->colors) ? $tmux->colors : 0;
$nntpproxy = $pdo->getSetting('nntpproxy');
$tablepergroup = $pdo->getSetting('tablepergroup');
$tablepergroup = $tablepergroup != '' ? $tablepergroup : 0;
// Check that Db patch level is current. Also checks nZEDb.xml is valid.
Utility::isPatched();
Utility::clearScreen();
echo "Starting Tmux...\n";
// Create a placeholder session so tmux commands do not throw server not found errors.
exec('tmux new-session -ds placeholder 2>/dev/null');
// Search for NNTPProxy session that might be running from a user threaded.php run. Setup a clean environment to run in.
exec("tmux list-session | grep NNTPProxy", $nntpkill);
if (count($nntpkill) !== 0) {
    exec("tmux kill-session -t NNTPProxy");
    echo $pdo->log->notice("Found NNTPProxy tmux session and killing it.");
} else {
    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');
Пример #20
0
if (!Utility::endsWith($pdo->getSetting('sabvdir'), "/")) {
    $pdo->getSetting('sabvdir');
}
$basepath = $pdo->getSetting('sabcompletedir');
$webpath = $pdo->getSetting('sabvdir');
$subpath = "";
if (isset($_REQUEST["sp"])) {
    $subpath = urldecode($_REQUEST["sp"]);
}
$listmode = true;
if (isset($_REQUEST["lm"])) {
    $listmode = $_REQUEST["lm"] == "1";
}
$path = $basepath . $subpath;
$webpath .= $subpath;
if (!Utility::startsWith(realpath($path), realpath($basepath))) {
    $page->show403();
}
$files = glob(preg_replace('/(\\*|\\?|\\[)/', '[$1]', $path) . "/*");
$items = array();
$dirs = array();
foreach ($files as $f) {
    $i = array();
    $i["name"] = basename($f);
    $i["isdir"] = is_dir($f) ? 1 : 0;
    $i["fullname"] = $f;
    $i["webpath"] = $webpath . "/" . $i["name"] . ($i["isdir"] == 1 ? "/" : "");
    $i["mtime"] = filemtime($f);
    $i["pathinfo"] = pathinfo($f);
    if ($i["isdir"] == 1) {
        $i["pathinfo"]["extension"] = "";
Пример #21
0
 /**
  * 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.
  *
  * @access public
  */
 public function isNFO(&$possibleNFO, $guid)
 {
     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);
         // 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;
                 // Or binary.
             } else {
                 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..
         $getid3 = new getid3();
         $check = $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;
 }
Пример #22
0
 /**
  * Gets raw html content using adeurl and any trailing url.
  *
  * @param string $trailing - required
  *
  * @return bool - true if page has content
  */
 private function getUrl($trailing = "")
 {
     if (!empty($trailing)) {
         $this->_ch = curl_init(self::ADE . $trailing);
     }
     if (!empty($this->directLink)) {
         $this->_ch = curl_init($this->directLink);
         $this->directLink = "";
     }
     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);
     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);
     return true;
 }
Пример #23
0
 /**
  * @param $seriesid
  * @param $seriesName
  *
  * @return array|bool
  */
 public function TheTVDBAPI($seriesid, $seriesName)
 {
     $apiresponse = Utility::getUrl([$this->MIRROR . '/api/' . self::APIKEY . '/series/' . $seriesid . '/all/en.xml']);
     //.zip?
     if (!$apiresponse) {
         return false;
     }
     $TheTVDBAPIXML = @simplexml_load_string($apiresponse);
     if (!$TheTVDBAPIXML) {
         return false;
     }
     foreach ($TheTVDBAPIXML->Episode as $episode) {
         $episodetvdbIDArray[] = (int) $episode->id;
         $episodenumberArray[] = (int) $episode->Combined_episodenumber;
         $episodeseasonArray[] = (int) $episode->Combined_season;
         $episodedirectorArray[] = preg_replace('/^\\||\\|$/', '', (string) $episode->Director);
         $episodenameArray[] = preg_replace('/^\\||\\|$/', '', (string) $episode->EpisodeName);
         $episodefirstairedArray[] = (string) $episode->FirstAired;
         $episodegueststarsArray[] = preg_replace('/^\\||\\|$/', '', (string) $episode->GuestStars);
         $episodeimdbID[] = str_replace('tt', '', (string) $episode->IMDB_ID);
         $episodeoverviewArray[] = preg_replace('/^\\||\\|$/', '', (string) $episode->Overview);
         $episoderatingArray[] = preg_replace('/^\\||\\|$/', '', (string) $episode->Rating);
         $episodewriterArray[] = preg_replace('/^\\||\\|$/', '', (string) $episode->Writer);
         $episodeabsolutenumberArray[] = (int) $episode->absolute_number;
     }
     $TheTVDBAPIArray = array('tvdbid' => $seriesid, 'actors' => preg_replace('/^\\||\\|$/', '', (string) $TheTVDBAPIXML->Series->Actors), 'airsday' => preg_replace('/^\\||\\|$/', '', (string) $TheTVDBAPIXML->Series->Airs_DayOfWeek), 'airstime' => preg_replace('/^\\||\\|$/', '', (string) $TheTVDBAPIXML->Series->Airs_Time), 'contentrating' => (string) $TheTVDBAPIXML->Series->ContentRating, 'firstaired' => (string) $TheTVDBAPIXML->Series->FirstAired, 'genre' => preg_replace('/^\\||\\|$/', '', (string) $TheTVDBAPIXML->Series->Genre), 'imdbid' => (int) preg_replace('/^[^\\d]+/', '', (string) $TheTVDBAPIXML->Series->IMDB_ID), 'network' => (string) $TheTVDBAPIXML->Series->Network, 'overview' => (string) $TheTVDBAPIXML->Series->Overview, 'rating' => (double) $TheTVDBAPIXML->Series->Rating, 'ratingcount' => (int) $TheTVDBAPIXML->Series->RatingCount, 'runtime' => (int) $TheTVDBAPIXML->Series->Runtime, 'seriesname' => $seriesName, 'status' => (string) $TheTVDBAPIXML->Series->Status, 'episodetvdbID' => isset($episodetvdbIDArray) ? $episodetvdbIDArray : [], 'episodenumber' => isset($episodenumberArray) ? $episodenumberArray : [], 'episodeseason' => isset($episodeseasonArray) ? $episodeseasonArray : [], 'episodedirector' => isset($episodedirectorArray) ? $episodedirectorArray : [], 'episodename' => isset($episodenameArray) ? $episodenameArray : [], 'episodefirstaired' => isset($episodefirstairedArray) ? $episodefirstairedArray : [], 'episodegueststars' => isset($episodegueststarsArray) ? $episodegueststarsArray : [], 'episodeimdbID' => isset($episodeimdbID) ? $episodeimdbID : [], 'episodeoverview' => isset($episodeoverviewArray) ? $episodeoverviewArray : [], 'episoderating' => isset($episoderatingArray) ? $episoderatingArray : [], 'episodewriter' => isset($episodewriterArray) ? $episodewriterArray : [], 'episodeabsolutenumber' => isset($episodeabsolutenumberArray) ? $episodeabsolutenumberArray : []);
     return $TheTVDBAPIArray;
 }
Пример #24
0
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->getNZBPath($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);
                            $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."));
    }
}
Пример #25
0
 }
 $episodeArray = '';
 if ($data['episodeinfoid'] > 0) {
     $episode = new Episode();
     $episodeArray = $episode->getEpisodeInfoByID($data['episodeinfoid']);
 }
 $mov = '';
 if ($data['imdbid'] != '' && $data['imdbid'] != 00) {
     $movie = new Film();
     $mov = $movie->getMovieInfo($data['imdbid']);
     $trakt = new TraktTv();
     $traktSummary = $trakt->movieSummary('tt' . $data['imdbid'], 'full');
     if ($traktSummary !== false && isset($traktSummary['trailer']) && $traktSummary['trailer'] !== '' && preg_match('/[\\/?]v[\\/\\=](\\w+)$/i', $traktSummary['trailer'], $youtubeM)) {
         $mov['trailer'] = '<embed width="480" height="345" src="' . 'https://www.youtube.com/v/' . $youtubeM[1] . '" type="application/x-shockwave-flash"></embed>';
     } else {
         $mov['trailer'] = \newznab\utility\Utility::imdb_trailers($data['imdbid']);
     }
     if ($mov && isset($mov['title'])) {
         $mov['title'] = str_replace(array('/', '\\'), '', $mov['title']);
         $mov['actors'] = $movie->makeFieldLinks($mov, 'actors');
         $mov['genre'] = $movie->makeFieldLinks($mov, 'genre');
         $mov['director'] = $movie->makeFieldLinks($mov, 'director');
     } else {
         if ($traktSummary !== false) {
             $mov['title'] = str_replace(array('/', '\\'), '', $traktSummary['title']);
         } else {
             $mov = false;
         }
     }
 }
 $xxx = '';
Пример #26
0
<?php

use newznab\utility\Utility;
$releases = new Releases();
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();
    }
Пример #27
0
 /**
  * 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 = \newznab\utility\Utility::isWindows() ? '' : ' > /dev/null 2>&1';
             $this->_yEncTempInput = NN_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);
             }
         }
     }
 }
Пример #28
0
 /**
  * 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;
 }
 // different between individual databases
 $pdo->queryExec('ALTER TABLE tmp_pre ADD COLUMN groupname VARCHAR (255)');
 // Drop indexes on tmp_pre
 $pdo->queryExec('ALTER TABLE tmp_pre DROP INDEX `ix_prehash_nfo`, DROP INDEX `ix_prehash_predate`, DROP INDEX `ix_prehash_source`, DROP INDEX `ix_prehash_title`, DROP INDEX `ix_prehash_requestid`');
 foreach ($all_matches as $matches) {
     if (preg_match('#^(.+)/(\\d+)_#', $matches, $match)) {
         $timematch = -1 + $progress['last'];
         // Skip patches the user does not want.
         if ($match[2] < $timematch) {
             echo 'Skipping dump ' . $match[2] . ', as your minimum unix time argument is ' . $timematch . PHP_EOL;
             --$total;
             continue;
         }
         // Download the dump.
         $file['url'] = $baseUrl . '/' . $match[1] . '/' . $match[2] . $fileName . '?dl=1';
         $dump = Utility::getUrl($file);
         if (!$dump) {
             echo 'Error downloading dump ' . $match[2] . ' you can try manually importing it.' . PHP_EOL;
             continue;
         }
         // Make sure we didn't get a HTML page.
         if (strlen($dump) < 5000 && strpos($dump, '<!DOCTYPE html>') !== false) {
             echo 'The dump file ' . $match[2] . ' might be missing from dropbox.' . PHP_EOL;
             continue;
         }
         // Decompress.
         $dump = gzdecode($dump);
         if (!$dump) {
             echo 'Error decompressing dump ' . $match[2] . '.' . PHP_EOL;
             continue;
         }
Пример #30
0
 /**
  * @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);
         }
     }
     return $data;
 }