diff --git a/misc/testing/PostProc/updateTvRage.php b/misc/testing/PostProc/updateTvRage.php index 9ffc90aa6..96811a94b 100644 --- a/misc/testing/PostProc/updateTvRage.php +++ b/misc/testing/PostProc/updateTvRage.php @@ -7,7 +7,7 @@ use newznab\utility\Utility; $pdo = new Settings(); -$tvrage = new TvAnger(['Settings' => $pdo, 'Echo' => true]); +$tvrage = new TvRage(['Settings' => $pdo, 'Echo' => true]); $shows = $pdo->queryDirect("SELECT rageid FROM tvrage WHERE imgdata IS NULL ORDER BY rageid DESC LIMIT 2000"); if ($shows->rowCount() > 0) { diff --git a/misc/update_scripts/update_tvschedule.php b/misc/update_scripts/update_tvschedule.php index e7e8d48a9..67d41cfa0 100644 --- a/misc/update_scripts/update_tvschedule.php +++ b/misc/update_scripts/update_tvschedule.php @@ -3,4 +3,4 @@ // Run this once per day. require_once("config.php"); -(new \TvAnger(['Echo' => true]))->updateSchedule(); \ No newline at end of file +(new \TvRage(['Echo' => true]))->updateSchedule(); \ No newline at end of file diff --git a/newznab/controllers/Info.php b/newznab/controllers/Info.php index d9c774743..b0cb0d6ed 100644 --- a/newznab/controllers/Info.php +++ b/newznab/controllers/Info.php @@ -339,7 +339,7 @@ class Info ] ); $movie = new Movie(['Echo' => $this->echo, 'Settings' => $this->pdo]); - $tvRage = new TvAnger(['Echo' => $this->echo, 'Settings' => $this->pdo]); + $tvRage = new TvRage(['Echo' => $this->echo, 'Settings' => $this->pdo]); foreach ($res as $arr) { $fetchedBinary = $nzbContents->getNFOfromNZB($arr['guid'], $arr['id'], $arr['groupid'], $groups->getByNameByID($arr['groupid'])); diff --git a/newznab/controllers/TvAnger.php b/newznab/controllers/TvAnger.php deleted file mode 100644 index 59a5d9cb3..000000000 --- a/newznab/controllers/TvAnger.php +++ /dev/null @@ -1,1164 +0,0 @@ - false, - 'Settings' => null, - ]; - $options += $defaults; - - $this->pdo = ($options['Settings'] instanceof Settings ? $options['Settings'] : new Settings()); - $this->rageqty = ($this->pdo->getSetting('maxrageprocessed') != '') ? $this->pdo->getSetting('maxrageprocessed') : 75; - $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - - $this->xmlEpisodeInfoUrl = - "http://services.tvrage.com/myfeeds/tvrageepisodes.php?key=" . TvAnger::APIKEY; - } - - /** - * Get rage info for a ID. - * - * @param int $id - * - * @return array|bool - */ - public function getByID($id) - { - return $this->pdo->queryOneRow(sprintf("SELECT * FROM tvrage WHERE id = %d", $id)); - } - - /** - * Get rage info for a rage ID. - * - * @param int $id - * - * @return array - */ - public function getByRageID($id) - { - return $this->pdo->query(sprintf("SELECT * FROM tvrage WHERE rageid = %d", $id)); - } - - /** - * Get rage info for a title. - * - * @param $title - * - * @return bool - */ - public function getByTitle($title) - { - // Set string to differentiate between mysql and PG for string replacement matching operations - $string = '"\'"'; - - // Check if we already have an entry for this show. - $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE LOWER(releasetitle) = LOWER(%s)", $this->pdo->escapeString($title))); - if (isset($res['rageid'])) { - return $res['rageid']; - } - - $title2 = str_replace(' and ', ' & ', $title); - if ($title != $title2) { - $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE LOWER(releasetitle) = LOWER(%s)", $this->pdo->escapeString($title2))); - if (isset($res['rageid'])) { - return $res['rageid']; - } - $pieces = explode(' ', $title2); - $title4 = '%'; - foreach ($pieces as $piece) { - $title4 .= str_replace(["'", "!"], "", $piece) . '%'; - } - $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE replace(replace(releasetitle, %s, ''), '!', '') LIKE %s", $string, $this->pdo->escapeString($title4))); - if (isset($res['rageid'])) { - return $res['rageid']; - } - } - - // Some words are spelled correctly 2 ways - // example theatre and theater - $title3 = str_replace('er', 're', $title); - if ($title != $title3) { - $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE LOWER(releasetitle) = LOWER(%s)", $this->pdo->escapeString($title3))); - if (isset($res['rageid'])) { - return $res['rageid']; - } - $pieces = explode(' ', $title3); - $title4 = '%'; - foreach ($pieces as $piece) { - $title4 .= str_replace(["'", "!"], "", $piece) . '%'; - } - $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE replace(replace(releasetitle, %s, ''), '!', '') LIKE %s", $string, $this->pdo->escapeString($title4))); - if (isset($res['rageid'])) { - return $res['rageid']; - } - } - - // If there was not an exact title match, look for title with missing chars - // example release name :Zorro 1990, tvrage name Zorro (1990) - // Only search if the title contains more than one word to prevent incorrect matches - $pieces = explode(' ', $title); - if (count($pieces) > 1) { - $title4 = '%'; - foreach ($pieces as $piece) { - $title4 .= str_replace(["'", "!"], "", $piece) . '%'; - } - $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE replace(replace(releasetitle, %s, ''), '!', '') LIKE %s", $string, $this->pdo->escapeString($title4))); - if (isset($res['rageid'])) { - return $res['rageid']; - } - } - - return false; - } - - /** - * Get a country code for a country name. - * - * @param string $country - * - * @return mixed - */ - public function countryCode($country) - { - if (!is_array($country) && strlen($country) > 2) { - $code = $this->pdo->queryOneRow( - 'SELECT code FROM countries WHERE LOWER(name) = LOWER(' . $this->pdo->escapeString($country) . ')' - ); - if (isset($code['code'])) { - return $code['code']; - } - } - return $country; - } - - /** - * @param $rageid - * @param $releasename - * @param string $desc - * @param $genre - * @param $country - * @param $imgbytes - */ - public function add($rageid, $releasename, $desc, $genre, $country, $imgbytes) - { - $releasename = str_replace(['.', '_'], [' ', ' '], $releasename); - $country = $this->countryCode($country); - - if ($rageid != -2) { - $ckid = $this->pdo->queryOneRow('SELECT id FROM tvrage WHERE rageid = ' . $rageid); - } else { - $ckid = $this->pdo->queryOneRow('SELECT id FROM tvrage WHERE releasetitle = ' . $this->pdo->escapeString($releasename)); - } - - if (!isset($ckid['id'])) { - $this->pdo->queryExec(sprintf('INSERT INTO tvrage (rageid, releasetitle, description, genre, country, createddate, imgdata) VALUES (%s, %s, %s, %s, %s, NOW(), %s)', $rageid, $this->pdo->escapeString($releasename), $this->pdo->escapeString(substr($desc, 0, 10000)), $this->pdo->escapeString(substr($genre, 0, 64)), $this->pdo->escapeString($country), $this->pdo->escapeString($imgbytes))); - } else { - $this->pdo->queryExec(sprintf('UPDATE tvrage SET releasetitle = %s, description = %s, genre = %s, country = %s, createddate = NOW(), imgdata = %s WHERE id = %d', $this->pdo->escapeString($releasename), $this->pdo->escapeString(substr($desc, 0, 10000)), $this->pdo->escapeString(substr($genre, 0, 64)), $this->pdo->escapeString($country), $this->pdo->escapeString($imgbytes), $ckid['id'])); - } - } - - public function update($id, $rageid, $releasename, $desc, $genre, $country, $imgbytes) - { - $country = $this->countryCode($country); - if ($imgbytes != '') { - $imgbytes = ', imgdata = ' . $this->pdo->escapeString($imgbytes); - } - - $this->pdo->queryExec(sprintf('UPDATE tvrage SET rageid = %d, releasetitle = %s, description = %s, genre = %s, country = %s %s WHERE id = %d', $rageid, $this->pdo->escapeString($releasename), $this->pdo->escapeString(substr($desc, 0, 10000)), $this->pdo->escapeString($genre), $this->pdo->escapeString($country), $imgbytes, $id)); - } - - public function delete($id) - { - return $this->pdo->queryExec(sprintf("DELETE FROM tvrage WHERE id = %d", $id)); - } - - public function fetchShowQuickInfo($show, array $options = []) - { - $defaults = ['exact' => '', 'episode' => '']; - $options += $defaults; - $ret = []; - - if (!$show) { - return false; - } - - $url = $this->showQuickInfoURL . urlencode($show); - $url .= !empty($options['episode']) ? '&ep=' . urlencode($options['episode']) : ''; - $url .= !empty($options['exact']) ? '&exact=' . urlencode($options['exact']) : ''; - $fp = fopen($url, "r", false, stream_context_create(Utility::streamSslContextOptions())); - if ($fp) { - while (!feof($fp)) { - $line = fgets($fp, 1024); - list ($sec, $val) = explode('@', $line, 2); - $val = trim($val); - - switch ($sec) { - case 'Show ID': - $ret['rageid'] = $val; - break; - case 'Show Name': - $ret['name'] = $val; - break; - case 'Show URL': - $ret['url'] = $val; - break; - case 'Premiered': - $ret['premier'] = $val; - break; - case 'Country': - $ret['country'] = $val; - break; - case 'Status': - $ret['status'] = $val; - break; - case 'Classification': - $ret['classification'] = $val; - break; - case 'Genres': - $ret['genres'] = $val; - break; - case 'Network': - $ret['network'] = $val; - break; - case 'Airtime': - $ret['airtime'] = $val; - break; - case 'Latest Episode': - list ($ep, $title, $airdate) = explode('^', $val); - $ret['episode']['latest'] = - $ep . ", \"" . $title . "\" aired on " . $airdate; - break; - case 'Next Episode': - list ($ep, $title, $airdate) = explode('^', $val); - $ret['episode']['next'] = $ep . ", \"" . $title . "\" airs on " . $airdate; - break; - case 'Episode Info': - list ($ep, $title, $airdate) = explode('^', $val); - $ret['episode']['info'] = $ep . ", \"" . $title . "\" aired on " . $airdate; - break; - case 'Episode URL': - $ret['episode']['url'] = $val; - break; - case '': - break; - - default: - break; - } - } - fclose($fp); - - return $ret; - } - return false; - } - - public function getRange($start, $num, $ragename = "") - { - if ($start === false) { - $limit = ""; - } else { - $limit = " LIMIT " . $num . " OFFSET " . $start; - } - - $rsql = ''; - if ($ragename != "") { - $rsql .= sprintf("AND tvrage.releasetitle LIKE %s ", $this->pdo->escapeString("%" . $ragename . "%")); - } - - return $this->pdo->query(sprintf("SELECT id, rageid, releasetitle, description, createddate FROM tvrage WHERE 1=1 %s ORDER BY rageid ASC" . $limit, $rsql)); - } - - public function getCount($ragename = "") - { - $rsql = ''; - if ($ragename != "") { - $rsql .= sprintf("AND tvrage.releasetitle LIKE %s ", $this->pdo->escapeString("%" . $ragename . "%")); - } - - $res = $this->pdo->queryOneRow(sprintf("SELECT COUNT(id) AS num FROM tvrage WHERE 1=1 %s", $rsql)); - return $res["num"]; - } - - public function getCalendar($date = "") - { - if (!preg_match('/\d{4}-\d{2}-\d{2}/', $date)) { - $date = date("Y-m-d"); - } - $sql = sprintf("SELECT * FROM tvrageepisodes WHERE DATE(airdate) = %s ORDER BY airdate ASC", $this->pdo->escapeString($date)); - return $this->pdo->query($sql); - } - - public function getSeriesList($uid, $letter = "", $ragename = "") - { - $rsql = ''; - if ($letter != "") { - if ($letter == '0-9') { - $letter = '[0-9]'; - } - - $rsql .= sprintf("AND tvrage.releasetitle REGEXP %s", $this->pdo->escapeString('^' . $letter)); - } - $tsql = ''; - if ($ragename != '') { - $tsql .= sprintf("AND tvrage.releasetitle LIKE %s", $this->pdo->escapeString("%" . $ragename . "%")); - } - - return $this->pdo->query( - sprintf(" - SELECT tvrage.id, tvrage.rageid, tvrage.releasetitle, tvrage.genre, tvrage.country, tvrage.createddate, tvrage.prevdate, tvrage.nextdate, - userseries.id AS userseriesid - FROM tvrage - LEFT OUTER JOIN userseries ON userseries.userid = %d - AND userseries.rageid = tvrage.rageid - WHERE tvrage.rageid IN (SELECT DISTINCT rageid FROM releases WHERE categoryid BETWEEN 5000 AND 5999 AND rageid > 0) - AND tvrage.rageid > 0 %s %s - GROUP BY tvrage.rageid - ORDER BY tvrage.releasetitle ASC", - $uid, - $rsql, - $tsql - ) - ); - } - - public function updateSchedule() - { - $countries = $this->pdo->query("SELECT DISTINCT(country) AS country FROM tvrage WHERE country != ''"); - $showsindb = $this->pdo->query("SELECT DISTINCT(rageid) AS rageid FROM tvrage"); - $showarray = []; - foreach ($showsindb as $show) { - $showarray[] = $show['rageid']; - } - foreach ($countries as $country) { - if ($this->echooutput) { - echo $this->pdo->log->headerOver('Updating schedule for: ') . $this->pdo->log->primary($country['country']); - } - - $sched = Utility::getURL(['url' => $this->xmlFullScheduleUrl . $country['country']]); - if ($sched !== false && ($xml = @simplexml_load_string($sched))) { - $tzOffset = 60 * 60 * 6; - $yesterday = strtotime("-1 day") - $tzOffset; - $xmlSchedule = []; - - foreach ($xml->DAY as $sDay) { - $currDay = strtotime($sDay['attr']); - foreach ($sDay as $sTime) { - $currTime = (string)$sTime['attr']; - foreach ($sTime as $sShow) { - $currShowName = (string)$sShow['name']; - $currShowId = (string)$sShow->sid; - $day_time = strtotime($sDay['attr'] . ' ' . $currTime); - $tag = ($currDay < $yesterday) ? 'prev' : 'next'; - if ($tag == 'prev' || ($tag == 'next' && !isset($xmlSchedule[$currShowId]['next']))) { - $xmlSchedule[$currShowId][$tag] = ['name' => $currShowName, 'day' => $currDay, 'time' => $currTime, 'day_time' => $day_time, 'day_date' => date("Y-m-d H:i:s", $day_time), 'title' => html_entity_decode((string)$sShow->title, ENT_QUOTES, 'UTF-8'), 'episode' => html_entity_decode((string)$sShow->ep, ENT_QUOTES, 'UTF-8')]; - $xmlSchedule[$currShowId]['showname'] = $currShowName; - } - - // Only add it here, no point adding it to tvrage aswell that will automatically happen when an ep gets posted. - if ($sShow->ep == "01x01") { - $showarray[] = $sShow->sid; - } - - // Only stick current shows and new shows in there. - if (in_array($currShowId, $showarray)) { - $this->pdo->queryExec(sprintf("INSERT INTO tvrageepisodes (rageid, showtitle, fullep, airdate, link, eptitle) VALUES (%d, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE airdate = %s, link = %s ,eptitle = %s, showtitle = %s", $sShow->sid, $this->pdo->escapeString($currShowName), $this->pdo->escapeString($sShow->ep), $this->pdo->escapeString(date("Y-m-d H:i:s", $day_time)), $this->pdo->escapeString($sShow->link), $this->pdo->escapeString($sShow->title), $this->pdo->escapeString(date("Y-m-d H:i:s", $day_time)), $this->pdo->escapeString($sShow->link), $this->pdo->escapeString($sShow->title), $this->pdo->escapeString($currShowName))); - } - } - } - } - // Update series info. - foreach ($xmlSchedule as $showId => $epInfo) { - $res = $this->pdo->query(sprintf("SELECT * FROM tvrage WHERE rageid = %d", $showId)); - if (sizeof($res) > 0) { - foreach ($res as $arr) { - $prev_ep = $next_ep = ""; - $query = []; - - // Previous episode. - if (isset($epInfo['prev']) && $epInfo['prev']['episode'] != '') { - $prev_ep = $epInfo['prev']['episode'] . ', "' . $epInfo['prev']['title'] . '"'; - $query[] = sprintf("prevdate = %s, previnfo = %s", $this->pdo->from_unixtime($epInfo['prev']['day_time']), $this->pdo->escapeString($prev_ep)); - } - - // Next episode. - if (isset($epInfo['next']) && $epInfo['next']['episode'] != '') { - if ($prev_ep == "" && $arr['nextinfo'] != '' && $epInfo['next']['day_time'] > strtotime($arr["nextdate"]) && strtotime(date('Y-m-d', strtotime($arr["nextdate"]))) < $yesterday) { - $this->pdo->queryExec(sprintf("UPDATE tvrage SET prevdate = nextdate, previnfo = nextinfo WHERE id = %d", $arr['id'])); - $prev_ep = "SWAPPED with: " . $arr['nextinfo'] . " - " . date("r", strtotime($arr["nextdate"])); - } - $next_ep = $epInfo['next']['episode'] . ', "' . $epInfo['next']['title'] . '"'; - $query[] = sprintf("nextdate = %s, nextinfo = %s", $this->pdo->from_unixtime($epInfo['next']['day_time']), $this->pdo->escapeString($next_ep)); - } else { - $query[] = "nextdate = NULL, nextinfo = NULL"; - } - - // Output. - if ($this->echooutput) { - echo $this->pdo->log->primary($epInfo['showname'] . " (" . $showId . "):"); - if (isset($epInfo['prev']['day_time'])) { - echo $this->pdo->log->headerOver("Prev EP: ") . $this->pdo->log->primary("{$prev_ep} - " . date("m/d/Y H:i T", $epInfo['prev']['day_time'])); - } - if (isset($epInfo['next']['day_time'])) { - echo $this->pdo->log->headerOver("Next EP: ") . $this->pdo->log->primary("{$next_ep} - " . date("m/d/Y H:i T", $epInfo['next']['day_time'])); - } - echo "\n"; - } - - // Update info. - if (count($query) > 0) { - $sql = join(", ", $query); - $sql = sprintf("UPDATE tvrage SET {$sql} WHERE id = %d", $arr['id']); - $this->pdo->queryExec($sql); - } - } - } - } - } else { - // No response from tvrage. - if ($this->echooutput) { - echo $this->pdo->log->info("Schedule not found."); - } - } - } - if ($this->echooutput) { - echo $this->pdo->log->primary("Updated the TVRage schedule succesfully."); - } - } - - public function getEpisodeInfo($rageid, $series, $episode) - { - $result = ['title' => '', 'airdate' => '']; - - $series = str_ireplace("s", "", $series); - $episode = str_ireplace("e", "", $episode); - $xml = Utility::getUrl(['url' => $this->xmlEpisodeInfoUrl . "&sid=" . $rageid . "&ep=" . $series . "x" . $episode]); - if ($xml !== false) { - if (preg_match('/no show found/i', $xml)) { - return false; - } - - $xmlObj = @simplexml_load_string($xml); - $arrXml = Utility::objectsIntoArray($xmlObj); - if (is_array($arrXml)) { - if (isset($arrXml['episode']['airdate']) && $arrXml['episode']['airdate'] != '0000-00-00') { - $result['airdate'] = $arrXml['episode']['airdate']; - } - if (isset($arrXml['episode']['title'])) { - $result['title'] = $arrXml['episode']['title']; - } - - return $result; - } - return false; - } - return false; - } - - public function getRageInfoFromPage($rageid) - { - $result = ['desc' => '', 'imgurl' => '']; - $page = Utility::getUrl(['url' => $this->showInfoUrl . $rageid]); - $matches = ''; - if ($page !== false) { - // Description. - preg_match('@
(.*?)
@is', $page, $matches); - if (isset($matches[1])) { - $desc = $matches[1]; - $desc = preg_replace('/
.*/s', '', $desc); - $desc = preg_replace('/ ?/', '', $desc); - $desc = preg_replace('/
(\n)?
/', ' / ', $desc); - $desc = preg_replace('/\n/', ' ', $desc); - $desc = preg_replace('//', '', $desc); - $desc = preg_replace('//', '', $desc); - $desc = preg_replace('/<.*?>/', '', $desc); - $desc = str_replace('()', '', $desc); - $desc = trim(preg_replace('/\s{2,}/', ' ', $desc)); - $result['desc'] = $desc; - } - // Image. - preg_match("@src=[\"'](http://images.tvrage.com/shows.*?)[\"']@i", $page, $matches); - if (isset($matches[1])) { - $result['imgurl'] = $matches[1]; - } - } - return $result; - } - - /** - * @param string $rageid - * - * @return array|bool|mixed - */ - public function getRageInfoFromService($rageid) - { - $result = ['genres' => '', 'country' => '', 'showid' => $rageid]; - // Full search gives us the akas. - $xml = Utility::getUrl(['url' => $this->xmlShowInfoUrl . $rageid]); - if ($xml !== false) { - $arrXml = Utility::objectsIntoArray(simplexml_load_string($xml)); - if (is_array($arrXml)) { - $result['genres'] = (isset($arrXml['genres'])) ? $arrXml['genres'] : ''; - $result['country'] = (isset($arrXml['origin_country'])) ? $arrXml['origin_country'] : ''; - $result = $this->countryCode($result); - return $result; - } - return false; - } - return false; - } - - // - /** - * Convert 2012-24-07 to 2012-07-24, there is probably a better way - * - * This shouldn't ever happen as I've never heard of a date starting with year being followed by day value. - * Could this be a mistake? i.e. trying to solve the mm-dd-yyyy/dd-mm-yyyy confusion into a yyyy-mm-dd? - * - * @param string $date - * - * @return string - */ - public function checkDate($date) - { - if (!empty($date)) { - $chk = explode(" ", $date); - $chkd = explode("-", $chk[0]); - if ($chkd[1] > 12) { - $date = date('Y-m-d H:i:s', strtotime($chkd[1] . " " . $chkd[2] . " " . $chkd[0])); - } - } else { - $date = null; - } - - return $date; - } - - public function updateEpInfo($show, $relid) - { - if ($this->echooutput) { - echo $this->pdo->log->headerOver("Updating Episode: ") . $this->pdo->log->primary($show['cleanname'] . " " . $show['seriesfull'] . (($show['year'] != '') ? ' ' . $show['year'] : '') . (($show['country'] != '') ? ' [' . $show['country'] . ']' : '')); - } - - $tvairdate = (isset($show['airdate']) && !empty($show['airdate'])) ? $this->pdo->escapeString($this->checkDate($show['airdate'])) : "NULL"; - $this->pdo->queryExec(sprintf("UPDATE releases SET seriesfull = %s, season = %s, episode = %s, tvairdate = %s WHERE id = %d", $this->pdo->escapeString($show['seriesfull']), $this->pdo->escapeString($show['season']), $this->pdo->escapeString($show['episode']), $tvairdate, $relid)); - } - - public function updateRageInfo($rageid, $show, $tvrShow, $relid) - { - // Try and get the episode specific info from tvrage. - $epinfo = $this->getEpisodeInfo($rageid, $show['season'], $show['episode']); - if ($epinfo !== false) { - $tvairdate = (!empty($epinfo['airdate'])) ? $this->pdo->escapeString($epinfo['airdate']) : "NULL"; - $tvtitle = (!empty($epinfo['title'])) ? $this->pdo->escapeString($epinfo['title']) : "NULL"; - - $this->pdo->queryExec(sprintf("UPDATE releases set tvtitle = %s, tvairdate = %s, rageid = %d where id = %d", $this->pdo->escapeString(trim($tvtitle)), $tvairdate, $tvrShow['showid'], $relid)); - } else { - $this->pdo->queryExec(sprintf("UPDATE releases SET rageid = %d WHERE id = %d", $tvrShow['showid'], $relid)); - } - - $genre = ''; - if (isset($tvrShow['genres']) && is_array($tvrShow['genres']) && !empty($tvrShow['genres'])) { - if (is_array($tvrShow['genres']['genre'])) { - $genre = implode('|', $tvrShow['genres']['genre']); - } else { - $genre = $tvrShow['genres']['genre']; - } - } - - $country = ''; - if (isset($tvrShow['country']) && !empty($tvrShow['country'])) { - $country = $this->countryCode($tvrShow['country']); - } - - $rInfo = $this->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; - } - } - } - $this->add($rageid, $show['cleanname'], $desc, $genre, $country, $imgbytes); - } - - public function updateRageInfoTrakt($rageid, $show, $traktArray, $relid) - { - // Try and get the episode specific info from tvrage. - $epinfo = $this->getEpisodeInfo($rageid, $show['season'], $show['episode']); - if ($epinfo !== false) { - $tvairdate = (!empty($epinfo['airdate'])) ? $this->pdo->escapeString($epinfo['airdate']) : "NULL"; - $tvtitle = (!empty($epinfo['title'])) ? $this->pdo->escapeString($epinfo['title']) : "NULL"; - $this->pdo->queryExec(sprintf("UPDATE releases SET tvtitle = %s, tvairdate = %s, rageid = %d WHERE id = %d", $this->pdo->escapeString(trim($tvtitle)), $tvairdate, $traktArray['ids']['tvrage'], $relid)); - } else { - $this->pdo->queryExec(sprintf("UPDATE releases SET rageid = %d WHERE id = %d", $traktArray['ids']['tvrage'], $relid)); - } - - $genre = $country = ''; - - $rInfo = $this->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; - } - } - } - - $this->add($rageid, $show['cleanname'], $desc, $genre, $country, $imgbytes); - } - - public function processTvReleases($groupID = '', $guidChar = '', $lookupTvRage = 1, $local = false) - { - $ret = 0; - if ($lookupTvRage == 0) { - return $ret; - } - $trakt = new TraktTv(['Settings' => $this->pdo]); - - // Get all releases without a rageid which are in a tv category. - - $res = $this->pdo->query( - sprintf(" - SELECT r.searchname, r.id - FROM releases r - WHERE r.nzbstatus = 1 - AND r.rageid = -1 - AND r.size > 1048576 - AND r.categoryid BETWEEN 5000 AND 5999 - %s %s %s - ORDER BY r.postdate DESC - LIMIT %d", - ($groupID === '' ? '' : 'AND r.groupid = ' . $groupID), - ($guidChar === '' ? '' : 'AND r.guid ' . $this->pdo->likeString($guidChar, false, true)), - ($lookupTvRage == 2 ? 'AND r.isrenamed = 1' : ''), - $this->rageqty - ) - ); - $tvcount = count($res); - - if ($this->echooutput && $tvcount > 1) { - echo $this->pdo->log->header("Processing TV for " . $tvcount . " release(s)."); - } - - foreach ($res as $arr) { - $show = $this->parseNameEpSeason($arr['searchname']); - if (is_array($show) && $show['name'] != '') { - // Update release with season, ep, and airdate info (if available) from releasetitle. - $this->updateEpInfo($show, $arr['id']); - - // Find the rageID. - $id = $this->getByTitle($show['cleanname']); - - // Force local lookup only - if ($local == true) { - $lookupTvRage = false; - } - - if ($id === false && $lookupTvRage) { - // If it doesnt exist locally and lookups are allowed lets try to get it. - if ($this->echooutput) { - echo $this->pdo->log->primaryOver("TVRage ID for ") . $this->pdo->log->headerOver($show['cleanname']) . $this->pdo->log->primary(" not found in local db, checking web."); - } - - $tvrShow = $this->getRageMatch($show); - if ($tvrShow !== false && is_array($tvrShow)) { - // Get all tv info and add show. - $this->updateRageInfo($tvrShow['showid'], $show, $tvrShow, $arr['id']); - } else if ($tvrShow === false) { - // If tvrage fails, try trakt. - $traktArray = $trakt->episodeSummary($show['name'], $show['season'], $show['episode']); - if ($traktArray !== false) { - if (isset($traktArray['ids']['tvrage']) && $traktArray['ids']['tvrage'] !== 0) { - if ($this->echooutput) { - echo $this->pdo->log->primary('Found TVRage ID on trakt:' . $traktArray['ids']['tvrage']); - } - $this->updateRageInfoTrakt($traktArray['ids']['tvrage'], $show, $traktArray, $arr['id']); - } - // No match, add to tvrage with rageID = -2 and $show['cleanname'] title only. - else { - $this->add(-2, $show['cleanname'], '', '', '', ''); - } - } - // No match, add to tvrage with rageID = -2 and $show['cleanname'] title only. - else { - $this->add(-2, $show['cleanname'], '', '', '', ''); - } - } else { - // $tvrShow probably equals -1 but we'll do this as a catchall instead of a specific else if. - // Skip because we couldnt connect to tvrage.com. - } - } else if ($id > 0) { - //if ($this->echooutput) { - // echo $this->pdo->log->AlternateOver("TV series: ") . $this->pdo->log->header($show['cleanname'] . " " . $show['seriesfull'] . (($show['year'] != '') ? ' ' . $show['year'] : '') . (($show['country'] != '') ? ' [' . $show['country'] . ']' : '')); - // } - $tvairdate = (isset($show['airdate']) && !empty($show['airdate'])) ? $this->pdo->escapeString($this->checkDate($show['airdate'])) : "NULL"; - $tvtitle = "NULL"; - - if ($lookupTvRage) { - $epinfo = $this->getEpisodeInfo($id, $show['season'], $show['episode']); - if ($epinfo !== false) { - if (isset($epinfo['airdate'])) { - $tvairdate = $this->pdo->escapeString($this->checkDate($epinfo['airdate'])); - } - - if (!empty($epinfo['title'])) { - $tvtitle = $this->pdo->escapeString(trim($epinfo['title'])); - } - } - } - if ($tvairdate == "NULL") { - $this->pdo->queryExec(sprintf('UPDATE releases SET tvtitle = %s, rageid = %d WHERE id = %d', $tvtitle, $id, $arr['id'])); - } else { - $this->pdo->queryExec(sprintf('UPDATE releases SET tvtitle = %s, tvairdate = %s, rageid = %d WHERE id = %d', $tvtitle, $tvairdate, $id, $arr['id'])); - } - // Cant find rageid, so set rageid to n/a. - } else { - $this->pdo->queryExec(sprintf('UPDATE releases SET rageid = -2 WHERE id = %d', $arr['id'])); - } - // Not a tv episode, so set rageid to n/a. - } else { - $this->pdo->queryExec(sprintf('UPDATE releases SET rageid = -2 WHERE id = %d', $arr['id'])); - } - $ret++; - } - return $ret; - } - - 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; - } - } - - public function checkMatch($ourName, $tvrName) - { - // Clean up name ($ourName is already clean). - $tvrName = $this->cleanName($tvrName); - $tvrName = preg_replace('/ of /i', '', $tvrName); - $ourName = preg_replace('/ of /i', '', $ourName); - - // Create our arrays. - $ourArr = explode(' ', $ourName); - $tvrArr = explode(' ', $tvrName); - - // Set our match counts. - $numMatches = 0; - $totalMatches = sizeof($ourArr) + sizeof($tvrArr); - - // Loop through each array matching again the opposite value, if they match increment! - foreach ($ourArr as $oname) { - if (preg_match('/ ' . preg_quote($oname, '/') . ' /i', ' ' . $tvrName . ' ')) { - $numMatches++; - } - } - foreach ($tvrArr as $tname) { - if (preg_match('/ ' . preg_quote($tname, '/') . ' /i', ' ' . $ourName . ' ')) { - $numMatches++; - } - } - - // Check what we're left with. - if ($numMatches <= 0) { - return false; - } else { - $matchpct = ($numMatches / $totalMatches) * 100; - } - - if ($matchpct >= TvAnger::MATCH_PROBABILITY) { - return $matchpct; - } else { - return false; - } - } - - public function cleanName($str) - { - $str = str_replace(['.', '_'], ' ', $str); - - $str = str_replace(['à', 'á', 'â', 'ã', 'ä', 'æ', 'À', 'Á', 'Â', 'Ã', 'Ä'], 'a', $str); - $str = str_replace(['ç', 'Ç'], 'c', $str); - $str = str_replace(['Σ', 'è', 'é', 'ê', 'ë', 'È', 'É', 'Ê', 'Ë'], 'e', $str); - $str = str_replace(['ì', 'í', 'î', 'ï', 'Ì', 'Í', 'Î', 'Ï'], 'i', $str); - $str = str_replace(['ò', 'ó', 'ô', 'õ', 'ö', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö'], 'o', $str); - $str = str_replace(['ù', 'ú', 'û', 'ü', 'ū', 'Ú', 'Û', 'Ü', 'Ū'], 'u', $str); - $str = str_replace('ß', 'ss', $str); - - $str = str_replace('&', 'and', $str); - $str = preg_replace('/^(history|discovery) channel/i', '', $str); - $str = str_replace(['\'', ':', '!', '"', '#', '*', '’', ',', '(', ')', '?'], '', $str); - $str = str_replace('$', 's', $str); - $str = preg_replace('/\s{2,}/', ' ', $str); - - $str = trim($str, '\"'); - return trim($str); - } - - public function parseNameEpSeason($relname) - { - $showInfo = ['name' => '', 'season' => '', 'episode' => '', 'seriesfull' => '', 'airdate' => '', 'country' => '', 'year' => '', 'cleanname' => '']; - $matches = ''; - - $following = '[^a-z0-9](\d\d-\d\d|\d{1,2}x\d{2,3}|(19|20)\d\d|(480|720|1080)[ip]|AAC2?|BDRip|BluRay|D0?\d|DD5|DiVX|DLMux|DTS|DVD(Rip)?|E\d{2,3}|[HX][-_. ]?264|ITA(-ENG)?|[HPS]DTV|PROPER|REPACK|S\d+[^a-z0-9]?(E\d+)?|WEB[-_. ]?(DL|Rip)|XViD)[^a-z0-9]'; - - // For names that don't start with the title. - if (preg_match('/[^a-z0-9]{2,}(?P[\w .-]*?)' . $following . '/i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - } else if (preg_match('/^(?P[a-z0-9][\w .-]*?)' . $following . '/i', $relname, $matches)) { - // For names that start with the title. - $showInfo['name'] = $matches[1]; - } - - if (!empty($showInfo['name'])) { - // S01E01-E02 and S01E01-02 - if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?e(\d{1,3})(?:[e-])(\d{1,3})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = [intval($matches[3]), intval($matches[4])]; - } - //S01E0102 - lame no delimit numbering, regex would collide if there was ever 1000 ep season. - else if (preg_match('/^(.*?)[^a-z0-9]s(\d{2})[^a-z0-9]?e(\d{2})(\d{2})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = [intval($matches[3]), intval($matches[4])]; - } - // S01E01 and S01.E01 - else if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?e(\d{1,3})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = intval($matches[3]); - } - // S01 - else if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = 'all'; - } - // S01D1 and S1D1 - else if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?d\d{1}[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = 'all'; - } - // 1x01 - else if (preg_match('/^(.*?)[^a-z0-9](\d{1,2})x(\d{1,3})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = intval($matches[3]); - } - // 2009.01.01 and 2009-01-01 - else if (preg_match('/^(.*?)[^a-z0-9](19|20)(\d{2})[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = $matches[2] . $matches[3]; - $showInfo['episode'] = $matches[4] . '/' . $matches[5]; - $showInfo['airdate'] = $matches[2] . $matches[3] . '-' . $matches[4] . '-' . $matches[5]; //yy-m-d - } - // 01.01.2009 - else if (preg_match('/^(.*?)[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9](19|20)(\d{2})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = $matches[4] . $matches[5]; - $showInfo['episode'] = $matches[2] . '/' . $matches[3]; - $showInfo['airdate'] = $matches[4] . $matches[5] . '-' . $matches[2] . '-' . $matches[3]; //yy-m-d - } - // 01.01.09 - else if (preg_match('/^(.*?)[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = ($matches[4] <= 99 && $matches[4] > 15) ? '19' . $matches[4] : '20' . $matches[4]; - $showInfo['episode'] = $matches[2] . '/' . $matches[3]; - $showInfo['airdate'] = $showInfo['season'] . '-' . $matches[2] . '-' . $matches[3]; //yy-m-d - } - // 2009.E01 - else if (preg_match('/^(.*?)[^a-z0-9]20(\d{2})[^a-z0-9](\d{1,3})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = '20' . $matches[2]; - $showInfo['episode'] = intval($matches[3]); - } - // 2009.Part1 - else if (preg_match('/^(.*?)[^a-z0-9](19|20)(\d{2})[^a-z0-9]Part(\d{1,2})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = $matches[2] . $matches[3]; - $showInfo['episode'] = intval($matches[4]); - } - // Part1/Pt1 - else if (preg_match('/^(.*?)[^a-z0-9](?:Part|Pt)[^a-z0-9](\d{1,2})[^a-z0-9]/i', $relname, $matches)) { - $showInfo['season'] = 1; - $showInfo['episode'] = intval($matches[2]); - } - //The.Pacific.Pt.VI.HDTV.XviD-XII / Part.IV - else if (preg_match('/^(.*?)[^a-z0-9](?:Part|Pt)[^a-z0-9]([ivx]+)/i', $relname, $matches)) { - $showInfo['season'] = 1; - $epLow = strtolower($matches[2]); - switch ($epLow) { - case 'i': $e = 1; - break; - case 'ii': $e = 2; - break; - case 'iii': $e = 3; - break; - case 'iv': $e = 4; - break; - case 'v': $e = 5; - break; - case 'vi': $e = 6; - break; - case 'vii': $e = 7; - break; - case 'viii': $e = 8; - break; - case 'ix': $e = 9; - break; - case 'x': $e = 10; - break; - case 'xi': $e = 11; - break; - case 'xii': $e = 12; - break; - case 'xiii': $e = 13; - break; - case 'xiv': $e = 14; - break; - case 'xv': $e = 15; - break; - case 'xvi': $e = 16; - break; - case 'xvii': $e = 17; - break; - case 'xviii': $e = 18; - break; - case 'xix': $e = 19; - break; - case 'xx': $e = 20; - break; - default: - $e = 0; - } - $showInfo['episode'] = $e; - } - // Band.Of.Brothers.EP06.Bastogne.DVDRiP.XviD-DEiTY - else if (preg_match('/^(.*?)[^a-z0-9]EP?[^a-z0-9]?(\d{1,3})/i', $relname, $matches)) { - $showInfo['season'] = 1; - $showInfo['episode'] = intval($matches[2]); - } - // Season.1 - else if (preg_match('/^(.*?)[^a-z0-9]Seasons?[^a-z0-9]?(\d{1,2})/i', $relname, $matches)) { - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = 'all'; - } - - $countryMatch = $yearMatch = ''; - // Country or origin matching. - if (preg_match('/\W(US|UK|AU|NZ|CA|NL|Canada|Australia|America|United[^a-z0-9]States|United[^a-z0-9]Kingdom)\W/', $showInfo['name'], $countryMatch)) { - $currentCountry = strtolower($countryMatch[1]); - if ($currentCountry == 'canada') { - $showInfo['country'] = 'CA'; - } else if ($currentCountry == 'australia') { - $showInfo['country'] = 'AU'; - } else if ($currentCountry == 'america' || $currentCountry == 'united states') { - $showInfo['country'] = 'US'; - } else if ($currentCountry == 'united kingdom') { - $showInfo['country'] = 'UK'; - } else { - $showInfo['country'] = strtoupper($countryMatch[1]); - } - } - - // Clean show name. - $showInfo['cleanname'] = $this->cleanName($showInfo['name']); - - // Check for dates instead of seasons. - if (strlen($showInfo['season']) == 4) { - $showInfo['seriesfull'] = $showInfo['season'] . "/" . $showInfo['episode']; - } else { - // Get year if present (not for releases with dates as seasons). - if (preg_match('/[^a-z0-9](19|20)(\d{2})/i', $relname, $yearMatch)) { - $showInfo['year'] = $yearMatch[1] . $yearMatch[2]; - } - - $showInfo['season'] = sprintf('S%02d', $showInfo['season']); - // Check for multi episode release. - if (is_array($showInfo['episode'])) { - $tmpArr = []; - foreach ($showInfo['episode'] as $ep) { - $tmpArr[] = sprintf('E%02d', $ep); - } - $showInfo['episode'] = implode('', $tmpArr); - } else { - $showInfo['episode'] = sprintf('E%02d', $showInfo['episode']); - } - - $showInfo['seriesfull'] = $showInfo['season'] . $showInfo['episode']; - } - $showInfo['airdate'] = (!empty($showInfo['airdate'])) ? $showInfo['airdate'] . ' 00:00:00' : ''; - return $showInfo; - } - return false; - } - - public function getGenres() - { - return ['Action', 'Adult/Porn', 'Adventure', 'Anthology', 'Arts & Crafts', 'Automobiles', 'Buy, Sell & Trade', 'Celebrities', 'Children', 'Cinema/Theatre', 'Comedy', 'Cooking/Food', 'Crime', 'Current Events', - 'Dance', 'Debate', 'Design/Decorating', 'Discovery/Science', 'Drama', 'Educational', 'Family', 'Fantasy', 'Fashion/Make-up', 'Financial/Business', 'Fitness', 'Garden/Landscape', 'History', - 'Horror/Supernatural', 'Housing/Building', 'How To/Do It Yourself', 'Interview', 'Lifestyle', 'Literature', 'Medical', 'Military/War', 'Music', 'Mystery', 'Pets/Animals', 'Politics', 'Puppets', - 'Religion', 'Romance/Dating', 'Sci-Fi', 'Sketch/Improv', 'Soaps', 'Sports', 'Super Heroes', 'Talent', 'Tech/Gaming', 'Teens', 'Thriller', 'Travel', 'Western', 'Wildlife']; - } - -} \ No newline at end of file diff --git a/newznab/controllers/TvRage.php b/newznab/controllers/TvRage.php index 158ce4418..0290ec05b 100644 --- a/newznab/controllers/TvRage.php +++ b/newznab/controllers/TvRage.php @@ -2,316 +2,481 @@ use newznab\db\Settings; use newznab\utility\Utility; -use newznab\libraries\Cache; +/** + * Class TvRage + */ class TvRage { const APIKEY = '7FwjZ8loweFcOhHfnU3E'; const MATCH_PROBABILITY = 75; /** - * @var newznab\db\Settings + * @var \newznab\db\Settings */ public $pdo; - /** - * @var bool - */ public $echooutput; + public $rageqty; + public $showInfoUrl = 'http://www.tvrage.com/shows/id-'; + public $showQuickInfoURL = 'http://services.tvrage.com/tools/quickinfo.php?show='; + public $xmlFullSearchUrl = 'http://services.tvrage.com/feeds/full_search.php?show='; + public $xmlShowInfoUrl = 'http://services.tvrage.com/feeds/showinfo.php?sid='; + public $xmlFullShowInfoUrl = 'http://services.tvrage.com/feeds/full_show_info.php?sid='; + public $xmlEpisodeInfoUrl; + public $xmlFullScheduleUrl = 'http://services.tvrage.com/feeds/fullschedule.php?country='; - public function __construct($echooutput = false) + /** + * @param array $options Class instances / Echo to CLI. + */ + public function __construct(array $options = []) { - $this->echooutput = (NN_ECHOCLI && $echooutput); - $this->pdo = new Settings(); + $defaults = [ + 'Echo' => false, + 'Settings' => null, + ]; + $options += $defaults; - $this->xmlFullSearchUrl = "http://services.tvrage.com/feeds/full_search.php?show="; - $this->xmlFullShowInfoUrl = "http://services.tvrage.com/feeds/full_show_info.php?sid="; - $this->xmlEpisodeInfoUrl = "http://services.tvrage.com/myfeeds/episodeinfo.php?key=".TvRage::APIKEY; - $this->xmlFullScheduleUrl = "http://services.tvrage.com/feeds/fullschedule.php?country="; + $this->pdo = ($options['Settings'] instanceof Settings ? $options['Settings'] : new Settings()); + $this->rageqty = ($this->pdo->getSetting('maxrageprocessed') != '') ? $this->pdo->getSetting('maxrageprocessed') : 75; + $this->echooutput = ($options['Echo'] && NN_ECHOCLI); - $this->showInfoUrl = "http://www.tvrage.com/shows/id-"; + $this->xmlEpisodeInfoUrl = + "http://services.tvrage.com/myfeeds/tvrageepisodes.php?key=" . TvRage::APIKEY; } /** - * Find an tvrage URL in an string. + * Get rage info for a ID. + * + * @param int $id + * + * @return array|bool */ - public function parseRageIdFromNfo($str) - { - preg_match('/tvrage\.com\/shows\/id-(\d{1,6})/si', $str, $matches); - if (isset($matches[1])) - return trim($matches[1]); - return false; - } - public function getByID($id) { - return $this->pdo->queryOneRow(sprintf("select * from tvrage where id = %d", $id )); + return $this->pdo->queryOneRow(sprintf("SELECT * FROM tvrage WHERE id = %d", $id)); } + /** + * Get rage info for a rage ID. + * + * @param int $id + * + * @return array + */ public function getByRageID($id) { - return $this->pdo->query(sprintf("select * from tvrage where rageid = %d", $id )); + return $this->pdo->query(sprintf("SELECT * FROM tvrage WHERE rageid = %d", $id)); } + /** + * Get rage info for a title. + * + * @param $title + * + * @return bool + */ public function getByTitle($title) { - // check if we already have an entry for this show - $sql = sprintf("SELECT rageid from tvrage where (releasetitle = %s or releasetitle = %s)", $this->pdo->escapeString($title), $this->pdo->escapeString(str_replace(' and ', ' & ', $title))); - $res = $this->pdo->queryOneRow($sql); - if ($res) - return $res["rageid"]; + // Set string to differentiate between mysql and PG for string replacement matching operations + $string = '"\'"'; + + // Check if we already have an entry for this show. + $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE LOWER(releasetitle) = LOWER(%s)", $this->pdo->escapeString($title))); + if (isset($res['rageid'])) { + return $res['rageid']; + } + + $title2 = str_replace(' and ', ' & ', $title); + if ($title != $title2) { + $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE LOWER(releasetitle) = LOWER(%s)", $this->pdo->escapeString($title2))); + if (isset($res['rageid'])) { + return $res['rageid']; + } + $pieces = explode(' ', $title2); + $title4 = '%'; + foreach ($pieces as $piece) { + $title4 .= str_replace(["'", "!"], "", $piece) . '%'; + } + $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE replace(replace(releasetitle, %s, ''), '!', '') LIKE %s", $string, $this->pdo->escapeString($title4))); + if (isset($res['rageid'])) { + return $res['rageid']; + } + } + + // Some words are spelled correctly 2 ways + // example theatre and theater + $title3 = str_replace('er', 're', $title); + if ($title != $title3) { + $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE LOWER(releasetitle) = LOWER(%s)", $this->pdo->escapeString($title3))); + if (isset($res['rageid'])) { + return $res['rageid']; + } + $pieces = explode(' ', $title3); + $title4 = '%'; + foreach ($pieces as $piece) { + $title4 .= str_replace(["'", "!"], "", $piece) . '%'; + } + $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE replace(replace(releasetitle, %s, ''), '!', '') LIKE %s", $string, $this->pdo->escapeString($title4))); + if (isset($res['rageid'])) { + return $res['rageid']; + } + } + + // If there was not an exact title match, look for title with missing chars + // example release name :Zorro 1990, tvrage name Zorro (1990) + // Only search if the title contains more than one word to prevent incorrect matches + $pieces = explode(' ', $title); + if (count($pieces) > 1) { + $title4 = '%'; + foreach ($pieces as $piece) { + $title4 .= str_replace(["'", "!"], "", $piece) . '%'; + } + $res = $this->pdo->queryOneRow(sprintf("SELECT rageid FROM tvrage WHERE replace(replace(releasetitle, %s, ''), '!', '') LIKE %s", $string, $this->pdo->escapeString($title4))); + if (isset($res['rageid'])) { + return $res['rageid']; + } + } return false; } + /** + * Get a country code for a country name. + * + * @param string $country + * + * @return mixed + */ + public function countryCode($country) + { + if (!is_array($country) && strlen($country) > 2) { + $code = $this->pdo->queryOneRow( + 'SELECT code FROM countries WHERE LOWER(name) = LOWER(' . $this->pdo->escapeString($country) . ')' + ); + if (isset($code['code'])) { + return $code['code']; + } + } + return $country; + } + + /** + * @param $rageid + * @param $releasename + * @param string $desc + * @param $genre + * @param $country + * @param $imgbytes + */ public function add($rageid, $releasename, $desc, $genre, $country, $imgbytes) { - $releasename = str_replace(array('.','_'), array(' ',' '), $releasename); + $releasename = str_replace(['.', '_'], [' ', ' '], $releasename); + $country = $this->countryCode($country); - return $this->pdo->queryInsert(sprintf("insert into tvrage (rageid, releasetitle, description, genre, country, createddate, imgdata) values (%d, %s, %s, %s, %s, now(), %s)", - $rageid, $this->pdo->escapeString($releasename), $this->pdo->escapeString($desc), $this->pdo->escapeString($genre), $this->pdo->escapeString($country), $this->pdo->escapeString($imgbytes))); + if ($rageid != -2) { + $ckid = $this->pdo->queryOneRow('SELECT id FROM tvrage WHERE rageid = ' . $rageid); + } else { + $ckid = $this->pdo->queryOneRow('SELECT id FROM tvrage WHERE releasetitle = ' . $this->pdo->escapeString($releasename)); + } + + if (!isset($ckid['id'])) { + $this->pdo->queryExec(sprintf('INSERT INTO tvrage (rageid, releasetitle, description, genre, country, createddate, imgdata) VALUES (%s, %s, %s, %s, %s, NOW(), %s)', $rageid, $this->pdo->escapeString($releasename), $this->pdo->escapeString(substr($desc, 0, 10000)), $this->pdo->escapeString(substr($genre, 0, 64)), $this->pdo->escapeString($country), $this->pdo->escapeString($imgbytes))); + } else { + $this->pdo->queryExec(sprintf('UPDATE tvrage SET releasetitle = %s, description = %s, genre = %s, country = %s, createddate = NOW(), imgdata = %s WHERE id = %d', $this->pdo->escapeString($releasename), $this->pdo->escapeString(substr($desc, 0, 10000)), $this->pdo->escapeString(substr($genre, 0, 64)), $this->pdo->escapeString($country), $this->pdo->escapeString($imgbytes), $ckid['id'])); + } } public function update($id, $rageid, $releasename, $desc, $genre, $country, $imgbytes) { + $country = $this->countryCode($country); + if ($imgbytes != '') { + $imgbytes = ', imgdata = ' . $this->pdo->escapeString($imgbytes); + } - if ($imgbytes != "") - $imgbytes = sprintf(", imgdata = %s", $this->pdo->escapeString($imgbytes)); - - $this->pdo->queryExec(sprintf("update tvrage set rageid = %d, releasetitle = %s, description = %s, genre = %s, country = %s %s where id = %d", - $rageid, $this->pdo->escapeString($releasename), $this->pdo->escapeString($desc), $this->pdo->escapeString($genre), $this->pdo->escapeString($country), $imgbytes, $id )); + $this->pdo->queryExec(sprintf('UPDATE tvrage SET rageid = %d, releasetitle = %s, description = %s, genre = %s, country = %s %s WHERE id = %d', $rageid, $this->pdo->escapeString($releasename), $this->pdo->escapeString(substr($desc, 0, 10000)), $this->pdo->escapeString($genre), $this->pdo->escapeString($country), $imgbytes, $id)); } public function delete($id) { - return $this->pdo->queryExec(sprintf("DELETE from tvrage where id = %d",$id)); + return $this->pdo->queryExec(sprintf("DELETE FROM tvrage WHERE id = %d", $id)); } - public function getRange($start, $num, $ragename="") + public function fetchShowQuickInfo($show, array $options = []) { + $defaults = ['exact' => '', 'episode' => '']; + $options += $defaults; + $ret = []; - if ($start === false) + if (!$show) { + return false; + } + + $url = $this->showQuickInfoURL . urlencode($show); + $url .= !empty($options['episode']) ? '&ep=' . urlencode($options['episode']) : ''; + $url .= !empty($options['exact']) ? '&exact=' . urlencode($options['exact']) : ''; + $fp = fopen($url, "r", false, stream_context_create(Utility::streamSslContextOptions())); + if ($fp) { + while (!feof($fp)) { + $line = fgets($fp, 1024); + list ($sec, $val) = explode('@', $line, 2); + $val = trim($val); + + switch ($sec) { + case 'Show ID': + $ret['rageid'] = $val; + break; + case 'Show Name': + $ret['name'] = $val; + break; + case 'Show URL': + $ret['url'] = $val; + break; + case 'Premiered': + $ret['premier'] = $val; + break; + case 'Country': + $ret['country'] = $val; + break; + case 'Status': + $ret['status'] = $val; + break; + case 'Classification': + $ret['classification'] = $val; + break; + case 'Genres': + $ret['genres'] = $val; + break; + case 'Network': + $ret['network'] = $val; + break; + case 'Airtime': + $ret['airtime'] = $val; + break; + case 'Latest Episode': + list ($ep, $title, $airdate) = explode('^', $val); + $ret['episode']['latest'] = + $ep . ", \"" . $title . "\" aired on " . $airdate; + break; + case 'Next Episode': + list ($ep, $title, $airdate) = explode('^', $val); + $ret['episode']['next'] = $ep . ", \"" . $title . "\" airs on " . $airdate; + break; + case 'Episode Info': + list ($ep, $title, $airdate) = explode('^', $val); + $ret['episode']['info'] = $ep . ", \"" . $title . "\" aired on " . $airdate; + break; + case 'Episode URL': + $ret['episode']['url'] = $val; + break; + case '': + break; + + default: + break; + } + } + fclose($fp); + + return $ret; + } + return false; + } + + public function getRange($start, $num, $ragename = "") + { + if ($start === false) { $limit = ""; - else - $limit = " LIMIT ".$start.",".$num; + } else { + $limit = " LIMIT " . $num . " OFFSET " . $start; + } $rsql = ''; - if ($ragename != "") - $rsql .= sprintf("and tvrage.releasetitle like %s ", $this->pdo->escapeString("%".$ragename."%")); + if ($ragename != "") { + $rsql .= sprintf("AND tvrage.releasetitle LIKE %s ", $this->pdo->escapeString("%" . $ragename . "%")); + } - return $this->pdo->query(sprintf(" SELECT id, rageid, releasetitle, description, createddate from tvrage where 1=1 %s order by rageid asc".$limit, $rsql)); + return $this->pdo->query(sprintf("SELECT id, rageid, releasetitle, description, createddate FROM tvrage WHERE 1=1 %s ORDER BY rageid ASC" . $limit, $rsql)); } - public function getCount($ragename="") + public function getCount($ragename = "") { - $rsql = ''; - if ($ragename != "") - $rsql .= sprintf("and tvrage.releasetitle like %s ", $this->pdo->escapeString("%".$ragename."%")); + if ($ragename != "") { + $rsql .= sprintf("AND tvrage.releasetitle LIKE %s ", $this->pdo->escapeString("%" . $ragename . "%")); + } - $res = $this->pdo->queryOneRow(sprintf("select count(id) as num from tvrage where 1=1 %s ", $rsql)); + $res = $this->pdo->queryOneRow(sprintf("SELECT COUNT(id) AS num FROM tvrage WHERE 1=1 %s", $rsql)); return $res["num"]; } public function getCalendar($date = "") { - if(!preg_match('/\d{4}-\d{2}-\d{2}/',$date)) + if (!preg_match('/\d{4}-\d{2}-\d{2}/', $date)) { $date = date("Y-m-d"); - $sql = sprintf("SELECT * FROM episodeinfo WHERE rageid > %d AND DATE(airdate) = %s order by airdate asc ", 0, $this->pdo->escapeString($date)); + } + $sql = sprintf("SELECT * FROM tvrageepisodes WHERE DATE(airdate) = %s ORDER BY airdate ASC", $this->pdo->escapeString($date)); return $this->pdo->query($sql); } - public function getSeriesList($uid, $letter="", $ragename="") + public function getSeriesList($uid, $letter = "", $ragename = "") { - $rsql = ''; - if ($letter != "") - { - if ($letter == '0-9') + if ($letter != "") { + if ($letter == '0-9') { $letter = '[0-9]'; + } - $rsql .= sprintf("and tvrage.releasetitle REGEXP %s", $this->pdo->escapeString('^'.$letter)); + $rsql .= sprintf("AND tvrage.releasetitle REGEXP %s", $this->pdo->escapeString('^' . $letter)); } $tsql = ''; - if ($ragename != '') - { - $tsql .= sprintf("and tvrage.releasetitle like %s", $this->pdo->escapeString("%".$ragename."%")); + if ($ragename != '') { + $tsql .= sprintf("AND tvrage.releasetitle LIKE %s", $this->pdo->escapeString("%" . $ragename . "%")); } - $sql = sprintf(" SELECT tvrage.id, tvrage.rageid, tvrage.releasetitle, tvrage.genre, tvrage.country, tvrage.createddate, tvrage.prevdate, tvrage.nextdate, userseries.id as userseriesID from tvrage left outer join userseries on userseries.userid = %d and userseries.rageid = tvrage.rageid where tvrage.rageid > 0 %s %s group by tvrage.rageid order by tvrage.releasetitle asc", $uid, $rsql, $tsql); - return $this->pdo->query($sql); + return $this->pdo->query( + sprintf(" + SELECT tvrage.id, tvrage.rageid, tvrage.releasetitle, tvrage.genre, tvrage.country, tvrage.createddate, tvrage.prevdate, tvrage.nextdate, + userseries.id AS userseriesid + FROM tvrage + LEFT OUTER JOIN userseries ON userseries.userid = %d + AND userseries.rageid = tvrage.rageid + WHERE tvrage.rageid IN (SELECT DISTINCT rageid FROM releases WHERE categoryid BETWEEN 5000 AND 5999 AND rageid > 0) + AND tvrage.rageid > 0 %s %s + GROUP BY tvrage.rageid + ORDER BY tvrage.releasetitle ASC", + $uid, + $rsql, + $tsql + ) + ); } public function updateSchedule() { - - $countries = $this->pdo->query("select distinct(country) as country from tvrage where country != ''"); - $showsindb = $this->pdo->query("select distinct(rageid) as rageid from tvrage"); + $countries = $this->pdo->query("SELECT DISTINCT(country) AS country FROM tvrage WHERE country != ''"); + $showsindb = $this->pdo->query("SELECT DISTINCT(rageid) AS rageid FROM tvrage"); $showarray = []; - foreach($showsindb as $show) - { + foreach ($showsindb as $show) { $showarray[] = $show['rageid']; } - - if ($this->echooutput) - echo 'TVRage : Updating schedule...'; - - foreach($countries as $country) - { - if ($this->echooutput) - echo '..'.strtoupper($country['country']).".."; - - try - { - $raw = Utility::getURL($this->xmlFullScheduleUrl.$country['country']); - $xml = new SimpleXMLElement($raw); - $sched = $xml->xpath('/schedule/DAY'); - }catch(Exception $e){ - # Simply no data or unparseable - continue; + foreach ($countries as $country) { + if ($this->echooutput) { + echo $this->pdo->log->headerOver('Updating schedule for: ') . $this->pdo->log->primary($country['country']); } - if ($sched !== false) - { - $tzOffset = 60*60*6; + $sched = Utility::getURL(['url' => $this->xmlFullScheduleUrl . $country['country']]); + if ($sched !== false && ($xml = @simplexml_load_string($sched))) { + $tzOffset = 60 * 60 * 6; $yesterday = strtotime("-1 day") - $tzOffset; $xmlSchedule = []; - foreach ($sched as $dayObj) - { - $currDay = (string)$dayObj['attr']; - foreach ($dayObj->time as $sTime) - { - $currTime = (string) $sTime['attr']; - foreach ($sTime as $sShow) - { - $currShowName = (string) $sShow['name']; - $currShowId = (string) $sShow->sid; - $day_time= strtotime($currDay.' '.$currTime); + foreach ($xml->DAY as $sDay) { + $currDay = strtotime($sDay['attr']); + foreach ($sDay as $sTime) { + $currTime = (string)$sTime['attr']; + foreach ($sTime as $sShow) { + $currShowName = (string)$sShow['name']; + $currShowId = (string)$sShow->sid; + $day_time = strtotime($sDay['attr'] . ' ' . $currTime); $tag = ($currDay < $yesterday) ? 'prev' : 'next'; - if ($tag == 'prev' || ($tag == 'next' && !isset($xmlSchedule[$currShowId]['next']))) - { - $xmlSchedule[$currShowId][$tag] = array( - 'name'=> $currShowName, - 'day' => $currDay, - 'time' => $currTime, - 'day_time' => $day_time, - 'day_date' => date("Y-m-d H:i:s", $day_time), - 'title' => html_entity_decode((string)$sShow->title, ENT_QUOTES, 'UTF-8'), - 'episode' => html_entity_decode((string)$sShow->ep, ENT_QUOTES, 'UTF-8'), - ); + if ($tag == 'prev' || ($tag == 'next' && !isset($xmlSchedule[$currShowId]['next']))) { + $xmlSchedule[$currShowId][$tag] = ['name' => $currShowName, 'day' => $currDay, 'time' => $currTime, 'day_time' => $day_time, 'day_date' => date("Y-m-d H:i:s", $day_time), 'title' => html_entity_decode((string)$sShow->title, ENT_QUOTES, 'UTF-8'), 'episode' => html_entity_decode((string)$sShow->ep, ENT_QUOTES, 'UTF-8')]; $xmlSchedule[$currShowId]['showname'] = $currShowName; } - if($sShow->ep == "01x01") - { - // Only add it here, no point adding it to tvrage aswell - // that will automatically happen when an ep gets posted + + // Only add it here, no point adding it to tvrage aswell that will automatically happen when an ep gets posted. + if ($sShow->ep == "01x01") { $showarray[] = $sShow->sid; - } - if(in_array($currShowId,$showarray)) //only stick current shows and new shows in there - { - $showname = $this->pdo->escapeString($currShowName); - $title = $this->pdo->escapeString($sShow->title); - $fullep = $this->pdo->escapeString($sShow->ep); - $link = $this->pdo->escapeString($sShow->link); - $airdate = $this->pdo->escapeString(date("Y-m-d H:i:s", $day_time)); - $sql = sprintf('INSERT into episodeinfo (rageid,showtitle,fullep,airdate,link,eptitle) VALUES (%d,%s,%s,%s,%s,%s) - ON DUPLICATE KEY UPDATE rageid = %1$d, airdate = %4$s, link = %5$s, eptitle = %6$s, showtitle = %2$s', - $sShow->sid,$showname,$fullep,$airdate,$link,$title); - $this->pdo->queryInsert($sql); + } + + // Only stick current shows and new shows in there. + if (in_array($currShowId, $showarray)) { + $this->pdo->queryExec(sprintf("INSERT INTO tvrageepisodes (rageid, showtitle, fullep, airdate, link, eptitle) VALUES (%d, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE airdate = %s, link = %s ,eptitle = %s, showtitle = %s", $sShow->sid, $this->pdo->escapeString($currShowName), $this->pdo->escapeString($sShow->ep), $this->pdo->escapeString(date("Y-m-d H:i:s", $day_time)), $this->pdo->escapeString($sShow->link), $this->pdo->escapeString($sShow->title), $this->pdo->escapeString(date("Y-m-d H:i:s", $day_time)), $this->pdo->escapeString($sShow->link), $this->pdo->escapeString($sShow->title), $this->pdo->escapeString($currShowName))); } } } } - // update series info - foreach ($xmlSchedule as $showId=>$epInfo) - { - $res = $this->pdo->query(sprintf("select *, UNIX_TIMESTAMP(nextdate) as nextDateU, UNIX_TIMESTAMP(DATE(nextdate)) as nextDateDay from tvrage where rageid = %d", $showId)); - if (sizeof($res) > 0) - { - foreach ($res as $arr) - { + // Update series info. + foreach ($xmlSchedule as $showId => $epInfo) { + $res = $this->pdo->query(sprintf("SELECT * FROM tvrage WHERE rageid = %d", $showId)); + if (sizeof($res) > 0) { + foreach ($res as $arr) { $prev_ep = $next_ep = ""; $query = []; - // previous episode - if (isset($epInfo['prev']) && $epInfo['prev']['episode'] != '') - { - $prev_ep = $epInfo['prev']['episode'].', "'.$epInfo['prev']['title'].'"'; - $query[] = sprintf("prevdate = FROM_UNIXTIME(%s), previnfo = %s", $epInfo['prev']['day_time'], $this->pdo->escapeString($prev_ep)); + // Previous episode. + if (isset($epInfo['prev']) && $epInfo['prev']['episode'] != '') { + $prev_ep = $epInfo['prev']['episode'] . ', "' . $epInfo['prev']['title'] . '"'; + $query[] = sprintf("prevdate = %s, previnfo = %s", $this->pdo->from_unixtime($epInfo['prev']['day_time']), $this->pdo->escapeString($prev_ep)); } - // next episode - if (isset($epInfo['next']) && $epInfo['next']['episode'] != '') - { - if ($prev_ep == "" && $arr['nextinfo'] != '' && $epInfo['next']['day_time'] > $arr['nextDateU'] && $arr['nextDateDay'] < $yesterday) - { - $this->pdo->queryExec(sprintf("update tvrage set prevdate = nextdate, previnfo = nextinfo where id = %d", $arr['id'])); - $prev_ep = "SWAPPED with: ".$arr['nextinfo']." - ".date("r", $arr['nextDateU']); + // Next episode. + if (isset($epInfo['next']) && $epInfo['next']['episode'] != '') { + if ($prev_ep == "" && $arr['nextinfo'] != '' && $epInfo['next']['day_time'] > strtotime($arr["nextdate"]) && strtotime(date('Y-m-d', strtotime($arr["nextdate"]))) < $yesterday) { + $this->pdo->queryExec(sprintf("UPDATE tvrage SET prevdate = nextdate, previnfo = nextinfo WHERE id = %d", $arr['id'])); + $prev_ep = "SWAPPED with: " . $arr['nextinfo'] . " - " . date("r", strtotime($arr["nextdate"])); } - $next_ep = $epInfo['next']['episode'].', "'.$epInfo['next']['title'].'"'; - $query[] = sprintf("nextdate = FROM_UNIXTIME(%s), nextinfo = %s", $epInfo['next']['day_time'], $this->pdo->escapeString($next_ep)); - } - else - { - $query[] = "nextdate = null, nextinfo = null"; + $next_ep = $epInfo['next']['episode'] . ', "' . $epInfo['next']['title'] . '"'; + $query[] = sprintf("nextdate = %s, nextinfo = %s", $this->pdo->from_unixtime($epInfo['next']['day_time']), $this->pdo->escapeString($next_ep)); + } else { + $query[] = "nextdate = NULL, nextinfo = NULL"; } - // output - /* - if ($this->echooutput) - { - echo $epInfo['showname']." (".$showId."):\n"; - echo " -prev: {$prev_ep} - ".(isset($epInfo['prev']['day_time']) ? date("r",$epInfo['prev']['day_time']) : "")."\n"; - echo " -next: {$next_ep} - ".(isset($epInfo['next']['day_time']) ? date("r",$epInfo['next']['day_time']) : "")."\n"; + // Output. + if ($this->echooutput) { + echo $this->pdo->log->primary($epInfo['showname'] . " (" . $showId . "):"); + if (isset($epInfo['prev']['day_time'])) { + echo $this->pdo->log->headerOver("Prev EP: ") . $this->pdo->log->primary("{$prev_ep} - " . date("m/d/Y H:i T", $epInfo['prev']['day_time'])); + } + if (isset($epInfo['next']['day_time'])) { + echo $this->pdo->log->headerOver("Next EP: ") . $this->pdo->log->primary("{$next_ep} - " . date("m/d/Y H:i T", $epInfo['next']['day_time'])); + } + echo "\n"; } - */ - // update info - if (count($query) > 0) - { - $sql = str_ireplace("%", "%%", join(", ", $query)); - $sql = sprintf("update tvrage set {$sql} where id = %d", $arr['id']); + // Update info. + if (count($query) > 0) { + $sql = join(", ", $query); + $sql = sprintf("UPDATE tvrage SET {$sql} WHERE id = %d", $arr['id']); $this->pdo->queryExec($sql); } } } - } // end update series info + } + } else { + // No response from tvrage. + if ($this->echooutput) { + echo $this->pdo->log->info("Schedule not found."); + } } - } // end foreach country - - if ($this->echooutput) - echo "TVRage : Schedule complete...\n"; + } + if ($this->echooutput) { + echo $this->pdo->log->primary("Updated the TVRage schedule succesfully."); + } } public function getEpisodeInfo($rageid, $series, $episode) { - $result = array('title'=>'', 'airdate'=>''); + $result = ['title' => '', 'airdate' => '']; $series = str_ireplace("s", "", $series); $episode = str_ireplace("e", "", $episode); - - $lookupUrl = $this->xmlEpisodeInfoUrl."&sid=".$rageid."&ep=".$series."x".$episode; - - $xml = $this->fetchCache($lookupUrl); - if ($xml === false) - $xml = Utility::getUrl(['url' => $lookupUrl, 'verifycert' => false]); - - if ($xml !== false) - { - $this->storeCache($lookupUrl, $xml); - - if (preg_match('/no show found/i', $xml)) + $xml = Utility::getUrl(['url' => $this->xmlEpisodeInfoUrl . "&sid=" . $rageid . "&ep=" . $series . "x" . $episode]); + if ($xml !== false) { + if (preg_match('/no show found/i', $xml)) { return false; + } $xmlObj = @simplexml_load_string($xml); - $arrXml = objectsIntoArray($xmlObj); - if (is_array($arrXml)) - { - if (isset($arrXml['episode']['airdate']) && $arrXml['episode']['airdate'] != '0000-00-00') + $arrXml = Utility::objectsIntoArray($xmlObj); + if (is_array($arrXml)) { + if (isset($arrXml['episode']['airdate']) && $arrXml['episode']['airdate'] != '0000-00-00') { $result['airdate'] = $arrXml['episode']['airdate']; - if (isset($arrXml['episode']['title'])) + } + if (isset($arrXml['episode']['title'])) { $result['title'] = $arrXml['episode']['title']; + } return $result; } @@ -322,19 +487,11 @@ class TvRage public function getRageInfoFromPage($rageid) { - $result = array('desc'=>'', 'imgurl'=>''); - - $lookupUrl = $this->showInfoUrl.$rageid; - - $page = $this->fetchCache($lookupUrl); - if ($page === false) - $page = Utility::getUrl(['url' => $lookupUrl, 'verifycert' => false]); - - if ($page !== false) - { - $this->storeCache($lookupUrl, $page); - - //description + $result = ['desc' => '', 'imgurl' => '']; + $page = Utility::getUrl(['url' => $this->showInfoUrl . $rageid]); + $matches = ''; + if ($page !== false) { + // Description. preg_match('@
(.*?)
@is', $page, $matches); if (isset($matches[1])) { $desc = $matches[1]; @@ -349,7 +506,7 @@ class TvRage $desc = trim(preg_replace('/\s{2,}/', ' ', $desc)); $result['desc'] = $desc; } - // image + // Image. preg_match("@src=[\"'](http://images.tvrage.com/shows.*?)[\"']@i", $page, $matches); if (isset($matches[1])) { $result['imgurl'] = $matches[1]; @@ -358,28 +515,22 @@ class TvRage return $result; } + /** + * @param string $rageid + * + * @return array|bool|mixed + */ public function getRageInfoFromService($rageid) { - $result = array('genres'=>'', 'country'=>'', 'showid'=>$rageid); - - $lookupUrl = $this->xmlFullShowInfoUrl.$rageid; - - $xml = $this->fetchCache($lookupUrl); - if ($xml === false) - $xml = Utility::getUrl(['url' => $lookupUrl, 'verifycert' => false]); - - if ($xml !== false) - { - $this->storeCache($lookupUrl, $xml); - - $xml = str_replace('', '', $xml); - $xmlObj = @simplexml_load_string($xml); - $arrXml = Utility::objectsIntoArray($xmlObj); - - if (is_array($arrXml)) - { + $result = ['genres' => '', 'country' => '', 'showid' => $rageid]; + // Full search gives us the akas. + $xml = Utility::getUrl(['url' => $this->xmlShowInfoUrl . $rageid]); + if ($xml !== false) { + $arrXml = Utility::objectsIntoArray(simplexml_load_string($xml)); + if (is_array($arrXml)) { $result['genres'] = (isset($arrXml['genres'])) ? $arrXml['genres'] : ''; $result['country'] = (isset($arrXml['origin_country'])) ? $arrXml['origin_country'] : ''; + $result = $this->countryCode($result); return $result; } return false; @@ -387,606 +538,603 @@ class TvRage return false; } - public function updateEpInfo($show, $relid) + // + /** + * Convert 2012-24-07 to 2012-07-24, there is probably a better way + * + * This shouldn't ever happen as I've never heard of a date starting with year being followed by day value. + * Could this be a mistake? i.e. trying to solve the mm-dd-yyyy/dd-mm-yyyy confusion into a yyyy-mm-dd? + * + * @param string $date + * + * @return string + */ + public function checkDate($date) { - $this->pdo = new newznab\db\Settings; - - if (empty($show['airdate']) || !strtotime($show['airdate'])) { - $tvairdate = "null"; - } else { - $tvairdate = $this->pdo->escapestring($show['airdate']); - } - $this->pdo->queryExec(sprintf("update releases set seriesfull = %s, season = %s, episode = %s, tvairdate=%s where id = %d", - $this->pdo->escapeString($show['seriesfull']), $this->pdo->escapeString($show['season']), $this->pdo->escapeString($show['episode']), $tvairdate, $relid)); - } - - public function refreshRageInfo($id) - { - $row = $this->getByID($id); - $rageid = $row["rageid"]; - - $rInfo = $this->getRageInfoFromPage($rageid); - $desc = ''; - if (isset($rInfo['desc']) && !empty($rInfo['desc'])) - $desc = $rInfo['desc']; - - $imgbytes = ''; - if (isset($rInfo['imgurl']) && !empty($rInfo['imgurl'])) - { - $img = Utility::getUrl([$rInfo['imgurl']]); - if ($img !== false) - { - $im = @imagecreatefromstring($img); - if($im !== false) - $imgbytes = $img; + if (!empty($date)) { + $chk = explode(" ", $date); + $chkd = explode("-", $chk[0]); + if ($chkd[1] > 12) { + $date = date('Y-m-d H:i:s', strtotime($chkd[1] . " " . $chkd[2] . " " . $chkd[0])); } + } else { + $date = null; } - $sql = sprintf("update tvrage set description = %s, imgdata = %s where id = %d", $this->pdo->escapeString($desc), $this->pdo->escapeString($imgbytes), $id); - return $this->pdo->queryExec($sql); + return $date; + } + public function updateEpInfo($show, $relid) + { + if ($this->echooutput) { + echo $this->pdo->log->headerOver("Updating Episode: ") . $this->pdo->log->primary($show['cleanname'] . " " . $show['seriesfull'] . (($show['year'] != '') ? ' ' . $show['year'] : '') . (($show['country'] != '') ? ' [' . $show['country'] . ']' : '')); + } + + $tvairdate = (isset($show['airdate']) && !empty($show['airdate'])) ? $this->pdo->escapeString($this->checkDate($show['airdate'])) : "NULL"; + $this->pdo->queryExec(sprintf("UPDATE releases SET seriesfull = %s, season = %s, episode = %s, tvairdate = %s WHERE id = %d", $this->pdo->escapeString($show['seriesfull']), $this->pdo->escapeString($show['season']), $this->pdo->escapeString($show['episode']), $tvairdate, $relid)); } public function updateRageInfo($rageid, $show, $tvrShow, $relid) { - $this->pdo = new newznab\db\Settings; + // Try and get the episode specific info from tvrage. + $epinfo = $this->getEpisodeInfo($rageid, $show['season'], $show['episode']); + if ($epinfo !== false) { + $tvairdate = (!empty($epinfo['airdate'])) ? $this->pdo->escapeString($epinfo['airdate']) : "NULL"; + $tvtitle = (!empty($epinfo['title'])) ? $this->pdo->escapeString($epinfo['title']) : "NULL"; - $idCheck = $this->getByRageID($rageid); - - $epinfo = false; - - //check local releases to see if we already have the data - if ($idCheck && sizeof($idCheck) > 0) - { - $epinfo = $this->pdo->queryOneRow(sprintf("select tvtitle as title, tvairdate as airdate from releases where tvairdate is not null and season = %s and episode = %s and rageid = %d", $this->pdo->escapeString($show['season']), $this->pdo->escapeString($show['episode']), $idCheck[0]['rageid'])); - - //check tvdb episodeinfo data - if ($epinfo == false) - $epinfo = $this->pdo->queryOneRow(sprintf("select eptitle as title, airdate as airdate from episodeinfo where airdate is not null and fullep = %s and rageid = %d", $this->pdo->escapeString(str_replace('S', '', $show['season']).'x'.str_replace('E', '', $show['episode'])), $idCheck[0]['rageid'])); - } - - // try and get the episode specific info from tvrage if its not available locally - if ($epinfo == false) - $epinfo = $this->getEpisodeInfo($rageid, $show['season'], $show['episode']); - - if ($epinfo !== false) - { - $tvairdate = (!empty($epinfo['airdate'])) ? $this->pdo->escapeString($epinfo['airdate']) : "null"; - $tvtitle = (!empty($epinfo['title'])) ? $this->pdo->escapeString($epinfo['title']) : "null"; - - $this->pdo->queryExec(sprintf("update releases set tvtitle=trim(%s), tvairdate=%s, rageid = %d where id = %d", $tvtitle, $tvairdate, $tvrShow['showid'], $relid)); - } - else - { - $this->pdo->queryExec(sprintf("update releases set rageid = %d where id = %d", $tvrShow['showid'], $relid)); + $this->pdo->queryExec(sprintf("UPDATE releases set tvtitle = %s, tvairdate = %s, rageid = %d where id = %d", $this->pdo->escapeString(trim($tvtitle)), $tvairdate, $tvrShow['showid'], $relid)); + } else { + $this->pdo->queryExec(sprintf("UPDATE releases SET rageid = %d WHERE id = %d", $tvrShow['showid'], $relid)); } $genre = ''; - if (isset($tvrShow['genres']) && is_array($tvrShow['genres']) && !empty($tvrShow['genres'])) - { - if (is_array($tvrShow['genres']['genre'])) + if (isset($tvrShow['genres']) && is_array($tvrShow['genres']) && !empty($tvrShow['genres'])) { + if (is_array($tvrShow['genres']['genre'])) { $genre = implode('|', $tvrShow['genres']['genre']); - else + } else { $genre = $tvrShow['genres']['genre']; + } } $country = ''; - if (isset($tvrShow['country']) && !empty($tvrShow['country'])) - $country = $tvrShow['country']; + if (isset($tvrShow['country']) && !empty($tvrShow['country'])) { + $country = $this->countryCode($tvrShow['country']); + } $rInfo = $this->getRageInfoFromPage($rageid); $desc = ''; - if (isset($rInfo['desc']) && !empty($rInfo['desc'])) + if (isset($rInfo['desc']) && !empty($rInfo['desc'])) { $desc = $rInfo['desc']; + } $imgbytes = ''; - if (isset($rInfo['imgurl']) && !empty($rInfo['imgurl'])) - { - $img = Utility::getUrl([$rInfo['imgurl']]); - if ($img !== false) - { + if (isset($rInfo['imgurl']) && !empty($rInfo['imgurl'])) { + $img = Utility::getUrl(['url' => $rInfo['imgurl']]); + if ($img !== false) { $im = @imagecreatefromstring($img); - if($im !== false) + if ($im !== false) { $imgbytes = $img; + } + } + } + $this->add($rageid, $show['cleanname'], $desc, $genre, $country, $imgbytes); + } + + public function updateRageInfoTrakt($rageid, $show, $traktArray, $relid) + { + // Try and get the episode specific info from tvrage. + $epinfo = $this->getEpisodeInfo($rageid, $show['season'], $show['episode']); + if ($epinfo !== false) { + $tvairdate = (!empty($epinfo['airdate'])) ? $this->pdo->escapeString($epinfo['airdate']) : "NULL"; + $tvtitle = (!empty($epinfo['title'])) ? $this->pdo->escapeString($epinfo['title']) : "NULL"; + $this->pdo->queryExec(sprintf("UPDATE releases SET tvtitle = %s, tvairdate = %s, rageid = %d WHERE id = %d", $this->pdo->escapeString(trim($tvtitle)), $tvairdate, $traktArray['ids']['tvrage'], $relid)); + } else { + $this->pdo->queryExec(sprintf("UPDATE releases SET rageid = %d WHERE id = %d", $traktArray['ids']['tvrage'], $relid)); + } + + $genre = $country = ''; + + $rInfo = $this->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; + } } } $this->add($rageid, $show['cleanname'], $desc, $genre, $country, $imgbytes); } - public function processTvReleases($lookupTvRage=true, $numtoProcess=100) + public function processTvReleases($groupID = '', $guidChar = '', $lookupTvRage = 1, $local = false) { $ret = 0; - $nfo = new Nfo(); + if ($lookupTvRage == 0) { + return $ret; + } + $trakt = new TraktTv(['Settings' => $this->pdo]); - // get all releases without a rageid which are in a tv category. - $result = $this->pdo->queryDirect(sprintf("SELECT searchname, id from releases where rageid = -1 and categoryid in ( select id from category where parentid = %d ) order by postdate desc limit %d ", Category::CAT_PARENT_TV, $numtoProcess)); + // Get all releases without a rageid which are in a tv category. - if ($this->pdo->getNumRows($result) > 0) - { - if ($this->echooutput) - echo "TVRage : Looking up ".$this->pdo->getNumRows($result)." releases".($lookupTvRage?" using local and web\n":" local only\n"); + $res = $this->pdo->query( + sprintf(" + SELECT r.searchname, r.id + FROM releases r + WHERE r.nzbstatus = 1 + AND r.rageid = -1 + AND r.size > 1048576 + AND r.categoryid BETWEEN 5000 AND 5999 + %s %s %s + ORDER BY r.postdate DESC + LIMIT %d", + ($groupID === '' ? '' : 'AND r.groupid = ' . $groupID), + ($guidChar === '' ? '' : 'AND r.guid ' . $this->pdo->likeString($guidChar, false, true)), + ($lookupTvRage == 2 ? 'AND r.isrenamed = 1' : ''), + $this->rageqty + ) + ); + $tvcount = count($res); - while ($arr = $this->pdo->getAssocArray($result)) - { - $rageID = false; - /* Preliminary Rage id Detection from NFO file */ - $rawnfo = ''; - if($nfo->getNfo($arr['id'], $rawnfo)) - $rageID = $this->parseRageIdFromNfo($rawnfo); + if ($this->echooutput && $tvcount > 1) { + echo $this->pdo->log->header("Processing TV for " . $tvcount . " release(s)."); + } - if($rageID){ - // Set RageID (if matched db) and move along - $res = $this->pdo->query(sprintf("SELECT count(id) as cnt from tvrage where rageid = %d", $rageID)); - if(count($res) >= 1 && intval($res[0]['cnt']) > 1) - { - $this->pdo->queryExec(sprintf("update releases set rageid = %d where id = %d", $rageID, $arr["id"])); - continue; - } - } + foreach ($res as $arr) { + $show = $this->parseNameEpSeason($arr['searchname']); + if (is_array($show) && $show['name'] != '') { + // Update release with season, ep, and airdate info (if available) from releasetitle. + $this->updateEpInfo($show, $arr['id']); - $show = $this->parseNameEpSeason($arr['searchname']); - if (is_array($show) && $show['name'] != '') - { - // update release with season, ep, and airdate info (if available) from releasetitle - $this->updateEpInfo($show, $arr['id']); + // Find the rageID. + $id = $this->getByTitle($show['cleanname']); - // find the rageid - $id = $this->getByTitle($show['cleanname']); + // Force local lookup only + if ($local == true) { + $lookupTvRage = false; + } - if ($id === false && $lookupTvRage) - { - // if it doesnt exist locally and lookups are allowed lets try to get it - if ($this->echooutput) - echo "TVRage : Didnt find ".$show['cleanname']." locally, checking web\n"; + if ($id === false && $lookupTvRage) { + // If it doesnt exist locally and lookups are allowed lets try to get it. + if ($this->echooutput) { + echo $this->pdo->log->primaryOver("TVRage ID for ") . $this->pdo->log->headerOver($show['cleanname']) . $this->pdo->log->primary(" not found in local db, checking web."); + } - $tvrShow = $this->getRageMatch($show); - if ($tvrShow !== false && is_array($tvrShow)) - { - // get all tv info and add show - $this->updateRageInfo($tvrShow['showid'], $show, $tvrShow, $arr['id']); - } - elseif ($tvrShow === false) - { - // no match - //add to tvrage with rageid = -2 and $show['cleanname'] title only - $this->add(-2, $show['cleanname'], '', '', '', ''); - } - else - { - // $tvrShow probably equals -1 but we'll do this as a catchall instead of a specific elseif + $tvrShow = $this->getRageMatch($show); + if ($tvrShow !== false && is_array($tvrShow)) { + // Get all tv info and add show. + $this->updateRageInfo($tvrShow['showid'], $show, $tvrShow, $arr['id']); + } else if ($tvrShow === false) { + // If tvrage fails, try trakt. + $traktArray = $trakt->episodeSummary($show['name'], $show['season'], $show['episode']); + if ($traktArray !== false) { + if (isset($traktArray['ids']['tvrage']) && $traktArray['ids']['tvrage'] !== 0) { + if ($this->echooutput) { + echo $this->pdo->log->primary('Found TVRage ID on trakt:' . $traktArray['ids']['tvrage']); + } + $this->updateRageInfoTrakt($traktArray['ids']['tvrage'], $show, $traktArray, $arr['id']); + } + // No match, add to tvrage with rageID = -2 and $show['cleanname'] title only. + else { + $this->add(-2, $show['cleanname'], '', '', '', ''); + } + } + // No match, add to tvrage with rageID = -2 and $show['cleanname'] title only. + else { + $this->add(-2, $show['cleanname'], '', '', '', ''); + } + } else { + // $tvrShow probably equals -1 but we'll do this as a catchall instead of a specific else if. + // Skip because we couldnt connect to tvrage.com. + } + } else if ($id > 0) { + //if ($this->echooutput) { + // echo $this->pdo->log->AlternateOver("TV series: ") . $this->pdo->log->header($show['cleanname'] . " " . $show['seriesfull'] . (($show['year'] != '') ? ' ' . $show['year'] : '') . (($show['country'] != '') ? ' [' . $show['country'] . ']' : '')); + // } + $tvairdate = (isset($show['airdate']) && !empty($show['airdate'])) ? $this->pdo->escapeString($this->checkDate($show['airdate'])) : "NULL"; + $tvtitle = "NULL"; - //skip because we couldnt connect to tvrage.com - } - - } - elseif ($id > 0) - { - $tvairdate = (isset($show['airdate']) && !empty($show['airdate'])) ? $this->pdo->escapeString($show['airdate']) : "null"; - $tvtitle = "null"; - - if ($lookupTvRage) - { - if ($tvairdate == "null") - { - - //check local releases to see if we already have the data - $epinfo = $this->pdo->queryOneRow(sprintf("select tvtitle as title, tvairdate as airdate from releases where tvairdate is not null and season = %s and episode = %s and rageid = %d", $this->pdo->escapeString($show['season']), $this->pdo->escapeString($show['episode']), $id)); - - //check tvdb episodeinfo data - if ($epinfo == false) - { - $sql = sprintf("select eptitle as title, airdate as airdate from episodeinfo where airdate is not null and fullep = %s and rageid = %d", $this->pdo->escapeString(str_replace('S', '', $show['season']).'x'.str_replace('E', '', $show['episode'])), $id); - $epinfo = $this->pdo->queryOneRow($sql); - } - - if ($epinfo == false) - $epinfo = $this->getEpisodeInfo($id, $show['season'], $show['episode']); - - if ($epinfo !== false) - { - if (!empty($epinfo['airdate'])) - $tvairdate = $this->pdo->escapeString($epinfo['airdate']); - - if (!empty($epinfo['title'])) - $tvtitle = $this->pdo->escapeString($epinfo['title']); - } - } - } - $this->pdo->queryExec(sprintf("update releases set tvtitle=trim(%s), tvairdate=%s, rageid = %d where id = %d", $tvtitle, $tvairdate, $id, $arr["id"])); - } - else - { - // cant find rageid, so set rageid to n/a - $this->pdo->queryExec(sprintf("update releases set rageid = -2 where id = %d", $arr["id"])); - } - } - else - { - // not a tv episode, so set rageid to n/a - $this->pdo->queryExec(sprintf("update releases set rageid = -2 where id = %d", $arr["id"])); - } - $ret++; - } - - } + if ($lookupTvRage) { + $epinfo = $this->getEpisodeInfo($id, $show['season'], $show['episode']); + if ($epinfo !== false) { + if (isset($epinfo['airdate'])) { + $tvairdate = $this->pdo->escapeString($this->checkDate($epinfo['airdate'])); + } + if (!empty($epinfo['title'])) { + $tvtitle = $this->pdo->escapeString(trim($epinfo['title'])); + } + } + } + if ($tvairdate == "NULL") { + $this->pdo->queryExec(sprintf('UPDATE releases SET tvtitle = %s, rageid = %d WHERE id = %d', $tvtitle, $id, $arr['id'])); + } else { + $this->pdo->queryExec(sprintf('UPDATE releases SET tvtitle = %s, tvairdate = %s, rageid = %d WHERE id = %d', $tvtitle, $tvairdate, $id, $arr['id'])); + } + // Cant find rageid, so set rageid to n/a. + } else { + $this->pdo->queryExec(sprintf('UPDATE releases SET rageid = -2 WHERE id = %d', $arr['id'])); + } + // Not a tv episode, so set rageid to n/a. + } else { + $this->pdo->queryExec(sprintf('UPDATE releases SET rageid = -2 WHERE id = %d', $arr['id'])); + } + $ret++; + } return $ret; } 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 = []; - $lookupUrl = $this->xmlFullSearchUrl.urlencode(strtolower($title)); - - $xml = $this->fetchCache($lookupUrl); - if ($xml === false) - $xml = Utility::getUrl(['url' => $lookupUrl, 'verifycert' => false]); - - if ($xml !== false) - { - $this->storeCache($lookupUrl, $xml); - - $xml = str_replace('', '', $xml); - $xmlObj = @simplexml_load_string($xml); - $arrXml = Utility::objectsIntoArray($xmlObj); - - if (isset($arrXml['show']) && is_array($arrXml['show'])) - { - // 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 + 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) - { - $titlepct = $urlpct = $akapct = 0; + foreach ($arrXml['show'] as $arr) { + $tvrlink = ''; - // get a match percentage based on our name and the name returned from tvr + // 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][] = array('title'=>$arr['name'], 'showid'=>$arr['showid'], 'country'=>$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][] = array('title'=>$urltitle, 'showid'=>$arr['showid'], 'country'=>$arr['country'], 'genres'=>$arr['genres'], 'tvr'=>$arr); + if ($titlepct !== false) { + $titleMatches[$titlepct][] = ['title' => $arr['name'], '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'])) - { - if (is_array($arr['akas']['aka'])) - { - // multuple akas - foreach($arr['akas']['aka'] as $aka) - { - $akapct = $this->checkMatch($title, $aka); - if ($akapct !== false) - $akaMatches[$akapct][] = array('title'=>$aka, 'showid'=>$arr['showid'], 'country'=>$arr['country'], 'genres'=>$arr['genres'], 'tvr'=>$arr); - } - } else { - // one aka - $akapct = $this->checkMatch($title, $arr['akas']['aka']); - if ($akapct !== false) - $akaMatches[$akapct][] = array('title'=>$arr['akas']['aka'], 'showid'=>$arr['showid'], 'country'=>$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 + // 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 'TVRage : Found 100% match: "'.$titleMatches[100][0]['title'].'"'."\n"; + // 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 'TVRage : Found 100% url match: "'.$urlMatches[100][0]['title'].'"'."\n"; + // 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 'TVRage : Found 100% aka match: "'.$akaMatches[100][0]['title'].'"'."\n"; + // 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'])) + // 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 'TVRage : Found '.$mk.'% match: "'.$titleMatches[$mk][0]['title'].'"'."\n"; + 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'])) + // 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 'TVRage : Found '.$ak.'% aka match: "'.$akaMatches[$ak][0]['title'].'"'."\n"; + 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 { - if ($this->echooutput) - echo 'TVRage : Error connecting to tvrage'."\n"; return -1; } - - if ($this->echooutput) - echo 'TVRage : No match found online'."\n"; - return false; } public function checkMatch($ourName, $tvrName) { - // clean up name ($ourName is already clean) + // Clean up name ($ourName is already clean). $tvrName = $this->cleanName($tvrName); $tvrName = preg_replace('/ of /i', '', $tvrName); $ourName = preg_replace('/ of /i', '', $ourName); - // create our arrays + // Create our arrays. $ourArr = explode(' ', $ourName); $tvrArr = explode(' ', $tvrName); - // set our match counts + // Set our match counts. $numMatches = 0; - $totalMatches = sizeof($ourArr)+sizeof($tvrArr); + $totalMatches = sizeof($ourArr) + sizeof($tvrArr); - // loop through each array matching again the opposite value, if they match increment! - foreach($ourArr as $oname) - { - if (preg_match('/ '.preg_quote($oname, '/').' /i', ' '.$tvrName.' ')) + // Loop through each array matching again the opposite value, if they match increment! + foreach ($ourArr as $oname) { + if (preg_match('/ ' . preg_quote($oname, '/') . ' /i', ' ' . $tvrName . ' ')) { $numMatches++; + } } - foreach($tvrArr as $tname) - { - if (preg_match('/ '.preg_quote($tname, '/').' /i', ' '.$ourName.' ')) + foreach ($tvrArr as $tname) { + if (preg_match('/ ' . preg_quote($tname, '/') . ' /i', ' ' . $ourName . ' ')) { $numMatches++; + } } - // check what we're left with - if ($numMatches <= 0) + // Check what we're left with. + if ($numMatches <= 0) { return false; - else - $matchpct = ($numMatches/$totalMatches)*100; + } else { + $matchpct = ($numMatches / $totalMatches) * 100; + } - if ($matchpct >= TvRage::MATCH_PROBABILITY) + if ($matchpct >= TvRage::MATCH_PROBABILITY) { return $matchpct; - else + } else { return false; + } } public function cleanName($str) { - $str = str_replace(array('.', '_', '-'), ' ', $str); + $str = str_replace(['.', '_'], ' ', $str); - $str = str_replace(array('à','á','â','ã','ä','æ','À','Á','Â','Ã','Ä'), 'a', $str); - $str = str_replace(array('ç','Ç'), 'c', $str); - $str = str_replace(array('Σ','è','é','ê','ë','È','É','Ê','Ë'), 'e', $str); - $str = str_replace(array('ì','í','î','ï','Ì','Í','Î','Ï'), 'i', $str); - $str = str_replace(array('ò','ó','ô','õ','ö','Ò','Ó','Ô','Õ','Ö'), 'o', $str); - $str = str_replace(array('ù','ú','û','ü','ū','Ú','Û','Ü','Ū'), 'u', $str); + $str = str_replace(['à', 'á', 'â', 'ã', 'ä', 'æ', 'À', 'Á', 'Â', 'Ã', 'Ä'], 'a', $str); + $str = str_replace(['ç', 'Ç'], 'c', $str); + $str = str_replace(['Σ', 'è', 'é', 'ê', 'ë', 'È', 'É', 'Ê', 'Ë'], 'e', $str); + $str = str_replace(['ì', 'í', 'î', 'ï', 'Ì', 'Í', 'Î', 'Ï'], 'i', $str); + $str = str_replace(['ò', 'ó', 'ô', 'õ', 'ö', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö'], 'o', $str); + $str = str_replace(['ù', 'ú', 'û', 'ü', 'ū', 'Ú', 'Û', 'Ü', 'Ū'], 'u', $str); $str = str_replace('ß', 'ss', $str); $str = str_replace('&', 'and', $str); $str = preg_replace('/^(history|discovery) channel/i', '', $str); - $str = str_replace(array('\'', ':', '!', '"', '#', '*', '’', ',', '(', ')', '?'), '', $str); + $str = str_replace(['\'', ':', '!', '"', '#', '*', '’', ',', '(', ')', '?'], '', $str); $str = str_replace('$', 's', $str); $str = preg_replace('/\s{2,}/', ' ', $str); + $str = trim($str, '\"'); return trim($str); } - public function fetchCache($key) - { - $cache = new Cache; - $ret = $cache->get($key); - if ($ret !== false) { - return $ret; - } - return false; - } - - public function storeCache($key, $data) - { - $cache = new Cache; - $ret = $cache->set($key, $data, 900); - if ($ret !== false){ - return $ret; - } - - return false; - } - public function parseNameEpSeason($relname) { - $showInfo = array( - 'name' => '', - 'season' => '', - 'episode' => '', - 'seriesfull' => '', - 'airdate' => '', - 'country' => '', - 'year' => '', - 'cleanname' => '' - ); + $showInfo = ['name' => '', 'season' => '', 'episode' => '', 'seriesfull' => '', 'airdate' => '', 'country' => '', 'year' => '', 'cleanname' => '']; + $matches = ''; - //S01E01-E02 - //S01E01-02 - if (preg_match('/^(.*?)[\. \-]s(\d{1,2})\.?e(\d{1,3})(?:\-e?|\-?e)(\d{1,3})\./i', $relname, $matches)) { + $following = '[^a-z0-9](\d\d-\d\d|\d{1,2}x\d{2,3}|(19|20)\d\d|(480|720|1080)[ip]|AAC2?|BDRip|BluRay|D0?\d|DD5|DiVX|DLMux|DTS|DVD(Rip)?|E\d{2,3}|[HX][-_. ]?264|ITA(-ENG)?|[HPS]DTV|PROPER|REPACK|S\d+[^a-z0-9]?(E\d+)?|WEB[-_. ]?(DL|Rip)|XViD)[^a-z0-9]'; + + // For names that don't start with the title. + if (preg_match('/[^a-z0-9]{2,}(?P[\w .-]*?)' . $following . '/i', $relname, $matches)) { $showInfo['name'] = $matches[1]; - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = array(intval($matches[3]), intval($matches[4])); - //S01E0102 - lame no delimit numbering, regex would collide if there was ever 1000 ep season - } elseif (preg_match('/^(.*?)[\. \-]s(\d{2})\.?e(\d{2})(\d{2})\./i', $relname, $matches)) { + } else if (preg_match('/^(?P[a-z0-9][\w .-]*?)' . $following . '/i', $relname, $matches)) { + // For names that start with the title. $showInfo['name'] = $matches[1]; - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = array(intval($matches[3]), intval($matches[4])); - //S01E01 - //S01.E01 - } elseif (preg_match('/^(.*?)[\. \-]s(\d{1,2})\.?e(\d{1,3})\.?/i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = intval($matches[3]); - //S01 - } elseif (preg_match('/^(.*?)[\. \-]s(\d{1,2})\./i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = 'all'; - //S01D1 - //S1D1 - } elseif (preg_match('/^(.*?)[\. \-]s(\d{1,2})d\d{1}\./i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = 'all'; - //1x01 - } elseif (preg_match('/^(.*?)[\. \-](\d{1,2})x(\d{1,3})\./i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = intval($matches[3]); - //2009.01.01 - //2009-01-01 - } elseif (preg_match('/^(.*?)[\. \-](19|20)(\d{2})[\.\-](\d{2})[\.\-](\d{2})\./i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = $matches[2].$matches[3]; - $showInfo['episode'] = $matches[4].'/'.$matches[5]; - $showInfo['airdate'] = $matches[2].$matches[3].'-'.$matches[4].'-'.$matches[5]; //yy-m-d - //01.01.2009 - } elseif (preg_match('/^(.*?)[\. \-](\d{2}).(\d{2})\.(19|20)(\d{2})\./i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = $matches[4].$matches[5]; - $showInfo['episode'] = $matches[2].'/'.$matches[3]; - $showInfo['airdate'] = $matches[4].$matches[5].'-'.$matches[2].'-'.$matches[3]; //yy-m-d - //01.01.09 - } elseif (preg_match('/^(.*?)[\. \-](\d{2}).(\d{2})\.(\d{2})\./i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = ($matches[4] <= 99 && $matches[4] > 15) ? '19'.$matches[4] : '20'.$matches[4]; - $showInfo['episode'] = $matches[2].'/'.$matches[3]; - $showInfo['airdate'] = $showInfo['season'].'-'.$matches[2].'-'.$matches[3]; //yy-m-d - //2009.E01 - } elseif (preg_match('/^(.*?)[\. \-]20(\d{2})\.e(\d{1,3})\./i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = '20'.$matches[2]; - $showInfo['episode'] = intval($matches[3]); - //2009.Part1 - } elseif (preg_match('/^(.*?)[\. \-]20(\d{2})\.Part(\d{1,2})\./i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = '20'.$matches[2]; - $showInfo['episode'] = intval($matches[3]); - //Part1/Pt1 - } elseif (preg_match('/^(.*?)[\. \-](?:Part|Pt)\.?(\d{1,2})\./i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = 1; - $showInfo['episode'] = intval($matches[2]); - //The.Pacific.Pt.VI.HDTV.XviD-XII / Part.IV - } elseif (preg_match('/^(.*?)[\. \-](?:Part|Pt)\.?([ivx]+)/i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = 1; - $epLow = strtolower($matches[2]); - switch($epLow) { - case 'i': $e = 1; break; - case 'ii': $e = 2; break; - case 'iii': $e = 3; break; - case 'iv': $e = 4; break; - case 'v': $e = 5; break; - case 'vi': $e = 6; break; - case 'vii': $e = 7; break; - case 'viii': $e = 8; break; - case 'ix': $e = 9; break; - case 'x': $e = 10; break; - case 'xi': $e = 11; break; - case 'xii': $e = 12; break; - case 'xiii': $e = 13; break; - case 'xiv': $e = 14; break; - case 'xv': $e = 15; break; - case 'xvi': $e = 16; break; - case 'xvii': $e = 17; break; - case 'xviii': $e = 18; break; - case 'xix': $e = 19; break; - case 'xx': $e = 20; break; - } - $showInfo['episode'] = $e; - //Band.Of.Brothers.EP06.Bastogne.DVDRiP.XviD-DEiTY - } elseif (preg_match('/^(.*?)[\. \-]EP?\.?(\d{1,3})/i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = 1; - $showInfo['episode'] = intval($matches[2]); - //Season.1 - } elseif (preg_match('/^(.*?)[\. \-]Seasons?\.?(\d{1,2})/i', $relname, $matches)) { - $showInfo['name'] = $matches[1]; - $showInfo['season'] = intval($matches[2]); - $showInfo['episode'] = 'all'; } if (!empty($showInfo['name'])) { - //country or origin matching - if (preg_match('/[\._ ](US|UK|AU|NZ|CA|NL|Canada|Australia|America)/', $showInfo['name'], $countryMatch)) - { - if (strtolower($countryMatch[1]) == 'canada') - $showInfo['country'] = 'CA'; - elseif (strtolower($countryMatch[1]) == 'australia') - $showInfo['country'] = 'AU'; - elseif (strtolower($countryMatch[1]) == 'america') - $showInfo['country'] = 'US'; - else - $showInfo['country'] = strtoupper($countryMatch[1]); + // S01E01-E02 and S01E01-02 + if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?e(\d{1,3})(?:[e-])(\d{1,3})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = intval($matches[2]); + $showInfo['episode'] = [intval($matches[3]), intval($matches[4])]; + } + //S01E0102 - lame no delimit numbering, regex would collide if there was ever 1000 ep season. + else if (preg_match('/^(.*?)[^a-z0-9]s(\d{2})[^a-z0-9]?e(\d{2})(\d{2})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = intval($matches[2]); + $showInfo['episode'] = [intval($matches[3]), intval($matches[4])]; + } + // S01E01 and S01.E01 + else if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?e(\d{1,3})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = intval($matches[2]); + $showInfo['episode'] = intval($matches[3]); + } + // S01 + else if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = intval($matches[2]); + $showInfo['episode'] = 'all'; + } + // S01D1 and S1D1 + else if (preg_match('/^(.*?)[^a-z0-9]s(\d{1,2})[^a-z0-9]?d\d{1}[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = intval($matches[2]); + $showInfo['episode'] = 'all'; + } + // 1x01 + else if (preg_match('/^(.*?)[^a-z0-9](\d{1,2})x(\d{1,3})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = intval($matches[2]); + $showInfo['episode'] = intval($matches[3]); + } + // 2009.01.01 and 2009-01-01 + else if (preg_match('/^(.*?)[^a-z0-9](19|20)(\d{2})[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = $matches[2] . $matches[3]; + $showInfo['episode'] = $matches[4] . '/' . $matches[5]; + $showInfo['airdate'] = $matches[2] . $matches[3] . '-' . $matches[4] . '-' . $matches[5]; //yy-m-d + } + // 01.01.2009 + else if (preg_match('/^(.*?)[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9](19|20)(\d{2})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = $matches[4] . $matches[5]; + $showInfo['episode'] = $matches[2] . '/' . $matches[3]; + $showInfo['airdate'] = $matches[4] . $matches[5] . '-' . $matches[2] . '-' . $matches[3]; //yy-m-d + } + // 01.01.09 + else if (preg_match('/^(.*?)[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9](\d{2})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = ($matches[4] <= 99 && $matches[4] > 15) ? '19' . $matches[4] : '20' . $matches[4]; + $showInfo['episode'] = $matches[2] . '/' . $matches[3]; + $showInfo['airdate'] = $showInfo['season'] . '-' . $matches[2] . '-' . $matches[3]; //yy-m-d + } + // 2009.E01 + else if (preg_match('/^(.*?)[^a-z0-9]20(\d{2})[^a-z0-9](\d{1,3})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = '20' . $matches[2]; + $showInfo['episode'] = intval($matches[3]); + } + // 2009.Part1 + else if (preg_match('/^(.*?)[^a-z0-9](19|20)(\d{2})[^a-z0-9]Part(\d{1,2})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = $matches[2] . $matches[3]; + $showInfo['episode'] = intval($matches[4]); + } + // Part1/Pt1 + else if (preg_match('/^(.*?)[^a-z0-9](?:Part|Pt)[^a-z0-9](\d{1,2})[^a-z0-9]/i', $relname, $matches)) { + $showInfo['season'] = 1; + $showInfo['episode'] = intval($matches[2]); + } + //The.Pacific.Pt.VI.HDTV.XviD-XII / Part.IV + else if (preg_match('/^(.*?)[^a-z0-9](?:Part|Pt)[^a-z0-9]([ivx]+)/i', $relname, $matches)) { + $showInfo['season'] = 1; + $epLow = strtolower($matches[2]); + switch ($epLow) { + case 'i': $e = 1; + break; + case 'ii': $e = 2; + break; + case 'iii': $e = 3; + break; + case 'iv': $e = 4; + break; + case 'v': $e = 5; + break; + case 'vi': $e = 6; + break; + case 'vii': $e = 7; + break; + case 'viii': $e = 8; + break; + case 'ix': $e = 9; + break; + case 'x': $e = 10; + break; + case 'xi': $e = 11; + break; + case 'xii': $e = 12; + break; + case 'xiii': $e = 13; + break; + case 'xiv': $e = 14; + break; + case 'xv': $e = 15; + break; + case 'xvi': $e = 16; + break; + case 'xvii': $e = 17; + break; + case 'xviii': $e = 18; + break; + case 'xix': $e = 19; + break; + case 'xx': $e = 20; + break; + default: + $e = 0; + } + $showInfo['episode'] = $e; + } + // Band.Of.Brothers.EP06.Bastogne.DVDRiP.XviD-DEiTY + else if (preg_match('/^(.*?)[^a-z0-9]EP?[^a-z0-9]?(\d{1,3})/i', $relname, $matches)) { + $showInfo['season'] = 1; + $showInfo['episode'] = intval($matches[2]); + } + // Season.1 + else if (preg_match('/^(.*?)[^a-z0-9]Seasons?[^a-z0-9]?(\d{1,2})/i', $relname, $matches)) { + $showInfo['season'] = intval($matches[2]); + $showInfo['episode'] = 'all'; } - //clean show name + $countryMatch = $yearMatch = ''; + // Country or origin matching. + if (preg_match('/\W(US|UK|AU|NZ|CA|NL|Canada|Australia|America|United[^a-z0-9]States|United[^a-z0-9]Kingdom)\W/', $showInfo['name'], $countryMatch)) { + $currentCountry = strtolower($countryMatch[1]); + if ($currentCountry == 'canada') { + $showInfo['country'] = 'CA'; + } else if ($currentCountry == 'australia') { + $showInfo['country'] = 'AU'; + } else if ($currentCountry == 'america' || $currentCountry == 'united states') { + $showInfo['country'] = 'US'; + } else if ($currentCountry == 'united kingdom') { + $showInfo['country'] = 'UK'; + } else { + $showInfo['country'] = strtoupper($countryMatch[1]); + } + } + + // Clean show name. $showInfo['cleanname'] = $this->cleanName($showInfo['name']); - //check for dates instead of seasons + // Check for dates instead of seasons. if (strlen($showInfo['season']) == 4) { - $showInfo['seriesfull'] = $showInfo['season']."/".$showInfo['episode']; + $showInfo['seriesfull'] = $showInfo['season'] . "/" . $showInfo['episode']; } else { - //get year if present (not for releases with dates as seasons) - if (preg_match('/[\._ ](19|20)(\d{2})/i', $relname, $yearMatch)) - $showInfo['year'] = $yearMatch[1].$yearMatch[2]; + // Get year if present (not for releases with dates as seasons). + if (preg_match('/[^a-z0-9](19|20)(\d{2})/i', $relname, $yearMatch)) { + $showInfo['year'] = $yearMatch[1] . $yearMatch[2]; + } $showInfo['season'] = sprintf('S%02d', $showInfo['season']); - //check for multi episode release + // Check for multi episode release. if (is_array($showInfo['episode'])) { $tmpArr = []; foreach ($showInfo['episode'] as $ep) { @@ -996,72 +1144,21 @@ class TvRage } else { $showInfo['episode'] = sprintf('E%02d', $showInfo['episode']); } - $showInfo['seriesfull'] = $showInfo['season'].$showInfo['episode']; + + $showInfo['seriesfull'] = $showInfo['season'] . $showInfo['episode']; } - $showInfo['airdate'] = (!empty($showInfo['airdate'])) ? $showInfo['airdate'].' 00:00:00' : ''; + $showInfo['airdate'] = (!empty($showInfo['airdate'])) ? $showInfo['airdate'] . ' 00:00:00' : ''; return $showInfo; } - return false; } public function getGenres() - { - return array( - 'Action', - 'Adult/Porn', - 'Adventure', - 'Anthology', - 'Arts & Crafts', - 'Automobiles', - 'Buy, Sell & Trade', - 'Celebrities', - 'Children', - 'Cinema/Theatre', - 'Comedy', - 'Cooking/Food', - 'Crime', - 'Current Events', - 'Dance', - 'Debate', - 'Design/Decorating', - 'Discovery/Science', - 'Drama', - 'Educational', - 'Family', - 'Fantasy', - 'Fashion/Make-up', - 'Financial/Business', - 'Fitness', - 'Garden/Landscape', - 'History', - 'Horror/Supernatural', - 'Housing/Building', - 'How To/Do It Yourself', - 'Interview', - 'Lifestyle', - 'Literature', - 'Medical', - 'Military/War', - 'Music', - 'Mystery', - 'Pets/Animals', - 'Politics', - 'Puppets', - 'Religion', - 'Romance/Dating', - 'Sci-Fi', - 'Sketch/Improv', - 'Soaps', - 'Sports', - 'Super Heroes', - 'Talent', - 'Tech/Gaming', - 'Teens', - 'Thriller', - 'Travel', - 'Western', - 'Wildlife' - ); - } -} + { + return ['Action', 'Adult/Porn', 'Adventure', 'Anthology', 'Arts & Crafts', 'Automobiles', 'Buy, Sell & Trade', 'Celebrities', 'Children', 'Cinema/Theatre', 'Comedy', 'Cooking/Food', 'Crime', 'Current Events', + 'Dance', 'Debate', 'Design/Decorating', 'Discovery/Science', 'Drama', 'Educational', 'Family', 'Fantasy', 'Fashion/Make-up', 'Financial/Business', 'Fitness', 'Garden/Landscape', 'History', + 'Horror/Supernatural', 'Housing/Building', 'How To/Do It Yourself', 'Interview', 'Lifestyle', 'Literature', 'Medical', 'Military/War', 'Music', 'Mystery', 'Pets/Animals', 'Politics', 'Puppets', + 'Religion', 'Romance/Dating', 'Sci-Fi', 'Sketch/Improv', 'Soaps', 'Sports', 'Super Heroes', 'Talent', 'Tech/Gaming', 'Teens', 'Thriller', 'Travel', 'Western', 'Wildlife']; + } + +} \ No newline at end of file diff --git a/newznab/processing/PProcess.php b/newznab/processing/PProcess.php index 607216e0f..718b35e72 100644 --- a/newznab/processing/PProcess.php +++ b/newznab/processing/PProcess.php @@ -267,7 +267,7 @@ class PProcess { $processTV = (is_numeric($processTV) ? $processTV : $this->pdo->getSetting('lookuptvrage')); if ($processTV > 0) { - (new \TvAnger(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processTvReleases($groupID, $guidChar, $processTV); + (new \TvRage(['Echo' => $this->echooutput, 'Settings' => $this->pdo]))->processTvReleases($groupID, $guidChar, $processTV); } } diff --git a/www/pages/calendar.php b/www/pages/calendar.php index 14c561f1c..a8da23431 100644 --- a/www/pages/calendar.php +++ b/www/pages/calendar.php @@ -4,7 +4,7 @@ if (!$page->users->isLoggedIn()) { $page->show403(); } -$tvrage = new TvAnger(['Settings' => $page->settings]); +$tvrage = new TvRage(['Settings' => $page->settings]); $date = date("Y-m-d"); if (isset($_GET["date"])) { diff --git a/www/pages/details.php b/www/pages/details.php index da735b9a6..eef9a63b0 100644 --- a/www/pages/details.php +++ b/www/pages/details.php @@ -29,7 +29,7 @@ if (isset($_GET["id"])) $rage = ''; if ($data["rageid"] != '') { - $tvrage = new TvAnger(); + $tvrage = new TvRage(); $rageinfo = $tvrage->getByRageID($data["rageid"]); if (count($rageinfo) > 0) diff --git a/www/pages/series.php b/www/pages/series.php index 3ca7924ed..868d1d2e8 100644 --- a/www/pages/series.php +++ b/www/pages/series.php @@ -5,7 +5,7 @@ if (!$page->users->isLoggedIn()) { } $releases = new Releases(); -$tvrage = new TvAnger(); +$tvrage = new TvRage(); $cat = new Category(); $us = new UserSeries();