예제 #1
1
 /**
  * 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 = Misc::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;
 }
예제 #2
1
파일: Nfo.php 프로젝트: egandt/nZEDb
 /**
  * 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);
         $result = Misc::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..
         $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;
 }
예제 #3
1
 /**
  * @param        $region
  * @param        $params
  * @param        $public_key
  * @param        $private_key
  * @param string $associate_tag
  *
  * @return bool|SimpleXMLElement|string
  */
 private function aws_signed_request($region, $params, $public_key, $private_key, $associate_tag = "")
 {
     if ($public_key !== "" && $private_key !== "" && $associate_tag !== "") {
         $method = "GET";
         // Must be in small case.
         $host = "ecs.amazonaws." . $region;
         $uri = "/onca/xml";
         $params["Service"] = "AWSECommerceService";
         $params["AWSAccessKeyId"] = $public_key;
         $params["AssociateTag"] = $associate_tag;
         $params["Timestamp"] = gmdate("Y-m-d\\TH:i:s\\Z");
         $params["Version"] = "2009-03-31";
         /* The params need to be sorted by the key, as Amazon does this at
         			their end and then generates the hash of the same. If the params
         			are not in order then the generated hash will be different thus
         			failing the authetication process.
         			*/
         ksort($params);
         $canonicalized_query = array();
         foreach ($params as $param => $value) {
             $param = str_replace("%7E", "~", rawurlencode($param));
             $value = str_replace("%7E", "~", rawurlencode($value));
             $canonicalized_query[] = $param . "=" . $value;
         }
         $canonicalized_query = implode("&", $canonicalized_query);
         $string_to_sign = $method . "\n" . $host . "\n" . $uri . "\n" . $canonicalized_query;
         /* Calculate the signature using HMAC with SHA256 and base64-encoding.
          * The 'hash_hmac' function is only available from PHP 5 >= 5.1.2.
          */
         $signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
         // Encode the signature for the request.
         $signature = str_replace("%7E", "~", rawurlencode($signature));
         // Create request.
         $request = "http://" . $host . $uri . "?" . $canonicalized_query . "&Signature=" . $signature;
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $request);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_TIMEOUT, 30);
         curl_setopt_array($ch, Misc::curlSslContextOptions());
         $xml_response = curl_exec($ch);
         if ($xml_response === False) {
             return False;
         } else {
             // Parse XML.
             $parsed_xml = @simplexml_load_string($xml_response);
             return $parsed_xml === False ? False : $parsed_xml;
         }
     } else {
         return "missingkey";
     }
 }
예제 #4
0
 /**
  * @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 = Misc::getValidVersionsFile();
     $this->_setColourMasks();
 }
예제 #5
0
파일: run.php 프로젝트: kaibosh/nZEDb
<?php

require_once realpath(dirname(dirname(dirname(dirname(__DIR__)))) . DIRECTORY_SEPARATOR . 'indexer.php');
use nzedb\Tmux;
use nzedb\db\Settings;
use nzedb\utility\Misc;
$pdo = new Settings();
$DIR = nZEDb_MISC;
// Check that Db patch level is current. Also checks nZEDb.xml is valid.
Misc::isPatched();
Misc::clearScreen();
$patch = $pdo->getSetting('sqlpatch');
$patch = $patch != '' ? $patch : 0;
$delaytimet = $pdo->getSetting('delaytime');
$delaytimet = $delaytimet ? (int) $delaytimet : 2;
$nntpproxy = $pdo->getSetting('nntpproxy');
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);
}
$t = new Tmux();
$tmux = $t->get();
$tmux_session = isset($tmux->tmux_session) ? $tmux->tmux_session : 0;
$seq = isset($tmux->sequential) ? $tmux->sequential : 0;
예제 #6
0
<?php

require_once realpath(dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR . 'indexer.php');
use nzedb\db\Settings;
use nzedb\utility\Misc;
$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/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) {
    Misc::setCoversConstant($row['value']);
} else {
    die("Unable to set Covers' constant!\n");
}
$path2covers = nZEDb_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.");
예제 #7
0
파일: Versions.php 프로젝트: zetas/nZEDb
 public function getValidVersionsFile($filepath = null)
 {
     $filepath = empty($filepath) ? $this->_filespec : $filepath;
     $temp = libxml_use_internal_errors(true);
     $this->_xml = simplexml_load_file($filepath);
     libxml_use_internal_errors($temp);
     if ($this->_xml === false) {
         if (Misc::isCLI()) {
             $this->out->error("Your versions XML file ({$filepath}) is broken, try updating from git.");
         }
         throw new \Exception("Failed to open versions XML file '{$filepath}'");
     }
     if ($this->_xml->count() > 0) {
         $vers = $this->_xml->xpath('/nzedb/versions');
         if ($vers[0]->count() == 0) {
             $this->out->error("Your versions XML file ({nZEDb_VERSIONS}) does not contain version info, try updating from git.");
             throw new \Exception("Failed to find versions node in XML file '{$filepath}'");
         } else {
             $this->out->primary("Your versions XML file ({nZEDb_VERSIONS}) looks okay, continuing.");
             $this->_vers =& $this->_xml->versions;
         }
     } else {
         throw new \RuntimeException("No elements in file!\n");
     }
     return $this->_xml;
 }
예제 #8
0
파일: Settings.php 프로젝트: kaibosh/nZEDb
 public function setCovers()
 {
     $path = $this->getSetting(['section' => 'site', 'subsection' => 'main', 'name' => 'coverspath', 'setting' => 'coverspath']);
     Misc::setCoversConstant($path);
 }
예제 #9
0
 * 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 . 'indexer.php';
use nzedb\db\DbUpdate;
use nzedb\utility\Git;
use nzedb\utility\Misc;
if (!Misc::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";
예제 #10
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 = Misc::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;
 }
예제 #11
0
    case 'submit':
        if ($captcha->getError() === false) {
            $email = $_POST['email'];
            if ($email == '') {
                $page->smarty->assign('error', "Missing Email");
            } else {
                // Check users exists and send an email.
                $ret = $page->users->getByEmail($email);
                if (!$ret) {
                    $sent = "true";
                    break;
                } else {
                    // Generate a forgottenpassword guid, store it in the user table.
                    $guid = md5(uniqid());
                    $page->users->updatePassResetGuid($ret["id"], $guid);
                    // Send the email
                    Misc::sendEmail($ret["email"], $page->settings->getSetting('title') . " Forgotten Password Request", "Someone has requested a password reset for this email address.<br>To reset the password use <a href=\"" . $page->serverurl . "forgottenpassword?action=reset&guid={$guid}\">this link</a>\n", $page->settings->getSetting('email'));
                    $sent = "true";
                    break;
                }
            }
        }
        break;
}
$page->smarty->assign(['email' => $email, 'confirmed' => $confirmed, 'sent' => $sent]);
$page->title = "Forgotten Password";
$page->meta_title = "Forgotten Password";
$page->meta_keywords = "forgotten,password,signup,registration";
$page->meta_description = "Forgotten Password";
$page->content = $page->smarty->fetch('forgottenpassword.tpl');
$page->render();
예제 #12
0
파일: indexer.php 프로젝트: kaibosh/nZEDb
<?php

/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * 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 'constants.php';
require_once 'autoloader.php';
require_once 'libs/autoloader.php';
use nzedb\config\Configure;
use nzedb\utility\Misc;
$config = new Configure('indexer');
define('HAS_WHICH', Misc::hasWhich() ? true : false);
예제 #13
0
파일: api.php 프로젝트: advhamstrong/nZEDb
     $relData = $releases->searchbyRageId(isset($_GET['rid']) ? $_GET['rid'] : '-1', isset($_GET['season']) ? $_GET['season'] : '', isset($_GET['ep']) ? $_GET['ep'] : '', $offset, limit(), isset($_GET['q']) ? $_GET['q'] : '', categoryID(), $maxAge);
     addLanguage($relData, $page->settings);
     printOutput($relData, $outputXML, $page, $offset);
     break;
     // Search movie releases.
 // Search movie releases.
 case 'm':
     verifyEmptyParameter('q');
     verifyEmptyParameter('imdbid');
     $maxAge = maxAge();
     $page->users->addApiRequest($uid, $_SERVER['REQUEST_URI']);
     $offset = offset();
     $imdbId = isset($_GET['imdbid']) ? $_GET['imdbid'] : '-1';
     $relData = $releases->searchbyImdbId($imdbId, $offset, limit(), isset($_GET['q']) ? $_GET['q'] : '', categoryID(), $maxAge);
     addCoverURL($relData, function ($release) {
         return Misc::getCoverURL(['type' => 'movies', 'id' => $release['imdbid']]);
     });
     addLanguage($relData, $page->settings);
     printOutput($relData, $outputXML, $page, $offset);
     break;
     // Get NZB.
 // Get NZB.
 case 'g':
     if (!isset($_GET['id'])) {
         showApiError(200, 'Missing parameter (id is required for downloading an NZB)');
     }
     $relData = $releases->getByGuid($_GET['id']);
     if ($relData) {
         header('Location:' . WWW_TOP . '/getnzb?i=' . $uid . '&r=' . $apiKey . '&id=' . $relData['guid'] . (isset($_GET['del']) && $_GET['del'] == '1' ? '&del=1' : ''));
     } else {
         showApiError(300, 'No such item (the guid you provided has no release in our database)');
예제 #14
0
파일: NNTP.php 프로젝트: kaibosh/nZEDb
 /**
  * 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 = Misc::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);
             }
         }
     }
 }
예제 #15
0
}
$total = count($data);
$predb = new PreDb();
$progress = $predb->progress(settings_array());
foreach ($data as $file) {
    if (preg_match("#^https://raw\\.githubusercontent\\.com/nZEDb/nZEDbPre_Dumps/master/dumps/{$filePattern}\$#", $file['download_url'])) {
        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;
            }
            // Download the dump.
            $dump = Misc::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." . PHP_EOL;
                continue;
            } else {
                if (nZEDb_DEBUG) {
                    echo "Dump {$match[2]} downloaded\n";
                }
            }
            // Make sure we didn't get an HTML page.
            if (strpos($dump, '<!DOCTYPE html>') !== false) {
                echo "The dump file {$match[2]} might be missing from GitHub." . PHP_EOL;
                continue;
            }
            // Decompress.
예제 #16
0
<?php

require_once './config.php';
use nzedb\NZBExport;
use nzedb\Releases;
use nzedb\utility\Misc;
if (Misc::isCLI()) {
    exit('This script is only for exporting from the web, use the script in misc/testing' . PHP_EOL);
}
$page = new AdminPage();
$rel = new Releases(['Settings' => $page->settings]);
$folder = $group = $fromDate = $toDate = $gzip = $output = '';
if ($page->isPostBack()) {
    $folder = $_POST["folder"];
    $fromDate = isset($_POST["postfrom"]) ? $_POST["postfrom"] : '';
    $toDate = isset($_POST["postto"]) ? $_POST["postto"] : '';
    $group = $_POST["group"];
    $gzip = $_POST["gzip"];
    if ($folder != '') {
        $output = (new NZBExport(['Browser' => true, 'Settings' => $page->settings, 'Releases' => $rel]))->beginExport([$folder, $fromDate, $toDate, $_POST["group"] === '-1' ? 0 : (int) $_POST["group"], $_POST["gzip"] === '1' ? true : false]);
    } else {
        $output = 'Error, a path is required!';
    }
} else {
    $fromDate = $rel->getEarliestUsenetPostDate();
    $toDate = $rel->getLatestUsenetPostDate();
}
$page->title = "Export Nzbs";
$page->smarty->assign(['output' => $output, 'folder' => $folder, 'fromdate' => $fromDate, 'todate' => $toDate, 'group' => $group, 'gzip' => $gzip, 'gziplist' => [1 => 'True', 0 => 'False'], 'grouplist' => $rel->getReleasedGroupsForSelect(true)]);
$page->content = $page->smarty->fetch('nzb-export.tpl');
$page->render();
예제 #17
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 = Misc::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;
 }
예제 #18
0
<?php

// Shitty script to check time/date in php mysql and system...
require_once realpath(dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR . 'indexer.php');
use nzedb\db\Settings;
use nzedb\utility\Misc;
$n = PHP_EOL;
// TODO change this to be able to use GnuWin
if (!nzedb\utility\Misc::isWin()) {
    echo 'These are the settings in your php.ini files:' . $n;
    echo 'CLI PHP timezone : ' . exec('cat /etc/php5/cli/php.ini | grep \'date.timezone =\' | cut -d \\  -f 3') . $n;
    echo 'apache2 timezone : ' . exec('cat /etc/php5/apache2/php.ini| grep \'date.timezone =\' | cut -d \\  -f 3') . $n;
}
$system = ' not supported on windows.';
$pdo = new Settings();
$MySQL = $pdo->queryOneRow('SELECT NOW() AS time, @@system_time_zone AS tz');
if (!Misc::isWin()) {
    $system = exec('date');
}
$php = date('D M d H:i:s T o');
$MySQL = date('D M d H:i:s T o', strtotime($MySQL['time'] . ' ' . $MySQL['tz']));
echo 'The various dates/times:' . $n;
echo 'System time      : ' . $system . $n;
echo 'MYSQL time       : ' . $MySQL . $n;
echo 'PHP time         : ' . $php . $n;
if ($MySQL === $system && $system === $php) {
    exit('Looks like all your dates/times are good.' . $n);
} else {
    exit('Looks like you have 1 or more dates/times set wrong.' . $n);
}
예제 #19
0
<?php

use nzedb\NZBGet;
use nzedb\utility\Misc;
if (!$page->users->isLoggedIn()) {
    $page->show403();
}
$nzbget = new NZBGet($page);
$output = "";
$data = $nzbget->getQueue();
if ($data !== false) {
    if (count($data > 0)) {
        $status = $nzbget->status();
        if ($status !== false) {
            $output .= "<div class='container text-center' style='display:block;'>\n\t\t\t\t<div style='width:16.666666667%;float:left;'><b>Avg Speed:</b><br /> " . Misc::bytesToSizeString($status['AverageDownloadRate'], 2) . "/s </div>\n\t\t\t\t<div style='width:16.666666667%;float:left;'><b>Speed:</b><br /> " . Misc::bytesToSizeString($status['DownloadRate'], 2) . "/s </div>\n\t\t\t\t<div style='width:16.666666667%;float:left;'><b>Limit:</b><br /> " . Misc::bytesToSizeString($status['DownloadLimit'], 2) . "/s </div>\n\t\t\t\t<div style='width:16.666666667%;float:left;'><b>Queue Left(no pars):</b><br /> " . Misc::bytesToSizeString($status['RemainingSizeLo'], 2) . " </div>\n\t\t\t\t<div style='width:16.666666667%;float:left;'><b>Free Space:</b><br /> " . Misc::bytesToSizeString($status['FreeDiskSpaceMB'] * 1024000, 2) . " </div>\n\t\t\t\t<div style='width:16.666666667%;float:left;'><b>Status:</b><br /> " . ($status['Download2Paused'] == 1 ? 'Paused' : 'Downloading') . " </div>\n\t\t\t</div>";
        }
        $count = 1;
        $output .= "<table class='table table-striped table-condensed table-highlight data'>\n\t\t\t\t<thead>\n\t\t\t\t\t<tr >\n\t\t\t\t\t\t<th style='width=10px;text-align:center;'>#</th>\n\t\t\t\t\t\t<th style='text-align:left;'>Name</th>\n\t\t\t\t\t\t<th style='width:80px;text-align:center;'>Size</th>\n\t\t\t\t\t\t<th style='width:80px;text-align:center;'>Left(+pars)</th>\n\t\t\t\t\t\t<th style='width:50px;text-align:center;'>Done</th>\n\t\t\t\t\t\t<th style='width:80px;text-align:center;'>Status</th>\n\t\t\t\t\t\t<th style='width:50px;text-align:center;'>Delete</th>\n\t\t\t\t\t\t<th style='width:80px;text-align:center;'><a href='?pall'>Pause all</a></th>\n\t\t\t\t\t\t<th style='width:80px;text-align:center;'><a href='?rall'>Resume all</a></th>\n\t\t\t\t\t</tr>\n\t\t\t\t</thead>\n\t\t\t\t<tbody>";
        foreach ($data as $item) {
            $output .= "<tr>" . "<td style='text-align:center;width:10px'>" . $count . "</td>" . "<td style='text-align:left;'>" . $item['NZBName'] . "</td>" . "<td style='text-align:center;'>" . $item['FileSizeMB'] . " MB</td>" . "<td style='text-align:center;'>" . $item['RemainingSizeMB'] . " MB</td>" . "<td style='text-align:center;'>" . ($item['FileSizeMB'] == 0 ? 0 : round(100 - $item['RemainingSizeMB'] / $item['FileSizeMB'] * 100)) . "%</td>" . "<td style='text-align:center;'>" . ($item['ActiveDownloads'] > 0 ? 'Downloading' : 'Paused') . "</td>" . "<td style='text-align:center;'><a  onclick=\"return confirm('Are you sure?');\" href='?del=" . $item['LastID'] . "'>Delete</a></td>" . "<td style='text-align:center;'><a href='?pause=" . $item['LastID'] . "'>Pause</a></td>" . "<td style='text-align:center;'><a href='?resume=" . $item['LastID'] . "'>Resume</a></td>" . "</tr>";
            $count++;
        }
        $output .= "</tbody>\n\t\t</table>";
    } else {
        $output .= "<br /><br /><p style='text-align:center;'>The queue is currently empty.</p>";
    }
} else {
    $output .= "<p style='text-align:center;'>Error retreiving queue.</p>";
}
print $output;
예제 #20
0
파일: Users.php 프로젝트: kaibosh/nZEDb
 /**
  * Send a email for a invitation request.
  *
  * @param string $siteTitle Name of the admin's website.
  * @param string $siteEmail Email of the admin's website.
  * @param string $serverURL Address of the admin's website.
  * @param int    $userID    ID of the user sending the request.
  * @param string $emailTo   Email of the person to send the request.
  *
  * @return string
  */
 public function sendInvite($siteTitle, $siteEmail, $serverURL, $userID, $emailTo)
 {
     $sender = $this->getById($userID);
     $token = $this->hashSHA1(uniqid());
     $subject = $siteTitle . " Invitation";
     $url = $serverURL . "register?invitecode=" . $token;
     if (!is_null($sender['firstname']) || $sender['firstname'] != '') {
         $contents = $sender["firstname"] . " " . $sender["lastname"] . " has sent an invite to join " . $siteTitle . " to this email address.<br>To accept the invitation click <a href=\"{$url}\">this link</a>\n";
     } else {
         $contents = $sender["username"] . " has sent an invite to join " . $siteTitle . " to this email address.<br>To accept the invitation click <a href=\"{$url}\">this link</a>\n";
     }
     Misc::sendEmail($emailTo, $subject, $contents, $siteEmail);
     $this->addInvite($userID, $token);
     return $url;
 }
예제 #21
0
파일: ADM.php 프로젝트: zetas/nZEDb
 /**
  * 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, Misc::curlSslContextOptions());
     $this->_response = curl_exec($ch);
     if (!$this->_response) {
         curl_close($ch);
         return false;
     }
     curl_close($ch);
     $this->_html->load($this->_response);
     return true;
 }
예제 #22
0
파일: Steam.php 프로젝트: kaibosh/nZEDb
 /**
  * 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, Misc::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;
 }
예제 #23
0
require_once realpath(dirname(dirname(dirname(__DIR__))) . DIRECTORY_SEPARATOR . 'indexer.php');
require_once realpath(dirname(dirname(dirname(__DIR__))) . DS . 'libs' . DS . 'smarty' . DS . 'Autoloader.php');
Smarty_Autoloader::register();
use nzedb\ColorCLI;
use nzedb\Tmux;
use nzedb\db\Settings;
use nzedb\utility\Misc;
$pdo = new Settings();
$DIR = nZEDb_MISC;
$smarty = new Smarty();
$dbname = DB_NAME;
$cli = new ColorCLI();
if (isset($argv[1]) && ($argv[1] == "true" || $argv[1] == "safe")) {
    $restart = (new Tmux())->stopIfRunning();
    system("cd {$DIR} && git pull");
    if (Misc::hasCommand("php5")) {
        $PHP = "php5";
    } else {
        $PHP = "php";
    }
    echo $cli->header("Patching database - {$dbname}.");
    $safe = $argv[1] === "safe" ? true : false;
    system("{$PHP} " . nZEDb_ROOT . 'cli' . DS . "update_db.php true {$safe}");
    // Remove folders from smarty.
    $cleared = $smarty->clearCompiledTemplate();
    if ($cleared) {
        echo $cli->header("The smarty template cache has been cleaned for you");
    } else {
        echo $cli->header("You should clear your smarty template cache at: " . SMARTY_DIR . "templates_c");
    }
    if ($restart) {
예제 #24
0
파일: DB.php 프로젝트: zetas/nZEDb
 /**
  * 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 = Misc::isCLI();
     $defaults = ['checkVersion' => false, 'createDb' => false, 'ct' => new ConsoleTools(), 'dbhost' => defined('DB_HOST') ? DB_HOST : '', 'dbname' => defined('DB_NAME') ? DB_NAME : '', 'dbpass' => defined('DB_PASSWORD') ? DB_PASSWORD : '', 'dbport' => defined('DB_PORT') ? DB_PORT : '', 'dbsock' => defined('DB_SOCKET') ? DB_SOCKET : '', 'dbtype' => defined('DB_SYSTEM') ? DB_SYSTEM : '', 'dbuser' => defined('DB_USER') ? DB_USER : '', 'log' => new ColorCLI(), 'persist' => false];
     $options += $defaults;
     if (!$this->cli) {
         $options['log'] = null;
     }
     $this->opts = $options;
     if (!empty($this->opts['dbtype'])) {
         $this->dbSystem = strtolower($this->opts['dbtype']);
     }
     if (!$this->pdo instanceof \PDO) {
         $this->initialiseDatabase();
     }
     $this->cacheEnabled = defined('nZEDb_CACHE_TYPE') && nZEDb_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);
         }
     }
     $this->ct = $this->opts['ct'];
     $this->log = $this->opts['log'];
     $this->_debug = nZEDb_DEBUG || nZEDb_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 (defined('nZEDb_SQL_DELETE_LOW_PRIORITY') && nZEDb_SQL_DELETE_LOW_PRIORITY) {
         $this->DELETE_LOW_PRIORITY = ' LOW_PRIORITY ';
     }
     if (defined('nZEDb_SQL_DELETE_QUICK') && nZEDb_SQL_DELETE_QUICK) {
         $this->DELETE_QUICK = ' QUICK ';
     }
     return $this->pdo;
 }
예제 #25
0
파일: Releases.php 프로젝트: Atmos01/nZEDb
 /**
  * @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 = Misc::unzipGzipFile($nzbPath);
             if ($nzbContents) {
                 $filename = $guid;
                 $r = $this->getByGuid($guid);
                 if ($r) {
                     $filename = $r['searchname'];
                 }
                 $zipFile->addFile($nzbContents, $filename . '.nzb');
             }
         }
     }
     return $zipFile->file();
 }
예제 #26
0
파일: SABnzbd.php 프로젝트: kaibosh/nZEDb
 /**
  * Resume all NZB's in the SAB queue.
  *
  * @return bool|mixed
  */
 public function resumeAll()
 {
     return Misc::getUrl(['url' => $this->url . "api?mode=resume" . "&apikey=" . $this->apikey, 'verifycert' => false]);
 }
예제 #27
0
 /**
  * Try to find a IMDB id on yahoo.com
  *
  * @return bool
  */
 protected function yahooSearch()
 {
     $buffer = Misc::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;
 }
예제 #28
0
 /**
  * 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) {
             $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;
             }
             // 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']] = ['reqid' => $requestId, 'ident' => $release['id'], 'group' => $release['groupname'], 'sname' => $release['searchname']];
         }
     }
     // 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];
     // Do a web lookup.
     $returnXml = Misc::getUrl(['url' => $this->pdo->getSetting('request_url'), 'method' => 'post', 'postdata' => 'data=' . serialize($requestArray), 'verifycert' => false]);
     $renamed = 0;
     // Change the release titles and insert the PRE's if they don't exist.
     if ($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 = [];
             $groupIDArray = [];
             foreach ($returnXml->request as $result) {
                 if (isset($result['name']) && isset($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['group_id'] = $groupIDArray[$this->_release['groupname']];
                     } else {
                         $this->_release['group_id'] = $this->groups->getIDByName($this->_release['groupname']);
                         $groupIDArray[$this->_release['groupname']] = $this->_release['group_id'];
                     }
                     $this->_release['gid'] = $this->_release['group_id'];
                     $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'];
                 }
             }
             // 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(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;
                 }
                 $this->_requestIdNotFound($request['ident'], $status);
                 if ($this->echoOutput) {
                     echo '-';
                 }
             }
         }
     }
     return $renamed;
 }
예제 #29
-1
 public function addFromXml($releaseID, $xml)
 {
     $xmlObj = @simplexml_load_string($xml);
     $arrXml = Misc::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 ($track['@attributes']['type'] == 'General') {
                     if (isset($track['Format'])) {
                         $containerformat = $track['Format'];
                     }
                     if (isset($track['Overall_bit_rate'])) {
                         $overallbitrate = $track['Overall_bit_rate'];
                     }
                 } 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);
                             }
                         }
                     }
                 }
             }
         }
     }
 }
예제 #30
-1
파일: TvRage.php 프로젝트: zetas/nZEDb
 /**
  * Main function for matching a releae searchname to a TvRage title
  * Returns basic show information array or -1 int if no match
  *
  * @param $showInfo
  *
  * @return array|int
  */
 public function getShowInfo($showInfo)
 {
     $matchedTitle = -1;
     $title = $showInfo['cleanname'];
     // Full search gives us the akas.
     $xml = Misc::getUrl(['url' => $this->xmlFullSearchUrl . urlencode(strtolower($title))]);
     if ($xml !== false) {
         $arrXml = @Misc::objectsIntoArray(simplexml_load_string($xml));
         // CheckXML Response is valid before processing
         if (isset($arrXml['show']) && is_array($arrXml)) {
             // We got exactly 1 match so lets convert it to an array so we can use it in the logic below.
             if (isset($arrXml['show']['showid'])) {
                 $newArr[] = $arrXml['show'];
                 unset($arrXml);
                 $arrXml['show'] = $newArr;
             }
             $highestPercent = 0;
             foreach ($arrXml['show'] as $show) {
                 if ($title == $show['name']) {
                     $matchedTitle = $show;
                     break;
                 }
                 // Get a match percentage based on our name and the name returned from tvr.
                 $matchPercent = $this->checkMatch($title, $show['name'], self::MATCH_PROBABILITY);
                 if ($matchPercent > $highestPercent) {
                     $matchedTitle = $show;
                     $highestPercent = $matchPercent;
                 }
                 // Check if there are any akas for this result and get a match percentage for them too.
                 if (isset($show['akas']['aka'])) {
                     if (is_array($show['akas']['aka'])) {
                         // Multiple akas.
                         foreach ($show['akas']['aka'] as $aka) {
                             $matchPercent = $this->checkMatch($title, $aka, self::MATCH_PROBABILITY);
                             if ($matchPercent > $highestPercent) {
                                 $matchedTitle = $show;
                                 $highestPercent = $matchPercent;
                             }
                         }
                     } else {
                         // One aka.
                         $matchPercent = $this->checkMatch($title, $show['akas']['aka'], self::MATCH_PROBABILITY);
                         if ($matchPercent > $highestPercent) {
                             $show['akas']['aka'][] = $show['akas']['aka'];
                             $matchedTitle = $show;
                             $highestPercent = $matchPercent;
                         }
                     }
                 }
             }
         } else {
             if ($this->echooutput) {
                 echo $this->pdo->log->primary('Nothing returned from tvrage.');
             }
         }
     }
     return $this->formatShowInfo($matchedTitle);
 }