(.*?)\s?\(.*?<\/title>/i',
'tagline' => '/taglines:<\/h4>\s([^<]+)/i',
'plot' => '/\s*?(.*?)\s*?<\/p>/i',
'rating' => '/"ratingValue">([\d.]+)<\/span>/i',
'year' => '/
.*?\(.*?(\d{4}).*?<\/title>/i',
- 'cover' => '//'
+ 'cover' => '//',
];
- $imdb_regex_multi = [
+ $imdb_regex_multi = [
'genre' => '/href="\/genre\/(.*?)\?/i',
'language' => '//i'
+ 'type' => '//i',
];
- try {
- $buffer =
+ try {
+ $buffer =
$this->client->get(
- 'http://' . ($this->imdburl === false ? 'www' : 'akas') . '.imdb.com/title/tt' . $imdbId . '/',
+ 'http://'.($this->imdburl === false ? 'www' : 'akas').'.imdb.com/title/tt'.$imdbId.'/',
['headers' => [
'Accept-Language' => ((Settings::value('indexer.categorise.imdblanguage') != '') ? Settings::value('indexer.categorise.imdblanguage') : 'en'),
- 'useragent' => 'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) ' .
- 'Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10', 'foo=bar'
- ]
+ 'useragent' => 'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) '.
+ 'Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10', 'foo=bar',
+ ],
]
)->getBody()->getContents();
- } catch (RequestException $e) {
- if ($e->hasResponse()) {
- if($e->getCode() === 404) {
- ColorCLI::doEcho(ColorCLI::notice('Data not available on IMDB server'));
- } else if ($e->getCode() === 503) {
- ColorCLI::doEcho(ColorCLI::notice('IMDB service unavailable'));
- } else {
- ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from IMDB, http error reported: ' . $e->getCode()));
- }
- }
- } catch (\RuntimeException $e) {
- ColorCLI::doEcho(ColorCLI::notice('Runtime error: ' . $e->getCode()));
- }
+ } catch (RequestException $e) {
+ if ($e->hasResponse()) {
+ if ($e->getCode() === 404) {
+ ColorCLI::doEcho(ColorCLI::notice('Data not available on IMDB server'));
+ } elseif ($e->getCode() === 503) {
+ ColorCLI::doEcho(ColorCLI::notice('IMDB service unavailable'));
+ } else {
+ ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from IMDB, http error reported: '.$e->getCode()));
+ }
+ }
+ } catch (\RuntimeException $e) {
+ ColorCLI::doEcho(ColorCLI::notice('Runtime error: '.$e->getCode()));
+ }
- if (isset($buffer) && $buffer !== false) {
- $ret = [];
- foreach ($imdb_regex as $field => $regex) {
- if (preg_match($regex, $buffer, $matches)) {
- $match = $matches[1];
- $match1 = strip_tags(trim(rtrim($match)));
- $ret[$field] = $match1;
- }
- }
+ if (isset($buffer) && $buffer !== false) {
+ $ret = [];
+ foreach ($imdb_regex as $field => $regex) {
+ if (preg_match($regex, $buffer, $matches)) {
+ $match = $matches[1];
+ $match1 = strip_tags(trim(rtrim($match)));
+ $ret[$field] = $match1;
+ }
+ }
- $matches = [];
- foreach ($imdb_regex_multi as $field => $regex) {
- if (preg_match_all($regex, $buffer, $matches)) {
- $match2 = $matches[1];
- $match3 = array_map('trim', $match2);
- $ret[$field] = $match3;
- }
- }
+ $matches = [];
+ foreach ($imdb_regex_multi as $field => $regex) {
+ if (preg_match_all($regex, $buffer, $matches)) {
+ $match2 = $matches[1];
+ $match3 = array_map('trim', $match2);
+ $ret[$field] = $match3;
+ }
+ }
- if ($this->currentTitle !== '' && isset($ret['title'])) {
- // Check the similarity.
- similar_text($this->currentTitle, $ret['title'], $percent);
- if ($percent < 40) {
- if ($this->debug) {
- $this->debugging->log(
+ if ($this->currentTitle !== '' && isset($ret['title'])) {
+ // Check the similarity.
+ similar_text($this->currentTitle, $ret['title'], $percent);
+ if ($percent < 40) {
+ if ($this->debug) {
+ $this->debugging->log(
__CLASS__,
__FUNCTION__,
- 'Found (' .
- $ret['title'] .
- ') from IMDB, but it\'s only ' .
- $percent .
- '% similar to (' .
- $this->currentTitle . ')',
+ 'Found ('.
+ $ret['title'].
+ ') from IMDB, but it\'s only '.
+ $percent.
+ '% similar to ('.
+ $this->currentTitle.')',
Logger::LOG_INFO
);
- }
- return false;
- }
- }
+ }
- // Actors.
- if (preg_match('/(.+?)<\/table>/s', $buffer, $hit)) {
- if (preg_match_all('/\s*(.+?)\s*<\/span>/i', $hit[0], $results, PREG_PATTERN_ORDER)) {
- $ret['actors'] = $results[1];
- }
- }
+ return false;
+ }
+ }
- // Directors.
- if (preg_match('/itemprop="directors?".+?<\/div>/s', $buffer, $hit)) {
- if (preg_match_all('/"name">(.*?)<\/span>/is', $hit[0], $results, PREG_PATTERN_ORDER)) {
- $ret['director'] = $results[1];
- }
- }
- if ($this->echooutput && isset($ret['title'])) {
- ColorCLI::doEcho(ColorCLI::headerOver('IMDb Found ') . ColorCLI::primaryOver($ret['title']), true);
- }
- return $ret;
- }
- return false;
- }
+ // Actors.
+ if (preg_match('/(.+?)<\/table>/s', $buffer, $hit)) {
+ if (preg_match_all('/\s*(.+?)\s*<\/span>/i', $hit[0], $results, PREG_PATTERN_ORDER)) {
+ $ret['actors'] = $results[1];
+ }
+ }
- /**
- * Fetch TraktTV backdrop / cover / title.
- *
- * @param $imdbId
- *
- * @return bool|array
- */
- protected function fetchTraktTVProperties($imdbId)
- {
- if ($this->traktTv === null) {
- $this->traktTv = new TraktTv(['Settings' => $this->pdo]);
- }
- $resp = $this->traktTv->client->movieSummary('tt' . $imdbId, 'full');
- if ($resp !== false) {
- $ret = [];
- if (isset($resp['ids']['trakt'])) {
- $ret['id'] = $resp['ids']['trakt'];
- }
+ // Directors.
+ if (preg_match('/itemprop="directors?".+?<\/div>/s', $buffer, $hit)) {
+ if (preg_match_all('/"name">(.*?)<\/span>/is', $hit[0], $results, PREG_PATTERN_ORDER)) {
+ $ret['director'] = $results[1];
+ }
+ }
+ if ($this->echooutput && isset($ret['title'])) {
+ ColorCLI::doEcho(ColorCLI::headerOver('IMDb Found ').ColorCLI::primaryOver($ret['title']), true);
+ }
- if (isset($resp['title'])) {
- $ret['title'] = $resp['title'];
- } else {
- return false;
- }
- if ($this->echooutput) {
- ColorCLI::doEcho(ColorCLI::alternateOver('Trakt Found ') . ColorCLI::headerOver($ret['title']), true);
- }
- return $ret;
- }
- return false;
- }
+ return $ret;
+ }
- /**
- * Fetch OMDb backdrop / cover / title.
- *
- * @param $imdbId
- *
- * @return bool|array
- */
- protected function fetchOmdbAPIProperties($imdbId)
- {
- if ($this->omdbapikey !== '' && $this->omdbApi === null) {
- $this->omdbApi = new OMDbAPI($this->omdbapikey);
- $resp = $this->omdbApi->fetch('i', 'tt' . $imdbId);
+ return false;
+ }
- if (is_object($resp) && $resp->message === 'OK' && $resp->data->Response !== 'False') {
- $ret = [
- 'title' => !empty($resp->data->Title) ? $resp->data->Title : '',
- 'cover' => !empty($resp->data->Poster) ? $resp->data->Poster : '',
- 'genre' => !empty($resp->data->Genre) ? $resp->data->Genre : '',
- 'year' => !empty($resp->data->Year) ? $resp->data->Year : '',
- 'plot' => !empty($resp->data->Plot) ? $resp->data->Plot : '',
- 'rating' => !empty($resp->data->imdbRating) ? $resp->data->imdbRating : '',
- 'tagline' => !empty($resp->data->Tagline) ? $resp->data->Tagline : '',
- 'director' => !empty($resp->data->Director) ? $resp->data->Director : '',
- 'actors' => !empty($resp->data->Actors) ? $resp->data->Actors : '',
- 'language' => !empty($resp->data->Language) ? $resp->data->Language : ''
+ /**
+ * Fetch TraktTV backdrop / cover / title.
+ *
+ * @param $imdbId
+ *
+ * @return bool|array
+ */
+ protected function fetchTraktTVProperties($imdbId)
+ {
+ if ($this->traktTv === null) {
+ $this->traktTv = new TraktTv(['Settings' => $this->pdo]);
+ }
+ $resp = $this->traktTv->client->movieSummary('tt'.$imdbId, 'full');
+ if ($resp !== false) {
+ $ret = [];
+ if (isset($resp['ids']['trakt'])) {
+ $ret['id'] = $resp['ids']['trakt'];
+ }
+
+ if (isset($resp['title'])) {
+ $ret['title'] = $resp['title'];
+ } else {
+ return false;
+ }
+ if ($this->echooutput) {
+ ColorCLI::doEcho(ColorCLI::alternateOver('Trakt Found ').ColorCLI::headerOver($ret['title']), true);
+ }
+
+ return $ret;
+ }
+
+ return false;
+ }
+
+ /**
+ * Fetch OMDb backdrop / cover / title.
+ *
+ * @param $imdbId
+ *
+ * @return bool|array
+ */
+ protected function fetchOmdbAPIProperties($imdbId)
+ {
+ if ($this->omdbapikey !== '' && $this->omdbApi === null) {
+ $this->omdbApi = new OMDbAPI($this->omdbapikey);
+ $resp = $this->omdbApi->fetch('i', 'tt'.$imdbId);
+
+ if (is_object($resp) && $resp->message === 'OK' && $resp->data->Response !== 'False') {
+ $ret = [
+ 'title' => ! empty($resp->data->Title) ? $resp->data->Title : '',
+ 'cover' => ! empty($resp->data->Poster) ? $resp->data->Poster : '',
+ 'genre' => ! empty($resp->data->Genre) ? $resp->data->Genre : '',
+ 'year' => ! empty($resp->data->Year) ? $resp->data->Year : '',
+ 'plot' => ! empty($resp->data->Plot) ? $resp->data->Plot : '',
+ 'rating' => ! empty($resp->data->imdbRating) ? $resp->data->imdbRating : '',
+ 'tagline' => ! empty($resp->data->Tagline) ? $resp->data->Tagline : '',
+ 'director' => ! empty($resp->data->Director) ? $resp->data->Director : '',
+ 'actors' => ! empty($resp->data->Actors) ? $resp->data->Actors : '',
+ 'language' => ! empty($resp->data->Language) ? $resp->data->Language : '',
];
- if ($this->echooutput) {
- ColorCLI::doEcho(ColorCLI::alternateOver('OMDbAPI Found ') . ColorCLI::headerOver($ret['title']), true);
- }
- return $ret;
- }
- return false;
- }
- return false;
- }
+ if ($this->echooutput) {
+ ColorCLI::doEcho(ColorCLI::alternateOver('OMDbAPI Found ').ColorCLI::headerOver($ret['title']), true);
+ }
- /**
- * Update a release with a IMDB id.
- *
- * @param string $buffer Data to parse a IMDB id/Trakt Id from.
- * @param string $service Method that called this method.
- * @param int $id id of the release.
- * @param int $processImdb To get IMDB info on this IMDB id or not.
- *
- * @return string
- */
- public function doMovieUpdate($buffer, $service, $id, $processImdb = 1): string
- {
- $imdbID = false;
- if (is_string($buffer) && preg_match('/(?:imdb.*?)?(?:tt|Title\?)(?P\d{5,7})/i', $buffer, $matches)) {
- $imdbID = $matches['imdbid'];
- }
+ return $ret;
+ }
- if ($imdbID !== false) {
- $this->service = $service;
- if ($this->echooutput && $this->service !== '') {
- ColorCLI::doEcho(ColorCLI::headerOver($service . ' found IMDBid: ') . ColorCLI::primary('tt' . $imdbID));
- }
+ return false;
+ }
- $this->pdo->queryExec(sprintf('UPDATE releases SET imdbid = %s WHERE id = %d', $this->pdo->escapeString($imdbID), $id));
+ return false;
+ }
- // If set, scan for imdb info.
- if ($processImdb === 1) {
- $movCheck = $this->getMovieInfo($imdbID);
- if ($movCheck === false || (isset($movCheck['updateddate']) && (time() - strtotime($movCheck['updateddate'])) > 2592000)) {
- if ($this->updateMovieInfo($imdbID) === false) {
- $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $id));
- }
- }
- }
- }
- return $imdbID;
- }
+ /**
+ * Update a release with a IMDB id.
+ *
+ * @param string $buffer Data to parse a IMDB id/Trakt Id from.
+ * @param string $service Method that called this method.
+ * @param int $id id of the release.
+ * @param int $processImdb To get IMDB info on this IMDB id or not.
+ *
+ * @return string
+ */
+ public function doMovieUpdate($buffer, $service, $id, $processImdb = 1): string
+ {
+ $imdbID = false;
+ if (is_string($buffer) && preg_match('/(?:imdb.*?)?(?:tt|Title\?)(?P\d{5,7})/i', $buffer, $matches)) {
+ $imdbID = $matches['imdbid'];
+ }
- /**
- * Process releases with no IMDB id's.
- *
- * @param string $groupID (Optional) id of a group to work on.
- * @param string $guidChar (Optional) First letter of a release GUID to use to get work.
- * @param int $lookupIMDB (Optional) 0 Don't lookup IMDB, 1 lookup IMDB, 2 lookup IMDB on releases that were renamed.
- */
- public function processMovieReleases($groupID = '', $guidChar = '', $lookupIMDB = 1): void
- {
- if ($lookupIMDB === 0) {
- return;
- }
+ if ($imdbID !== false) {
+ $this->service = $service;
+ if ($this->echooutput && $this->service !== '') {
+ ColorCLI::doEcho(ColorCLI::headerOver($service.' found IMDBid: ').ColorCLI::primary('tt'.$imdbID));
+ }
- // Get all releases without an IMDB id.
- $res = $this->pdo->query(
+ $this->pdo->queryExec(sprintf('UPDATE releases SET imdbid = %s WHERE id = %d', $this->pdo->escapeString($imdbID), $id));
+
+ // If set, scan for imdb info.
+ if ($processImdb === 1) {
+ $movCheck = $this->getMovieInfo($imdbID);
+ if ($movCheck === false || (isset($movCheck['updateddate']) && (time() - strtotime($movCheck['updateddate'])) > 2592000)) {
+ if ($this->updateMovieInfo($imdbID) === false) {
+ $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $id));
+ }
+ }
+ }
+ }
+
+ return $imdbID;
+ }
+
+ /**
+ * Process releases with no IMDB id's.
+ *
+ * @param string $groupID (Optional) id of a group to work on.
+ * @param string $guidChar (Optional) First letter of a release GUID to use to get work.
+ * @param int $lookupIMDB (Optional) 0 Don't lookup IMDB, 1 lookup IMDB, 2 lookup IMDB on releases that were renamed.
+ */
+ public function processMovieReleases($groupID = '', $guidChar = '', $lookupIMDB = 1): void
+ {
+ if ($lookupIMDB === 0) {
+ return;
+ }
+
+ // Get all releases without an IMDB id.
+ $res = $this->pdo->query(
sprintf('
SELECT searchname, id
FROM releases
@@ -1154,308 +1176,309 @@ class Movie
%s %s %s
LIMIT %d',
$this->catWhere,
- ($groupID === '' ? '' : ('AND groups_id = ' . $groupID)),
- ($guidChar === '' ? '' : 'AND leftguid = ' . $this->pdo->escapeString($guidChar)),
+ ($groupID === '' ? '' : ('AND groups_id = '.$groupID)),
+ ($guidChar === '' ? '' : 'AND leftguid = '.$this->pdo->escapeString($guidChar)),
($lookupIMDB === 2 ? 'AND isrenamed = 1' : ''),
$this->movieqty
)
);
- $movieCount = count($res);
+ $movieCount = count($res);
- if ($movieCount > 0) {
- if ($this->traktTv === null) {
- $this->traktTv = new TraktTv(['Settings' => $this->pdo]);
- }
- if ($this->echooutput && $movieCount > 1) {
- ColorCLI::doEcho(ColorCLI::header('Processing ' . $movieCount . ' movie releases.'));
- }
+ if ($movieCount > 0) {
+ if ($this->traktTv === null) {
+ $this->traktTv = new TraktTv(['Settings' => $this->pdo]);
+ }
+ if ($this->echooutput && $movieCount > 1) {
+ ColorCLI::doEcho(ColorCLI::header('Processing '.$movieCount.' movie releases.'));
+ }
- // Loop over releases.
- foreach ($res as $arr) {
- // Try to get a name/year.
- if ($this->parseMovieSearchName($arr['searchname']) === false) {
- //We didn't find a name, so set to all 0's so we don't parse again.
- $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $arr['id']));
- continue;
- }
- $this->currentRelID = $arr['id'];
+ // Loop over releases.
+ foreach ($res as $arr) {
+ // Try to get a name/year.
+ if ($this->parseMovieSearchName($arr['searchname']) === false) {
+ //We didn't find a name, so set to all 0's so we don't parse again.
+ $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $arr['id']));
+ continue;
+ }
+ $this->currentRelID = $arr['id'];
- $movieName = $this->currentTitle;
- if ($this->currentYear !== false) {
- $movieName .= ' (' . $this->currentYear . ')';
- }
+ $movieName = $this->currentTitle;
+ if ($this->currentYear !== false) {
+ $movieName .= ' ('.$this->currentYear.')';
+ }
- if ($this->echooutput) {
- ColorCLI::doEcho(ColorCLI::primaryOver('Looking up: ') . ColorCLI::headerOver($movieName), true);
- }
+ if ($this->echooutput) {
+ ColorCLI::doEcho(ColorCLI::primaryOver('Looking up: ').ColorCLI::headerOver($movieName), true);
+ }
- $movieUpdated = false;
+ $movieUpdated = false;
- // Check local DB.
- $getIMDBid = $this->localIMDBsearch();
+ // Check local DB.
+ $getIMDBid = $this->localIMDBsearch();
- if ($getIMDBid !== false) {
- $imdbID = $this->doMovieUpdate('tt' . $getIMDBid, 'Local DB', $arr['id']);
- if ($imdbID !== false) {
- $movieUpdated = true;
- }
- }
+ if ($getIMDBid !== false) {
+ $imdbID = $this->doMovieUpdate('tt'.$getIMDBid, 'Local DB', $arr['id']);
+ if ($imdbID !== false) {
+ $movieUpdated = true;
+ }
+ }
- // Check OMDbAPI
- if ($movieUpdated === false) {
- $omdbTitle = strtolower(str_replace(' ', '_', $this->currentTitle));
- if ($this->omdbapikey !== '' && $this->omdbApi === null) {
- $this->omdbApi = new OMDbAPI($this->omdbapikey);
- $buffer = $this->omdbApi->search($omdbTitle, 'movie');
+ // Check OMDbAPI
+ if ($movieUpdated === false) {
+ $omdbTitle = strtolower(str_replace(' ', '_', $this->currentTitle));
+ if ($this->omdbapikey !== '' && $this->omdbApi === null) {
+ $this->omdbApi = new OMDbAPI($this->omdbapikey);
+ $buffer = $this->omdbApi->search($omdbTitle, 'movie');
- if (is_object($buffer) && $buffer->message === 'OK' && $buffer->data->Response !== 'False') {
- $getIMDBid = $buffer->data->Search[0]->imdbID;
+ if (is_object($buffer) && $buffer->message === 'OK' && $buffer->data->Response !== 'False') {
+ $getIMDBid = $buffer->data->Search[0]->imdbID;
- if (!empty($getIMDBid)) {
- $imdbID = $this->doMovieUpdate($getIMDBid, 'OMDbAPI', $arr['id']);
- if ($imdbID !== false) {
- $movieUpdated = true;
- }
- }
- }
- }
- }
+ if (! empty($getIMDBid)) {
+ $imdbID = $this->doMovieUpdate($getIMDBid, 'OMDbAPI', $arr['id']);
+ if ($imdbID !== false) {
+ $movieUpdated = true;
+ }
+ }
+ }
+ }
+ }
- // Check on Trakt.
- if ($movieUpdated === false) {
- $data = $this->traktTv->client->movieSummary($movieName, 'full');
- if ($data !== false) {
- $this->parseTraktTv($data);
- if (!empty($data['ids']['imdb'])) {
- $imdbID = $this->doMovieUpdate($data['ids']['imdb'], 'Trakt', $arr['id']);
- if ($imdbID !== false) {
- $movieUpdated = true;
- }
- }
- }
- }
+ // Check on Trakt.
+ if ($movieUpdated === false) {
+ $data = $this->traktTv->client->movieSummary($movieName, 'full');
+ if ($data !== false) {
+ $this->parseTraktTv($data);
+ if (! empty($data['ids']['imdb'])) {
+ $imdbID = $this->doMovieUpdate($data['ids']['imdb'], 'Trakt', $arr['id']);
+ if ($imdbID !== false) {
+ $movieUpdated = true;
+ }
+ }
+ }
+ }
- // Try on search engines.
- if ($movieUpdated === false) {
- if ($this->searchEngines && $this->currentYear !== false) {
- if ($this->imdbIDFromEngines() === true) {
- $movieUpdated = true;
- }
- }
- }
+ // Try on search engines.
+ if ($movieUpdated === false) {
+ if ($this->searchEngines && $this->currentYear !== false) {
+ if ($this->imdbIDFromEngines() === true) {
+ $movieUpdated = true;
+ }
+ }
+ }
- // We failed to get an IMDB id from all sources.
- if ($movieUpdated === false) {
- $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $arr['id']));
- }
- }
- }
- }
+ // We failed to get an IMDB id from all sources.
+ if ($movieUpdated === false) {
+ $this->pdo->queryExec(sprintf('UPDATE releases %s SET imdbid = 0000000 WHERE id = %d', $this->catWhere, $arr['id']));
+ }
+ }
+ }
+ }
- /**
- * Try to fetch an IMDB id locally.
- *
- * @return int|bool Int, the imdbid when true, Bool when false.
- */
- protected function localIMDBsearch()
- {
- $query = 'SELECT imdbid FROM movieinfo';
- $andYearIn = '';
+ /**
+ * Try to fetch an IMDB id locally.
+ *
+ * @return int|bool Int, the imdbid when true, Bool when false.
+ */
+ protected function localIMDBsearch()
+ {
+ $query = 'SELECT imdbid FROM movieinfo';
+ $andYearIn = '';
- //If we found a year, try looking in a 4 year range.
- if ($this->currentYear !== false) {
- $start = (int) $this->currentYear - 2;
- $end = (int) $this->currentYear + 2;
- $andYearIn = 'AND year IN (';
- while ($start < $end) {
- $andYearIn .= $start . ',';
- $start++;
- }
- $andYearIn .= $end . ')';
- }
- $IMDBCheck = $this->pdo->queryOneRow(
+ //If we found a year, try looking in a 4 year range.
+ if ($this->currentYear !== false) {
+ $start = (int) $this->currentYear - 2;
+ $end = (int) $this->currentYear + 2;
+ $andYearIn = 'AND year IN (';
+ while ($start < $end) {
+ $andYearIn .= $start.',';
+ $start++;
+ }
+ $andYearIn .= $end.')';
+ }
+ $IMDBCheck = $this->pdo->queryOneRow(
sprintf('%s WHERE title %s %s', $query, $this->pdo->likeString($this->currentTitle), $andYearIn));
- // Look by %word%word%word% etc..
- if ($IMDBCheck === false) {
- $pieces = explode(' ', $this->currentTitle);
- $tempTitle = '%';
- foreach ($pieces as $piece) {
- $tempTitle .= str_replace(["'", '!', '"'], '', $piece) . '%';
- }
- $IMDBCheck = $this->pdo->queryOneRow(
+ // Look by %word%word%word% etc..
+ if ($IMDBCheck === false) {
+ $pieces = explode(' ', $this->currentTitle);
+ $tempTitle = '%';
+ foreach ($pieces as $piece) {
+ $tempTitle .= str_replace(["'", '!', '"'], '', $piece).'%';
+ }
+ $IMDBCheck = $this->pdo->queryOneRow(
sprintf("%s WHERE replace(replace(title, \"'\", ''), '!', '') %s %s",
$query, $this->pdo->likeString($tempTitle), $andYearIn
)
);
- }
+ }
- // Try replacing er with re ?
- if ($IMDBCheck === false) {
- $tempTitle = str_replace('er', 're', $this->currentTitle);
- if ($tempTitle !== $this->currentTitle) {
- $IMDBCheck = $this->pdo->queryOneRow(
+ // Try replacing er with re ?
+ if ($IMDBCheck === false) {
+ $tempTitle = str_replace('er', 're', $this->currentTitle);
+ if ($tempTitle !== $this->currentTitle) {
+ $IMDBCheck = $this->pdo->queryOneRow(
sprintf('%s WHERE title %s %s',
$query, $this->pdo->likeString($tempTitle), $andYearIn
)
);
- // Final check if everything else failed.
- if ($IMDBCheck === false) {
- $pieces = explode(' ', $tempTitle);
- $tempTitle = '%';
- foreach ($pieces as $piece) {
- $tempTitle .= str_replace(["'", '!', '"'], '', $piece) . '%';
- }
- $IMDBCheck = $this->pdo->queryOneRow(
+ // Final check if everything else failed.
+ if ($IMDBCheck === false) {
+ $pieces = explode(' ', $tempTitle);
+ $tempTitle = '%';
+ foreach ($pieces as $piece) {
+ $tempTitle .= str_replace(["'", '!', '"'], '', $piece).'%';
+ }
+ $IMDBCheck = $this->pdo->queryOneRow(
sprintf("%s WHERE replace(replace(replace(title, \"'\", ''), '!', ''), '\"', '') %s %s",
$query, $this->pdo->likeString($tempTitle), $andYearIn
)
);
- }
- }
- }
+ }
+ }
+ }
- return (
+ return
$IMDBCheck === false
? false
: (is_numeric($IMDBCheck['imdbid'])
- ? (int)$IMDBCheck['imdbid']
+ ? (int) $IMDBCheck['imdbid']
: false
- )
- );
- }
+ );
+ }
- /**
- * Try to get an IMDB id from search engines.
- *
- * @return bool
- */
- protected function imdbIDFromEngines(): bool
- {
- if ($this->googleLimit < 41 && (time() - $this->googleBan) > 600) {
- if ($this->googleSearch() === true) {
- return true;
- }
- }
+ /**
+ * Try to get an IMDB id from search engines.
+ *
+ * @return bool
+ */
+ protected function imdbIDFromEngines(): bool
+ {
+ if ($this->googleLimit < 41 && (time() - $this->googleBan) > 600) {
+ if ($this->googleSearch() === true) {
+ return true;
+ }
+ }
- if ($this->yahooLimit < 41 && $this->yahooSearch() === true) {
- return true;
- }
+ if ($this->yahooLimit < 41 && $this->yahooSearch() === true) {
+ return true;
+ }
- // Not using this right now because bing's advanced search is not good enough.
- /*if ($this->bingLimit < 41) {
- if ($this->bingSearch() === true) {
- return true;
- }
- }*/
+ // Not using this right now because bing's advanced search is not good enough.
+ /*if ($this->bingLimit < 41) {
+ if ($this->bingSearch() === true) {
+ return true;
+ }
+ }*/
- return false;
- }
+ return false;
+ }
- /**
- * Try to find a IMDB id on google.com
- *
- * @return bool
- */
- protected function googleSearch(): bool
- {
- try {
- $buffer = $this->client->get(
- 'https://www.google.com/search?hl=en&as_q=&as_epq=' .
+ /**
+ * Try to find a IMDB id on google.com.
+ *
+ * @return bool
+ */
+ protected function googleSearch(): bool
+ {
+ try {
+ $buffer = $this->client->get(
+ 'https://www.google.com/search?hl=en&as_q=&as_epq='.
urlencode(
- $this->currentTitle .
- ' ' .
+ $this->currentTitle.
+ ' '.
$this->currentYear
- ) .
- '&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch=' .
- urlencode('www.imdb.com/title/') .
+ ).
+ '&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch='.
+ urlencode('www.imdb.com/title/').
'&as_occt=title&safe=images&tbs=&as_filetype=&as_rights='
)->getBody()->getContents();
- } catch (RequestException $e) {
- if ($e->hasResponse()) {
- if($e->getCode() === 404) {
- ColorCLI::doEcho(ColorCLI::notice('Data not available on Google search'));
- } else if ($e->getCode() === 503) {
- ColorCLI::doEcho(ColorCLI::notice('Google service unavailable'));
- } else {
- ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Google, http error reported: ' . $e->getCode()));
- }
- }
- } catch (\RuntimeException $e) {
- ColorCLI::doEcho(ColorCLI::notice('Runtime error: ' . $e->getCode()));
- }
+ } catch (RequestException $e) {
+ if ($e->hasResponse()) {
+ if ($e->getCode() === 404) {
+ ColorCLI::doEcho(ColorCLI::notice('Data not available on Google search'));
+ } elseif ($e->getCode() === 503) {
+ ColorCLI::doEcho(ColorCLI::notice('Google service unavailable'));
+ } else {
+ ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Google, http error reported: '.$e->getCode()));
+ }
+ }
+ } catch (\RuntimeException $e) {
+ ColorCLI::doEcho(ColorCLI::notice('Runtime error: '.$e->getCode()));
+ }
- // Make sure we got some data.
- if (!empty($buffer)) {
- $this->googleLimit++;
+ // Make sure we got some data.
+ if (! empty($buffer)) {
+ $this->googleLimit++;
- if (preg_match('/(To continue, please type the characters below)|(- did not match any documents\.)/i', $buffer, $matches)) {
- if (!empty($matches[1])) {
- $this->googleBan = time();
- }
- } else if ($this->doMovieUpdate($buffer, 'Google.com', $this->currentRelID) !== false) {
- return true;
- }
- }
- return false;
- }
+ if (preg_match('/(To continue, please type the characters below)|(- did not match any documents\.)/i', $buffer, $matches)) {
+ if (! empty($matches[1])) {
+ $this->googleBan = time();
+ }
+ } elseif ($this->doMovieUpdate($buffer, 'Google.com', $this->currentRelID) !== false) {
+ return true;
+ }
+ }
- /**
- * Try to find a IMDB id on bing.com
- *
- * @return bool
- */
- protected function bingSearch(): bool
- {
- try {
- $buffer = $this->client->get(
- 'http://www.bing.com/search?q=' .
+ return false;
+ }
+
+ /**
+ * Try to find a IMDB id on bing.com.
+ *
+ * @return bool
+ */
+ protected function bingSearch(): bool
+ {
+ try {
+ $buffer = $this->client->get(
+ 'http://www.bing.com/search?q='.
urlencode(
- '("' .
- $this->currentTitle .
- '" and "' .
- $this->currentYear .
+ '("'.
+ $this->currentTitle.
+ '" and "'.
+ $this->currentYear.
'") site:www.imdb.com/title/'
- ) .
+ ).
'&qs=n&form=QBLH&filt=all'
)->getBody()->getContents();
- } catch (RequestException $e) {
- if ($e->hasResponse()) {
- if($e->getCode() === 404) {
- ColorCLI::doEcho(ColorCLI::notice('Data not available on Bing search'));
- } else if ($e->getCode() === 503) {
- ColorCLI::doEcho(ColorCLI::notice('Bing search service unavailable'));
- } else {
- ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Bing search , http error reported: ' . $e->getCode()));
- }
- }
- } catch (\RuntimeException $e) {
- ColorCLI::doEcho(ColorCLI::notice('Runtime error: ' . $e->getCode()));
- }
+ } catch (RequestException $e) {
+ if ($e->hasResponse()) {
+ if ($e->getCode() === 404) {
+ ColorCLI::doEcho(ColorCLI::notice('Data not available on Bing search'));
+ } elseif ($e->getCode() === 503) {
+ ColorCLI::doEcho(ColorCLI::notice('Bing search service unavailable'));
+ } else {
+ ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Bing search , http error reported: '.$e->getCode()));
+ }
+ }
+ } catch (\RuntimeException $e) {
+ ColorCLI::doEcho(ColorCLI::notice('Runtime error: '.$e->getCode()));
+ }
- if (!empty($buffer)) {
- $this->bingLimit++;
+ if (! empty($buffer)) {
+ $this->bingLimit++;
- if ($this->doMovieUpdate($buffer, 'Bing.com', $this->currentRelID) !== false) {
- return true;
- }
- }
- return false;
- }
+ if ($this->doMovieUpdate($buffer, 'Bing.com', $this->currentRelID) !== false) {
+ return true;
+ }
+ }
- /**
- * Try to find a IMDB id on yahoo.com
- *
- * @return bool
- */
- protected function yahooSearch(): bool
- {
- try {
- $buffer = $this->client->get(
- 'http://search.yahoo.com/search?n=10&ei=UTF-8&va_vt=title&vo_vt=any&ve_vt=any&vp_vt=any&vf=all&vm=p&fl=0&fr=fp-top&p=' .
+ return false;
+ }
+
+ /**
+ * Try to find a IMDB id on yahoo.com.
+ *
+ * @return bool
+ */
+ protected function yahooSearch(): bool
+ {
+ try {
+ $buffer = $this->client->get(
+ 'http://search.yahoo.com/search?n=10&ei=UTF-8&va_vt=title&vo_vt=any&ve_vt=any&vp_vt=any&vf=all&vm=p&fl=0&fr=fp-top&p='.
urlencode(
- '' .
+ ''.
implode('+',
explode(
' ',
@@ -1469,95 +1492,98 @@ class Movie
)
)
)
- ) .
- '+' .
+ ).
+ '+'.
$this->currentYear
- ) .
- '&vs=' .
+ ).
+ '&vs='.
urlencode('www.imdb.com/title/')
)->getBody()->getContents();
- } catch (RequestException $e) {
- if ($e->hasResponse()) {
- if($e->getCode() === 404) {
- ColorCLI::doEcho(ColorCLI::notice('Data not available on Yahoo search'));
- } else if ($e->getCode() === 503) {
- ColorCLI::doEcho(ColorCLI::notice('Yahoo search service unavailable'));
- } else {
- ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Yahoo search, http error reported: ' . $e->getCode()));
- }
- }
- } catch (\RuntimeException $e) {
- ColorCLI::doEcho(ColorCLI::notice('Runtime error: ' . $e->getCode()));
- }
+ } catch (RequestException $e) {
+ if ($e->hasResponse()) {
+ if ($e->getCode() === 404) {
+ ColorCLI::doEcho(ColorCLI::notice('Data not available on Yahoo search'));
+ } elseif ($e->getCode() === 503) {
+ ColorCLI::doEcho(ColorCLI::notice('Yahoo search service unavailable'));
+ } else {
+ ColorCLI::doEcho(ColorCLI::notice('Unable to fetch data from Yahoo search, http error reported: '.$e->getCode()));
+ }
+ }
+ } catch (\RuntimeException $e) {
+ ColorCLI::doEcho(ColorCLI::notice('Runtime error: '.$e->getCode()));
+ }
- if (!empty($buffer)) {
- $this->yahooLimit++;
+ if (! empty($buffer)) {
+ $this->yahooLimit++;
- if ($this->doMovieUpdate($buffer, 'Yahoo.com', $this->currentRelID) !== false) {
- return true;
- }
- }
- return false;
- }
+ if ($this->doMovieUpdate($buffer, 'Yahoo.com', $this->currentRelID) !== false) {
+ return true;
+ }
+ }
- /**
- * Parse a movie name from a release search name.
- *
- * @param string $releaseName
- *
- * @return bool
- */
- protected function parseMovieSearchName($releaseName): bool
- {
- $name = $year = '';
- $followingList = '[^\w]((1080|480|720)p|AC3D|Directors([^\w]CUT)?|DD5\.1|(DVD|BD|BR)(Rip)?|BluRay|divx|HDTV|iNTERNAL|LiMiTED|(Real\.)?Proper|RE(pack|Rip)|Sub\.?(fix|pack)|Unrated|WEB-DL|(x|H)[-._ ]?264|xvid)[^\w]';
+ return false;
+ }
- /* Initial scan of getting a year/name.
- * [\w. -]+ Gets 0-9a-z. - characters, most scene movie titles contain these chars.
- * ie: [61420]-[FULL]-[a.b.foreignEFNet]-[ Coraline.2009.DUTCH.INTERNAL.1080p.BluRay.x264-VeDeTT ]-[21/85] - "vedett-coralien-1080p.r04" yEnc
- * Then we look up the year, (19|20)\d\d, so $matches[1] would be Coraline $matches[2] 2009
- */
- if (preg_match('/(?P[\w. -]+)[^\w](?P(19|20)\d\d)/i', $releaseName, $matches)) {
- $name = $matches['name'];
- $year = $matches['year'];
+ /**
+ * Parse a movie name from a release search name.
+ *
+ * @param string $releaseName
+ *
+ * @return bool
+ */
+ protected function parseMovieSearchName($releaseName): bool
+ {
+ $name = $year = '';
+ $followingList = '[^\w]((1080|480|720)p|AC3D|Directors([^\w]CUT)?|DD5\.1|(DVD|BD|BR)(Rip)?|BluRay|divx|HDTV|iNTERNAL|LiMiTED|(Real\.)?Proper|RE(pack|Rip)|Sub\.?(fix|pack)|Unrated|WEB-DL|(x|H)[-._ ]?264|xvid)[^\w]';
- /* If we didn't find a year, try to get a name anyways.
- * Try to look for a title before the $followingList and after anything but a-z0-9 two times or more (-[ for example)
- */
- } else if (preg_match('/([^\w]{2,})?(?P[\w .-]+?)' . $followingList . '/i', $releaseName, $matches)) {
- $name = $matches['name'];
- }
+ /* Initial scan of getting a year/name.
+ * [\w. -]+ Gets 0-9a-z. - characters, most scene movie titles contain these chars.
+ * ie: [61420]-[FULL]-[a.b.foreignEFNet]-[ Coraline.2009.DUTCH.INTERNAL.1080p.BluRay.x264-VeDeTT ]-[21/85] - "vedett-coralien-1080p.r04" yEnc
+ * Then we look up the year, (19|20)\d\d, so $matches[1] would be Coraline $matches[2] 2009
+ */
+ if (preg_match('/(?P[\w. -]+)[^\w](?P(19|20)\d\d)/i', $releaseName, $matches)) {
+ $name = $matches['name'];
+ $year = $matches['year'];
- // Check if we got something.
- if ($name !== '') {
+ /* If we didn't find a year, try to get a name anyways.
+ * Try to look for a title before the $followingList and after anything but a-z0-9 two times or more (-[ for example)
+ */
+ } elseif (preg_match('/([^\w]{2,})?(?P[\w .-]+?)'.$followingList.'/i', $releaseName, $matches)) {
+ $name = $matches['name'];
+ }
+
+ // Check if we got something.
+ if ($name !== '') {
// If we still have any of the words in $followingList, remove them.
- $name = preg_replace('/' . $followingList . '/i', ' ', $name);
- // Remove periods, underscored, anything between parenthesis.
- $name = preg_replace('/\(.*?\)|[._]/i', ' ', $name);
- // Finally remove multiple spaces and trim leading spaces.
- $name = trim(preg_replace('/\s{2,}/', ' ', $name));
- // Check if the name is long enough and not just numbers.
- if (strlen($name) > 4 && !preg_match('/^\d+$/', $name)) {
- if ($this->debug && $this->echooutput) {
- ColorCLI::doEcho("DB name: {$releaseName}", true);
- }
- $this->currentTitle = $name;
- $this->currentYear = ($year === '' ? false : $year);
- return true;
- }
- }
- return false;
- }
+ $name = preg_replace('/'.$followingList.'/i', ' ', $name);
+ // Remove periods, underscored, anything between parenthesis.
+ $name = preg_replace('/\(.*?\)|[._]/i', ' ', $name);
+ // Finally remove multiple spaces and trim leading spaces.
+ $name = trim(preg_replace('/\s{2,}/', ' ', $name));
+ // Check if the name is long enough and not just numbers.
+ if (strlen($name) > 4 && ! preg_match('/^\d+$/', $name)) {
+ if ($this->debug && $this->echooutput) {
+ ColorCLI::doEcho("DB name: {$releaseName}", true);
+ }
+ $this->currentTitle = $name;
+ $this->currentYear = ($year === '' ? false : $year);
- /**
- * Get IMDB genres.
- *
- * @return array
- */
- public function getGenres(): array
- {
- return [
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Get IMDB genres.
+ *
+ * @return array
+ */
+ public function getGenres(): array
+ {
+ return [
'Action',
'Adventure',
'Animation',
@@ -1583,8 +1609,7 @@ class Movie
'Talk-Show',
'Thriller',
'War',
- 'Western'
+ 'Western',
];
- }
-
+ }
}
diff --git a/nntmux/Music.php b/nntmux/Music.php
index f883efc4e..68e08ba07 100755
--- a/nntmux/Music.php
+++ b/nntmux/Music.php
@@ -1,175 +1,177 @@
false,
'Settings' => null,
];
- $options += $defaults;
+ $options += $defaults;
- $this->echooutput = ($options['Echo'] && NN_ECHOCLI);
+ $this->echooutput = ($options['Echo'] && NN_ECHOCLI);
- $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB());
- $this->pubkey = Settings::value('APIs..amazonpubkey');
- $this->privkey = Settings::value('APIs..amazonprivkey');
- $this->asstag = Settings::value('APIs..amazonassociatetag');
- $this->musicqty = Settings::value('..maxmusicprocessed') != '' ? Settings::value('..maxmusicprocessed') : 150;
- $this->sleeptime = Settings::value('..amazonsleep') != '' ? Settings::value('..amazonsleep') : 1000;
- $this->imgSavePath = NN_COVERS . 'music' . DS;
- $this->renamed = '';
- if (Settings::value('..lookupmusic') == 2) {
- $this->renamed = 'AND isrenamed = 1';
- }
+ $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB());
+ $this->pubkey = Settings::value('APIs..amazonpubkey');
+ $this->privkey = Settings::value('APIs..amazonprivkey');
+ $this->asstag = Settings::value('APIs..amazonassociatetag');
+ $this->musicqty = Settings::value('..maxmusicprocessed') != '' ? Settings::value('..maxmusicprocessed') : 150;
+ $this->sleeptime = Settings::value('..amazonsleep') != '' ? Settings::value('..amazonsleep') : 1000;
+ $this->imgSavePath = NN_COVERS.'music'.DS;
+ $this->renamed = '';
+ if (Settings::value('..lookupmusic') == 2) {
+ $this->renamed = 'AND isrenamed = 1';
+ }
- $this->failCache = [];
- }
+ $this->failCache = [];
+ }
- /**
- * @param $id
- *
- * @return array|bool
- */
- public function getMusicInfo($id)
- {
- return $this->pdo->queryOneRow(sprintf('SELECT musicinfo.*, genres.title AS genres FROM musicinfo LEFT OUTER JOIN genres ON genres.id = musicinfo.genres_id WHERE musicinfo.id = %d ', $id));
- }
+ /**
+ * @param $id
+ *
+ * @return array|bool
+ */
+ public function getMusicInfo($id)
+ {
+ return $this->pdo->queryOneRow(sprintf('SELECT musicinfo.*, genres.title AS genres FROM musicinfo LEFT OUTER JOIN genres ON genres.id = musicinfo.genres_id WHERE musicinfo.id = %d ', $id));
+ }
- /**
- * @param $artist
- * @param $album
- *
- * @return array|bool
- */
- public function getMusicInfoByName($artist, $album)
- {
- $pdo = $this->pdo;
- $like = 'ILIKE';
- if ($pdo->DbSystem() === 'mysql') {
- $like = 'LIKE';
- }
+ /**
+ * @param $artist
+ * @param $album
+ *
+ * @return array|bool
+ */
+ public function getMusicInfoByName($artist, $album)
+ {
+ $pdo = $this->pdo;
+ $like = 'ILIKE';
+ if ($pdo->DbSystem() === 'mysql') {
+ $like = 'LIKE';
+ }
- //only used to get a count of words
- $searchwords = $searchsql = '';
- $ft = $pdo->queryDirect("SHOW INDEX FROM musicinfo WHERE key_name = 'ix_musicinfo_artist_title_ft'");
- if ($ft->rowCount() !== 2) {
- $searchsql .= sprintf(" artist LIKE %s AND title %s %s'", $pdo->escapeString('%' . $artist . '%'), $like, $pdo->escapeString('%' . $album . '%'));
- } else {
- $album = preg_replace('/( - | -|\(.+\)|\(|\))/', ' ', $album);
- $album = preg_replace('/[^\w ]+/', '', $album);
- $album = preg_replace('/(WEB|FLAC|CD)/', '', $album);
- $album = trim(preg_replace('/\s\s+/i', ' ', $album));
- $album = trim($album);
- $words = explode(' ', $album);
+ //only used to get a count of words
+ $searchwords = $searchsql = '';
+ $ft = $pdo->queryDirect("SHOW INDEX FROM musicinfo WHERE key_name = 'ix_musicinfo_artist_title_ft'");
+ if ($ft->rowCount() !== 2) {
+ $searchsql .= sprintf(" artist LIKE %s AND title %s %s'", $pdo->escapeString('%'.$artist.'%'), $like, $pdo->escapeString('%'.$album.'%'));
+ } else {
+ $album = preg_replace('/( - | -|\(.+\)|\(|\))/', ' ', $album);
+ $album = preg_replace('/[^\w ]+/', '', $album);
+ $album = preg_replace('/(WEB|FLAC|CD)/', '', $album);
+ $album = trim(preg_replace('/\s\s+/i', ' ', $album));
+ $album = trim($album);
+ $words = explode(' ', $album);
- foreach ($words as $word) {
- $word = trim(rtrim(trim($word), '-'));
- if ($word !== '' && $word !== '-') {
- $word = '+' . $word;
- $searchwords .= sprintf('%s ', $word);
- }
- }
- $searchwords = trim($searchwords);
- $searchsql .= sprintf(' MATCH(artist, title) AGAINST(%s IN BOOLEAN MODE)', $pdo->escapeString($searchwords));
- }
- return $pdo->queryOneRow(sprintf('SELECT * FROM musicinfo WHERE %s', $searchsql));
- }
+ foreach ($words as $word) {
+ $word = trim(rtrim(trim($word), '-'));
+ if ($word !== '' && $word !== '-') {
+ $word = '+'.$word;
+ $searchwords .= sprintf('%s ', $word);
+ }
+ }
+ $searchwords = trim($searchwords);
+ $searchsql .= sprintf(' MATCH(artist, title) AGAINST(%s IN BOOLEAN MODE)', $pdo->escapeString($searchwords));
+ }
- /**
- * @param $cat
- * @param $start
- * @param $num
- * @param $orderby
- * @param array $excludedcats
- *
- * @return array
- */
- public function getMusicRange($cat, $start, $num, $orderby, array $excludedcats = [])
- {
- $browseby = $this->getBrowseBy();
+ return $pdo->queryOneRow(sprintf('SELECT * FROM musicinfo WHERE %s', $searchsql));
+ }
- $catsrch = '';
- if (count($cat) > 0 && $cat[0] != -1) {
- $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat);
- }
+ /**
+ * @param $cat
+ * @param $start
+ * @param $num
+ * @param $orderby
+ * @param array $excludedcats
+ *
+ * @return array
+ */
+ public function getMusicRange($cat, $start, $num, $orderby, array $excludedcats = [])
+ {
+ $browseby = $this->getBrowseBy();
- $exccatlist = '';
- if (count($excludedcats) > 0) {
- $exccatlist = ' AND r.categories_id NOT IN (' . implode(',', $excludedcats) . ')';
- }
+ $catsrch = '';
+ if (count($cat) > 0 && $cat[0] != -1) {
+ $catsrch = (new Category(['Settings' => $this->pdo]))->getCategorySearch($cat);
+ }
- $order = $this->getMusicOrder($orderby);
+ $exccatlist = '';
+ if (count($excludedcats) > 0) {
+ $exccatlist = ' AND r.categories_id NOT IN ('.implode(',', $excludedcats).')';
+ }
- $music = $this->pdo->queryCalc(
+ $order = $this->getMusicOrder($orderby);
+
+ $music = $this->pdo->queryCalc(
sprintf("
SELECT SQL_CALC_FOUND_ROWS
m.id,
@@ -189,20 +191,20 @@ class Music
$exccatlist,
$order[0],
$order[1],
- ($start === false ? '' : ' LIMIT ' . $num . ' OFFSET ' . $start)
+ ($start === false ? '' : ' LIMIT '.$num.' OFFSET '.$start)
), true, NN_CACHE_EXPIRY_MEDIUM
);
- $musicIDs = $releaseIDs = false;
+ $musicIDs = $releaseIDs = false;
- if (is_array($music['result'])) {
- foreach ($music['result'] AS $mus => $id) {
- $musicIDs[] = $id['id'];
- $releaseIDs[] = $id['grp_release_id'];
- }
- }
+ if (is_array($music['result'])) {
+ foreach ($music['result'] as $mus => $id) {
+ $musicIDs[] = $id['id'];
+ $releaseIDs[] = $id['grp_release_id'];
+ }
+ }
- $sql = sprintf("
+ $sql = sprintf("
SELECT
GROUP_CONCAT(r.id ORDER BY r.postdate DESC SEPARATOR ',') AS grp_release_id,
GROUP_CONCAT(r.rarinnerfilecount ORDER BY r.postdate DESC SEPARATOR ',') as grp_rarinnerfilecount,
@@ -238,24 +240,24 @@ class Music
$order[0],
$order[1]
);
- $return = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM);
- if (!empty($return)) {
- $return[0]['_totalcount'] = $music['total'] ?? 0;
- }
+ $return = $this->pdo->query($sql, true, NN_CACHE_EXPIRY_MEDIUM);
+ if (! empty($return)) {
+ $return[0]['_totalcount'] = $music['total'] ?? 0;
+ }
- return $return;
- }
+ return $return;
+ }
- /**
- * @param $orderby
- *
- * @return array
- */
- public function getMusicOrder($orderby)
- {
- $order = ($orderby == '') ? 'r.postdate' : $orderby;
- $orderArr = explode("_", $order);
- switch ($orderArr[0]) {
+ /**
+ * @param $orderby
+ *
+ * @return array
+ */
+ public function getMusicOrder($orderby)
+ {
+ $order = ($orderby == '') ? 'r.postdate' : $orderby;
+ $orderArr = explode('_', $order);
+ switch ($orderArr[0]) {
case 'artist':
$orderfield = 'm.artist';
break;
@@ -279,87 +281,90 @@ class Music
$orderfield = 'r.postdate';
break;
}
- $ordersort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc';
- return array($orderfield, $ordersort);
- }
+ $ordersort = (isset($orderArr[1]) && preg_match('/^asc|desc$/i', $orderArr[1])) ? $orderArr[1] : 'desc';
- /**
- * @return array
- */
- public function getMusicOrdering()
- {
- return array('artist_asc', 'artist_desc', 'posted_asc', 'posted_desc', 'size_asc', 'size_desc', 'files_asc', 'files_desc', 'stats_asc', 'stats_desc', 'year_asc', 'year_desc', 'genre_asc', 'genre_desc');
- }
+ return [$orderfield, $ordersort];
+ }
- /**
- * @return array
- */
- public function getBrowseByOptions()
- {
- return array('artist' => 'artist', 'title' => 'title', 'genre' => 'genres_id', 'year' => 'year');
- }
+ /**
+ * @return array
+ */
+ public function getMusicOrdering()
+ {
+ return ['artist_asc', 'artist_desc', 'posted_asc', 'posted_desc', 'size_asc', 'size_desc', 'files_asc', 'files_desc', 'stats_asc', 'stats_desc', 'year_asc', 'year_desc', 'genre_asc', 'genre_desc'];
+ }
- /**
- * @return string
- */
- public function getBrowseBy()
- {
- $browseby = ' ';
- $browsebyArr = $this->getBrowseByOptions();
- foreach ($browsebyArr as $bbk => $bbv) {
- if (isset($_REQUEST[$bbk]) && !empty($_REQUEST[$bbk])) {
- $bbs = stripslashes($_REQUEST[$bbk]);
- if (stripos($bbv, 'id') !== false) {
- $browseby .= 'AND m.' . $bbv . ' = ' . $bbs;
- } else {
- $browseby .= 'AND m.' . $bbv . ' ' . $this->pdo->likeString($bbs, true, true);
- }
- }
- }
- return $browseby;
- }
+ /**
+ * @return array
+ */
+ public function getBrowseByOptions()
+ {
+ return ['artist' => 'artist', 'title' => 'title', 'genre' => 'genres_id', 'year' => 'year'];
+ }
- /**
- * @param $data
- * @param $field
- *
- * @return string
- */
- public function makeFieldLinks($data, $field)
- {
- $tmpArr = explode(', ', $data[$field]);
- $newArr = [];
- $i = 0;
- foreach ($tmpArr as $ta) {
- if (trim($ta) == '') {
- continue;
- }
- if ($i > 5) {
- break;
- } //only use first 6
- $newArr[] = '' . $ta . '';
- $i++;
- }
- return implode(', ', $newArr);
- }
+ /**
+ * @return string
+ */
+ public function getBrowseBy()
+ {
+ $browseby = ' ';
+ $browsebyArr = $this->getBrowseByOptions();
+ foreach ($browsebyArr as $bbk => $bbv) {
+ if (isset($_REQUEST[$bbk]) && ! empty($_REQUEST[$bbk])) {
+ $bbs = stripslashes($_REQUEST[$bbk]);
+ if (stripos($bbv, 'id') !== false) {
+ $browseby .= 'AND m.'.$bbv.' = '.$bbs;
+ } else {
+ $browseby .= 'AND m.'.$bbv.' '.$this->pdo->likeString($bbs, true, true);
+ }
+ }
+ }
- /**
- * @param $id
- * @param $title
- * @param $asin
- * @param $url
- * @param $salesrank
- * @param $artist
- * @param $publisher
- * @param $releasedate
- * @param $year
- * @param $tracks
- * @param $cover
- * @param $genres_id
- */
- public function update($id, $title, $asin, $url, $salesrank, $artist, $publisher, $releasedate, $year, $tracks, $cover, $genres_id)
- {
- $this->pdo->queryExec(
+ return $browseby;
+ }
+
+ /**
+ * @param $data
+ * @param $field
+ *
+ * @return string
+ */
+ public function makeFieldLinks($data, $field)
+ {
+ $tmpArr = explode(', ', $data[$field]);
+ $newArr = [];
+ $i = 0;
+ foreach ($tmpArr as $ta) {
+ if (trim($ta) == '') {
+ continue;
+ }
+ if ($i > 5) {
+ break;
+ } //only use first 6
+ $newArr[] = ''.$ta.'';
+ $i++;
+ }
+
+ return implode(', ', $newArr);
+ }
+
+ /**
+ * @param $id
+ * @param $title
+ * @param $asin
+ * @param $url
+ * @param $salesrank
+ * @param $artist
+ * @param $publisher
+ * @param $releasedate
+ * @param $year
+ * @param $tracks
+ * @param $cover
+ * @param $genres_id
+ */
+ public function update($id, $title, $asin, $url, $salesrank, $artist, $publisher, $releasedate, $year, $tracks, $cover, $genres_id)
+ {
+ $this->pdo->queryExec(
sprintf('
UPDATE musicinfo
SET title = %s, asin = %s, url = %s, salesrank = %s, artist = %s, publisher = %s, releasedate = %s,
@@ -371,129 +376,129 @@ class Music
$this->pdo->escapeString($year), $this->pdo->escapeString($tracks), $cover, $genres_id, $id
)
);
- }
+ }
- /**
- * @param $title
- * @param $year
- * @param null $amazdata
- *
- * @return bool
- */
- public function updateMusicInfo($title, $year, $amazdata = null)
- {
- $gen = new Genres(['Settings' => $this->pdo]);
- $ri = new ReleaseImage($this->pdo);
- $titlepercent = 0;
+ /**
+ * @param $title
+ * @param $year
+ * @param null $amazdata
+ *
+ * @return bool
+ */
+ public function updateMusicInfo($title, $year, $amazdata = null)
+ {
+ $gen = new Genres(['Settings' => $this->pdo]);
+ $ri = new ReleaseImage($this->pdo);
+ $titlepercent = 0;
- $mus = [];
- if ($title != '') {
- $amaz = $this->fetchAmazonProperties($title);
- } else if ($amazdata != null) {
- $amaz = $amazdata;
- } else {
- $amaz = false;
- }
+ $mus = [];
+ if ($title != '') {
+ $amaz = $this->fetchAmazonProperties($title);
+ } elseif ($amazdata != null) {
+ $amaz = $amazdata;
+ } else {
+ $amaz = false;
+ }
- if (!$amaz) {
- return false;
- }
+ if (! $amaz) {
+ return false;
+ }
- if (isset($amaz->Items->Item->ItemAttributes->Title)) {
- $mus['title'] = (string)$amaz->Items->Item->ItemAttributes->Title;
- if (empty($mus['title'])) {
- return false;
- }
- } else {
- return false;
- }
+ if (isset($amaz->Items->Item->ItemAttributes->Title)) {
+ $mus['title'] = (string) $amaz->Items->Item->ItemAttributes->Title;
+ if (empty($mus['title'])) {
+ return false;
+ }
+ } else {
+ return false;
+ }
- // Load genres.
- $defaultGenres = $gen->getGenres(Genres::MUSIC_TYPE);
- $genreassoc = [];
- foreach ($defaultGenres as $dg) {
- $genreassoc[$dg['id']] = strtolower($dg['title']);
- }
+ // Load genres.
+ $defaultGenres = $gen->getGenres(Genres::MUSIC_TYPE);
+ $genreassoc = [];
+ foreach ($defaultGenres as $dg) {
+ $genreassoc[$dg['id']] = strtolower($dg['title']);
+ }
- // Get album properties.
- $mus['coverurl'] = (string)$amaz->Items->Item->LargeImage->URL;
- if ($mus['coverurl'] != '') {
- $mus['cover'] = 1;
- } else {
- $mus['cover'] = 0;
- }
+ // Get album properties.
+ $mus['coverurl'] = (string) $amaz->Items->Item->LargeImage->URL;
+ if ($mus['coverurl'] != '') {
+ $mus['cover'] = 1;
+ } else {
+ $mus['cover'] = 0;
+ }
- $mus['asin'] = (string)$amaz->Items->Item->ASIN;
+ $mus['asin'] = (string) $amaz->Items->Item->ASIN;
- $mus['url'] = (string)$amaz->Items->Item->DetailPageURL;
- $mus['url'] = str_replace('%26tag%3Dws', '%26tag%3Dopensourceins%2D21', $mus['url']);
+ $mus['url'] = (string) $amaz->Items->Item->DetailPageURL;
+ $mus['url'] = str_replace('%26tag%3Dws', '%26tag%3Dopensourceins%2D21', $mus['url']);
- $mus['salesrank'] = (string)$amaz->Items->Item->SalesRank;
- if ($mus['salesrank'] == '') {
- $mus['salesrank'] = 'null';
- }
+ $mus['salesrank'] = (string) $amaz->Items->Item->SalesRank;
+ if ($mus['salesrank'] == '') {
+ $mus['salesrank'] = 'null';
+ }
- $mus['artist'] = (string)$amaz->Items->Item->ItemAttributes->Artist;
- if (empty($mus['artist'])) {
- $mus['artist'] = (string)$amaz->Items->Item->ItemAttributes->Creator;
- if (empty($mus['artist'])) {
- $mus['artist'] = '';
- }
- }
+ $mus['artist'] = (string) $amaz->Items->Item->ItemAttributes->Artist;
+ if (empty($mus['artist'])) {
+ $mus['artist'] = (string) $amaz->Items->Item->ItemAttributes->Creator;
+ if (empty($mus['artist'])) {
+ $mus['artist'] = '';
+ }
+ }
- $mus['publisher'] = (string)$amaz->Items->Item->ItemAttributes->Publisher;
+ $mus['publisher'] = (string) $amaz->Items->Item->ItemAttributes->Publisher;
- $mus['releasedate'] = $this->pdo->escapeString((string)$amaz->Items->Item->ItemAttributes->ReleaseDate);
- if ($mus['releasedate'] == "''") {
- $mus['releasedate'] = 'null';
- }
+ $mus['releasedate'] = $this->pdo->escapeString((string) $amaz->Items->Item->ItemAttributes->ReleaseDate);
+ if ($mus['releasedate'] == "''") {
+ $mus['releasedate'] = 'null';
+ }
- $mus['review'] = "";
- if (isset($amaz->Items->Item->EditorialReviews)) {
- $mus['review'] = trim(strip_tags((string)$amaz->Items->Item->EditorialReviews->EditorialReview->Content));
- }
+ $mus['review'] = '';
+ if (isset($amaz->Items->Item->EditorialReviews)) {
+ $mus['review'] = trim(strip_tags((string) $amaz->Items->Item->EditorialReviews->EditorialReview->Content));
+ }
- $mus['year'] = $year;
- if ($mus['year'] == '') {
- $mus['year'] = ($mus['releasedate'] != 'null' ? substr($mus['releasedate'], 1, 4) : date('Y'));
- }
+ $mus['year'] = $year;
+ if ($mus['year'] == '') {
+ $mus['year'] = ($mus['releasedate'] != 'null' ? substr($mus['releasedate'], 1, 4) : date('Y'));
+ }
- $mus['tracks'] = '';
- if (isset($amaz->Items->Item->Tracks)) {
- $tmpTracks = (array)$amaz->Items->Item->Tracks->Disc;
- $tracks = $tmpTracks['Track'];
- $mus['tracks'] = (is_array($tracks) && !empty($tracks)) ? implode('|', $tracks) : '';
- }
+ $mus['tracks'] = '';
+ if (isset($amaz->Items->Item->Tracks)) {
+ $tmpTracks = (array) $amaz->Items->Item->Tracks->Disc;
+ $tracks = $tmpTracks['Track'];
+ $mus['tracks'] = (is_array($tracks) && ! empty($tracks)) ? implode('|', $tracks) : '';
+ }
- similar_text($mus['artist'] . " " . $mus['title'], $title, $titlepercent);
- if ($titlepercent < 60) {
- return false;
- }
+ similar_text($mus['artist'].' '.$mus['title'], $title, $titlepercent);
+ if ($titlepercent < 60) {
+ return false;
+ }
- $genreKey = -1;
- $genreName = '';
- if (isset($amaz->Items->Item->BrowseNodes)) {
- // Had issues getting this out of the browsenodes obj.
- // Workaround is to get the xml and load that into its own obj.
- $amazGenresXml = $amaz->Items->Item->BrowseNodes->asXml();
- $amazGenresObj = simplexml_load_string($amazGenresXml);
- $amazGenres = $amazGenresObj->xpath('//BrowseNodeId');
+ $genreKey = -1;
+ $genreName = '';
+ if (isset($amaz->Items->Item->BrowseNodes)) {
+ // Had issues getting this out of the browsenodes obj.
+ // Workaround is to get the xml and load that into its own obj.
+ $amazGenresXml = $amaz->Items->Item->BrowseNodes->asXml();
+ $amazGenresObj = simplexml_load_string($amazGenresXml);
+ $amazGenres = $amazGenresObj->xpath('//BrowseNodeId');
- foreach ($amazGenres as $amazGenre) {
- $currNode = trim($amazGenre[0]);
- if (empty($genreName)) {
- $genreMatch = $this->matchBrowseNode($currNode);
- if ($genreMatch !== false) {
- $genreName = $genreMatch;
- break;
- }
- }
- }
+ foreach ($amazGenres as $amazGenre) {
+ $currNode = trim($amazGenre[0]);
+ if (empty($genreName)) {
+ $genreMatch = $this->matchBrowseNode($currNode);
+ if ($genreMatch !== false) {
+ $genreName = $genreMatch;
+ break;
+ }
+ }
+ }
- if (in_array(strtolower($genreName), $genreassoc, false)) {
- $genreKey = array_search(strtolower($genreName), $genreassoc, false);
- } else {
- $genreKey = $this->pdo->queryInsert(
+ if (in_array(strtolower($genreName), $genreassoc, false)) {
+ $genreKey = array_search(strtolower($genreName), $genreassoc, false);
+ } else {
+ $genreKey = $this->pdo->queryInsert(
sprintf('
INSERT INTO genres (title, type)
VALUES (%s, %d)',
@@ -501,160 +506,154 @@ class Music
Genres::MUSIC_TYPE
)
);
- }
- }
- $mus['musicgenre'] = $genreName;
- $mus['musicgenres_id'] = $genreKey;
+ }
+ }
+ $mus['musicgenre'] = $genreName;
+ $mus['musicgenres_id'] = $genreKey;
- $check = $this->pdo->queryOneRow(sprintf('SELECT id FROM musicinfo WHERE asin = %s', $this->pdo->escapeString($mus['asin'])));
- if ($check === false) {
- $musicId = $this->pdo->queryInsert(sprintf('INSERT INTO musicinfo (title, asin, url, salesrank, artist, publisher, '
- . 'releasedate, review, year, genres_id, tracks, cover, createddate, updateddate) VALUES '
- . '(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, now(), now())', $this->pdo->escapeString($mus['title']), $this->pdo->escapeString($mus['asin']), $this->pdo->escapeString($mus['url']), $mus['salesrank'], $this->pdo->escapeString($mus['artist']), $this->pdo->escapeString($mus['publisher']), $mus['releasedate'], $this->pdo->escapeString($mus['review']), $this->pdo->escapeString($mus['year']), ($mus['musicgenres_id'] == -1 ? "null" : $mus['musicgenres_id']), $this->pdo->escapeString($mus['tracks']), $mus['cover']));
- } else {
- $musicId = $check['id'];
- $this->pdo->queryExec(sprintf('UPDATE musicinfo SET title = %s, asin = %s, url = %s, salesrank = %s, artist = %s, '
- . 'publisher = %s, releasedate = %s, review = %s, year = %s, genres_id = %s, tracks = %s, cover = %s, '
- . 'updateddate = NOW() WHERE id = %d', $this->pdo->escapeString($mus['title']), $this->pdo->escapeString($mus['asin']), $this->pdo->escapeString($mus['url']), $mus['salesrank'], $this->pdo->escapeString($mus['artist']), $this->pdo->escapeString($mus['publisher']), $mus['releasedate'], $this->pdo->escapeString($mus['review']), $this->pdo->escapeString($mus['year']), ($mus['musicgenres_id'] == -1 ? "null" : $mus['musicgenres_id']), $this->pdo->escapeString($mus['tracks']), $mus['cover'], $musicId));
- }
+ $check = $this->pdo->queryOneRow(sprintf('SELECT id FROM musicinfo WHERE asin = %s', $this->pdo->escapeString($mus['asin'])));
+ if ($check === false) {
+ $musicId = $this->pdo->queryInsert(sprintf('INSERT INTO musicinfo (title, asin, url, salesrank, artist, publisher, '
+ .'releasedate, review, year, genres_id, tracks, cover, createddate, updateddate) VALUES '
+ .'(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, now(), now())', $this->pdo->escapeString($mus['title']), $this->pdo->escapeString($mus['asin']), $this->pdo->escapeString($mus['url']), $mus['salesrank'], $this->pdo->escapeString($mus['artist']), $this->pdo->escapeString($mus['publisher']), $mus['releasedate'], $this->pdo->escapeString($mus['review']), $this->pdo->escapeString($mus['year']), ($mus['musicgenres_id'] == -1 ? 'null' : $mus['musicgenres_id']), $this->pdo->escapeString($mus['tracks']), $mus['cover']));
+ } else {
+ $musicId = $check['id'];
+ $this->pdo->queryExec(sprintf('UPDATE musicinfo SET title = %s, asin = %s, url = %s, salesrank = %s, artist = %s, '
+ .'publisher = %s, releasedate = %s, review = %s, year = %s, genres_id = %s, tracks = %s, cover = %s, '
+ .'updateddate = NOW() WHERE id = %d', $this->pdo->escapeString($mus['title']), $this->pdo->escapeString($mus['asin']), $this->pdo->escapeString($mus['url']), $mus['salesrank'], $this->pdo->escapeString($mus['artist']), $this->pdo->escapeString($mus['publisher']), $mus['releasedate'], $this->pdo->escapeString($mus['review']), $this->pdo->escapeString($mus['year']), ($mus['musicgenres_id'] == -1 ? 'null' : $mus['musicgenres_id']), $this->pdo->escapeString($mus['tracks']), $mus['cover'], $musicId));
+ }
- if ($musicId) {
- if ($this->echooutput) {
- ColorCLI::doEcho(
- ColorCLI::header(PHP_EOL . 'Added/updated album: ') .
- ColorCLI::alternateOver(' Artist: ') .
- ColorCLI::primary($mus['artist']) .
- ColorCLI::alternateOver(' Title: ') .
- ColorCLI::primary($mus['title']) .
- ColorCLI::alternateOver(' Year: ') .
+ if ($musicId) {
+ if ($this->echooutput) {
+ ColorCLI::doEcho(
+ ColorCLI::header(PHP_EOL.'Added/updated album: ').
+ ColorCLI::alternateOver(' Artist: ').
+ ColorCLI::primary($mus['artist']).
+ ColorCLI::alternateOver(' Title: ').
+ ColorCLI::primary($mus['title']).
+ ColorCLI::alternateOver(' Year: ').
ColorCLI::primary($mus['year'])
);
- }
- $mus['cover'] = $ri->saveImage($musicId, $mus['coverurl'], $this->imgSavePath, 250, 250);
- } else {
- if ($this->echooutput) {
- if ($mus['artist'] == '') {
- $artist = '';
- } else {
- $artist = 'Artist: ' . $mus['artist'] . ', Album: ';
- }
- ColorCLI::doEcho(
- ColorCLI::headerOver('Nothing to update: ') .
+ }
+ $mus['cover'] = $ri->saveImage($musicId, $mus['coverurl'], $this->imgSavePath, 250, 250);
+ } else {
+ if ($this->echooutput) {
+ if ($mus['artist'] == '') {
+ $artist = '';
+ } else {
+ $artist = 'Artist: '.$mus['artist'].', Album: ';
+ }
+ ColorCLI::doEcho(
+ ColorCLI::headerOver('Nothing to update: ').
ColorCLI::primaryOver(
- $artist .
- $mus['title'] .
- ' (' .
- $mus['year'] .
+ $artist.
+ $mus['title'].
+ ' ('.
+ $mus['year'].
')'
)
);
- }
- }
+ }
+ }
- return $musicId;
- }
+ return $musicId;
+ }
- /**
- * @param $title
- *
- * @return bool|mixed
- * @throws \Exception
- */
- public function fetchAmazonProperties($title)
- {
- $response = false;
- $conf = new GenericConfiguration();
- $client = new Client();
- $request = new GuzzleRequest($client);
+ /**
+ * @param $title
+ *
+ * @return bool|mixed
+ * @throws \Exception
+ */
+ public function fetchAmazonProperties($title)
+ {
+ $response = false;
+ $conf = new GenericConfiguration();
+ $client = new Client();
+ $request = new GuzzleRequest($client);
- try {
- $conf
+ try {
+ $conf
->setCountry('com')
->setAccessKey($this->pubkey)
->setSecretKey($this->privkey)
->setAssociateTag($this->asstag)
->setRequest($request)
->setResponseTransformer(new XmlToSimpleXmlObject());
- } catch (\Exception $e) {
- echo $e->getMessage();
- }
+ } catch (\Exception $e) {
+ echo $e->getMessage();
+ }
- $apaiIo = new ApaiIO($conf);
- // Try Music category.
- try {
- $search = new Search();
- $search->setCategory('Music');
- $search->setKeywords($title);
- $search->setResponseGroup(['Large']);
- $response = $apaiIo->runOperation($search);
- } catch (\Exception $e) {
- // Empty because we try another method.
- }
+ $apaiIo = new ApaiIO($conf);
+ // Try Music category.
+ try {
+ $search = new Search();
+ $search->setCategory('Music');
+ $search->setKeywords($title);
+ $search->setResponseGroup(['Large']);
+ $response = $apaiIo->runOperation($search);
+ } catch (\Exception $e) {
+ // Empty because we try another method.
+ }
- // Try MP3 category.
- if ($response === false) {
- usleep(700000);
- try {
- $search = new Search();
- $search->setCategory('MP3Downloads');
- $search->setKeywords($title);
- $search->setResponseGroup(['Large']);
- $response = $apaiIo->runOperation($search);
- } catch (\Exception $e) {
- // Empty because we try another method.
- }
- }
+ // Try MP3 category.
+ if ($response === false) {
+ usleep(700000);
+ try {
+ $search = new Search();
+ $search->setCategory('MP3Downloads');
+ $search->setKeywords($title);
+ $search->setResponseGroup(['Large']);
+ $response = $apaiIo->runOperation($search);
+ } catch (\Exception $e) {
+ // Empty because we try another method.
+ }
+ }
- // Try Digital Music category.
- if ($response === false) {
- usleep(700000);
- try {
- $search = new Search();
- $search->setCategory('DigitalMusic');
- $search->setKeywords($title);
- $search->setResponseGroup(['Large']);
- $response = $apaiIo->runOperation($search);
- } catch (\Exception $e) {
- // Empty because we try another method.
- }
- }
+ // Try Digital Music category.
+ if ($response === false) {
+ usleep(700000);
+ try {
+ $search = new Search();
+ $search->setCategory('DigitalMusic');
+ $search->setKeywords($title);
+ $search->setResponseGroup(['Large']);
+ $response = $apaiIo->runOperation($search);
+ } catch (\Exception $e) {
+ // Empty because we try another method.
+ }
+ }
- // Try Music Tracks category.
- if ($response === false) {
- usleep(700000);
- try {
- $search = new Search();
- $search->setCategory('MusicTracks');
- $search->setKeywords($title);
- $search->setResponseGroup(['Large']);
- $response = $apaiIo->runOperation($search);
- } catch (\Exception $e) {
- // Empty because we exhausted all possibilities.
- }
- }
- if ($response === false)
- {
- throw new \Exception('Could not connect to Amazon');
- }
- else
- {
- if (isset($response->Items->Item->ItemAttributes->Title))
- {
- return $response;
- }
- else
- {
- return false;
- }
- }
- }
+ // Try Music Tracks category.
+ if ($response === false) {
+ usleep(700000);
+ try {
+ $search = new Search();
+ $search->setCategory('MusicTracks');
+ $search->setKeywords($title);
+ $search->setResponseGroup(['Large']);
+ $response = $apaiIo->runOperation($search);
+ } catch (\Exception $e) {
+ // Empty because we exhausted all possibilities.
+ }
+ }
+ if ($response === false) {
+ throw new \Exception('Could not connect to Amazon');
+ } else {
+ if (isset($response->Items->Item->ItemAttributes->Title)) {
+ return $response;
+ } else {
+ return false;
+ }
+ }
+ }
- /**
- * @param bool $local
- */
- public function processMusicReleases($local = false)
- {
- $res = $this->pdo->queryDirect(
+ /**
+ * @param bool $local
+ */
+ public function processMusicReleases($local = false)
+ {
+ $res = $this->pdo->queryDirect(
sprintf('
SELECT searchname, id
FROM releases
@@ -670,112 +669,112 @@ class Music
$this->musicqty
)
);
- if ($res instanceof \Traversable && $res->rowCount() > 0) {
- if ($this->echooutput) {
- ColorCLI::doEcho(
- ColorCLI::header('Processing ' . $res->rowCount() .' music release(s).'
+ if ($res instanceof \Traversable && $res->rowCount() > 0) {
+ if ($this->echooutput) {
+ ColorCLI::doEcho(
+ ColorCLI::header('Processing '.$res->rowCount().' music release(s).'
)
);
- }
+ }
- foreach ($res as $arr) {
- $startTime = microtime(true);
- $usedAmazon = false;
- $album = $this->parseArtist($arr['searchname']);
- if ($album !== false) {
- $newname = $album['name'] . ' (' . $album['year'] . ')';
+ foreach ($res as $arr) {
+ $startTime = microtime(true);
+ $usedAmazon = false;
+ $album = $this->parseArtist($arr['searchname']);
+ if ($album !== false) {
+ $newname = $album['name'].' ('.$album['year'].')';
- if ($this->echooutput) {
- ColorCLI::doEcho(ColorCLI::headerOver('Looking up: ') . ColorCLI::primary($newname));
- }
+ if ($this->echooutput) {
+ ColorCLI::doEcho(ColorCLI::headerOver('Looking up: ').ColorCLI::primary($newname));
+ }
- // Do a local lookup first
- $musicCheck = $this->getMusicInfoByName('', $album["name"]);
+ // Do a local lookup first
+ $musicCheck = $this->getMusicInfoByName('', $album['name']);
- if ($musicCheck === false && in_array($album['name'] . $album['year'], $this->failCache, false)) {
- // Lookup recently failed, no point trying again
- if ($this->echooutput) {
- ColorCLI::doEcho(ColorCLI::headerOver('Cached previous failure. Skipping.') . PHP_EOL);
- }
- $albumId = -2;
- } else if ($musicCheck === false && $local === false) {
- $albumId = $this->updateMusicInfo($album['name'], $album['year']);
- $usedAmazon = true;
- if ($albumId === false) {
- $albumId = -2;
- $this->failCache[] = $album['name'] . $album['year'];
- }
- } else {
- $albumId = $musicCheck['id'];
- }
+ if ($musicCheck === false && in_array($album['name'].$album['year'], $this->failCache, false)) {
+ // Lookup recently failed, no point trying again
+ if ($this->echooutput) {
+ ColorCLI::doEcho(ColorCLI::headerOver('Cached previous failure. Skipping.').PHP_EOL);
+ }
+ $albumId = -2;
+ } elseif ($musicCheck === false && $local === false) {
+ $albumId = $this->updateMusicInfo($album['name'], $album['year']);
+ $usedAmazon = true;
+ if ($albumId === false) {
+ $albumId = -2;
+ $this->failCache[] = $album['name'].$album['year'];
+ }
+ } else {
+ $albumId = $musicCheck['id'];
+ }
- // Update release.
- $this->pdo->queryExec(sprintf('UPDATE releases SET musicinfo_id = %d WHERE id = %d', $albumId, $arr['id']));
- } // No album found.
- else {
- $this->pdo->queryExec(sprintf('UPDATE releases SET musicinfo_id = %d WHERE id = %d', -2, $arr['id']));
- echo '.';
- }
+ // Update release.
+ $this->pdo->queryExec(sprintf('UPDATE releases SET musicinfo_id = %d WHERE id = %d', $albumId, $arr['id']));
+ } // No album found.
+ else {
+ $this->pdo->queryExec(sprintf('UPDATE releases SET musicinfo_id = %d WHERE id = %d', -2, $arr['id']));
+ echo '.';
+ }
- // Sleep to not flood amazon.
- $diff = floor((microtime(true) - $startTime) * 1000000);
- if ($this->sleeptime * 1000 - $diff > 0 && $usedAmazon === true) {
- usleep($this->sleeptime * 1000 - $diff);
- }
- }
+ // Sleep to not flood amazon.
+ $diff = floor((microtime(true) - $startTime) * 1000000);
+ if ($this->sleeptime * 1000 - $diff > 0 && $usedAmazon === true) {
+ usleep($this->sleeptime * 1000 - $diff);
+ }
+ }
- if ($this->echooutput) {
- echo "\n";
- }
+ if ($this->echooutput) {
+ echo "\n";
+ }
+ } else {
+ if ($this->echooutput) {
+ ColorCLI::doEcho(ColorCLI::header('No music releases to process.'));
+ }
+ }
+ }
- } else {
- if ($this->echooutput) {
- ColorCLI::doEcho(ColorCLI::header('No music releases to process.'));
- }
- }
- }
+ /**
+ * @param $releasename
+ *
+ * @return array|bool
+ */
+ public function parseArtist($releasename)
+ {
+ if (preg_match('/(.+?)(\d{1,2} \d{1,2} )?\(?(19\d{2}|20[0-1][\d])\b/', $releasename, $name)) {
+ $result = [];
+ $result['year'] = $name[3];
- /**
- * @param $releasename
- *
- * @return array|bool
- */
- public function parseArtist($releasename)
- {
- if (preg_match('/(.+?)(\d{1,2} \d{1,2} )?\(?(19\d{2}|20[0-1][\d])\b/', $releasename, $name)) {
- $result = [];
- $result["year"] = $name[3];
+ $a = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(Bootleg|Boxset|Clean.+Version|Compiled by.+|\dCD|Digipak|DIRFIX|DVBS|FLAC|(Ltd )?(Deluxe|Limited|Special).+Edition|Promo|PROOF|Reissue|Remastered|REPACK|RETAIL(.+UK)?|SACD|Sampler|SAT|Summer.+Mag|UK.+Import|Deluxe.+Version|VINYL|WEB)/i', ' ', $name[1]);
+ $b = preg_replace('/( |-)([a-z]+[\d]+[a-z]+[\d]+.+|[a-z]{2,}[\d]{2,}?.+|3FM|B00[a-z0-9]+|BRC482012|H056|UXM1DW086|(4WCD|ATL|bigFM|CDP|DST|ERE|FIM|MBZZ|MSOne|MVRD|QEDCD|RNB|SBD|SFT|ZYX)( |-)\d.+)/i', ' ', $a);
+ $c = preg_replace('/( |-)(\d{1,2} \d{1,2} )?([A-Z])( ?$)|\(?[\d]{8,}\)?|( |-)(CABLE|FREEWEB|LINE|MAG|MCD|YMRSMILES)|\(([a-z]{2,}[\d]{2,}|ost)\)|-web-/i', ' ', $b);
+ $d = preg_replace('/VA( |-)/', 'Various Artists ', $c);
+ $e = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(DAB|DE|DVBC|EP|FIX|IT|Jap|NL|PL|(Pure )?FM|SSL|VLS)( |-)/i', ' ', $d);
+ $f = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(CABLE|CD(A|EP|M|R|S)?|QEDCD|SAT|SBD)( |-)/i', ' ', $e);
+ $g = str_replace(['_', '-'], ' ', $f);
+ $h = trim(preg_replace('/\s\s+/', ' ', $g));
+ $newname = trim(preg_replace('/ [a-z]{2}$| [a-z]{3} \d{2,}$|\d{5,} \d{5,}$|-WEB$/i', '', $h));
- $a = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(Bootleg|Boxset|Clean.+Version|Compiled by.+|\dCD|Digipak|DIRFIX|DVBS|FLAC|(Ltd )?(Deluxe|Limited|Special).+Edition|Promo|PROOF|Reissue|Remastered|REPACK|RETAIL(.+UK)?|SACD|Sampler|SAT|Summer.+Mag|UK.+Import|Deluxe.+Version|VINYL|WEB)/i', ' ', $name[1]);
- $b = preg_replace('/( |-)([a-z]+[\d]+[a-z]+[\d]+.+|[a-z]{2,}[\d]{2,}?.+|3FM|B00[a-z0-9]+|BRC482012|H056|UXM1DW086|(4WCD|ATL|bigFM|CDP|DST|ERE|FIM|MBZZ|MSOne|MVRD|QEDCD|RNB|SBD|SFT|ZYX)( |-)\d.+)/i', ' ', $a);
- $c = preg_replace('/( |-)(\d{1,2} \d{1,2} )?([A-Z])( ?$)|\(?[\d]{8,}\)?|( |-)(CABLE|FREEWEB|LINE|MAG|MCD|YMRSMILES)|\(([a-z]{2,}[\d]{2,}|ost)\)|-web-/i', ' ', $b);
- $d = preg_replace('/VA( |-)/', 'Various Artists ', $c);
- $e = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(DAB|DE|DVBC|EP|FIX|IT|Jap|NL|PL|(Pure )?FM|SSL|VLS)( |-)/i', ' ', $d);
- $f = preg_replace('/( |-)(\d{1,2} \d{1,2} )?(CABLE|CD(A|EP|M|R|S)?|QEDCD|SAT|SBD)( |-)/i', ' ', $e);
- $g = str_replace(['_', '-'], ' ', $f);
- $h = trim(preg_replace('/\s\s+/', ' ', $g));
- $newname = trim(preg_replace('/ [a-z]{2}$| [a-z]{3} \d{2,}$|\d{5,} \d{5,}$|-WEB$/i', '', $h));
+ if (! preg_match('/^[a-z0-9]+$/i', $newname) && strlen($newname) > 10) {
+ $result['name'] = $newname;
- if (!preg_match('/^[a-z0-9]+$/i', $newname) && strlen($newname) > 10) {
- $result['name'] = $newname;
- return $result;
- } else {
- return false;
- }
- } else {
- return false;
- }
- }
+ return $result;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
- /**
- * @param bool $activeOnly
- *
- * @return array
- */
- public function getGenres($activeOnly = false)
- {
- if ($activeOnly) {
- return $this->pdo->query('
+ /**
+ * @param bool $activeOnly
+ *
+ * @return array
+ */
+ public function getGenres($activeOnly = false)
+ {
+ if ($activeOnly) {
+ return $this->pdo->query('
SELECT ge.*
FROM genres ge
INNER JOIN
@@ -786,27 +785,26 @@ class Music
WHERE ge.type = " . Category::MUSIC_ROOT . "
ORDER BY title'
);
- } else {
- return $this->pdo->query('
+ } else {
+ return $this->pdo->query('
SELECT * FROM genres
WHERE type = " . Category::MUSIC_ROOT . "
ORDER BY title'
);
- }
- }
+ }
+ }
+ /**
+ * @param $nodeId
+ *
+ * @return bool|string
+ */
+ public function matchBrowseNode($nodeId)
+ {
+ $str = '';
- /**
- * @param $nodeId
- *
- * @return bool|string
- */
- public function matchBrowseNode($nodeId)
- {
- $str = '';
-
- //music nodes above mp3 download nodes
- switch ($nodeId) {
+ //music nodes above mp3 download nodes
+ switch ($nodeId) {
case '163420':
$str = 'Music Video & Concerts';
break;
@@ -899,7 +897,7 @@ class Music
$str = 'Miscellaneous';
break;
}
- return ($str != '') ? $str : false;
- }
+ return ($str != '') ? $str : false;
+ }
}
diff --git a/nntmux/NNTP.php b/nntmux/NNTP.php
index 14d2e3953..7742adfa8 100755
--- a/nntmux/NNTP.php
+++ b/nntmux/NNTP.php
@@ -1,9 +1,10 @@
true,
'Logger' => null,
'Settings' => null,
];
- $options += $defaults;
+ $options += $defaults;
- parent::__construct();
+ parent::__construct();
- $this->_echo = ($options['Echo'] && NN_ECHOCLI);
+ $this->_echo = ($options['Echo'] && NN_ECHOCLI);
- $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB());
+ $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB());
- $this->_debugBool = (NN_LOGGING || NN_DEBUG);
- if ($this->_debugBool) {
- try {
- $this->_debugging = ($options['Logger'] instanceof Logger ? $options['Logger'] : new Logger(['ColorCLI' => $this->pdo->log]));
- } catch (LoggerException $error) {
- $this->_debugBool = false;
- }
- }
+ $this->_debugBool = (NN_LOGGING || NN_DEBUG);
+ if ($this->_debugBool) {
+ try {
+ $this->_debugging = ($options['Logger'] instanceof Logger ? $options['Logger'] : new Logger(['ColorCLI' => $this->pdo->log]));
+ } catch (LoggerException $error) {
+ $this->_debugBool = false;
+ }
+ }
- $this->_nntpRetries = Settings::value('..nntpretries') !== '' ? (int)Settings::value('..nntpretries') : 0 + 1;
- }
+ $this->_nntpRetries = Settings::value('..nntpretries') !== '' ? (int) Settings::value('..nntpretries') : 0 + 1;
+ }
- /**
- * Destruct.
- * Close the NNTP connection if still connected.
- *
- * @access public
- */
- public function __destruct()
- {
- $this->doQuit();
- }
+ /**
+ * Destruct.
+ * Close the NNTP connection if still connected.
+ */
+ public function __destruct()
+ {
+ $this->doQuit();
+ }
- /**
- * Connect to a usenet server.
- *
- * @param boolean $compression Should we attempt to enable XFeature Gzip compression on this connection?
- * @param boolean $alternate Use the alternate NNTP connection.
- *
- * @return mixed On success = (bool) Did we successfully connect to the usenet?
- * @throws \Exception
- * On failure = (object) PEAR_Error.
- *
- * @access public
- */
- public function doConnect($compression = true, $alternate = false)
- {
- if (// (Alternate is wanted, AND current server is alt, OR Alternate is not wanted AND current is main.) AND
- (($alternate && $this->_currentServer === env('NNTP_SERVER_A')) || (!$alternate && $this->_currentServer === env('NNTP_SERVER'))) &&
+ /**
+ * Connect to a usenet server.
+ *
+ * @param bool $compression Should we attempt to enable XFeature Gzip compression on this connection?
+ * @param bool $alternate Use the alternate NNTP connection.
+ *
+ * @return mixed On success = (bool) Did we successfully connect to the usenet?
+ * @throws \Exception
+ * On failure = (object) PEAR_Error.
+ */
+ public function doConnect($compression = true, $alternate = false)
+ {
+ if (// (Alternate is wanted, AND current server is alt, OR Alternate is not wanted AND current is main.) AND
+ (($alternate && $this->_currentServer === env('NNTP_SERVER_A')) || (! $alternate && $this->_currentServer === env('NNTP_SERVER'))) &&
// Don't reconnect to usenet if:
// We are already connected to usenet.
parent::_isConnected()
) {
- return true;
- }
+ return true;
+ }
- $this->doQuit();
+ $this->doQuit();
- $ret = $connected = $cError = $aError = false;
+ $ret = $connected = $cError = $aError = false;
- // Set variables to connect based on if we are using the alternate provider or not.
- if (!$alternate) {
- $sslEnabled = env('NNTP_SSLENABLED') ? true : false;
- $this->_currentServer = env('NNTP_SERVER');
- $this->_currentPort = env('NNTP_PORT');
- $userName = env('NNTP_USERNAME');
- $password = env('NNTP_PASSWORD');
- $socketTimeout = !empty(env('NNTP_SOCKET_TIMEOUT')) ? env('NNTP_SOCKET_TIMEOUT') : $this->_socketTimeout;
- } else {
- $sslEnabled = env('NNTP_SSLENABLED_A') ? true : false;
- $this->_currentServer = env('NNTP_SERVER_A');
- $this->_currentPort = env('NNTP_PORT_A');
- $userName = env('NNTP_USERNAME_A');
- $password = env('NNTP_PASSWORD_A');
- $socketTimeout = !empty(env('NNTP_SOCKET_TIMEOUT_A')) ? env('NNTP_SOCKET_TIMEOUT_A') : $this->_socketTimeout;
- }
+ // Set variables to connect based on if we are using the alternate provider or not.
+ if (! $alternate) {
+ $sslEnabled = env('NNTP_SSLENABLED') ? true : false;
+ $this->_currentServer = env('NNTP_SERVER');
+ $this->_currentPort = env('NNTP_PORT');
+ $userName = env('NNTP_USERNAME');
+ $password = env('NNTP_PASSWORD');
+ $socketTimeout = ! empty(env('NNTP_SOCKET_TIMEOUT')) ? env('NNTP_SOCKET_TIMEOUT') : $this->_socketTimeout;
+ } else {
+ $sslEnabled = env('NNTP_SSLENABLED_A') ? true : false;
+ $this->_currentServer = env('NNTP_SERVER_A');
+ $this->_currentPort = env('NNTP_PORT_A');
+ $userName = env('NNTP_USERNAME_A');
+ $password = env('NNTP_PASSWORD_A');
+ $socketTimeout = ! empty(env('NNTP_SOCKET_TIMEOUT_A')) ? env('NNTP_SOCKET_TIMEOUT_A') : $this->_socketTimeout;
+ }
- $enc = ($sslEnabled ? ' (ssl)' : ' (non-ssl)');
- $sslEnabled = ($sslEnabled ? 'tls' : false);
+ $enc = ($sslEnabled ? ' (ssl)' : ' (non-ssl)');
+ $sslEnabled = ($sslEnabled ? 'tls' : false);
- // Try to connect until we run of out tries.
- $retries = $this->_nntpRetries;
- while (true) {
- $retries--;
- $authenticated = false;
+ // Try to connect until we run of out tries.
+ $retries = $this->_nntpRetries;
+ while (true) {
+ $retries--;
+ $authenticated = false;
- // If we are not connected, try to connect.
- if (!$connected) {
- $ret = $this->connect($this->_currentServer, $sslEnabled, $this->_currentPort, 5, $socketTimeout);
- }
+ // If we are not connected, try to connect.
+ if (! $connected) {
+ $ret = $this->connect($this->_currentServer, $sslEnabled, $this->_currentPort, 5, $socketTimeout);
+ }
- // Check if we got an error while connecting.
- $cErr = $this->isError($ret);
+ // Check if we got an error while connecting.
+ $cErr = $this->isError($ret);
- // If no error, we are connected.
- if (!$cErr) {
- // Say that we are connected so we don't retry.
- $connected = true;
- // When there is no error it returns bool if we are allowed to post or not.
- $this->_postingAllowed = $ret;
- } else {
- // Only fetch the message once.
- if (!$cError) {
- $cError = $ret->getMessage();
- }
- }
+ // If no error, we are connected.
+ if (! $cErr) {
+ // Say that we are connected so we don't retry.
+ $connected = true;
+ // When there is no error it returns bool if we are allowed to post or not.
+ $this->_postingAllowed = $ret;
+ } else {
+ // Only fetch the message once.
+ if (! $cError) {
+ $cError = $ret->getMessage();
+ }
+ }
- // If error, try to connect again.
- if ($cErr && $retries > 0) {
- continue;
- }
+ // If error, try to connect again.
+ if ($cErr && $retries > 0) {
+ continue;
+ }
- // If we have no more retries and could not connect, return an error.
- if ($retries === 0 && !$connected) {
- $message =
- 'Cannot connect to server ' .
- $this->_currentServer .
- $enc .
- ': ' .
+ // If we have no more retries and could not connect, return an error.
+ if ($retries === 0 && ! $connected) {
+ $message =
+ 'Cannot connect to server '.
+ $this->_currentServer.
+ $enc.
+ ': '.
$cError;
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR);
- }
- return $this->throwError(ColorCLI::error($message));
- }
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR);
+ }
- // If we are connected, try to authenticate.
- if ($connected === true && $authenticated === false) {
+ return $this->throwError(ColorCLI::error($message));
+ }
+
+ // If we are connected, try to authenticate.
+ if ($connected === true && $authenticated === false) {
// If the username is empty it probably means the server does not require a username.
- if ($userName === '') {
- $authenticated = true;
+ if ($userName === '') {
+ $authenticated = true;
- // Try to authenticate to usenet.
- } else {
- $ret2 = $this->authenticate($userName, $password);
+ // Try to authenticate to usenet.
+ } else {
+ $ret2 = $this->authenticate($userName, $password);
- // Check if there was an error authenticating.
- $aErr = $this->isError($ret2);
+ // Check if there was an error authenticating.
+ $aErr = $this->isError($ret2);
- // If there was no error, then we are authenticated.
- if (!$aErr) {
- $authenticated = true;
- } elseif (!$aError) {
- $aError = $ret2->getMessage();
- }
+ // If there was no error, then we are authenticated.
+ if (! $aErr) {
+ $authenticated = true;
+ } elseif (! $aError) {
+ $aError = $ret2->getMessage();
+ }
- // If error, try to authenticate again.
- if ($aErr && $retries > 0) {
- continue;
- }
+ // If error, try to authenticate again.
+ if ($aErr && $retries > 0) {
+ continue;
+ }
- // If we ran out of retries, return an error.
- if ($retries === 0 && $authenticated === false) {
- $message =
- 'Cannot authenticate to server ' .
- $this->_currentServer .
- $enc .
- ' - ' .
- $userName .
- ' (' . $aError . ')';
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR);
- }
- return $this->throwError(ColorCLI::error($message));
- }
- }
- }
+ // If we ran out of retries, return an error.
+ if ($retries === 0 && $authenticated === false) {
+ $message =
+ 'Cannot authenticate to server '.
+ $this->_currentServer.
+ $enc.
+ ' - '.
+ $userName.
+ ' ('.$aError.')';
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR);
+ }
- // If we are connected and authenticated, try enabling compression if we have it enabled.
- if ($connected === true && $authenticated === true) {
- // Check if we should use compression on the connection.
- if ($compression === false || (int)Settings::value('..compressedheaders') === 0) {
- $this->_compressionSupported = false;
- }
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, 'Connected to ' . $this->_currentServer . '.', Logger::LOG_INFO);
- }
- return true;
- }
- // If we reached this point and have not connected after all retries, break out of the loop.
- if ($retries === 0) {
- break;
- }
+ return $this->throwError(ColorCLI::error($message));
+ }
+ }
+ }
- // Sleep .4 seconds between retries.
- usleep(400000);
- }
- // If we somehow got out of the loop, return an error.
- $message = 'Unable to connect to ' . $this->_currentServer . $enc;
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR);
- }
- return $this->throwError(ColorCLI::error($message));
- }
+ // If we are connected and authenticated, try enabling compression if we have it enabled.
+ if ($connected === true && $authenticated === true) {
+ // Check if we should use compression on the connection.
+ if ($compression === false || (int) Settings::value('..compressedheaders') === 0) {
+ $this->_compressionSupported = false;
+ }
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, 'Connected to '.$this->_currentServer.'.', Logger::LOG_INFO);
+ }
- /**
- * Disconnect from the current NNTP server.
- *
- * @param bool $force Force quit even if not connected?
- *
- * @return mixed On success : (bool) Did we successfully disconnect from usenet?
- * On Failure : (object) PEAR_Error.
- *
- * @access public
- */
- public function doQuit($force = false)
- {
- $this->_resetProperties();
+ return true;
+ }
+ // If we reached this point and have not connected after all retries, break out of the loop.
+ if ($retries === 0) {
+ break;
+ }
- // Check if we are connected to usenet.
- if ($force === true || parent::_isConnected(false)) {
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, 'Disconnecting from ' . $this->_currentServer, Logger::LOG_INFO);
- }
- // Disconnect from usenet.
- return parent::disconnect();
- }
- return true;
- }
+ // Sleep .4 seconds between retries.
+ usleep(400000);
+ }
+ // If we somehow got out of the loop, return an error.
+ $message = 'Unable to connect to '.$this->_currentServer.$enc;
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_ERROR);
+ }
- /**
- * Reset some properties when disconnecting from usenet.
- *
- * @void
- *
- * @access protected
- */
- protected function _resetProperties(): void
- {
- $this->_compressionEnabled = false;
- $this->_compressionSupported = true;
- $this->_currentGroup = '';
- $this->_postingAllowed = false;
- parent::_resetProperties();
- }
+ return $this->throwError(ColorCLI::error($message));
+ }
- /**
- * Attempt to enable compression if the admin enabled the site setting.
- *
- * @note This can be used to enable compression if the server was connected without compression.
- *
- * @access public
- * @throws \Exception
- */
- public function enableCompression(): void
- {
- if ((int)Settings::value('..compressedheaders') !== 1) {
- return;
- }
- $this->_enableCompression();
- }
+ /**
+ * Disconnect from the current NNTP server.
+ *
+ * @param bool $force Force quit even if not connected?
+ *
+ * @return mixed On success : (bool) Did we successfully disconnect from usenet?
+ * On Failure : (object) PEAR_Error.
+ */
+ public function doQuit($force = false)
+ {
+ $this->_resetProperties();
- /**
- * @param string $group Name of the group to select.
- * @param bool $articles (optional) experimental! When true the article numbers is returned in 'articles'.
- * @param bool $force Force a refresh to get updated data from the usenet server.
- *
- * @return mixed On success : (array) Group information.
- * @throws \Exception
- * On failure : (object) PEAR_Error.
- *
- * @access public
- */
- public function selectGroup($group, $articles = false, $force = false)
- {
- $connected = $this->_checkConnection(false);
- if ($connected !== true) {
- return $connected;
- }
+ // Check if we are connected to usenet.
+ if ($force === true || parent::_isConnected(false)) {
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, 'Disconnecting from '.$this->_currentServer, Logger::LOG_INFO);
+ }
+ // Disconnect from usenet.
+ return parent::disconnect();
+ }
- // Check if the current selected group is the same, or if we have not selected a group or if a fresh summary is wanted.
- if ($force || $this->_currentGroup !== $group || $this->_selectedGroupSummary === null) {
- $this->_currentGroup = $group;
- return parent::selectGroup($group, $articles);
- }
- return $this->_selectedGroupSummary;
- }
+ return true;
+ }
- /**
- * Fetch an overview of article(s) in the currently selected group.
- *
- * @param string $range
- * @param bool $names
- * @param bool $forceNames
- *
- * @return mixed On success : (array) Multidimensional array with article headers.
- * @throws \Exception
- * On failure : (object) PEAR_Error.
- *
- * @access public
- */
- public function getOverview($range = null, $names = true, $forceNames = true)
- {
- $connected = $this->_checkConnection();
- if ($connected !== true) {
- return $connected;
- }
+ /**
+ * Reset some properties when disconnecting from usenet.
+ *
+ * @void
+ */
+ protected function _resetProperties(): void
+ {
+ $this->_compressionEnabled = false;
+ $this->_compressionSupported = true;
+ $this->_currentGroup = '';
+ $this->_postingAllowed = false;
+ parent::_resetProperties();
+ }
- // Enabled header compression if not enabled.
- $this->_enableCompression();
- return parent::getOverview($range, $names, $forceNames);
- }
+ /**
+ * Attempt to enable compression if the admin enabled the site setting.
+ *
+ * @note This can be used to enable compression if the server was connected without compression.
+ *
+ * @throws \Exception
+ */
+ public function enableCompression(): void
+ {
+ if ((int) Settings::value('..compressedheaders') !== 1) {
+ return;
+ }
+ $this->_enableCompression();
+ }
- /**
- * Pass a XOVER command to the NNTP provider, return array of articles using the overview format as array keys.
- *
- * @note This is a faster implementation of getOverview.
- *
- * Example successful return:
- * array(9) {
- * 'Number' => string(9) "679871775"
- * 'Subject' => string(18) "This is an example"
- * 'From' => string(19) "Example@example.com"
- * 'Date' => string(24) "26 Jun 2014 13:08:22 GMT"
- * 'Message-ID' => string(57) ""
- * 'References' => string(0) ""
- * 'Bytes' => string(3) "123"
- * 'Lines' => string(1) "9"
- * 'Xref' => string(66) "e alt.test:679871775"
- * }
- *
- * @param string $range Range of articles to get the overview for. Examples follow:
- * Single article number: "679871775"
- * Range of article numbers: "679871775-679999999"
- * All newer than article number: "679871775-"
- * All older than article number: "-679871775"
- * Message-ID: ""
- *
- * @return array|object Multi-dimensional Array of headers on success, PEAR object on failure.
- * @throws \Exception
- */
- public function getXOVER($range)
- {
- // Check if we are still connected.
- $connected = $this->_checkConnection();
- if ($connected !== true) {
- return $connected;
- }
+ /**
+ * @param string $group Name of the group to select.
+ * @param bool $articles (optional) experimental! When true the article numbers is returned in 'articles'.
+ * @param bool $force Force a refresh to get updated data from the usenet server.
+ *
+ * @return mixed On success : (array) Group information.
+ * @throws \Exception
+ * On failure : (object) PEAR_Error.
+ */
+ public function selectGroup($group, $articles = false, $force = false)
+ {
+ $connected = $this->_checkConnection(false);
+ if ($connected !== true) {
+ return $connected;
+ }
- // Enabled header compression if not enabled.
- $this->_enableCompression();
+ // Check if the current selected group is the same, or if we have not selected a group or if a fresh summary is wanted.
+ if ($force || $this->_currentGroup !== $group || $this->_selectedGroupSummary === null) {
+ $this->_currentGroup = $group;
- // Send XOVER command to NNTP with wanted articles.
- $response = $this->_sendCommand('XOVER ' . $range);
- if ($this->isError($response)) {
- return $response;
- }
+ return parent::selectGroup($group, $articles);
+ }
- // Verify the NNTP server got the right command, get the headers data.
- if ($response === NET_NNTP_PROTOCOL_RESPONSECODE_OVERVIEW_FOLLOWS) {
- $data = $this->_getTextResponse();
- if ($this->isError($data)) {
- return $data;
- }
- } else {
- return $this->_handleErrorResponse($response);
- }
+ return $this->_selectedGroupSummary;
+ }
- // Fetch the header overview format (for setting the array keys on the return array).
- if ($this->_overviewFormatCache !== null && isset($this->_overviewFormatCache['Xref'])) {
- $overview = $this->_overviewFormatCache;
- } else {
- $overview = $this->getOverviewFormat(false, true);
- if ($this->isError($overview)) {
- return $overview;
- }
- $this->_overviewFormatCache = $overview;
- }
- // Add the "Number" key.
- $overview = array_merge(['Number' => false], $overview);
+ /**
+ * Fetch an overview of article(s) in the currently selected group.
+ *
+ * @param string $range
+ * @param bool $names
+ * @param bool $forceNames
+ *
+ * @return mixed On success : (array) Multidimensional array with article headers.
+ * @throws \Exception
+ * On failure : (object) PEAR_Error.
+ */
+ public function getOverview($range = null, $names = true, $forceNames = true)
+ {
+ $connected = $this->_checkConnection();
+ if ($connected !== true) {
+ return $connected;
+ }
- // Iterator used for selecting the header elements to insert into the overview format array.
- $iterator = 0;
+ // Enabled header compression if not enabled.
+ $this->_enableCompression();
- // Loop over strings of headers.
- foreach ($data as $key => $header) {
+ return parent::getOverview($range, $names, $forceNames);
+ }
+
+ /**
+ * Pass a XOVER command to the NNTP provider, return array of articles using the overview format as array keys.
+ *
+ * @note This is a faster implementation of getOverview.
+ *
+ * Example successful return:
+ * array(9) {
+ * 'Number' => string(9) "679871775"
+ * 'Subject' => string(18) "This is an example"
+ * 'From' => string(19) "Example@example.com"
+ * 'Date' => string(24) "26 Jun 2014 13:08:22 GMT"
+ * 'Message-ID' => string(57) ""
+ * 'References' => string(0) ""
+ * 'Bytes' => string(3) "123"
+ * 'Lines' => string(1) "9"
+ * 'Xref' => string(66) "e alt.test:679871775"
+ * }
+ *
+ * @param string $range Range of articles to get the overview for. Examples follow:
+ * Single article number: "679871775"
+ * Range of article numbers: "679871775-679999999"
+ * All newer than article number: "679871775-"
+ * All older than article number: "-679871775"
+ * Message-ID: ""
+ *
+ * @return array|object Multi-dimensional Array of headers on success, PEAR object on failure.
+ * @throws \Exception
+ */
+ public function getXOVER($range)
+ {
+ // Check if we are still connected.
+ $connected = $this->_checkConnection();
+ if ($connected !== true) {
+ return $connected;
+ }
+
+ // Enabled header compression if not enabled.
+ $this->_enableCompression();
+
+ // Send XOVER command to NNTP with wanted articles.
+ $response = $this->_sendCommand('XOVER '.$range);
+ if ($this->isError($response)) {
+ return $response;
+ }
+
+ // Verify the NNTP server got the right command, get the headers data.
+ if ($response === NET_NNTP_PROTOCOL_RESPONSECODE_OVERVIEW_FOLLOWS) {
+ $data = $this->_getTextResponse();
+ if ($this->isError($data)) {
+ return $data;
+ }
+ } else {
+ return $this->_handleErrorResponse($response);
+ }
+
+ // Fetch the header overview format (for setting the array keys on the return array).
+ if ($this->_overviewFormatCache !== null && isset($this->_overviewFormatCache['Xref'])) {
+ $overview = $this->_overviewFormatCache;
+ } else {
+ $overview = $this->getOverviewFormat(false, true);
+ if ($this->isError($overview)) {
+ return $overview;
+ }
+ $this->_overviewFormatCache = $overview;
+ }
+ // Add the "Number" key.
+ $overview = array_merge(['Number' => false], $overview);
+
+ // Iterator used for selecting the header elements to insert into the overview format array.
+ $iterator = 0;
+
+ // Loop over strings of headers.
+ foreach ($data as $key => $header) {
// Split the individual headers by tab.
- $header = explode("\t", $header);
+ $header = explode("\t", $header);
- // Make sure it's not empty.
- if ($header === false) {
- continue;
- }
+ // Make sure it's not empty.
+ if ($header === false) {
+ continue;
+ }
- // Temp array to store the header.
- $headerArray = $overview;
+ // Temp array to store the header.
+ $headerArray = $overview;
- // Loop over the overview format and insert the individual header elements.
- foreach ($overview as $name => $element) {
- // Strip Xref:
- if ($element === true) {
- $header[$iterator] = substr($header[$iterator], 6);
- }
- $headerArray[$name] = $header[$iterator++];
- }
- // Add the individual header array back to the return array.
- $data[$key] = $headerArray;
- $iterator = 0;
- }
- // Return the array of headers.
- return $data;
- }
+ // Loop over the overview format and insert the individual header elements.
+ foreach ($overview as $name => $element) {
+ // Strip Xref:
+ if ($element === true) {
+ $header[$iterator] = substr($header[$iterator], 6);
+ }
+ $headerArray[$name] = $header[$iterator++];
+ }
+ // Add the individual header array back to the return array.
+ $data[$key] = $headerArray;
+ $iterator = 0;
+ }
+ // Return the array of headers.
+ return $data;
+ }
- /**
- * Fetch valid groups.
- *
- * Returns a list of valid groups (that the client is permitted to select) and associated information.
- *
- * @param string $wildMat (optional) http://tools.ietf.org/html/rfc3977#section-4
- *
- * @return array|object Pear error on failure, array with groups on success.
- * @access public
- */
- public function getGroups($wildMat = null)
- {
- // Enabled header compression if not enabled.
- $this->_enableCompression();
- return parent::getGroups($wildMat);
- }
+ /**
+ * Fetch valid groups.
+ *
+ * Returns a list of valid groups (that the client is permitted to select) and associated information.
+ *
+ * @param string $wildMat (optional) http://tools.ietf.org/html/rfc3977#section-4
+ *
+ * @return array|object Pear error on failure, array with groups on success.
+ */
+ public function getGroups($wildMat = null)
+ {
+ // Enabled header compression if not enabled.
+ $this->_enableCompression();
- /**
- * Download multiple article bodies and string them together.
- *
- * @param string $groupName The name of the group the articles are in.
- * @param mixed $identifiers (string) Message-ID.
- * (int) Article number.
- * (array) Article numbers or Message-ID's (can contain both in the same array)
- * @param bool $alternate Use the alternate NNTP provider?
- *
- * @return mixed On success : (string) The article bodies.
- * @throws \Exception
- * On failure : (object) PEAR_Error.
- *
- * @access public
- */
- public function getMessages($groupName, $identifiers, $alternate = false)
- {
- $connected = $this->_checkConnection();
- if ($connected !== true) {
- return $connected;
- }
+ return parent::getGroups($wildMat);
+ }
- // String to hold all the bodies.
- $body = '';
+ /**
+ * Download multiple article bodies and string them together.
+ *
+ * @param string $groupName The name of the group the articles are in.
+ * @param mixed $identifiers (string) Message-ID.
+ * (int) Article number.
+ * (array) Article numbers or Message-ID's (can contain both in the same array)
+ * @param bool $alternate Use the alternate NNTP provider?
+ *
+ * @return mixed On success : (string) The article bodies.
+ * @throws \Exception
+ * On failure : (object) PEAR_Error.
+ */
+ public function getMessages($groupName, $identifiers, $alternate = false)
+ {
+ $connected = $this->_checkConnection();
+ if ($connected !== true) {
+ return $connected;
+ }
- $aConnected = false;
- $nntp = ($alternate === true ? new NNTP(['Echo' => $this->_echo, 'Settings' => $this->pdo]) : null);
+ // String to hold all the bodies.
+ $body = '';
- // Check if the msgIds are in an array.
- if (is_array($identifiers)) {
+ $aConnected = false;
+ $nntp = ($alternate === true ? new self(['Echo' => $this->_echo, 'Settings' => $this->pdo]) : null);
- $loops = $messageSize = 0;
+ // Check if the msgIds are in an array.
+ if (is_array($identifiers)) {
+ $loops = $messageSize = 0;
- // Loop over the message-ID's or article numbers.
- foreach ($identifiers as $wanted) {
+ // Loop over the message-ID's or article numbers.
+ foreach ($identifiers as $wanted) {
/* This is to attempt to prevent string size overflow.
* We get the size of 1 body in bytes, we increment the loop on every loop,
@@ -568,741 +549,732 @@ class NNTP extends \Net_NNTP_Client
* If we exceed, return the data.
* If we don't do this, these errors are fatal.
*/
- if ((++$loops * $messageSize) >= 1700000000) {
- return $body;
- }
+ if ((++$loops * $messageSize) >= 1700000000) {
+ return $body;
+ }
- // Download the body.
- $message = $this->_getMessage($groupName, $wanted);
+ // Download the body.
+ $message = $this->_getMessage($groupName, $wanted);
- // Append the body to $body.
- if (!$this->isError($message)) {
- $body .= $message;
+ // Append the body to $body.
+ if (! $this->isError($message)) {
+ $body .= $message;
- if ($messageSize === 0) {
- $messageSize = strlen($message);
- }
+ if ($messageSize === 0) {
+ $messageSize = strlen($message);
+ }
- // If there is an error try the alternate provider or return the PEAR error.
- } else {
- // Check if admin has enabled alternate in site->edit.
- if ($alternate === true) {
- if ($aConnected === false) {
- // Check if the current connected server is the alternate or not.
- if ($this->_currentServer === env('NNTP_SERVER')) {
- // It's the main so connect to the alternate.
- $aConnected = $nntp->doConnect(true, true);
- } else {
- // It's the alternate so connect to the main.
- $aConnected = $nntp->doConnect();
- }
- }
- // If we connected successfully to usenet try to download the article body.
- if ($aConnected === true) {
- $newBody = $nntp->_getMessage($groupName, $wanted);
- // Check if we got an error.
- if ($nntp->isError($newBody)) {
- if ($aConnected) {
- $nntp->doQuit();
- }
- // If we got some data, return it.
- if ($body !== '') {
- return $body;
- }
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $newBody->getMessage(), Logger::LOG_NOTICE);
- }
- // Return the error.
- return $newBody;
- }
- // Append the alternate body to the main body.
- $body .= $newBody;
- }
- } else {
- // If we got some data, return it.
- if ($body !== '') {
- return $body;
- }
- return $message;
- }
- }
- }
+ // If there is an error try the alternate provider or return the PEAR error.
+ } else {
+ // Check if admin has enabled alternate in site->edit.
+ if ($alternate === true) {
+ if ($aConnected === false) {
+ // Check if the current connected server is the alternate or not.
+ if ($this->_currentServer === env('NNTP_SERVER')) {
+ // It's the main so connect to the alternate.
+ $aConnected = $nntp->doConnect(true, true);
+ } else {
+ // It's the alternate so connect to the main.
+ $aConnected = $nntp->doConnect();
+ }
+ }
+ // If we connected successfully to usenet try to download the article body.
+ if ($aConnected === true) {
+ $newBody = $nntp->_getMessage($groupName, $wanted);
+ // Check if we got an error.
+ if ($nntp->isError($newBody)) {
+ if ($aConnected) {
+ $nntp->doQuit();
+ }
+ // If we got some data, return it.
+ if ($body !== '') {
+ return $body;
+ }
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $newBody->getMessage(), Logger::LOG_NOTICE);
+ }
+ // Return the error.
+ return $newBody;
+ }
+ // Append the alternate body to the main body.
+ $body .= $newBody;
+ }
+ } else {
+ // If we got some data, return it.
+ if ($body !== '') {
+ return $body;
+ }
- // If it's a string check if it's a valid message-ID.
- } else if (is_string($identifiers) || is_numeric($identifiers)) {
- $body = $this->_getMessage($groupName, $identifiers);
- if ($alternate === true && $this->isError($body)) {
- $nntp->doConnect(true, true);
- $body = $nntp->_getMessage($groupName, $identifiers);
- $aConnected = true;
- }
+ return $message;
+ }
+ }
+ }
- // Else return an error.
- } else {
- $message = 'Wrong Identifier type, array, int or string accepted. This type of var was passed: ' . gettype($identifiers);
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING);
- }
- return $this->throwError(ColorCLI::error($message));
- }
+ // If it's a string check if it's a valid message-ID.
+ } elseif (is_string($identifiers) || is_numeric($identifiers)) {
+ $body = $this->_getMessage($groupName, $identifiers);
+ if ($alternate === true && $this->isError($body)) {
+ $nntp->doConnect(true, true);
+ $body = $nntp->_getMessage($groupName, $identifiers);
+ $aConnected = true;
+ }
- if ($aConnected === true) {
- $nntp->doQuit();
- }
+ // Else return an error.
+ } else {
+ $message = 'Wrong Identifier type, array, int or string accepted. This type of var was passed: '.gettype($identifiers);
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING);
+ }
- return $body;
- }
+ return $this->throwError(ColorCLI::error($message));
+ }
- /**
- * Download a full article, the body and the header, return an array with named keys and their
- * associated values, optionally decode the body using yEnc.
- *
- * @param string $groupName The name of the group the article is in.
- * @param mixed $identifier (string)The message-ID of the article to download.
- * (int) The article number.
- * @param bool $yEnc Attempt to yEnc decode the body.
- *
- * @return mixed On success : (array) The article.
- * On failure : (object) PEAR_Error.
- *
- * @access public
- */
- public function get_Article($groupName, $identifier, $yEnc = false)
- {
- $connected = $this->_checkConnection();
- if ($connected !== true) {
- return $connected;
- }
+ if ($aConnected === true) {
+ $nntp->doQuit();
+ }
- // Make sure the requested group is already selected, if not select it.
- if (parent::group() !== $groupName) {
- // Select the group.
- $summary = $this->selectGroup($groupName);
- // If there was an error selecting the group, return PEAR error object.
- if ($this->isError($summary)) {
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_NOTICE);
- }
- return $summary;
- }
- }
+ return $body;
+ }
- // Check if it's an article number or message-ID.
- if (!is_numeric($identifier)) {
- // If it's a message-ID, check if it has the required triangular brackets.
- $identifier = $this->_formatMessageID($identifier);
- }
+ /**
+ * Download a full article, the body and the header, return an array with named keys and their
+ * associated values, optionally decode the body using yEnc.
+ *
+ * @param string $groupName The name of the group the article is in.
+ * @param mixed $identifier (string)The message-ID of the article to download.
+ * (int) The article number.
+ * @param bool $yEnc Attempt to yEnc decode the body.
+ *
+ * @return mixed On success : (array) The article.
+ * On failure : (object) PEAR_Error.
+ */
+ public function get_Article($groupName, $identifier, $yEnc = false)
+ {
+ $connected = $this->_checkConnection();
+ if ($connected !== true) {
+ return $connected;
+ }
- // Download the article.
- $article = parent::getArticle($identifier);
- // If there was an error downloading the article, return a PEAR error object.
- if ($this->isError($article)) {
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $article->getMessage(), Logger::LOG_NOTICE);
- }
- return $article;
- }
+ // Make sure the requested group is already selected, if not select it.
+ if (parent::group() !== $groupName) {
+ // Select the group.
+ $summary = $this->selectGroup($groupName);
+ // If there was an error selecting the group, return PEAR error object.
+ if ($this->isError($summary)) {
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_NOTICE);
+ }
- $ret = $article;
- // Make sure the article is an array and has more than 1 element.
- if (count($article) > 0) {
- $ret = [];
- $body = '';
- $emptyLine = false;
- foreach ($article as $line) {
- // If we found the empty line it means we are done reading the header and we will start reading the body.
- if (!$emptyLine) {
- if ($line === '') {
- $emptyLine = True;
- continue;
- }
+ return $summary;
+ }
+ }
- // Use the line type of the article as the array key (From, Subject, etc..).
- if (preg_match('/([A-Z-]+?): (.*)/i', $line, $matches)) {
- // If the line type takes more than 1 line, append the rest of the content to the same key.
- if (array_key_exists($matches[1], $ret)) {
- $ret[$matches[1]] .= $matches[2];
- } else {
- $ret[$matches[1]] = $matches[2];
- }
- }
+ // Check if it's an article number or message-ID.
+ if (! is_numeric($identifier)) {
+ // If it's a message-ID, check if it has the required triangular brackets.
+ $identifier = $this->_formatMessageID($identifier);
+ }
- // Now we have the header, so get the body from the rest of the lines.
- } else {
- $body .= $line;
- }
- }
- // Finally we decode the message using yEnc.
- $ret['Message'] = ($yEnc ? Yenc::decodeIgnore($body) : $body);
- }
- return $ret;
- }
+ // Download the article.
+ $article = parent::getArticle($identifier);
+ // If there was an error downloading the article, return a PEAR error object.
+ if ($this->isError($article)) {
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $article->getMessage(), Logger::LOG_NOTICE);
+ }
- /**
- * Download a full article header.
- *
- * @param string $groupName The name of the group the article is in.
- * @param mixed $identifier (string) The message-ID of the article to download.
- * (int) The article number.
- *
- * @return mixed On success : (array) The header.
- * @throws \Exception
- * On failure : (object) PEAR_Error.
- *
- * @access public
- */
- public function get_Header($groupName, $identifier)
- {
- $connected = $this->_checkConnection();
- if ($connected !== true) {
- return $connected;
- }
+ return $article;
+ }
- // Make sure the requested group is already selected, if not select it.
- if (parent::group() !== $groupName) {
- // Select the group.
- $summary = $this->selectGroup($groupName);
- // Return PEAR error object on failure.
- if ($this->isError($summary)) {
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_NOTICE);
- }
- return $summary;
- }
- }
+ $ret = $article;
+ // Make sure the article is an array and has more than 1 element.
+ if (count($article) > 0) {
+ $ret = [];
+ $body = '';
+ $emptyLine = false;
+ foreach ($article as $line) {
+ // If we found the empty line it means we are done reading the header and we will start reading the body.
+ if (! $emptyLine) {
+ if ($line === '') {
+ $emptyLine = true;
+ continue;
+ }
- // Check if it's an article number or message-id.
- if (!is_numeric($identifier)) {
- // Verify we have the required triangular brackets if it is a message-id.
- $identifier = $this->_formatMessageID($identifier);
- }
+ // Use the line type of the article as the array key (From, Subject, etc..).
+ if (preg_match('/([A-Z-]+?): (.*)/i', $line, $matches)) {
+ // If the line type takes more than 1 line, append the rest of the content to the same key.
+ if (array_key_exists($matches[1], $ret)) {
+ $ret[$matches[1]] .= $matches[2];
+ } else {
+ $ret[$matches[1]] = $matches[2];
+ }
+ }
- // Download the header.
- $header = parent::getHeader($identifier);
- // If we failed, return PEAR error object.
- if ($this->isError($header)) {
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $header->getMessage(), Logger::LOG_NOTICE);
- }
- return $header;
- }
+ // Now we have the header, so get the body from the rest of the lines.
+ } else {
+ $body .= $line;
+ }
+ }
+ // Finally we decode the message using yEnc.
+ $ret['Message'] = ($yEnc ? Yenc::decodeIgnore($body) : $body);
+ }
- $ret = $header;
- if (count($header) > 0) {
- $ret = [];
- // Use the line types of the header as array keys (From, Subject, etc).
- foreach ($header as $line) {
- if (preg_match('/([A-Z-]+?): (.*)/i', $line, $matches)) {
- // If the line type takes more than 1 line, re-use the same array key.
- if (array_key_exists($matches[1], $ret)) {
- $ret[$matches[1]] .= $matches[2];
- } else {
- $ret[$matches[1]] = $matches[2];
- }
- }
- }
- }
- return $ret;
- }
+ return $ret;
+ }
- /**
- * Post an article to usenet.
- *
- * @param string|array $groups mixed (array) Groups. ie.: $groups = array('alt.test', 'alt.testing', 'free.pt');
- * (string) Group. ie.: $groups = 'alt.test';
- * @param string $subject string The subject. ie.: $subject = 'Test article';
- * @param string|\Exception $body string The message. ie.: $message = 'This is only a test, please disregard.';
- * @param string $from string The poster. ie.: $from = '';
- * @param $extra string Extra, separated by \r\n
- * ie.: $extra = 'Organization: \r\nNNTP-Posting-Host: <127.0.0.1>';
- * @param $yEnc bool Encode the message with yEnc?
- * @param $compress bool Compress the message with GZip?
- *
- * @throws \Exception
- *
- * @return mixed On success : (bool) True.
- * On failure : (object) PEAR_Error.
- *
- * @access public
- */
- public function postArticle($groups, $subject, $body, $from, $yEnc = true, $compress = true, $extra = '')
- {
- if (!$this->_postingAllowed) {
- $message = 'You do not have the right to post articles on server ' . $this->_currentServer;
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE);
- }
- return $this->throwError(ColorCLI::error($message));
- }
+ /**
+ * Download a full article header.
+ *
+ * @param string $groupName The name of the group the article is in.
+ * @param mixed $identifier (string) The message-ID of the article to download.
+ * (int) The article number.
+ *
+ * @return mixed On success : (array) The header.
+ * @throws \Exception
+ * On failure : (object) PEAR_Error.
+ */
+ public function get_Header($groupName, $identifier)
+ {
+ $connected = $this->_checkConnection();
+ if ($connected !== true) {
+ return $connected;
+ }
- $connected = $this->_checkConnection();
- if ($connected !== true) {
- return $connected;
- }
+ // Make sure the requested group is already selected, if not select it.
+ if (parent::group() !== $groupName) {
+ // Select the group.
+ $summary = $this->selectGroup($groupName);
+ // Return PEAR error object on failure.
+ if ($this->isError($summary)) {
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_NOTICE);
+ }
- // Throw errors if subject or from are more than 510 chars.
- if (strlen($subject) > 510) {
- $message = 'Max length of subject is 510 chars.';
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING);
- }
- return $this->throwError(ColorCLI::error($message));
- }
+ return $summary;
+ }
+ }
- if (strlen($from) > 510) {
- $message = 'Max length of from is 510 chars.';
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING);
- }
- return $this->throwError(ColorCLI::error($message));
- }
+ // Check if it's an article number or message-id.
+ if (! is_numeric($identifier)) {
+ // Verify we have the required triangular brackets if it is a message-id.
+ $identifier = $this->_formatMessageID($identifier);
+ }
- // Check if the group is string or array.
- if (is_array($groups)) {
- $groups = implode(', ', $groups);
- }
+ // Download the header.
+ $header = parent::getHeader($identifier);
+ // If we failed, return PEAR error object.
+ if ($this->isError($header)) {
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $header->getMessage(), Logger::LOG_NOTICE);
+ }
- // Check if we should encode to yEnc.
- if ($yEnc) {
- $bin = $compress ? gzdeflate($body, 4) : $body;
- $body = Yenc::encode($bin, $subject);
- // If not yEnc, then check if the body is 510+ chars, split it at 510 chars and separate with \r\n
- } else {
- $body = $this->_splitLines($body, $compress);
- }
+ return $header;
+ }
- // From is required by NNTP servers, but parent function mail does not require it, so format it.
- $from = 'From: ' . $from;
- // If we had extra stuff to post, format it with from.
- if ($extra !== '') {
- $from = $from . "\r\n" . $extra;
- }
+ $ret = $header;
+ if (count($header) > 0) {
+ $ret = [];
+ // Use the line types of the header as array keys (From, Subject, etc).
+ foreach ($header as $line) {
+ if (preg_match('/([A-Z-]+?): (.*)/i', $line, $matches)) {
+ // If the line type takes more than 1 line, re-use the same array key.
+ if (array_key_exists($matches[1], $ret)) {
+ $ret[$matches[1]] .= $matches[2];
+ } else {
+ $ret[$matches[1]] = $matches[2];
+ }
+ }
+ }
+ }
- return parent::mail($groups, $subject, $body, $from);
- }
+ return $ret;
+ }
- /**
- * Restart the NNTP connection if an error occurs in the selectGroup
- * function, if it does not restart display the error.
- *
- * @param NNTP $nntp Instance of class NNTP.
- * @param string $group Name of the group.
- * @param bool $comp Use compression or not?
- *
- * @return mixed On success : (array) The group summary.
- * @throws \Exception
- * On Failure : (object) PEAR_Error.
- *
- * @access public
- */
- public function dataError($nntp, $group, $comp = true)
- {
- // Disconnect.
- $nntp->doQuit();
- // Try reconnecting. This uses another round of max retries.
- if ($nntp->doConnect($comp) !== true) {
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, 'Unable to reconnect to usenet!', Logger::LOG_NOTICE);
- }
- return $this->throwError('Unable to reconnect to usenet!');
- }
+ /**
+ * Post an article to usenet.
+ *
+ * @param string|array $groups mixed (array) Groups. ie.: $groups = array('alt.test', 'alt.testing', 'free.pt');
+ * (string) Group. ie.: $groups = 'alt.test';
+ * @param string $subject string The subject. ie.: $subject = 'Test article';
+ * @param string|\Exception $body string The message. ie.: $message = 'This is only a test, please disregard.';
+ * @param string $from string The poster. ie.: $from = '';
+ * @param $extra string Extra, separated by \r\n
+ * ie.: $extra = 'Organization: \r\nNNTP-Posting-Host: <127.0.0.1>';
+ * @param $yEnc bool Encode the message with yEnc?
+ * @param $compress bool Compress the message with GZip?
+ *
+ * @throws \Exception
+ *
+ * @return mixed On success : (bool) True.
+ * On failure : (object) PEAR_Error.
+ */
+ public function postArticle($groups, $subject, $body, $from, $yEnc = true, $compress = true, $extra = '')
+ {
+ if (! $this->_postingAllowed) {
+ $message = 'You do not have the right to post articles on server '.$this->_currentServer;
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE);
+ }
- // Try re-selecting the group.
- $data = $nntp->selectGroup($group);
- if ($this->isError($data)) {
- $message = "Code {$data->code}: {$data->message}\nSkipping group: {$group}";
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE);
- }
+ return $this->throwError(ColorCLI::error($message));
+ }
- if ($this->_echo) {
- ColorCLI::doEcho(ColorCLI::error($message), true);
- }
- $nntp->doQuit();
- }
- return $data;
- }
+ $connected = $this->_checkConnection();
+ if ($connected !== true) {
+ return $connected;
+ }
- /**
- * Path to yyDecoder binary.
- * @var bool|string
- * @access protected
- */
- protected $_yyDecoderPath;
+ // Throw errors if subject or from are more than 510 chars.
+ if (strlen($subject) > 510) {
+ $message = 'Max length of subject is 510 chars.';
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING);
+ }
- /**
- * If on unix, hide yydecode CLI output.
- * @var string
- * @access protected
- */
- protected $_yEncSilence;
+ return $this->throwError(ColorCLI::error($message));
+ }
- /**
- * Path to temp yEnc input storage file.
- * @var string
- * @access protected
- */
- protected $_yEncTempInput;
+ if (strlen($from) > 510) {
+ $message = 'Max length of from is 510 chars.';
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_WARNING);
+ }
- /**
- * Path to temp yEnc output storage file.
- * @var string
- * @access protected
- */
- protected $_yEncTempOutput;
+ return $this->throwError(ColorCLI::error($message));
+ }
- /**
- * Split a string into lines of 510 chars ending with \r\n.
- * Usenet limits lines to 512 chars, with \r\n that leaves us 510.
- *
- * @param string $string The string to split.
- * @param bool $compress Compress the string with gzip?
- *
- * @return string The split string.
- *
- * @access protected
- */
- protected function _splitLines($string, $compress = false): string
- {
- // Check if the length is longer than 510 chars.
- if (strlen($string) > 510) {
- // If it is, split it @ 510 and terminate with \r\n.
- $string = chunk_split($string, 510, "\r\n");
- }
+ // Check if the group is string or array.
+ if (is_array($groups)) {
+ $groups = implode(', ', $groups);
+ }
- // Compress the string if requested.
- return ($compress ? gzdeflate($string, 4) : $string);
- }
+ // Check if we should encode to yEnc.
+ if ($yEnc) {
+ $bin = $compress ? gzdeflate($body, 4) : $body;
+ $body = Yenc::encode($bin, $subject);
+ // If not yEnc, then check if the body is 510+ chars, split it at 510 chars and separate with \r\n
+ } else {
+ $body = $this->_splitLines($body, $compress);
+ }
- /**
- * Try to see if the NNTP server implements XFeature GZip Compression,
- * change the compression bool object if so.
- *
- * @param bool $secondTry This is only used if enabling compression fails, the function will call itself to retry.
- * @return mixed On success : (bool) True: The server understood and compression is enabled.
- * (bool) False: The server did not understand, compression is not enabled.
- * On failure : (object) PEAR_Error.
- *
- * @access protected
- */
- protected function _enableCompression($secondTry = false)
- {
- if ($this->_compressionEnabled === true) {
- return true;
- }
- if ($this->_compressionSupported === false) {
- return false;
- }
+ // From is required by NNTP servers, but parent function mail does not require it, so format it.
+ $from = 'From: '.$from;
+ // If we had extra stuff to post, format it with from.
+ if ($extra !== '') {
+ $from = $from."\r\n".$extra;
+ }
- // Send this command to the usenet server.
- $response = $this->_sendCommand('XFEATURE COMPRESS GZIP');
+ return parent::mail($groups, $subject, $body, $from);
+ }
- // Check if it's good.
- if ($this->isError($response)) {
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $response->getMessage(), Logger::LOG_NOTICE);
- }
- $this->_compressionSupported = false;
- return $response;
- }
- if ($response !== 290) {
- if ($secondTry === false) {
- // Retry.
- $this->cmdQuit();
- if ($this->_checkConnection()) {
- return $this->_enableCompression(true);
- }
- }
- $msg = "Sent 'XFEATURE COMPRESS GZIP' to server, got '$response: " . $this->_currentStatusResponse() . "'";
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $msg, Logger::LOG_NOTICE);
- }
- $this->_compressionSupported = false;
+ /**
+ * Restart the NNTP connection if an error occurs in the selectGroup
+ * function, if it does not restart display the error.
+ *
+ * @param NNTP $nntp Instance of class NNTP.
+ * @param string $group Name of the group.
+ * @param bool $comp Use compression or not?
+ *
+ * @return mixed On success : (array) The group summary.
+ * @throws \Exception
+ * On Failure : (object) PEAR_Error.
+ */
+ public function dataError($nntp, $group, $comp = true)
+ {
+ // Disconnect.
+ $nntp->doQuit();
+ // Try reconnecting. This uses another round of max retries.
+ if ($nntp->doConnect($comp) !== true) {
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, 'Unable to reconnect to usenet!', Logger::LOG_NOTICE);
+ }
- return false;
+ return $this->throwError('Unable to reconnect to usenet!');
+ }
- }
+ // Try re-selecting the group.
+ $data = $nntp->selectGroup($group);
+ if ($this->isError($data)) {
+ $message = "Code {$data->code}: {$data->message}\nSkipping group: {$group}";
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE);
+ }
- $this->_compressionEnabled = true;
- $this->_compressionSupported = true;
- return true;
- }
+ if ($this->_echo) {
+ ColorCLI::doEcho(ColorCLI::error($message), true);
+ }
+ $nntp->doQuit();
+ }
- /**
- * Override PEAR NNTP's function to use our _getXFeatureTextResponse instead
- * of their _getTextResponse function since it is incompatible at decoding
- * headers when XFeature GZip compression is enabled server side.
- *
- * @return self|string Our overridden function when compression is enabled.
- * parent Parent function when no compression.
- *
- * @access protected
- */
- protected function _getTextResponse()
- {
- if ($this->_compressionEnabled === true &&
+ return $data;
+ }
+
+ /**
+ * Path to yyDecoder binary.
+ * @var bool|string
+ */
+ protected $_yyDecoderPath;
+
+ /**
+ * If on unix, hide yydecode CLI output.
+ * @var string
+ */
+ protected $_yEncSilence;
+
+ /**
+ * Path to temp yEnc input storage file.
+ * @var string
+ */
+ protected $_yEncTempInput;
+
+ /**
+ * Path to temp yEnc output storage file.
+ * @var string
+ */
+ protected $_yEncTempOutput;
+
+ /**
+ * Split a string into lines of 510 chars ending with \r\n.
+ * Usenet limits lines to 512 chars, with \r\n that leaves us 510.
+ *
+ * @param string $string The string to split.
+ * @param bool $compress Compress the string with gzip?
+ *
+ * @return string The split string.
+ */
+ protected function _splitLines($string, $compress = false): string
+ {
+ // Check if the length is longer than 510 chars.
+ if (strlen($string) > 510) {
+ // If it is, split it @ 510 and terminate with \r\n.
+ $string = chunk_split($string, 510, "\r\n");
+ }
+
+ // Compress the string if requested.
+ return $compress ? gzdeflate($string, 4) : $string;
+ }
+
+ /**
+ * Try to see if the NNTP server implements XFeature GZip Compression,
+ * change the compression bool object if so.
+ *
+ * @param bool $secondTry This is only used if enabling compression fails, the function will call itself to retry.
+ * @return mixed On success : (bool) True: The server understood and compression is enabled.
+ * (bool) False: The server did not understand, compression is not enabled.
+ * On failure : (object) PEAR_Error.
+ */
+ protected function _enableCompression($secondTry = false)
+ {
+ if ($this->_compressionEnabled === true) {
+ return true;
+ }
+ if ($this->_compressionSupported === false) {
+ return false;
+ }
+
+ // Send this command to the usenet server.
+ $response = $this->_sendCommand('XFEATURE COMPRESS GZIP');
+
+ // Check if it's good.
+ if ($this->isError($response)) {
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $response->getMessage(), Logger::LOG_NOTICE);
+ }
+ $this->_compressionSupported = false;
+
+ return $response;
+ }
+ if ($response !== 290) {
+ if ($secondTry === false) {
+ // Retry.
+ $this->cmdQuit();
+ if ($this->_checkConnection()) {
+ return $this->_enableCompression(true);
+ }
+ }
+ $msg = "Sent 'XFEATURE COMPRESS GZIP' to server, got '$response: ".$this->_currentStatusResponse()."'";
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $msg, Logger::LOG_NOTICE);
+ }
+ $this->_compressionSupported = false;
+
+ return false;
+ }
+
+ $this->_compressionEnabled = true;
+ $this->_compressionSupported = true;
+
+ return true;
+ }
+
+ /**
+ * Override PEAR NNTP's function to use our _getXFeatureTextResponse instead
+ * of their _getTextResponse function since it is incompatible at decoding
+ * headers when XFeature GZip compression is enabled server side.
+ *
+ * @return self|string Our overridden function when compression is enabled.
+ * parent Parent function when no compression.
+ */
+ protected function _getTextResponse()
+ {
+ if ($this->_compressionEnabled === true &&
isset($this->_currentStatusResponse[1]) &&
stripos($this->_currentStatusResponse[1], 'COMPRESS=GZIP') !== false) {
+ return $this->_getXFeatureTextResponse();
+ }
- return $this->_getXFeatureTextResponse();
- }
- return parent::_getTextResponse();
- }
+ return parent::_getTextResponse();
+ }
- /**
- * Loop over the compressed data when XFeature GZip Compress is turned on,
- * string the data until we find a indicator
- * (period, carriage feed, line return ;; .\r\n), decompress the data,
- * split the data (bunch of headers in a string) into an array, finally
- * return the array.
- *
- * Have we failed to decompress the data, was there a
- * problem downloading the data, etc..
- * @return array|string On success : (array) The headers.
- * On failure : (object) PEAR_Error.
- * On decompress failure: (string) error message
- *
- * @access protected
- */
- protected function &_getXFeatureTextResponse()
- {
- $possibleTerm = false;
- $data = null;
+ /**
+ * Loop over the compressed data when XFeature GZip Compress is turned on,
+ * string the data until we find a indicator
+ * (period, carriage feed, line return ;; .\r\n), decompress the data,
+ * split the data (bunch of headers in a string) into an array, finally
+ * return the array.
+ *
+ * Have we failed to decompress the data, was there a
+ * problem downloading the data, etc..
+ * @return array|string On success : (array) The headers.
+ * On failure : (object) PEAR_Error.
+ * On decompress failure: (string) error message
+ */
+ protected function &_getXFeatureTextResponse()
+ {
+ $possibleTerm = false;
+ $data = null;
- while (!feof($this->_socket)) {
+ while (! feof($this->_socket)) {
// Did we find a possible ending ? (.\r\n)
- if ($possibleTerm !== false) {
+ if ($possibleTerm !== false) {
// Loop, sleeping shortly, to allow the server time to upload data, if it has any.
- for ($i = 0; $i < 3; $i++) {
- // If the socket is really empty, fGets will get stuck here, so set the socket to non blocking in case.
- stream_set_blocking($this->_socket, 0);
+ for ($i = 0; $i < 3; $i++) {
+ // If the socket is really empty, fGets will get stuck here, so set the socket to non blocking in case.
+ stream_set_blocking($this->_socket, 0);
- // Now try to download from the socket.
- $buffer = fgets($this->_socket);
+ // Now try to download from the socket.
+ $buffer = fgets($this->_socket);
- // And set back the socket to blocking.
- stream_set_blocking($this->_socket, 1);
+ // And set back the socket to blocking.
+ stream_set_blocking($this->_socket, 1);
- // Don't sleep on last iteration.
- if (!empty($buffer)) {
- break;
- }
- if ($i < 2) {
- usleep(10000);
- }
- }
+ // Don't sleep on last iteration.
+ if (! empty($buffer)) {
+ break;
+ }
+ if ($i < 2) {
+ usleep(10000);
+ }
+ }
- // If the buffer was really empty, then we know $possibleTerm was the real ending.
- if (empty($buffer)) {
- // Remove .\r\n from end, decompress data.
- $deComp = @gzuncompress(mb_substr($data, 0, -3, '8bit'));
+ // If the buffer was really empty, then we know $possibleTerm was the real ending.
+ if (empty($buffer)) {
+ // Remove .\r\n from end, decompress data.
+ $deComp = @gzuncompress(mb_substr($data, 0, -3, '8bit'));
- if (!empty($deComp)) {
-
- $bytesReceived = strlen($data);
- if ($this->_echo && $bytesReceived > 10240) {
- ColorCLI::doEcho(
+ if (! empty($deComp)) {
+ $bytesReceived = strlen($data);
+ if ($this->_echo && $bytesReceived > 10240) {
+ ColorCLI::doEcho(
ColorCLI::primaryOver(
- 'Received ' . round($bytesReceived / 1024) .
- 'KB from group (' . $this->group() . ').'
+ 'Received '.round($bytesReceived / 1024).
+ 'KB from group ('.$this->group().').'
), true
);
- }
+ }
- // Split the string of headers into an array of individual headers, then return it.
- $deComp = explode("\r\n", trim($deComp));
- return $deComp;
- }
- $message = 'Decompression of OVER headers failed.';
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE);
- }
- $message = $this->throwError(ColorCLI::error($message), 1000);
- return $message;
+ // Split the string of headers into an array of individual headers, then return it.
+ $deComp = explode("\r\n", trim($deComp));
- }
- // The buffer was not empty, so we know this was not the real ending, so reset $possibleTerm.
- $possibleTerm = false;
- } else {
- // Get data from the stream.
- $buffer = fgets($this->_socket);
- }
+ return $deComp;
+ }
+ $message = 'Decompression of OVER headers failed.';
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE);
+ }
+ $message = $this->throwError(ColorCLI::error($message), 1000);
- // If we got no data at all try one more time to pull data.
- if (empty($buffer)) {
- usleep(10000);
- $buffer = fgets($this->_socket);
+ return $message;
+ }
+ // The buffer was not empty, so we know this was not the real ending, so reset $possibleTerm.
+ $possibleTerm = false;
+ } else {
+ // Get data from the stream.
+ $buffer = fgets($this->_socket);
+ }
- // If wet got nothing again, return error.
- if (empty($buffer)) {
- $message = 'Error fetching data from usenet server while downloading OVER headers.';
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE);
- }
- $message = $this->throwError(ColorCLI::error($message), 1000);
- return $message;
- }
- }
+ // If we got no data at all try one more time to pull data.
+ if (empty($buffer)) {
+ usleep(10000);
+ $buffer = fgets($this->_socket);
- // Append current buffer to rest of buffer.
- $data .= $buffer;
+ // If wet got nothing again, return error.
+ if (empty($buffer)) {
+ $message = 'Error fetching data from usenet server while downloading OVER headers.';
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE);
+ }
+ $message = $this->throwError(ColorCLI::error($message), 1000);
- // Check if we have the ending (.\r\n)
- if (substr($buffer, -3) === ".\r\n") {
- // We have a possible ending, next loop check if it is.
- $possibleTerm = true;
- }
- }
+ return $message;
+ }
+ }
- $message = 'Unspecified error while downloading OVER headers.';
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE);
- }
- $message = $this->throwError(ColorCLI::error($message), 1000);
- return $message;
- }
+ // Append current buffer to rest of buffer.
+ $data .= $buffer;
- /**
- * Check if the Message-ID has the required opening and closing brackets.
- *
- * @param string $messageID The Message-ID with or without brackets.
- *
- * @return string Message-ID with brackets.
- *
- * @access protected
- */
- protected function _formatMessageID($messageID): string
- {
- $messageID = (string)$messageID;
- if ($messageID === '') {
- return false;
- }
+ // Check if we have the ending (.\r\n)
+ if (substr($buffer, -3) === ".\r\n") {
+ // We have a possible ending, next loop check if it is.
+ $possibleTerm = true;
+ }
+ }
- // Check if the first char is <, if not add it.
- if ($messageID[0] !== '<') {
- $messageID = ('<' . $messageID);
- }
+ $message = 'Unspecified error while downloading OVER headers.';
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $message, Logger::LOG_NOTICE);
+ }
+ $message = $this->throwError(ColorCLI::error($message), 1000);
- // Check if the last char is >, if not add it.
- if (substr($messageID, -1) !== '>') {
- $messageID .= '>';
- }
- return $messageID;
- }
+ return $message;
+ }
- /**
- * Download an article body (an article without the header).
- *
- * @param string $groupName The name of the group the article is in.
- * @param mixed $identifier (string) The message-ID of the article to download.
- * (int) The article number.
- *
- * @return string On success : (string) The article's body.
- * @throws \Exception
- * On failure : (object) PEAR_Error.
- *
- * @access protected
- */
- protected function _getMessage($groupName, $identifier): ?string
- {
- // Make sure the requested group is already selected, if not select it.
- if (parent::group() !== $groupName) {
- // Select the group.
- $summary = $this->selectGroup($groupName);
- // If there was an error selecting the group, return PEAR error object.
- if ($this->isError($summary)) {
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_WARNING);
- }
- return $summary;
- }
- }
+ /**
+ * Check if the Message-ID has the required opening and closing brackets.
+ *
+ * @param string $messageID The Message-ID with or without brackets.
+ *
+ * @return string Message-ID with brackets.
+ */
+ protected function _formatMessageID($messageID): string
+ {
+ $messageID = (string) $messageID;
+ if ($messageID === '') {
+ return false;
+ }
- // Check if this is an article number or message-id.
- if (!is_numeric($identifier)) {
- // It's a message-id so check if it has the triangular brackets.
- $identifier = $this->_formatMessageID($identifier);
- }
+ // Check if the first char is <, if not add it.
+ if ($messageID[0] !== '<') {
+ $messageID = ('<'.$messageID);
+ }
- // Tell the news server we want the body of an article.
- $response = $this->_sendCommand('BODY ' . $identifier);
- if ($this->isError($response)) {
- return $response;
- }
+ // Check if the last char is >, if not add it.
+ if (substr($messageID, -1) !== '>') {
+ $messageID .= '>';
+ }
- $body = '';
- if ($response === NET_NNTP_PROTOCOL_RESPONSECODE_BODY_FOLLOWS) {
+ return $messageID;
+ }
+
+ /**
+ * Download an article body (an article without the header).
+ *
+ * @param string $groupName The name of the group the article is in.
+ * @param mixed $identifier (string) The message-ID of the article to download.
+ * (int) The article number.
+ *
+ * @return string On success : (string) The article's body.
+ * @throws \Exception
+ * On failure : (object) PEAR_Error.
+ */
+ protected function _getMessage($groupName, $identifier): ?string
+ {
+ // Make sure the requested group is already selected, if not select it.
+ if (parent::group() !== $groupName) {
+ // Select the group.
+ $summary = $this->selectGroup($groupName);
+ // If there was an error selecting the group, return PEAR error object.
+ if ($this->isError($summary)) {
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__, __FUNCTION__, $summary->getMessage(), Logger::LOG_WARNING);
+ }
+
+ return $summary;
+ }
+ }
+
+ // Check if this is an article number or message-id.
+ if (! is_numeric($identifier)) {
+ // It's a message-id so check if it has the triangular brackets.
+ $identifier = $this->_formatMessageID($identifier);
+ }
+
+ // Tell the news server we want the body of an article.
+ $response = $this->_sendCommand('BODY '.$identifier);
+ if ($this->isError($response)) {
+ return $response;
+ }
+
+ $body = '';
+ if ($response === NET_NNTP_PROTOCOL_RESPONSECODE_BODY_FOLLOWS) {
// Continue until connection is lost
- while (!feof($this->_socket)) {
+ while (! feof($this->_socket)) {
// Retrieve and append up to 1024 characters from the server.
- $line = fgets($this->_socket, 1024);
+ $line = fgets($this->_socket, 1024);
- // If the socket is empty/ an error occurs, false is returned.
- // Since the socket is blocking, the socket should not be empty, so it's definitely an error.
- if ($line === false) {
- return $this->throwError('Failed to read line from socket.', null);
- }
+ // If the socket is empty/ an error occurs, false is returned.
+ // Since the socket is blocking, the socket should not be empty, so it's definitely an error.
+ if ($line === false) {
+ return $this->throwError('Failed to read line from socket.', null);
+ }
- // Check if the line terminates the text response.
- if ($line === ".\r\n") {
- if ($this->_debugBool) {
- $this->_debugging->log(__CLASS__,
- __FUNCTION__, 'Fetched body for article ' . $identifier, Logger::LOG_INFO
+ // Check if the line terminates the text response.
+ if ($line === ".\r\n") {
+ if ($this->_debugBool) {
+ $this->_debugging->log(__CLASS__,
+ __FUNCTION__, 'Fetched body for article '.$identifier, Logger::LOG_INFO
);
- }
+ }
- // Attempt to yEnc decode and return the body.
- return Yenc::decodeIgnore($body);
- }
+ // Attempt to yEnc decode and return the body.
+ return Yenc::decodeIgnore($body);
+ }
- // Check for line that starts with double period, remove one.
- if ($line[0] === '.' && $line[1] === '.') {
- $line = substr($line, 1);
- }
+ // Check for line that starts with double period, remove one.
+ if ($line[0] === '.' && $line[1] === '.') {
+ $line = substr($line, 1);
+ }
- // Add the line to the rest of the lines.
- $body .= $line;
+ // Add the line to the rest of the lines.
+ $body .= $line;
+ }
- }
+ return $this->throwError('End of stream! Connection lost?', null);
+ }
- return $this->throwError('End of stream! Connection lost?', null);
- }
+ return $this->_handleErrorResponse($response);
+ }
- return $this->_handleErrorResponse($response);
- }
-
- /**
- * Check if we are still connected. Reconnect if not.
- *
- * @param bool $reSelectGroup Select back the group after connecting?
- *
- * @return mixed On success: (bool) True;
- * @throws \Exception
- * On failure: (object) PEAR_Error
- *
- * @access protected
- */
- protected function _checkConnection($reSelectGroup = true)
- {
- $currentGroup = $this->_currentGroup;
- // Check if we are connected.
- if (parent::_isConnected()) {
- $retVal = true;
- } else {
- switch ($this->_currentServer) {
+ /**
+ * Check if we are still connected. Reconnect if not.
+ *
+ * @param bool $reSelectGroup Select back the group after connecting?
+ *
+ * @return mixed On success: (bool) True;
+ * @throws \Exception
+ * On failure: (object) PEAR_Error
+ */
+ protected function _checkConnection($reSelectGroup = true)
+ {
+ $currentGroup = $this->_currentGroup;
+ // Check if we are connected.
+ if (parent::_isConnected()) {
+ $retVal = true;
+ } else {
+ switch ($this->_currentServer) {
case env('NNTP_SERVER'):
if (is_resource($this->_socket)) {
- $this->doQuit(true);
+ $this->doQuit(true);
}
$retVal = $this->doConnect();
break;
case env('NNTP_SERVER_A'):
if (is_resource($this->_socket)) {
- $this->doQuit(true);
+ $this->doQuit(true);
}
$retVal = $this->doConnect(true, true);
break;
@@ -1310,13 +1282,14 @@ class NNTP extends \Net_NNTP_Client
$retVal = $this->throwError('Wrong server constant used in NNTP checkConnection()!');
}
- if ($retVal === true && $reSelectGroup) {
- $group = $this->selectGroup($currentGroup);
- if ($this->isError($group)) {
- $retVal = $group;
- }
- }
- }
- return $retVal;
- }
+ if ($retVal === true && $reSelectGroup) {
+ $group = $this->selectGroup($currentGroup);
+ if ($this->isError($group)) {
+ $retVal = $group;
+ }
+ }
+ }
+
+ return $retVal;
+ }
}
diff --git a/nntmux/NZB.php b/nntmux/NZB.php
index 11f5b5e10..cf71c538d 100755
--- a/nntmux/NZB.php
+++ b/nntmux/NZB.php
@@ -1,10 +1,11 @@
string]
- * @access protected
- */
- protected $_tableNames;
+ /**
+ * Names of CBP tables.
+ *
+ * @var array [string => string]
+ */
+ protected $_tableNames;
- /**
- * Default constructor.
- *
- * @param \nntmux\db\DB $pdo
- *
- * @access public
- * @throws \Exception
- */
- public function __construct(&$pdo)
- {
- $this->pdo = ($pdo instanceof DB ? $pdo : new DB());
+ /**
+ * Default constructor.
+ *
+ * @param \nntmux\db\DB $pdo
+ *
+ * @throws \Exception
+ */
+ public function __construct(&$pdo)
+ {
+ $this->pdo = ($pdo instanceof DB ? $pdo : new DB());
- $nzbSplitLevel = Settings::value('..nzbsplitlevel');
- $this->nzbSplitLevel = (empty($nzbSplitLevel) ? 1 : $nzbSplitLevel);
- $this->siteNzbPath = (string)Settings::value('..nzbpath');
- if (substr($this->siteNzbPath, -1) !== DS) {
- $this->siteNzbPath .= DS;
- }
- $this->_nzbCommentString = sprintf(
+ $nzbSplitLevel = Settings::value('..nzbsplitlevel');
+ $this->nzbSplitLevel = (empty($nzbSplitLevel) ? 1 : $nzbSplitLevel);
+ $this->siteNzbPath = (string) Settings::value('..nzbpath');
+ if (substr($this->siteNzbPath, -1) !== DS) {
+ $this->siteNzbPath .= DS;
+ }
+ $this->_nzbCommentString = sprintf(
'NZB Generated by: NNTmux %s %s',
(new Versions())->getGitTagInFile(),
Utility::htmlfmt(date('F j, Y, g:i a O'))
);
- $this->_debug = (NN_DEBUG || NN_LOGGING);
+ $this->_debug = (NN_DEBUG || NN_LOGGING);
- if (NN_DEBUG || NN_LOGGING) {
- $this->_debug = true;
- try {
- $this->debugging = new Logger(['ColorCLI' => $this->pdo->log]);
- } catch (LoggerException $error) {
- $this->_debug = false;
- }
- }
- }
+ if (NN_DEBUG || NN_LOGGING) {
+ $this->_debug = true;
+ try {
+ $this->debugging = new Logger(['ColorCLI' => $this->pdo->log]);
+ } catch (LoggerException $error) {
+ $this->_debug = false;
+ }
+ }
+ }
- /**
- * Initiate class vars when writing NZB's.
- *
- * @param int $groupID
- *
- * @access public
- */
- public function initiateForWrite($groupID)
- {
- $this->groupID = $groupID;
- // Set table names
+ /**
+ * Initiate class vars when writing NZB's.
+ *
+ * @param int $groupID
+ */
+ public function initiateForWrite($groupID)
+ {
+ $this->groupID = $groupID;
+ // Set table names
- if ($this->groupID === '') {
- exit("{$this->groupID} is missing\n");
- }
- $this->_tableNames = [
- 'cName' => 'collections_' . $this->groupID,
- 'bName' => 'binaries_' . $this->groupID,
- 'pName' => 'parts_' . $this->groupID
+ if ($this->groupID === '') {
+ exit("{$this->groupID} is missing\n");
+ }
+ $this->_tableNames = [
+ 'cName' => 'collections_'.$this->groupID,
+ 'bName' => 'binaries_'.$this->groupID,
+ 'pName' => 'parts_'.$this->groupID,
];
- $this->setQueries();
- }
+ $this->setQueries();
+ }
- protected function setQueries(): void
- {
- $this->_collectionsQuery = "
+ protected function setQueries(): void
+ {
+ $this->_collectionsQuery = "
SELECT c.*, UNIX_TIMESTAMP(c.date) AS udate,
g.name AS groupname
FROM {$this->_tableNames['cName']} c
INNER JOIN groups g ON c.groups_id = g.id
WHERE c.releases_id = ";
- $this->_binariesQuery = "
+ $this->_binariesQuery = "
SELECT b.id, b.name, b.totalparts
FROM {$this->_tableNames['bName']} b
WHERE b.collections_id = %d
ORDER BY b.name ASC";
- $this->_partsQuery = "
+ $this->_partsQuery = "
SELECT DISTINCT(p.messageid), p.size, p.partnumber
FROM {$this->_tableNames['pName']} p
WHERE p.binaries_id = %d
ORDER BY p.partnumber ASC";
- }
+ }
- /**
- * Write an NZB to the hard drive for a single release.
- *
- * @param int $relID The ID of the release in the DB.
- * @param string $relGuid The guid of the release.
- * @param string $name The name of the release.
- * @param string $cTitle The name of the category this release is in.
- *
- * @return bool Have we successfully written the NZB to the hard drive?
- *
- * @access public
- */
- public function writeNZBforReleaseId($relID, $relGuid, $name, $cTitle): bool
- {
- $collections = $this->pdo->queryDirect($this->_collectionsQuery . $relID);
+ /**
+ * Write an NZB to the hard drive for a single release.
+ *
+ * @param int $relID The ID of the release in the DB.
+ * @param string $relGuid The guid of the release.
+ * @param string $name The name of the release.
+ * @param string $cTitle The name of the category this release is in.
+ *
+ * @return bool Have we successfully written the NZB to the hard drive?
+ */
+ public function writeNZBforReleaseId($relID, $relGuid, $name, $cTitle): bool
+ {
+ $collections = $this->pdo->queryDirect($this->_collectionsQuery.$relID);
- if (!$collections instanceof \Traversable) {
- return false;
- }
+ if (! $collections instanceof \Traversable) {
+ return false;
+ }
- $XMLWriter = new \XMLWriter();
- $XMLWriter->openMemory();
- $XMLWriter->setIndent(true);
- $XMLWriter->setIndentString(' ');
+ $XMLWriter = new \XMLWriter();
+ $XMLWriter->openMemory();
+ $XMLWriter->setIndent(true);
+ $XMLWriter->setIndentString(' ');
- $nzb_guid = '';
+ $nzb_guid = '';
- $XMLWriter->startDocument('1.0', 'UTF-8');
- $XMLWriter->startDTD(self::NZB_DTD_NAME, self::NZB_DTD_PUBLIC, self::NZB_DTD_EXTERNAL);
- $XMLWriter->endDTD();
- $XMLWriter->writeComment($this->_nzbCommentString);
+ $XMLWriter->startDocument('1.0', 'UTF-8');
+ $XMLWriter->startDTD(self::NZB_DTD_NAME, self::NZB_DTD_PUBLIC, self::NZB_DTD_EXTERNAL);
+ $XMLWriter->endDTD();
+ $XMLWriter->writeComment($this->_nzbCommentString);
- $XMLWriter->startElement('nzb');
- $XMLWriter->writeAttribute('xmlns', self::NZB_XML_NS);
- $XMLWriter->startElement('head');
- $XMLWriter->startElement('meta');
- $XMLWriter->writeAttribute('type', 'category');
- $XMLWriter->text($cTitle);
- $XMLWriter->endElement();
- $XMLWriter->startElement('meta');
- $XMLWriter->writeAttribute('type', 'name');
- $XMLWriter->text($name);
- $XMLWriter->endElement();
- $XMLWriter->endElement(); //head
+ $XMLWriter->startElement('nzb');
+ $XMLWriter->writeAttribute('xmlns', self::NZB_XML_NS);
+ $XMLWriter->startElement('head');
+ $XMLWriter->startElement('meta');
+ $XMLWriter->writeAttribute('type', 'category');
+ $XMLWriter->text($cTitle);
+ $XMLWriter->endElement();
+ $XMLWriter->startElement('meta');
+ $XMLWriter->writeAttribute('type', 'name');
+ $XMLWriter->text($name);
+ $XMLWriter->endElement();
+ $XMLWriter->endElement(); //head
- foreach ($collections as $collection) {
- $binaries = $this->pdo->queryDirect(sprintf($this->_binariesQuery, $collection['id']));
- if ($binaries === false) {
- return false;
- }
+ foreach ($collections as $collection) {
+ $binaries = $this->pdo->queryDirect(sprintf($this->_binariesQuery, $collection['id']));
+ if ($binaries === false) {
+ return false;
+ }
- $poster = $collection['fromname'];
+ $poster = $collection['fromname'];
- foreach ($binaries as $binary) {
- $parts = $this->pdo->queryDirect(sprintf($this->_partsQuery, $binary['id']));
- if ($parts === false) {
- return false;
- }
+ foreach ($binaries as $binary) {
+ $parts = $this->pdo->queryDirect(sprintf($this->_partsQuery, $binary['id']));
+ if ($parts === false) {
+ return false;
+ }
- $subject = $binary['name'] . '(1/' . $binary['totalparts'] . ')';
- $XMLWriter->startElement('file');
- $XMLWriter->writeAttribute('poster', $poster);
- $XMLWriter->writeAttribute('date', $collection['udate']);
- $XMLWriter->writeAttribute('subject', $subject);
- $XMLWriter->startElement('groups');
- if (preg_match_all('#(\S+):\S+#', $collection['xref'], $matches)) {
- $matches = array_unique($matches[1]);
- foreach ($matches as $group) {
- $XMLWriter->writeElement('group', $group);
- }
- } else {
- return false;
- }
- $XMLWriter->endElement(); //groups
- $XMLWriter->startElement('segments');
- foreach ($parts as $part) {
- if ($nzb_guid === '') {
- $nzb_guid = $part['messageid'];
- }
- $XMLWriter->startElement('segment');
- $XMLWriter->writeAttribute('bytes', $part['size']);
- $XMLWriter->writeAttribute('number', $part['partnumber']);
- $XMLWriter->text($part['messageid']);
- $XMLWriter->endElement();
- }
- $XMLWriter->endElement(); //segments
+ $subject = $binary['name'].'(1/'.$binary['totalparts'].')';
+ $XMLWriter->startElement('file');
+ $XMLWriter->writeAttribute('poster', $poster);
+ $XMLWriter->writeAttribute('date', $collection['udate']);
+ $XMLWriter->writeAttribute('subject', $subject);
+ $XMLWriter->startElement('groups');
+ if (preg_match_all('#(\S+):\S+#', $collection['xref'], $matches)) {
+ $matches = array_unique($matches[1]);
+ foreach ($matches as $group) {
+ $XMLWriter->writeElement('group', $group);
+ }
+ } else {
+ return false;
+ }
+ $XMLWriter->endElement(); //groups
+ $XMLWriter->startElement('segments');
+ foreach ($parts as $part) {
+ if ($nzb_guid === '') {
+ $nzb_guid = $part['messageid'];
+ }
+ $XMLWriter->startElement('segment');
+ $XMLWriter->writeAttribute('bytes', $part['size']);
+ $XMLWriter->writeAttribute('number', $part['partnumber']);
+ $XMLWriter->text($part['messageid']);
+ $XMLWriter->endElement();
+ }
+ $XMLWriter->endElement(); //segments
$XMLWriter->endElement(); //file
- }
- }
- $XMLWriter->endElement(); //nzb
- $XMLWriter->endDocument();
- $path = ($this->buildNZBPath($relGuid, $this->nzbSplitLevel, true) . $relGuid . '.nzb.gz');
- $fp = gzopen($path, 'wb7');
- if (!$fp) {
- return false;
- }
- gzwrite($fp, $XMLWriter->outputMemory());
- gzclose($fp);
- unset($XMLWriter);
- if (!is_file($path)) {
- echo "ERROR: $path does not exist.\n";
+ }
+ }
+ $XMLWriter->endElement(); //nzb
+ $XMLWriter->endDocument();
+ $path = ($this->buildNZBPath($relGuid, $this->nzbSplitLevel, true).$relGuid.'.nzb.gz');
+ $fp = gzopen($path, 'wb7');
+ if (! $fp) {
+ return false;
+ }
+ gzwrite($fp, $XMLWriter->outputMemory());
+ gzclose($fp);
+ unset($XMLWriter);
+ if (! is_file($path)) {
+ echo "ERROR: $path does not exist.\n";
- return false;
- }
- // Mark release as having NZB.
- $this->pdo->queryExec(
+ return false;
+ }
+ // Mark release as having NZB.
+ $this->pdo->queryExec(
sprintf('
UPDATE releases SET nzbstatus = %d %s WHERE id = %d',
- NZB::NZB_ADDED, ($nzb_guid === '' ? '' : ', nzb_guid = UNHEX( ' . $this->pdo->escapeString(md5($nzb_guid)) . ' )'),
+ self::NZB_ADDED, ($nzb_guid === '' ? '' : ', nzb_guid = UNHEX( '.$this->pdo->escapeString(md5($nzb_guid)).' )'),
$relID
)
);
- // Delete CBP for release that has its NZB created.
- $this->pdo->queryExec(
+ // Delete CBP for release that has its NZB created.
+ $this->pdo->queryExec(
sprintf('
DELETE c, b, p FROM %s c JOIN %s b ON(c.id=b.collections_id) STRAIGHT_JOIN %s p ON(b.id=p.binaries_id) WHERE c.releases_id = %d',
$this->_tableNames['cName'], $this->_tableNames['bName'], $this->_tableNames['pName'], $relID
)
);
- // Chmod to fix issues some users have with file permissions.
- chmod($path, 0777);
+ // Chmod to fix issues some users have with file permissions.
+ chmod($path, 0777);
- return true;
- }
+ return true;
+ }
- /**
- * Build a folder path on the hard drive where the NZB file will be stored.
- *
- * @param string $releaseGuid The guid of the release.
- * @param int $levelsToSplit How many sub-paths the folder will be in.
- * @param bool $createIfNotExist Create the folder if it doesn't exist.
- *
- * @return string $nzbpath The path to store the NZB file.
- *
- * @access public
- */
- public function buildNZBPath($releaseGuid, $levelsToSplit, $createIfNotExist)
- {
- $nzbPath = '';
+ /**
+ * Build a folder path on the hard drive where the NZB file will be stored.
+ *
+ * @param string $releaseGuid The guid of the release.
+ * @param int $levelsToSplit How many sub-paths the folder will be in.
+ * @param bool $createIfNotExist Create the folder if it doesn't exist.
+ *
+ * @return string $nzbpath The path to store the NZB file.
+ */
+ public function buildNZBPath($releaseGuid, $levelsToSplit, $createIfNotExist)
+ {
+ $nzbPath = '';
- for ($i = 0; $i < $levelsToSplit && $i < 32; $i++) {
- $nzbPath .= substr($releaseGuid, $i, 1) . DS;
- }
+ for ($i = 0; $i < $levelsToSplit && $i < 32; $i++) {
+ $nzbPath .= substr($releaseGuid, $i, 1).DS;
+ }
- $nzbPath = $this->siteNzbPath . $nzbPath;
+ $nzbPath = $this->siteNzbPath.$nzbPath;
- if ($createIfNotExist === true && !is_dir($nzbPath)) {
- mkdir($nzbPath, 0777, true);
- }
+ if ($createIfNotExist === true && ! is_dir($nzbPath)) {
+ mkdir($nzbPath, 0777, true);
+ }
- return $nzbPath;
- }
+ return $nzbPath;
+ }
- /**
- * Retrieve path + filename of the NZB to be stored.
- *
- * @param string $releaseGuid The guid of the release.
- * @param int $levelsToSplit How many sub-paths the folder will be in. (optional)
- * @param bool $createIfNotExist Create the folder if it doesn't exist. (optional)
- *
- * @return string Path+filename.
- *
- * @access public
- */
- public function getNZBPath($releaseGuid, $levelsToSplit = 0, $createIfNotExist = false): string
- {
- if ($levelsToSplit === 0) {
- $levelsToSplit = $this->nzbSplitLevel;
- }
+ /**
+ * Retrieve path + filename of the NZB to be stored.
+ *
+ * @param string $releaseGuid The guid of the release.
+ * @param int $levelsToSplit How many sub-paths the folder will be in. (optional)
+ * @param bool $createIfNotExist Create the folder if it doesn't exist. (optional)
+ *
+ * @return string Path+filename.
+ */
+ public function getNZBPath($releaseGuid, $levelsToSplit = 0, $createIfNotExist = false): string
+ {
+ if ($levelsToSplit === 0) {
+ $levelsToSplit = $this->nzbSplitLevel;
+ }
- return ($this->buildNZBPath($releaseGuid, $levelsToSplit, $createIfNotExist) . $releaseGuid . '.nzb.gz');
- }
+ return $this->buildNZBPath($releaseGuid, $levelsToSplit, $createIfNotExist).$releaseGuid.'.nzb.gz';
+ }
- /**
- * Determine is an NZB exists, returning the path+filename, if not return false.
- *
- * @param string $releaseGuid The guid of the release.
- *
- * @return bool|string On success: (string) Path+file name of the nzb.
- * On failure: (bool) False.
- *
- * @access public
- */
- public function NZBPath($releaseGuid)
- {
- $nzbFile = $this->getNZBPath($releaseGuid);
+ /**
+ * Determine is an NZB exists, returning the path+filename, if not return false.
+ *
+ * @param string $releaseGuid The guid of the release.
+ *
+ * @return bool|string On success: (string) Path+file name of the nzb.
+ * On failure: (bool) False.
+ */
+ public function NZBPath($releaseGuid)
+ {
+ $nzbFile = $this->getNZBPath($releaseGuid);
- return (is_file($nzbFile) ? $nzbFile : false);
- }
+ return is_file($nzbFile) ? $nzbFile : false;
+ }
- /**
- * Retrieve various information on a NZB file (the subject, # of pars,
- * file extensions, file sizes, file completion, group names, # of parts).
- *
- * @param string $nzb The NZB contents in a string.
- * @param array $options
- * 'no-file-key' => True - use numeric array key; False - Use filename as array key.
- * 'strip-count' => True - Strip file/part count from file name to make the array key; False - Leave file name as is.
- *
- * @return array $result Empty if not an NZB or the contents of the NZB.
- *
- * @access public
- */
- public function nzbFileList($nzb, array $options = []): array
- {
- $defaults = [
+ /**
+ * Retrieve various information on a NZB file (the subject, # of pars,
+ * file extensions, file sizes, file completion, group names, # of parts).
+ *
+ * @param string $nzb The NZB contents in a string.
+ * @param array $options
+ * 'no-file-key' => True - use numeric array key; False - Use filename as array key.
+ * 'strip-count' => True - Strip file/part count from file name to make the array key; False - Leave file name as is.
+ *
+ * @return array $result Empty if not an NZB or the contents of the NZB.
+ */
+ public function nzbFileList($nzb, array $options = []): array
+ {
+ $defaults = [
'no-file-key' => true,
'strip-count' => false,
];
- $options += $defaults;
+ $options += $defaults;
- $num_pars = $i = 0;
- $result = [];
+ $num_pars = $i = 0;
+ $result = [];
- if (!$nzb) {
- return $result;
- }
+ if (! $nzb) {
+ return $result;
+ }
- $xml = @simplexml_load_string(str_replace("\x0F", '', $nzb));
- if (!$xml || strtolower($xml->getName()) !== 'nzb') {
- return $result;
- }
+ $xml = @simplexml_load_string(str_replace("\x0F", '', $nzb));
+ if (! $xml || strtolower($xml->getName()) !== 'nzb') {
+ return $result;
+ }
- foreach ($xml->file as $file) {
- // Subject.
- $title = (string)$file->attributes()->subject;
+ foreach ($xml->file as $file) {
+ // Subject.
+ $title = (string) $file->attributes()->subject;
- // Amount of pars.
- if (stripos($title, '.par2')) {
- $num_pars++;
- }
+ // Amount of pars.
+ if (stripos($title, '.par2')) {
+ $num_pars++;
+ }
- if ($options['no-file-key'] === false) {
- $i = $title;
- if ($options['strip-count']) {
- // Strip file / part count to get proper sorting.
- $i = preg_replace('#\d+[- ._]?(/|\||[o0]f)[- ._]?\d+?(?![- ._]\d)#i', '', $i);
- // Change .rar and .par2 to be sorted before .part0x.rar and .volxxx+xxx.par2
- if (strpos($i, '.par2') !== false && !preg_match('#\.vol\d+\+\d+\.par2#i', $i)) {
- $i = str_replace('.par2', '.vol0.par2', $i);
- } else if (preg_match('#\.rar[^a-z0-9]#i', $i) && !preg_match('#\.part\d+\.rar#i', $i)) {
- $i = preg_replace('#\.rar(?:[^a-z0-9])#i', '.part0.rar', $i);
- }
- }
- }
+ if ($options['no-file-key'] === false) {
+ $i = $title;
+ if ($options['strip-count']) {
+ // Strip file / part count to get proper sorting.
+ $i = preg_replace('#\d+[- ._]?(/|\||[o0]f)[- ._]?\d+?(?![- ._]\d)#i', '', $i);
+ // Change .rar and .par2 to be sorted before .part0x.rar and .volxxx+xxx.par2
+ if (strpos($i, '.par2') !== false && ! preg_match('#\.vol\d+\+\d+\.par2#i', $i)) {
+ $i = str_replace('.par2', '.vol0.par2', $i);
+ } elseif (preg_match('#\.rar[^a-z0-9]#i', $i) && ! preg_match('#\.part\d+\.rar#i', $i)) {
+ $i = preg_replace('#\.rar(?:[^a-z0-9])#i', '.part0.rar', $i);
+ }
+ }
+ }
- $result[$i]['title'] = $title;
+ $result[$i]['title'] = $title;
- // Extensions.
- if (preg_match(
+ // Extensions.
+ if (preg_match(
'/\.(\d{2,3}|7z|ace|ai7|srr|srt|sub|aiff|asc|avi|audio|bin|bz2|'
- . 'c|cfc|cfm|chm|class|conf|cpp|cs|css|csv|cue|deb|divx|doc|dot|'
- . 'eml|enc|exe|file|gif|gz|hlp|htm|html|image|iso|jar|java|jpeg|'
- . 'jpg|js|lua|m|m3u|mkv|mm|mov|mp3|mp4|mpg|nfo|nzb|odc|odf|odg|odi|odp|'
- . 'ods|odt|ogg|par2|parity|pdf|pgp|php|pl|png|ppt|ps|py|r\d{2,3}|'
- . 'ram|rar|rb|rm|rpm|rtf|sfv|sig|sql|srs|swf|sxc|sxd|sxi|sxw|tar|'
- . 'tex|tgz|txt|vcf|video|vsd|wav|wma|wmv|xls|xml|xpi|xvid|zip7|zip)'
- . '[" ](?!(\)|\-))/i',
+ .'c|cfc|cfm|chm|class|conf|cpp|cs|css|csv|cue|deb|divx|doc|dot|'
+ .'eml|enc|exe|file|gif|gz|hlp|htm|html|image|iso|jar|java|jpeg|'
+ .'jpg|js|lua|m|m3u|mkv|mm|mov|mp3|mp4|mpg|nfo|nzb|odc|odf|odg|odi|odp|'
+ .'ods|odt|ogg|par2|parity|pdf|pgp|php|pl|png|ppt|ps|py|r\d{2,3}|'
+ .'ram|rar|rb|rm|rpm|rtf|sfv|sig|sql|srs|swf|sxc|sxd|sxi|sxw|tar|'
+ .'tex|tgz|txt|vcf|video|vsd|wav|wma|wmv|xls|xml|xpi|xvid|zip7|zip)'
+ .'[" ](?!(\)|\-))/i',
$title, $ext
)
) {
+ if (preg_match('/\.r\d{2,3}/i', $ext[0])) {
+ $ext[1] = 'rar';
+ }
+ $result[$i]['ext'] = strtolower($ext[1]);
+ } else {
+ $result[$i]['ext'] = '';
+ }
- if (preg_match('/\.r\d{2,3}/i', $ext[0])) {
- $ext[1] = 'rar';
- }
- $result[$i]['ext'] = strtolower($ext[1]);
- } else {
- $result[$i]['ext'] = '';
- }
+ $fileSize = $numSegments = 0;
- $fileSize = $numSegments = 0;
+ // Parts.
+ if (! isset($result[$i]['segments'])) {
+ $result[$i]['segments'] = [];
+ }
- // Parts.
- if (!isset($result[$i]['segments'])) {
- $result[$i]['segments'] = [];
- }
+ // File size.
+ foreach ($file->segments->segment as $segment) {
+ $result[$i]['segments'][] = (string) $segment;
+ $fileSize += $segment->attributes()->bytes;
+ $numSegments++;
+ }
+ $result[$i]['size'] = $fileSize;
- // File size.
- foreach ($file->segments->segment as $segment) {
- $result[$i]['segments'][] = (string)$segment;
- $fileSize += $segment->attributes()->bytes;
- $numSegments++;
- }
- $result[$i]['size'] = $fileSize;
+ // File completion.
+ if (preg_match('/(\d+)\)$/', $title, $parts)) {
+ $result[$i]['partstotal'] = $parts[1];
+ }
+ $result[$i]['partsactual'] = $numSegments;
- // File completion.
- if (preg_match('/(\d+)\)$/', $title, $parts)) {
- $result[$i]['partstotal'] = $parts[1];
- }
- $result[$i]['partsactual'] = $numSegments;
+ // Groups.
+ if (! isset($result[$i]['groups'])) {
+ $result[$i]['groups'] = [];
+ }
+ foreach ($file->groups->group as $g) {
+ $result[$i]['groups'][] = (string) $g;
+ }
- // Groups.
- if (!isset($result[$i]['groups'])) {
- $result[$i]['groups'] = [];
- }
- foreach ($file->groups->group as $g) {
- $result[$i]['groups'][] = (string)$g;
- }
+ unset($result[$i]['segments']['@attributes']);
+ if ($options['no-file-key']) {
+ $i++;
+ }
+ }
- unset($result[$i]['segments']['@attributes']);
- if ($options['no-file-key']) {
- $i++;
- }
- }
-
- return $result;
- }
+ return $result;
+ }
}
diff --git a/nntmux/NZBContents.php b/nntmux/NZBContents.php
index 9c4d1eafb..c2c735548 100755
--- a/nntmux/NZBContents.php
+++ b/nntmux/NZBContents.php
@@ -1,86 +1,78 @@
bool ; To echo to CLI or not.
- * 'NNTP' => NNTP ; Class NNTP.
- * 'Nfo' => Nfo ; Class Nfo.
- * 'NZB' => NZB ; Class NZB.
- * 'Settings' => DB ; Class nntmux\db\Settings.
- * 'PostProcess' => PostProcess ; Class PostProcess.
- * )
- *
- * @access public
- * @throws \Exception
- */
- public function __construct(array $options = [])
- {
- $defaults = [
+ /**
+ * Construct.
+ *
+ * @param array $options
+ * array(
+ * 'Echo' => bool ; To echo to CLI or not.
+ * 'NNTP' => NNTP ; Class NNTP.
+ * 'Nfo' => Nfo ; Class Nfo.
+ * 'NZB' => NZB ; Class NZB.
+ * 'Settings' => DB ; Class nntmux\db\Settings.
+ * 'PostProcess' => PostProcess ; Class PostProcess.
+ * )
+ *
+ * @throws \Exception
+ */
+ public function __construct(array $options = [])
+ {
+ $defaults = [
'Echo' => false,
'NNTP' => null,
'Nfo' => null,
@@ -88,229 +80,225 @@ Class NZBContents
'Settings' => null,
'PostProcess' => null,
];
- $options += $defaults;
+ $options += $defaults;
- $this->echooutput = ($options['Echo'] && NN_ECHOCLI);
- $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB());
- $this->nntp = ($options['NNTP'] instanceof NNTP ? $options['NNTP'] : new NNTP(['Echo' => $this->echooutput, 'Settings' => $this->pdo]));
- $this->nfo = ($options['Nfo'] instanceof Nfo ? $options['Nfo'] : new Nfo(['Echo' => $this->echooutput, 'Settings' => $this->pdo]));
- $this->pp = (
+ $this->echooutput = ($options['Echo'] && NN_ECHOCLI);
+ $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB());
+ $this->nntp = ($options['NNTP'] instanceof NNTP ? $options['NNTP'] : new NNTP(['Echo' => $this->echooutput, 'Settings' => $this->pdo]));
+ $this->nfo = ($options['Nfo'] instanceof Nfo ? $options['Nfo'] : new Nfo(['Echo' => $this->echooutput, 'Settings' => $this->pdo]));
+ $this->pp = (
$options['PostProcess'] instanceof PostProcess
? $options['PostProcess']
: new PostProcess(['Echo' => $this->echooutput, 'Nfo' => $this->nfo, 'Settings' => $this->pdo])
);
- $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo));
- $this->lookuppar2 = (int)Settings::value('..lookuppar2') === 1 ? true : false;
- $this->alternateNNTP = (int)Settings::value('..alternate_nntp') === 1 ? true : false;
- }
+ $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo));
+ $this->lookuppar2 = (int) Settings::value('..lookuppar2') === 1 ? true : false;
+ $this->alternateNNTP = (int) Settings::value('..alternate_nntp') === 1 ? true : false;
+ }
- /**
- * Look for an .nfo file in the NZB, return the NFO message id.
- * Gets the NZB completion.
- * Looks for PAR2 files in the NZB.
- *
- * @param string $guid
- * @param string $relID
- * @param int $groupID
- * @param string $groupName
- *
- * @return bool
- *
- * @access public
- */
- public function getNfoFromNZB($guid, $relID, $groupID, $groupName)
- {
- $fetchedBinary = false;
+ /**
+ * Look for an .nfo file in the NZB, return the NFO message id.
+ * Gets the NZB completion.
+ * Looks for PAR2 files in the NZB.
+ *
+ * @param string $guid
+ * @param string $relID
+ * @param int $groupID
+ * @param string $groupName
+ *
+ * @return bool
+ */
+ public function getNfoFromNZB($guid, $relID, $groupID, $groupName)
+ {
+ $fetchedBinary = false;
- $messageID = $this->parseNZB($guid, $relID, $groupID, true);
- if ($messageID !== false) {
- $fetchedBinary = $this->nntp->getMessages($groupName, $messageID['id'], $this->alternateNNTP);
- if ($this->nntp->isError($fetchedBinary)) {
- // NFO download failed, increment attempts.
- $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = nfostatus - 1 WHERE id = %d', $relID));
- if ($this->echooutput) {
- echo 'f';
- }
- return false;
- }
- if ($this->nfo->isNFO($fetchedBinary, $guid) === true) {
- if ($this->echooutput) {
- echo ($messageID['hidden'] === false ? '+' : '*');
- }
- } else {
- if ($this->echooutput) {
- echo '-';
- }
- $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', Nfo::NFO_NONFO, $relID));
- $fetchedBinary = false;
- }
- } else {
- if ($this->echooutput) {
- echo '-';
- }
- $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', Nfo::NFO_NONFO, $relID));
- }
+ $messageID = $this->parseNZB($guid, $relID, $groupID, true);
+ if ($messageID !== false) {
+ $fetchedBinary = $this->nntp->getMessages($groupName, $messageID['id'], $this->alternateNNTP);
+ if ($this->nntp->isError($fetchedBinary)) {
+ // NFO download failed, increment attempts.
+ $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = nfostatus - 1 WHERE id = %d', $relID));
+ if ($this->echooutput) {
+ echo 'f';
+ }
- return $fetchedBinary;
- }
+ return false;
+ }
+ if ($this->nfo->isNFO($fetchedBinary, $guid) === true) {
+ if ($this->echooutput) {
+ echo $messageID['hidden'] === false ? '+' : '*';
+ }
+ } else {
+ if ($this->echooutput) {
+ echo '-';
+ }
+ $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', Nfo::NFO_NONFO, $relID));
+ $fetchedBinary = false;
+ }
+ } else {
+ if ($this->echooutput) {
+ echo '-';
+ }
+ $this->pdo->queryExec(sprintf('UPDATE releases SET nfostatus = %d WHERE id = %d', Nfo::NFO_NONFO, $relID));
+ }
- /**
- * Gets the completion from the NZB, optionally looks if there is an NFO/PAR2 file.
- *
- * @param string $guid
- * @param int $relID
- * @param int $groupID
- * @param bool $nfoCheck
- *
- * @return array|bool
- *
- * @access public
- */
- public function parseNZB($guid, $relID, $groupID, $nfoCheck = false)
- {
- $nzbFile = $this->LoadNZB($guid);
- if ($nzbFile !== false) {
- $messageID = $hiddenID = '';
- $actualParts = $artificialParts = 0;
- $foundPAR2 = $this->lookuppar2 === false ? true : false;
- $foundNFO = $hiddenNFO = $nfoCheck === false ? true : false;
- $foundSRR = false;
+ return $fetchedBinary;
+ }
- foreach ($nzbFile->file as $nzbcontents) {
- foreach ($nzbcontents->segments->segment as $segment) {
- $actualParts++;
- }
+ /**
+ * Gets the completion from the NZB, optionally looks if there is an NFO/PAR2 file.
+ *
+ * @param string $guid
+ * @param int $relID
+ * @param int $groupID
+ * @param bool $nfoCheck
+ *
+ * @return array|bool
+ */
+ public function parseNZB($guid, $relID, $groupID, $nfoCheck = false)
+ {
+ $nzbFile = $this->LoadNZB($guid);
+ if ($nzbFile !== false) {
+ $messageID = $hiddenID = '';
+ $actualParts = $artificialParts = 0;
+ $foundPAR2 = $this->lookuppar2 === false ? true : false;
+ $foundNFO = $hiddenNFO = $nfoCheck === false ? true : false;
+ $foundSRR = false;
- $subject = (string)$nzbcontents->attributes()->subject;
- if (preg_match('/(\d+)\)$/', $subject, $parts)) {
- $artificialParts += $parts[1];
- }
+ foreach ($nzbFile->file as $nzbcontents) {
+ foreach ($nzbcontents->segments->segment as $segment) {
+ $actualParts++;
+ }
- if ($foundNFO === false) {
- if (preg_match('/\.\b(nfo|inf|ofn)\b(?![ .-])/i', $subject)) {
- $messageID = (string)$nzbcontents->segments->segment;
- $foundNFO = true;
- }
- }
+ $subject = (string) $nzbcontents->attributes()->subject;
+ if (preg_match('/(\d+)\)$/', $subject, $parts)) {
+ $artificialParts += $parts[1];
+ }
- if ($foundNFO === false && $hiddenNFO === false) {
- if (preg_match('/\(1\/1\)$/i', $subject) &&
- !preg_match('/\.(apk|bat|bmp|cbr|cbz|cfg|css|csv|cue|db|dll|doc|epub|exe|gif|htm|ico|idx|ini' .
- '|jpg|lit|log|m3u|mid|mobi|mp3|nib|nzb|odt|opf|otf|par|par2|pdf|psd|pps|png|ppt|r\d{2,4}' .
+ if ($foundNFO === false) {
+ if (preg_match('/\.\b(nfo|inf|ofn)\b(?![ .-])/i', $subject)) {
+ $messageID = (string) $nzbcontents->segments->segment;
+ $foundNFO = true;
+ }
+ }
+
+ if ($foundNFO === false && $hiddenNFO === false) {
+ if (preg_match('/\(1\/1\)$/i', $subject) &&
+ ! preg_match('/\.(apk|bat|bmp|cbr|cbz|cfg|css|csv|cue|db|dll|doc|epub|exe|gif|htm|ico|idx|ini'.
+ '|jpg|lit|log|m3u|mid|mobi|mp3|nib|nzb|odt|opf|otf|par|par2|pdf|psd|pps|png|ppt|r\d{2,4}'.
'|rar|sfv|srr|sub|srt|sql|rom|rtf|tif|torrent|ttf|txt|vb|vol\d+\+\d+|wps|xml|zip)/i',
- $subject))
- {
- $hiddenID = (string)$nzbcontents->segments->segment;
- $hiddenNFO = true;
- }
- }
+ $subject)) {
+ $hiddenID = (string) $nzbcontents->segments->segment;
+ $hiddenNFO = true;
+ }
+ }
- if ($foundPAR2 === false) {
- if (preg_match('/\.(par[&2" ]|\d{2,3}").+\(1\/1\)$/i', $subject)) {
- if ($this->pp->parsePAR2((string)$nzbcontents->segments->segment, $relID, $groupID, $this->nntp, 1) === true) {
- $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID));
- $foundPAR2 = true;
- }
- }
- }
- }
+ if ($foundPAR2 === false) {
+ if (preg_match('/\.(par[&2" ]|\d{2,3}").+\(1\/1\)$/i', $subject)) {
+ if ($this->pp->parsePAR2((string) $nzbcontents->segments->segment, $relID, $groupID, $this->nntp, 1) === true) {
+ $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID));
+ $foundPAR2 = true;
+ }
+ }
+ }
+ }
- if ($artificialParts <= 0 || $actualParts <= 0) {
- $completion = 0;
- } else {
- $completion = ($actualParts / $artificialParts) * 100;
- }
- if ($completion > 100) {
- $completion = 100;
- }
+ if ($artificialParts <= 0 || $actualParts <= 0) {
+ $completion = 0;
+ } else {
+ $completion = ($actualParts / $artificialParts) * 100;
+ }
+ if ($completion > 100) {
+ $completion = 100;
+ }
- $this->pdo->queryExec(sprintf('UPDATE releases SET completion = %d WHERE id = %d', $completion, $relID));
+ $this->pdo->queryExec(sprintf('UPDATE releases SET completion = %d WHERE id = %d', $completion, $relID));
- if ($foundNFO === true && strlen($messageID) > 1) {
- return array('hidden' => false, 'id' => $messageID);
- }
+ if ($foundNFO === true && strlen($messageID) > 1) {
+ return ['hidden' => false, 'id' => $messageID];
+ }
- if ($hiddenNFO === true && strlen($hiddenID) > 1) {
- return array('hidden' => true, 'id' => $hiddenID);
- }
- }
- return false;
- }
+ if ($hiddenNFO === true && strlen($hiddenID) > 1) {
+ return ['hidden' => true, 'id' => $hiddenID];
+ }
+ }
- /**
- * Decompress a NZB, load it into simplexml and return.
- *
- * @param string $guid Release guid.
- *
- * @return bool SimpleXMLElement
- *
- * @access public
- */
- public function LoadNZB($guid)
- {
- // Fetch the NZB location using the GUID.
- $nzbPath = $this->nzb->NZBPath($guid);
- if ($nzbPath === false) {
- if ($this->echooutput) {
- echo PHP_EOL . $guid . ' appears to be missing the nzb file, skipping.' . PHP_EOL;
- }
- return false;
- }
- $nzbContents = Utility::unzipGzipFile($nzbPath);
- if (!$nzbContents) {
- if ($this->echooutput) {
- echo
- PHP_EOL .
- 'Unable to decompress: ' .
- $nzbPath .
- ' - ' .
- fileperms($nzbPath) .
- ' - may have bad file permissions, skipping.' .
+ return false;
+ }
+
+ /**
+ * Decompress a NZB, load it into simplexml and return.
+ *
+ * @param string $guid Release guid.
+ *
+ * @return bool SimpleXMLElement
+ */
+ public function LoadNZB($guid)
+ {
+ // Fetch the NZB location using the GUID.
+ $nzbPath = $this->nzb->NZBPath($guid);
+ if ($nzbPath === false) {
+ if ($this->echooutput) {
+ echo PHP_EOL.$guid.' appears to be missing the nzb file, skipping.'.PHP_EOL;
+ }
+
+ return false;
+ }
+ $nzbContents = Utility::unzipGzipFile($nzbPath);
+ if (! $nzbContents) {
+ if ($this->echooutput) {
+ echo
+ PHP_EOL.
+ 'Unable to decompress: '.
+ $nzbPath.
+ ' - '.
+ fileperms($nzbPath).
+ ' - may have bad file permissions, skipping.'.
PHP_EOL;
- }
- return false;
- }
+ }
- $nzbFile = @simplexml_load_string($nzbContents);
- if (!$nzbFile) {
- if ($this->echooutput) {
- echo PHP_EOL . "Unable to load NZB: $guid appears to be an invalid NZB, skipping." . PHP_EOL;
- }
- return false;
- }
+ return false;
+ }
- return $nzbFile;
- }
+ $nzbFile = @simplexml_load_string($nzbContents);
+ if (! $nzbFile) {
+ if ($this->echooutput) {
+ echo PHP_EOL."Unable to load NZB: $guid appears to be an invalid NZB, skipping.".PHP_EOL;
+ }
- /**
- * Attempts to get the releasename from a par2 file
- *
- * @param string $guid
- * @param int $relID
- * @param int $groupID
- * @param int $nameStatus
- * @param int $show
- *
- * @return bool
- *
- * @access public
- */
- public function checkPAR2($guid, $relID, $groupID, $nameStatus, $show)
- {
- $nzbFile = $this->LoadNZB($guid);
- if ($nzbFile !== false) {
- foreach ($nzbFile->file as $nzbContents) {
- if ($nameStatus === 1 && $this->pp->parsePAR2((string)$nzbContents->segments->segment, $relID, $groupID, $this->nntp, $show) === true && preg_match('/\.(par[2" ]|\d{2,3}").+\(1\/1\)/i', (string)$nzbContents->attributes()->subject)) {
- $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID));
+ return false;
+ }
- return true;
- }
- }
- }
- if ($nameStatus === 1) {
- $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID));
- }
+ return $nzbFile;
+ }
- return false;
- }
+ /**
+ * Attempts to get the releasename from a par2 file.
+ *
+ * @param string $guid
+ * @param int $relID
+ * @param int $groupID
+ * @param int $nameStatus
+ * @param int $show
+ *
+ * @return bool
+ */
+ public function checkPAR2($guid, $relID, $groupID, $nameStatus, $show)
+ {
+ $nzbFile = $this->LoadNZB($guid);
+ if ($nzbFile !== false) {
+ foreach ($nzbFile->file as $nzbContents) {
+ if ($nameStatus === 1 && $this->pp->parsePAR2((string) $nzbContents->segments->segment, $relID, $groupID, $this->nntp, $show) === true && preg_match('/\.(par[2" ]|\d{2,3}").+\(1\/1\)/i', (string) $nzbContents->attributes()->subject)) {
+ $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID));
+
+ return true;
+ }
+ }
+ }
+ if ($nameStatus === 1) {
+ $this->pdo->queryExec(sprintf('UPDATE releases SET proc_par2 = 1 WHERE id = %d', $relID));
+ }
+
+ return false;
+ }
}
diff --git a/nntmux/NZBExport.php b/nntmux/NZBExport.php
index 6ec89a48c..4b0827c28 100755
--- a/nntmux/NZBExport.php
+++ b/nntmux/NZBExport.php
@@ -1,4 +1,5 @@
false, // Started from browser?
'Echo' => true, // Echo to CLI?
'NZB' => null,
'Releases' => null,
'Settings' => null,
];
- $options += $defaults;
+ $options += $defaults;
- $this->browser = $options['Browser'];
- $this->echoCLI = (!$this->browser && NN_ECHOCLI && $options['Echo']);
- $this->pdo = ($options['Settings'] instanceof DB ? $options['Setting'] : new DB());
- $this->releases = ($options['Releases'] instanceof Releases ? $options['Releases'] : new Releases(['Settings' => $this->pdo]));
- $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo));
- }
+ $this->browser = $options['Browser'];
+ $this->echoCLI = (! $this->browser && NN_ECHOCLI && $options['Echo']);
+ $this->pdo = ($options['Settings'] instanceof DB ? $options['Setting'] : new DB());
+ $this->releases = ($options['Releases'] instanceof Releases ? $options['Releases'] : new Releases(['Settings' => $this->pdo]));
+ $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo));
+ }
- /**
- * Export to user specified folder.
- *
- * @param array $params
- *
- * @return bool
- *
- * @access public
- */
- public function beginExport($params)
- {
- $gzip = false;
- if ($params[4] === true) {
- $gzip = true;
- }
+ /**
+ * Export to user specified folder.
+ *
+ * @param array $params
+ *
+ * @return bool
+ */
+ public function beginExport($params)
+ {
+ $gzip = false;
+ if ($params[4] === true) {
+ $gzip = true;
+ }
- $fromDate = $toDate = '';
- $path = $params[0];
+ $fromDate = $toDate = '';
+ $path = $params[0];
- // Check if the path ends with dir separator.
- if (substr($path, -1) !== DS) {
- $path .= DS;
- }
+ // Check if the path ends with dir separator.
+ if (substr($path, -1) !== DS) {
+ $path .= DS;
+ }
- // Check if it's a directory.
- if (!is_dir($path)) {
- $this->echoOut('Folder does not exist: ' . $path);
- return $this->returnValue();
- }
+ // Check if it's a directory.
+ if (! is_dir($path)) {
+ $this->echoOut('Folder does not exist: '.$path);
- // Check if we can write to it.
- if (!is_writable($path)) {
- $this->echoOut('Folder is not writable: ' . $path);
- return $this->returnValue();
- }
+ return $this->returnValue();
+ }
- // Check if the from date is the proper format.
- if (isset($params[1]) && $params[1] !== '') {
- if (!$this->checkDate($params[1])) {
- return $this->returnValue();
- }
- $fromDate = $params[1];
- }
+ // Check if we can write to it.
+ if (! is_writable($path)) {
+ $this->echoOut('Folder is not writable: '.$path);
- // Check if the to date is the proper format.
- if (isset($params[2]) && $params[2] !== '') {
- if (!$this->checkDate($params[2])) {
- return $this->returnValue();
- }
- $toDate = $params[2];
- }
+ return $this->returnValue();
+ }
- // Check if the group_id exists.
- if (isset($params[3]) && $params[3] !== 0) {
- if (!is_numeric($params[3])) {
- $this->echoOut('The group ID is not a number: ' . $params[3]);
- return $this->returnValue();
- }
- $groups = $this->pdo->query('SELECT id, name FROM groups WHERE id = ' . $params[3]);
- if (count($groups) === 0) {
- $this->echoOut('The group ID is not in the DB: ' . $params[3]);
- return $this->returnValue();
- }
- } else {
- $groups = $this->pdo->query('SELECT id, name FROM groups');
- }
+ // Check if the from date is the proper format.
+ if (isset($params[1]) && $params[1] !== '') {
+ if (! $this->checkDate($params[1])) {
+ return $this->returnValue();
+ }
+ $fromDate = $params[1];
+ }
- $exported = 0;
- // Loop over groups to take less RAM.
- foreach ($groups as $group) {
- $currentExport = 0;
- // Get all the releases based on the parameters.
- $releases = $this->releases->getForExport($fromDate, $toDate, $group['id']);
- $totalFound = count($releases);
- if ($totalFound === 0) {
- if ($this->echoCLI) {
- echo 'No releases found to export for group: ' . $group['name'] . PHP_EOL;
- }
- continue;
- }
- if ($this->echoCLI) {
- echo 'Found ' . $totalFound . ' releases to export for group: ' . $group['name'] . PHP_EOL;
- }
+ // Check if the to date is the proper format.
+ if (isset($params[2]) && $params[2] !== '') {
+ if (! $this->checkDate($params[2])) {
+ return $this->returnValue();
+ }
+ $toDate = $params[2];
+ }
- // Create a path to store the new NZB files.
- $currentPath = $path . $this->safeFilename($group['name']) . DS;
- if (!is_dir($currentPath)) {
- mkdir($currentPath);
- }
- foreach ($releases as $release) {
+ // Check if the group_id exists.
+ if (isset($params[3]) && $params[3] !== 0) {
+ if (! is_numeric($params[3])) {
+ $this->echoOut('The group ID is not a number: '.$params[3]);
+
+ return $this->returnValue();
+ }
+ $groups = $this->pdo->query('SELECT id, name FROM groups WHERE id = '.$params[3]);
+ if (count($groups) === 0) {
+ $this->echoOut('The group ID is not in the DB: '.$params[3]);
+
+ return $this->returnValue();
+ }
+ } else {
+ $groups = $this->pdo->query('SELECT id, name FROM groups');
+ }
+
+ $exported = 0;
+ // Loop over groups to take less RAM.
+ foreach ($groups as $group) {
+ $currentExport = 0;
+ // Get all the releases based on the parameters.
+ $releases = $this->releases->getForExport($fromDate, $toDate, $group['id']);
+ $totalFound = count($releases);
+ if ($totalFound === 0) {
+ if ($this->echoCLI) {
+ echo 'No releases found to export for group: '.$group['name'].PHP_EOL;
+ }
+ continue;
+ }
+ if ($this->echoCLI) {
+ echo 'Found '.$totalFound.' releases to export for group: '.$group['name'].PHP_EOL;
+ }
+
+ // Create a path to store the new NZB files.
+ $currentPath = $path.$this->safeFilename($group['name']).DS;
+ if (! is_dir($currentPath)) {
+ mkdir($currentPath);
+ }
+ foreach ($releases as $release) {
// Get path to the NZB file.
- $nzbFile = $this->nzb->NZBPath($release["guid"]);
- // Check if it exists.
- if ($nzbFile === false) {
- if ($this->echoCLI) {
- echo 'Unable to find NZB for release with GUID: ' . $release['guid'];
- }
- continue;
- }
+ $nzbFile = $this->nzb->NZBPath($release['guid']);
+ // Check if it exists.
+ if ($nzbFile === false) {
+ if ($this->echoCLI) {
+ echo 'Unable to find NZB for release with GUID: '.$release['guid'];
+ }
+ continue;
+ }
- // Create path to current file.
- $currentFile = $currentPath . $this->safeFilename($release['searchname']);
+ // Create path to current file.
+ $currentFile = $currentPath.$this->safeFilename($release['searchname']);
- // Check if the user wants them in gzip, copy it if so.
- if ($gzip) {
- if (!copy($nzbFile, $currentFile . '.nzb.gz')) {
- if ($this->echoCLI) {
- echo 'Unable to export NZB with GUID: ' . $release['guid'];
- }
- continue;
- }
- // If not, decompress it and create a file to store it in.
- } else {
- $nzbContents = Utility::unzipGzipFile($nzbFile);
- if (!$nzbContents) {
- if ($this->echoCLI) {
- echo 'Unable to export NZB with GUID: ' . $release['guid'];
- }
- continue;
- }
- $fh = fopen($currentFile . '.nzb', 'w');
- fwrite($fh, $nzbContents);
- fclose($fh);
- }
+ // Check if the user wants them in gzip, copy it if so.
+ if ($gzip) {
+ if (! copy($nzbFile, $currentFile.'.nzb.gz')) {
+ if ($this->echoCLI) {
+ echo 'Unable to export NZB with GUID: '.$release['guid'];
+ }
+ continue;
+ }
+ // If not, decompress it and create a file to store it in.
+ } else {
+ $nzbContents = Utility::unzipGzipFile($nzbFile);
+ if (! $nzbContents) {
+ if ($this->echoCLI) {
+ echo 'Unable to export NZB with GUID: '.$release['guid'];
+ }
+ continue;
+ }
+ $fh = fopen($currentFile.'.nzb', 'w');
+ fwrite($fh, $nzbContents);
+ fclose($fh);
+ }
- $currentExport++;
+ $currentExport++;
- if ($this->echoCLI && $currentExport % 10 === 0) {
- echo 'Exported ' . $currentExport . ' of ' . $totalFound . ' nzbs for group: ' . $group['name'] . "\r";
- }
- }
- if ($this->echoCLI && $currentExport > 0) {
- echo 'Exported ' . $currentExport . ' of ' . $totalFound . ' nzbs for group: ' . $group['name'] . PHP_EOL;
- }
- $exported += $currentExport;
- }
- if ($exported > 0) {
- $this->echoOut('Exported total of ' . $exported . ' NZB files to ' . $path);
- }
+ if ($this->echoCLI && $currentExport % 10 === 0) {
+ echo 'Exported '.$currentExport.' of '.$totalFound.' nzbs for group: '.$group['name']."\r";
+ }
+ }
+ if ($this->echoCLI && $currentExport > 0) {
+ echo 'Exported '.$currentExport.' of '.$totalFound.' nzbs for group: '.$group['name'].PHP_EOL;
+ }
+ $exported += $currentExport;
+ }
+ if ($exported > 0) {
+ $this->echoOut('Exported total of '.$exported.' NZB files to '.$path);
+ }
- return $this->returnValue();
- }
+ return $this->returnValue();
+ }
- /**
- * Return bool on CLI, string on browser.
- * @return bool|string
- *
- * @access protected
- */
- protected function returnValue()
- {
- return ($this->browser ? $this->retVal : true);
- }
+ /**
+ * Return bool on CLI, string on browser.
+ * @return bool|string
+ */
+ protected function returnValue()
+ {
+ return $this->browser ? $this->retVal : true;
+ }
- /**
- * Check if date is in good format.
- *
- * @param string $date
- *
- * @return bool
- *
- * @access protected
- */
- protected function checkDate($date)
- {
- if (!preg_match('/^(\d{2}\/){2}\d{4}$/', $date)) {
- $this->echoOut('Wrong date format: ' . $date);
- return false;
- }
- return true;
- }
+ /**
+ * Check if date is in good format.
+ *
+ * @param string $date
+ *
+ * @return bool
+ */
+ protected function checkDate($date)
+ {
+ if (! preg_match('/^(\d{2}\/){2}\d{4}$/', $date)) {
+ $this->echoOut('Wrong date format: '.$date);
- /**
- * Echo message to browser or CLI.
- *
- * @param string $message
- *
- * @access protected
- */
- protected function echoOut($message)
- {
- if ($this->browser) {
- $this->retVal .= $message . '
';
- } elseif ($this->echoCLI) {
- echo $message . PHP_EOL;
- }
- }
+ return false;
+ }
- /**
- * Remove unsafe chars from a filename.
- *
- * @param string $filename
- *
- * @return string
- *
- * @access protected
- */
- protected function safeFilename($filename)
- {
- return trim(preg_replace('/[^\w\s.-]*/i', '', $filename));
- }
+ return true;
+ }
+
+ /**
+ * Echo message to browser or CLI.
+ *
+ * @param string $message
+ */
+ protected function echoOut($message)
+ {
+ if ($this->browser) {
+ $this->retVal .= $message.'
';
+ } elseif ($this->echoCLI) {
+ echo $message.PHP_EOL;
+ }
+ }
+
+ /**
+ * Remove unsafe chars from a filename.
+ *
+ * @param string $filename
+ *
+ * @return string
+ */
+ protected function safeFilename($filename)
+ {
+ return trim(preg_replace('/[^\w\s.-]*/i', '', $filename));
+ }
}
diff --git a/nntmux/NZBGet.php b/nntmux/NZBGet.php
index 917a78013..e154eec8d 100755
--- a/nntmux/NZBGet.php
+++ b/nntmux/NZBGet.php
@@ -1,139 +1,125 @@
serverurl = $page->serverurl;
- $this->uid = $page->userdata['id'];
- $this->rsstoken = $page->userdata['rsstoken'];
+ /**
+ * Construct.
+ * Set up full URL.
+ *
+ * @var \BasePage
+ */
+ public function __construct(&$page)
+ {
+ $this->serverurl = $page->serverurl;
+ $this->uid = $page->userdata['id'];
+ $this->rsstoken = $page->userdata['rsstoken'];
- if (!empty($page->userdata['nzbgeturl'])) {
- $this->url = $page->userdata['nzbgeturl'];
- $this->userName = (empty($page->userdata['nzbgetusername']) ? '' : $page->userdata['nzbgetusername']);
- $this->password = (empty($page->userdata['nzbgetpassword']) ? '' : $page->userdata['nzbgetpassword']);
- }
+ if (! empty($page->userdata['nzbgeturl'])) {
+ $this->url = $page->userdata['nzbgeturl'];
+ $this->userName = (empty($page->userdata['nzbgetusername']) ? '' : $page->userdata['nzbgetusername']);
+ $this->password = (empty($page->userdata['nzbgetpassword']) ? '' : $page->userdata['nzbgetpassword']);
+ }
- $this->fullURL = $this->verifyURL($this->url);
- $this->Releases = new Releases();
- $this->pdo = new DB();
- $this->NZB = new NZB($this->pdo);
- $this->client = new Client();
- }
+ $this->fullURL = $this->verifyURL($this->url);
+ $this->Releases = new Releases();
+ $this->pdo = new DB();
+ $this->NZB = new NZB($this->pdo);
+ $this->client = new Client();
+ }
- /**
- * Send a NZB to NZBGet.
- *
- * @param string $guid Release identifier.
- *
- * @return bool|mixed
- *
- * @access public
- */
- public function sendNZBToNZBGet($guid)
- {
- $relData = $this->Releases->getByGuid($guid);
+ /**
+ * Send a NZB to NZBGet.
+ *
+ * @param string $guid Release identifier.
+ *
+ * @return bool|mixed
+ */
+ public function sendNZBToNZBGet($guid)
+ {
+ $relData = $this->Releases->getByGuid($guid);
- $string = Utility::unzipGzipFile($this->NZB->NZBPath($guid));
- $string = ($string === false ? '' : $string);
+ $string = Utility::unzipGzipFile($this->NZB->NZBPath($guid));
+ $string = ($string === false ? '' : $string);
- $header =
+ $header =
'
append
- ' . $relData['searchname'] . '
+ '.$relData['searchname'].'
- ' . $relData['category_name'] . '
+ '.$relData['category_name'].'
0
@@ -143,39 +129,37 @@ class NZBGet
- ' .
- base64_encode($string) .
+ '.
+ base64_encode($string).
'
';
- new Request('POST', $this->fullURL . 'append', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
- }
+ new Request('POST', $this->fullURL.'append', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
+ }
- /**
- * Send a NZB URL to NZBGet.
- *
- * @param string $guid Release identifier.
- *
- * @return bool|mixed
- *
- * @access public
- */
- public function sendURLToNZBGet($guid)
- {
- $reldata = $this->Releases->getByGuid($guid);
+ /**
+ * Send a NZB URL to NZBGet.
+ *
+ * @param string $guid Release identifier.
+ *
+ * @return bool|mixed
+ */
+ public function sendURLToNZBGet($guid)
+ {
+ $reldata = $this->Releases->getByGuid($guid);
- $header =
+ $header =
'
appendurl
- ' . $reldata['searchname'] . '.nzb' . '
+ '.$reldata['searchname'].'.nzb'.'
- ' . $reldata['category_name'] . '
+ '.$reldata['category_name'].'
0
@@ -185,13 +169,13 @@ class NZBGet
- ' .
- $this->serverurl .
- 'getnzb/' .
- $guid .
- '%26i%3D' .
- $this->uid .
- '%26r%3D' .
+ '.
+ $this->serverurl.
+ 'getnzb/'.
+ $guid.
+ '%26i%3D'.
+ $this->uid.
+ '%26r%3D'.
$this->rsstoken
.
'
@@ -199,19 +183,17 @@ class NZBGet
';
- new Request('POST', $this->fullURL . 'append', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
- }
+ new Request('POST', $this->fullURL.'append', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
+ }
- /**
- * Pause download queue on server. This method is equivalent for command "nzbget -P".
- *
- * @return void
- *
- * @access public
- */
- public function pauseAll()
- {
- $header =
+ /**
+ * Pause download queue on server. This method is equivalent for command "nzbget -P".
+ *
+ * @return void
+ */
+ public function pauseAll()
+ {
+ $header =
'
pausedownload2
@@ -221,19 +203,17 @@ class NZBGet
';
- new Request('POST', $this->fullURL . 'pausedownload2', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
- }
+ new Request('POST', $this->fullURL.'pausedownload2', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
+ }
- /**
- * Resume (previously paused) download queue on server. This method is equivalent for command "nzbget -U".
- *
- * @return void
- *
- * @access public
- */
- public function resumeAll()
- {
- $header =
+ /**
+ * Resume (previously paused) download queue on server. This method is equivalent for command "nzbget -U".
+ *
+ * @return void
+ */
+ public function resumeAll()
+ {
+ $header =
'
resumedownload2
@@ -243,19 +223,17 @@ class NZBGet
';
- new Request('POST', $this->fullURL . 'resumedownload2', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
- }
+ new Request('POST', $this->fullURL.'resumedownload2', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
+ }
- /**
- * Pause a single NZB from the queue.
- *
- * @param string $id
- *
- * @access public
- */
- public function pauseFromQueue($id)
- {
- $header =
+ /**
+ * Pause a single NZB from the queue.
+ *
+ * @param string $id
+ */
+ public function pauseFromQueue($id)
+ {
+ $header =
'
editqueue
@@ -272,25 +250,23 @@ class NZBGet
- ' . $id . '
+ '.$id.'
';
- new Request('POST', $this->fullURL . 'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
- }
+ new Request('POST', $this->fullURL.'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
+ }
- /**
- * Resume a single NZB from the queue.
- *
- * @param string $id
- *
- * @access public
- */
- public function resumeFromQueue($id)
- {
- $header =
+ /**
+ * Resume a single NZB from the queue.
+ *
+ * @param string $id
+ */
+ public function resumeFromQueue($id)
+ {
+ $header =
'
editqueue
@@ -307,25 +283,23 @@ class NZBGet
- ' . $id . '
+ '.$id.'
';
- new Request('POST', $this->fullURL . 'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
- }
+ new Request('POST', $this->fullURL.'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
+ }
- /**
- * Delete a single NZB from the queue.
- *
- * @param string $id
- *
- * @access public
- */
- public function delFromQueue($id)
- {
- $header =
+ /**
+ * Delete a single NZB from the queue.
+ *
+ * @param string $id
+ */
+ public function delFromQueue($id)
+ {
+ $header =
'
editqueue
@@ -342,121 +316,114 @@ class NZBGet
- ' . $id . '
+ '.$id.'
';
- new Request('POST', $this->fullURL . 'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
- }
+ new Request('POST', $this->fullURL.'editqueue', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
+ }
- /**
- * Set download speed limit. This method is equivalent for command "nzbget -R ".
- *
- * @param int $limit The speed to limit it to.
- *
- * @return bool
- *
- * @access public
- */
- public function rate($limit)
- {
- $header =
+ /**
+ * Set download speed limit. This method is equivalent for command "nzbget -R ".
+ *
+ * @param int $limit The speed to limit it to.
+ *
+ * @return bool
+ */
+ public function rate($limit)
+ {
+ $header =
'
rate
- ' . $limit . '
+ '.$limit.'
';
- new Request('POST', $this->fullURL . 'rate', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
- }
+ new Request('POST', $this->fullURL.'rate', ['Content-Type' => 'text/xml; charset=UTF8'], $header);
+ }
- /**
- * Get all items in download queue.
- *
- * @return array|bool
- *
- * @access public
- */
- public function getQueue()
- {
- $data = $this->client->get($this->fullURL . 'listgroups')->getBody()->getContents();
- $retVal = false;
- if ($data) {
- $xml = simplexml_load_string($data);
- if ($xml) {
- $retVal = [];
- $i = 0;
- foreach($xml->params->param->value->array->data->value as $value) {
- foreach ($value->struct->member as $member) {
- $value = (array)$member->value;
- $value = array_shift($value);
- if (!is_object($value)) {
- $retVal[$i][(string)$member->name] = $value;
- }
- }
- $i++;
- }
- }
- }
- return $retVal;
- }
+ /**
+ * Get all items in download queue.
+ *
+ * @return array|bool
+ */
+ public function getQueue()
+ {
+ $data = $this->client->get($this->fullURL.'listgroups')->getBody()->getContents();
+ $retVal = false;
+ if ($data) {
+ $xml = simplexml_load_string($data);
+ if ($xml) {
+ $retVal = [];
+ $i = 0;
+ foreach ($xml->params->param->value->array->data->value as $value) {
+ foreach ($value->struct->member as $member) {
+ $value = (array) $member->value;
+ $value = array_shift($value);
+ if (! is_object($value)) {
+ $retVal[$i][(string) $member->name] = $value;
+ }
+ }
+ $i++;
+ }
+ }
+ }
- /**
- * Request for current status (summary) information. Parts of informations returned by this method can be printed by command "nzbget -L".
- *
- * @return array|bool The status.
- *
- * @access public
- */
- public function status()
- {
- $data = $this->client->get($this->fullURL . 'status')->getBody()->getContents();
- $retVal = false;
- if ($data) {
- $xml = simplexml_load_string($data);
- if ($xml) {
- foreach($xml->params->param->value->struct->member as $member) {
- $value = (array)$member->value;
- $value = array_shift($value);
- if (!is_object($value)) {
- $retVal[(string)$member->name] = $value;
- }
+ return $retVal;
+ }
- }
- }
- }
- return $retVal;
- }
+ /**
+ * Request for current status (summary) information. Parts of informations returned by this method can be printed by command "nzbget -L".
+ *
+ * @return array|bool The status.
+ */
+ public function status()
+ {
+ $data = $this->client->get($this->fullURL.'status')->getBody()->getContents();
+ $retVal = false;
+ if ($data) {
+ $xml = simplexml_load_string($data);
+ if ($xml) {
+ foreach ($xml->params->param->value->struct->member as $member) {
+ $value = (array) $member->value;
+ $value = array_shift($value);
+ if (! is_object($value)) {
+ $retVal[(string) $member->name] = $value;
+ }
+ }
+ }
+ }
- /**
- * Verify if the NZBGet URL is correct.
- *
- * @param string $url NZBGet URL to verify.
- *
- * @return bool|string
- *
- * @access public
- */
- public function verifyURL ($url)
- {
- if (preg_match('/(?Phttps?):\/\/(?P.+?)(:(?P\d+\/)|\/)$/i', $url, $matches)) {
- return
- $matches['protocol'] .
- '://' .
- $this->userName .
- ':' .
- $this->password .
- '@' .
- $matches['url'] .
- (isset($matches['port']) ? ':' . $matches['port'] : (substr($matches['url'], -1) === '/' ? '' : '/')) .
+ return $retVal;
+ }
+
+ /**
+ * Verify if the NZBGet URL is correct.
+ *
+ * @param string $url NZBGet URL to verify.
+ *
+ * @return bool|string
+ */
+ public function verifyURL($url)
+ {
+ if (preg_match('/(?Phttps?):\/\/(?P.+?)(:(?P\d+\/)|\/)$/i', $url, $matches)) {
+ return
+ $matches['protocol'].
+ '://'.
+ $this->userName.
+ ':'.
+ $this->password.
+ '@'.
+ $matches['url'].
+ (isset($matches['port']) ? ':'.$matches['port'] : (substr($matches['url'], -1) === '/' ? '' : '/')).
'xmlrpc/';
- } else {
- return false;
- }
- }
+ } else {
+ return false;
+ }
+ }
}
diff --git a/nntmux/NZBImport.php b/nntmux/NZBImport.php
index 6c3d00c2e..aafd451c0 100755
--- a/nntmux/NZBImport.php
+++ b/nntmux/NZBImport.php
@@ -1,112 +1,101 @@
false, // Was this started from the browser?
'Echo' => true, // Echo to CLI?
'Binaries' => null,
@@ -116,271 +105,259 @@ class NZBImport
'Releases' => null,
'Settings' => null,
];
- $options += $defaults;
+ $options += $defaults;
- $this->echoCLI = (!$this->browser && NN_ECHOCLI && $options['Echo']);
- $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB());
- $this->binaries = ($options['Binaries'] instanceof Binaries ? $options['Binaries'] : new Binaries(['Settings' => $this->pdo, 'Echo' => $this->echoCLI]));
- $this->category = ($options['Categorize'] instanceof Categorize ? $options['Categorize'] : new Categorize(['Settings' => $this->pdo]));
- $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo));
- $this->releaseCleaner = ($options['ReleaseCleaning'] instanceof ReleaseCleaning ? $options['ReleaseCleaning'] : new ReleaseCleaning($this->pdo));
- $this->releases = ($options['Releases'] instanceof Releases ? $options['Releases'] : new Releases(['settings' => $this->pdo]));
- $this->groups = new Groups(['Settings' => $this->pdo]);
+ $this->echoCLI = (! $this->browser && NN_ECHOCLI && $options['Echo']);
+ $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB());
+ $this->binaries = ($options['Binaries'] instanceof Binaries ? $options['Binaries'] : new Binaries(['Settings' => $this->pdo, 'Echo' => $this->echoCLI]));
+ $this->category = ($options['Categorize'] instanceof Categorize ? $options['Categorize'] : new Categorize(['Settings' => $this->pdo]));
+ $this->nzb = ($options['NZB'] instanceof NZB ? $options['NZB'] : new NZB($this->pdo));
+ $this->releaseCleaner = ($options['ReleaseCleaning'] instanceof ReleaseCleaning ? $options['ReleaseCleaning'] : new ReleaseCleaning($this->pdo));
+ $this->releases = ($options['Releases'] instanceof Releases ? $options['Releases'] : new Releases(['settings' => $this->pdo]));
+ $this->groups = new Groups(['Settings' => $this->pdo]);
- $this->crossPostt = Settings::value('..crossposttime') !== '' ? Settings::value('..crossposttime') : 2;
- $this->browser = $options['Browser'];
- $this->retVal = '';
- }
+ $this->crossPostt = Settings::value('..crossposttime') !== '' ? Settings::value('..crossposttime') : 2;
+ $this->browser = $options['Browser'];
+ $this->retVal = '';
+ }
- /**
- * @param array $filesToProcess List of NZB files to import.
- * @param bool|string $useNzbName Use the NZB file name as release name?
- * @param bool $delete Delete the NZB when done?
- * @param bool $deleteFailed Delete the NZB if failed importing?
- *
- * @return string|bool
- *
- * @access public
- */
- public function beginImport($filesToProcess, $useNzbName = false, $delete = true, $deleteFailed = true)
- {
- // Get all the groups in the DB.
- if (!$this->getAllGroups()) {
- if ($this->browser) {
- return $this->retVal;
- } else {
- return false;
- }
- }
+ /**
+ * @param array $filesToProcess List of NZB files to import.
+ * @param bool|string $useNzbName Use the NZB file name as release name?
+ * @param bool $delete Delete the NZB when done?
+ * @param bool $deleteFailed Delete the NZB if failed importing?
+ *
+ * @return string|bool
+ */
+ public function beginImport($filesToProcess, $useNzbName = false, $delete = true, $deleteFailed = true)
+ {
+ // Get all the groups in the DB.
+ if (! $this->getAllGroups()) {
+ if ($this->browser) {
+ return $this->retVal;
+ } else {
+ return false;
+ }
+ }
- $start = date('Y-m-d H:i:s');
- $nzbsImported = $nzbsSkipped = 0;
+ $start = date('Y-m-d H:i:s');
+ $nzbsImported = $nzbsSkipped = 0;
- // Loop over the file names.
- foreach ($filesToProcess as $nzbFile) {
+ // Loop over the file names.
+ foreach ($filesToProcess as $nzbFile) {
+ $this->nzbGuid = '';
- $this->nzbGuid = '';
-
- // Check if the file is really there.
- if (is_file($nzbFile)) {
+ // Check if the file is really there.
+ if (is_file($nzbFile)) {
// Get the contents of the NZB file as a string.
- if (strtolower(substr($nzbFile, -7)) === '.nzb.gz') {
- $nzbString = Utility::unzipGzipFile($nzbFile);
- } else {
- $nzbString = file_get_contents($nzbFile);
- }
+ if (strtolower(substr($nzbFile, -7)) === '.nzb.gz') {
+ $nzbString = Utility::unzipGzipFile($nzbFile);
+ } else {
+ $nzbString = file_get_contents($nzbFile);
+ }
- if ($nzbString === false) {
- $this->echoOut('ERROR: Unable to read: ' . $nzbFile);
+ if ($nzbString === false) {
+ $this->echoOut('ERROR: Unable to read: '.$nzbFile);
- if ($deleteFailed) {
- @unlink($nzbFile);
- }
- $nzbsSkipped++;
- continue;
- }
+ if ($deleteFailed) {
+ @unlink($nzbFile);
+ }
+ $nzbsSkipped++;
+ continue;
+ }
- // Load it as a XML object.
- $nzbXML = @simplexml_load_string($nzbString);
- if ($nzbXML === false || strtolower($nzbXML->getName()) != 'nzb') {
- $this->echoOut('ERROR: Unable to load NZB XML data: ' . $nzbFile);
+ // Load it as a XML object.
+ $nzbXML = @simplexml_load_string($nzbString);
+ if ($nzbXML === false || strtolower($nzbXML->getName()) != 'nzb') {
+ $this->echoOut('ERROR: Unable to load NZB XML data: '.$nzbFile);
- if ($deleteFailed) {
- @unlink($nzbFile);
- }
- $nzbsSkipped++;
- continue;
- }
+ if ($deleteFailed) {
+ @unlink($nzbFile);
+ }
+ $nzbsSkipped++;
+ continue;
+ }
- // Try to insert the NZB details into the DB.
- $inserted = $this->scanNZBFile($nzbXML, ($useNzbName ? str_ireplace('.nzb', '', basename($nzbFile)) : false));
+ // Try to insert the NZB details into the DB.
+ $inserted = $this->scanNZBFile($nzbXML, ($useNzbName ? str_ireplace('.nzb', '', basename($nzbFile)) : false));
- if ($inserted) {
+ if ($inserted) {
// Try to copy the NZB to the NZB folder.
- $path = $this->nzb->getNZBPath($this->relGuid, 0, true);
+ $path = $this->nzb->getNZBPath($this->relGuid, 0, true);
- // Try to compress the NZB file in the NZB folder.
- $fp = gzopen($path, 'w5');
- gzwrite($fp, $nzbString);
- gzclose($fp);
+ // Try to compress the NZB file in the NZB folder.
+ $fp = gzopen($path, 'w5');
+ gzwrite($fp, $nzbString);
+ gzclose($fp);
- if (!is_file($path)) {
- $this->echoOut('ERROR: Problem compressing NZB file to: ' . $path);
+ if (! is_file($path)) {
+ $this->echoOut('ERROR: Problem compressing NZB file to: '.$path);
- // Remove the release.
- $this->pdo->queryExec("
+ // Remove the release.
+ $this->pdo->queryExec("
DELETE
FROM releases
WHERE guid = {$this->pdo->escapeString($this->relGuid)}"
);
- if ($deleteFailed) {
- @unlink($nzbFile);
- }
- $nzbsSkipped++;
- continue;
+ if ($deleteFailed) {
+ @unlink($nzbFile);
+ }
+ $nzbsSkipped++;
+ continue;
+ } else {
+ $this->updateNzbGuid();
- } else {
+ if ($delete) {
+ // Remove the nzb file.
+ @unlink($nzbFile);
+ }
- $this->updateNzbGuid();
-
- if ($delete) {
- // Remove the nzb file.
- @unlink($nzbFile);
- }
-
- $nzbsImported++;
- continue;
- }
-
- } else {
-
- $this->echoOut('ERROR: Failed to insert NZB!');
- if ($deleteFailed) {
- @unlink($nzbFile);
- }
- $nzbsSkipped++;
- continue;
- }
-
- } else {
- $this->echoOut('ERROR: Unable to fetch: ' . $nzbFile);
- $nzbsSkipped++;
- continue;
- }
- }
- $this->echoOut(
- 'Proccessed ' .
- $nzbsImported .
- ' NZBs in ' .
- (strtotime(date('Y-m-d H:i:s')) - strtotime($start)) .
- ' seconds, ' .
- $nzbsSkipped .
+ $nzbsImported++;
+ continue;
+ }
+ } else {
+ $this->echoOut('ERROR: Failed to insert NZB!');
+ if ($deleteFailed) {
+ @unlink($nzbFile);
+ }
+ $nzbsSkipped++;
+ continue;
+ }
+ } else {
+ $this->echoOut('ERROR: Unable to fetch: '.$nzbFile);
+ $nzbsSkipped++;
+ continue;
+ }
+ }
+ $this->echoOut(
+ 'Proccessed '.
+ $nzbsImported.
+ ' NZBs in '.
+ (strtotime(date('Y-m-d H:i:s')) - strtotime($start)).
+ ' seconds, '.
+ $nzbsSkipped.
' NZBs were skipped.'
);
- if ($this->browser) {
- return $this->retVal;
- } else {
- return true;
- }
- }
+ if ($this->browser) {
+ return $this->retVal;
+ } else {
+ return true;
+ }
+ }
- /**
- * @param object $nzbXML Reference of simpleXmlObject with NZB contents.
- * @param bool|string $useNzbName Use the NZB file name as release name?
- * @return bool
- *
- * @access protected
- */
- protected function scanNZBFile(&$nzbXML, $useNzbName = false)
- {
- $binary_names = [];
- $totalFiles = $totalSize = $groupID = 0;
- $isBlackListed = $groupName = $firstName = $posterName = $postDate = false;
+ /**
+ * @param object $nzbXML Reference of simpleXmlObject with NZB contents.
+ * @param bool|string $useNzbName Use the NZB file name as release name?
+ * @return bool
+ */
+ protected function scanNZBFile(&$nzbXML, $useNzbName = false)
+ {
+ $binary_names = [];
+ $totalFiles = $totalSize = $groupID = 0;
+ $isBlackListed = $groupName = $firstName = $posterName = $postDate = false;
- // Go through the NZB, get the details, look if it's blacklisted, look if we have the groups.
- foreach ($nzbXML->file as $file) {
+ // Go through the NZB, get the details, look if it's blacklisted, look if we have the groups.
+ foreach ($nzbXML->file as $file) {
+ $binary_names[] = $file['subject'];
+ $totalFiles++;
+ $groupID = -1;
- $binary_names[] = $file['subject'];
- $totalFiles++;
- $groupID = -1;
+ // Get the nzb info.
+ if ($firstName === false) {
+ $firstName = (string) $file->attributes()->subject;
+ }
+ if ($posterName === false) {
+ $posterName = (string) $file->attributes()->poster;
+ }
+ if ($postDate === false) {
+ $postDate = date('Y-m-d H:i:s', (string) $file->attributes()->date);
+ }
- // Get the nzb info.
- if ($firstName === false) {
- $firstName = (string)$file->attributes()->subject;
- }
- if ($posterName === false) {
- $posterName = (string)$file->attributes()->poster;
- }
- if ($postDate === false) {
- $postDate = date("Y-m-d H:i:s", (string)$file->attributes()->date);
- }
+ // Make a fake message array to use to check the blacklist.
+ $msg = ['Subject' => (string) $file->attributes()->subject, 'From' => (string) $file->attributes()->poster, 'Message-ID' => ''];
- // Make a fake message array to use to check the blacklist.
- $msg = ['Subject' => (string)$file->attributes()->subject, 'From' => (string)$file->attributes()->poster, 'Message-ID' => ''];
+ // Get the group names, group_id, check if it's blacklisted.
+ $groupArr = [];
+ foreach ($file->groups->group as $group) {
+ $group = (string) $group;
- // Get the group names, group_id, check if it's blacklisted.
- $groupArr = [];
- foreach ($file->groups->group as $group) {
- $group = (string)$group;
-
- // If group_id is -1 try to get a group_id.
- if ($groupID === -1) {
- if (array_key_exists($group, $this->allGroups)) {
- $groupID = $this->allGroups[$group];
- if (!$groupName) {
- $groupName = $group;
- }
- } else {
- $group = $this->groups->isValidGroup($group);
- if ($group !== false) {
- $groupID = $this->groups->add([
+ // If group_id is -1 try to get a group_id.
+ if ($groupID === -1) {
+ if (array_key_exists($group, $this->allGroups)) {
+ $groupID = $this->allGroups[$group];
+ if (! $groupName) {
+ $groupName = $group;
+ }
+ } else {
+ $group = $this->groups->isValidGroup($group);
+ if ($group !== false) {
+ $groupID = $this->groups->add([
'name' => $group,
'description' => 'Added by NZBimport script.',
'backfill_target' => 1,
'first_record' => 0,
'last_record' => 0,
'active' => 0,
- 'backfill' => 0
+ 'backfill' => 0,
]);
- $this->allGroups[$group] = $groupID;
+ $this->allGroups[$group] = $groupID;
- $this->echoOut("Adding missing group: ($group)");
- }
- }
- }
- // Add all the found groups to an array.
- $groupArr[] = $group;
+ $this->echoOut("Adding missing group: ($group)");
+ }
+ }
+ }
+ // Add all the found groups to an array.
+ $groupArr[] = $group;
- // Check if this NZB is blacklisted.
- if ($this->binaries->isBlackListed($msg, $group)) {
- $isBlackListed = true;
- break;
- }
- }
+ // Check if this NZB is blacklisted.
+ if ($this->binaries->isBlackListed($msg, $group)) {
+ $isBlackListed = true;
+ break;
+ }
+ }
- // If we found a group and it's not blacklisted.
- if ($groupID !== -1 && !$isBlackListed) {
+ // If we found a group and it's not blacklisted.
+ if ($groupID !== -1 && ! $isBlackListed) {
// Get the size of the release.
- if (count($file->segments->segment) > 0) {
- foreach ($file->segments->segment as $segment) {
- $totalSize += (int)$segment->attributes()->bytes;
- }
- }
+ if (count($file->segments->segment) > 0) {
+ foreach ($file->segments->segment as $segment) {
+ $totalSize += (int) $segment->attributes()->bytes;
+ }
+ }
+ } else {
+ if ($isBlackListed) {
+ $errorMessage = 'Subject is blacklisted: '.utf8_encode(trim($firstName));
+ } else {
+ $errorMessage = 'No group found for '.$firstName.' (one of '.implode(', ', $groupArr).' are missing';
+ }
+ $this->echoOut($errorMessage);
- } else {
- if ($isBlackListed) {
- $errorMessage = 'Subject is blacklisted: ' . utf8_encode(trim($firstName));
- } else {
- $errorMessage = 'No group found for ' . $firstName . ' (one of ' . implode(', ', $groupArr) . ' are missing';
- }
- $this->echoOut($errorMessage);
+ return false;
+ }
+ }
- return false;
- }
- }
+ // Sort values alphabetically but keep the keys intact
+ if (count($binary_names) > 0) {
+ asort($binary_names);
+ foreach ($nzbXML->file as $file) {
+ if ($file['subject'] == $binary_names[0]) {
+ $this->nzbGuid = md5($file->segments->segment);
+ break;
+ }
+ }
+ }
- // Sort values alphabetically but keep the keys intact
- if (count($binary_names) > 0) {
- asort($binary_names);
- foreach ($nzbXML->file as $file) {
- if ($file["subject"] == $binary_names[0]) {
- $this->nzbGuid = md5($file->segments->segment);
- break;
- }
- }
- }
-
- // Try to insert the NZB details into the DB.
- return $this->insertNZB(
+ // Try to insert the NZB details into the DB.
+ return $this->insertNZB(
[
'subject' => $firstName,
'useFName' => $useNzbName,
- 'postDate' => empty($postDate) ? date("Y-m-d H:i:s") : $postDate,
+ 'postDate' => empty($postDate) ? date('Y-m-d H:i:s') : $postDate,
'from' => empty($posterName) ? '' : $posterName,
'groups_id' => $groupID,
'groupName' => $groupName,
@@ -388,46 +365,44 @@ class NZBImport
'totalSize' => $totalSize,
]
);
- }
+ }
- /**
- * Insert the NZB details into the database.
- *
- * @param $nzbDetails
- *
- * @return bool
- *
- * @access protected
- */
- protected function insertNZB($nzbDetails)
- {
- // Make up a GUID for the release.
- $this->relGuid = $this->releases->createGUID();
+ /**
+ * Insert the NZB details into the database.
+ *
+ * @param $nzbDetails
+ *
+ * @return bool
+ */
+ protected function insertNZB($nzbDetails)
+ {
+ // Make up a GUID for the release.
+ $this->relGuid = $this->releases->createGUID();
- // Remove part count from subject.
- $partLess = preg_replace('/(\(\d+\/\d+\))*$/', 'yEnc', $nzbDetails['subject']);
- // Remove added yEnc from above and anything after.
- $subject = utf8_encode(trim(preg_replace('/yEnc.*$/i', 'yEnc', $partLess)));
+ // Remove part count from subject.
+ $partLess = preg_replace('/(\(\d+\/\d+\))*$/', 'yEnc', $nzbDetails['subject']);
+ // Remove added yEnc from above and anything after.
+ $subject = utf8_encode(trim(preg_replace('/yEnc.*$/i', 'yEnc', $partLess)));
- $renamed = 0;
- if ($nzbDetails['useFName']) {
- // If the user wants to use the file name.. use it.
- $cleanName = $nzbDetails['useFName'];
- $renamed = 1;
- } else {
- // Pass the subject through release cleaner to get a nicer name.
- $cleanName = $this->releaseCleaner->releaseCleaner($subject, $nzbDetails['from'], $nzbDetails['totalSize'], $nzbDetails['groupName']);
- if (isset($cleanName['properlynamed'])) {
- $cleanName = $cleanName['cleansubject'];
- $renamed = (isset($cleanName['properlynamed']) && $cleanName['properlynamed'] === true ? 1 : 0);
- }
- }
+ $renamed = 0;
+ if ($nzbDetails['useFName']) {
+ // If the user wants to use the file name.. use it.
+ $cleanName = $nzbDetails['useFName'];
+ $renamed = 1;
+ } else {
+ // Pass the subject through release cleaner to get a nicer name.
+ $cleanName = $this->releaseCleaner->releaseCleaner($subject, $nzbDetails['from'], $nzbDetails['totalSize'], $nzbDetails['groupName']);
+ if (isset($cleanName['properlynamed'])) {
+ $cleanName = $cleanName['cleansubject'];
+ $renamed = (isset($cleanName['properlynamed']) && $cleanName['properlynamed'] === true ? 1 : 0);
+ }
+ }
- $escapedSubject = $this->pdo->escapeString($subject);
- $escapedFromName = $this->pdo->escapeString($nzbDetails['from']);
+ $escapedSubject = $this->pdo->escapeString($subject);
+ $escapedFromName = $this->pdo->escapeString($nzbDetails['from']);
- // Look for a duplicate on name, poster and size.
- $dupeCheck = $this->pdo->queryOneRow(
+ // Look for a duplicate on name, poster and size.
+ $dupeCheck = $this->pdo->queryOneRow(
sprintf('
SELECT id
FROM releases
@@ -441,10 +416,10 @@ class NZBImport
)
);
- if ($dupeCheck === false) {
- $escapedSearchName = $this->pdo->escapeString($cleanName);
- // Insert the release into the DB.
- $relID = $this->releases->insertRelease(
+ if ($dupeCheck === false) {
+ $escapedSearchName = $this->pdo->escapeString($cleanName);
+ // Insert the release into the DB.
+ $relID = $this->releases->insertRelease(
[
'name' => $escapedSubject,
'searchname' => $escapedSearchName,
@@ -458,75 +433,74 @@ class NZBImport
'isrenamed' => $renamed,
'reqidstatus' => 0,
'predb_id' => 0,
- 'nzbstatus' => NZB::NZB_ADDED
+ 'nzbstatus' => NZB::NZB_ADDED,
]
);
- } else {
- //$this->echoOut('This release is already in our DB so skipping: ' . $subject);
- return false;
- }
+ } else {
+ //$this->echoOut('This release is already in our DB so skipping: ' . $subject);
+ return false;
+ }
- if (isset($relID) && $relID === false) {
- $this->echoOut('ERROR: Problem inserting: ' . $subject);
- return false;
- }
- return true;
- }
+ if (isset($relID) && $relID === false) {
+ $this->echoOut('ERROR: Problem inserting: '.$subject);
- /**
- * Get all groups in the DB.
- *
- * @return bool
- * @access protected
- */
- protected function getAllGroups()
- {
- $this->allGroups = [];
- $groups = $this->pdo->queryDirect('
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Get all groups in the DB.
+ *
+ * @return bool
+ */
+ protected function getAllGroups()
+ {
+ $this->allGroups = [];
+ $groups = $this->pdo->queryDirect('
SELECT id, name
FROM groups'
);
- if ($groups instanceof \Traversable) {
- foreach ($groups as $group) {
- $this->allGroups[$group['name']] = $group['id'];
- }
- }
+ if ($groups instanceof \Traversable) {
+ foreach ($groups as $group) {
+ $this->allGroups[$group['name']] = $group['id'];
+ }
+ }
- if (count($this->allGroups) === 0) {
- $this->echoOut('You have no groups in your database!');
- return false;
- }
- return true;
- }
+ if (count($this->allGroups) === 0) {
+ $this->echoOut('You have no groups in your database!');
- /**
- * Echo message to browser or CLI.
- *
- * @param string $message
- *
- * @access protected
- */
- protected function echoOut($message)
- {
- if ($this->browser) {
- $this->retVal .= $message . '
';
- } elseif ($this->echoCLI) {
- echo $message . PHP_EOL;
- }
- }
+ return false;
+ }
- /**
- * The function updates the NZB guid after there is no chance of deletion
- *
- * @access protected
- */
- protected function updateNzbGuid()
- {
- $this->pdo->queryExec("
+ return true;
+ }
+
+ /**
+ * Echo message to browser or CLI.
+ *
+ * @param string $message
+ */
+ protected function echoOut($message)
+ {
+ if ($this->browser) {
+ $this->retVal .= $message.'
';
+ } elseif ($this->echoCLI) {
+ echo $message.PHP_EOL;
+ }
+ }
+
+ /**
+ * The function updates the NZB guid after there is no chance of deletion.
+ */
+ protected function updateNzbGuid()
+ {
+ $this->pdo->queryExec("
UPDATE releases
SET nzb_guid = UNHEX({$this->pdo->escapeString($this->nzbGuid)})
WHERE guid = {$this->pdo->escapeString($this->relGuid)}"
);
- }
+ }
}
diff --git a/nntmux/NZBInfo.php b/nntmux/NZBInfo.php
index fb07a983c..fa3e7a47d 100755
--- a/nntmux/NZBInfo.php
+++ b/nntmux/NZBInfo.php
@@ -1,49 +1,51 @@
nfofileregex = '/[ "\(\[].*?\.(nfo|ofn)[ "\)\]]/iS';
$this->mediafileregex = '/.*\.(AVI|VOB|MKV|MP4|TS|WMV|MOV|M4V|F4V|MPG|MPEG)(\.001)?[ "\)\]]/iS';
$this->audiofileregex = '/\.(MP3|FLAC|AAC|OGG|AIFF)[ "\)\]]/iS';
@@ -54,305 +56,307 @@ class NZBInfo
$this->sfvfileregex = '/\.(sfv)[ "\)\]]/iS';
}
- public function loadFromString($str, $loadAllVars=false)
- {
- if (empty($this->source))
- $this->source = 'string';
- $this->loadAllVars = $loadAllVars;
+ public function loadFromString($str, $loadAllVars = false)
+ {
+ if (empty($this->source)) {
+ $this->source = 'string';
+ }
+ $this->loadAllVars = $loadAllVars;
- $xmlObj = @simplexml_load_string($str);
- if ($this->isValidNzb($xmlObj))
- $this->parseNzb($xmlObj);
+ $xmlObj = @simplexml_load_string($str);
+ if ($this->isValidNzb($xmlObj)) {
+ $this->parseNzb($xmlObj);
+ }
- unset($xmlObj);
+ unset($xmlObj);
- return $this->isLoaded;
- }
+ return $this->isLoaded;
+ }
- public function loadFromFile($loc, $loadAllVars=false)
+ public function loadFromFile($loc, $loadAllVars = false)
{
$this->source = $loc;
$this->loadAllVars = $loadAllVars;
- if (file_exists($loc))
- {
- if (preg_match('/\.(gz|zip)$/i', $loc, $ext))
- {
- switch(strtolower($ext[1]))
- {
+ if (file_exists($loc)) {
+ if (preg_match('/\.(gz|zip)$/i', $loc, $ext)) {
+ switch (strtolower($ext[1])) {
case 'gz':
$loc = 'compress.zlib://'.$loc;
break;
case 'zip':
$zip = new ZipArchive;
- if ($zip->open($loc) === true && $zip->numFiles == 1)
+ if ($zip->open($loc) === true && $zip->numFiles == 1) {
return $this->loadFromString($zip->getFromIndex(0), $loadAllVars);
- else
+ } else {
$loc = 'zip://'.$loc;
+ }
break;
}
}
libxml_use_internal_errors(true);
$xmlObj = @simplexml_load_file($loc);
- if ($this->isValidNzb($xmlObj))
+ if ($this->isValidNzb($xmlObj)) {
$this->parseNzb($xmlObj);
+ }
unset($xmlObj);
}
+
return $this->isLoaded;
}
- public function summarize()
- {
- $out = [];
- $out[] = 'Reading from '.basename($this->source).'...';
- if (!empty($this->nfofiles))
- $out[] = ' -nfo detected';
- if (!empty($this->samplefiles))
- $out[] = ' -sample detected';
- if (!empty($this->mediafiles))
- $out[] = ' -media detected';
- if (!empty($this->audio))
- $out[] = ' -audio detected';
+ public function summarize()
+ {
+ $out = [];
+ $out[] = 'Reading from '.basename($this->source).'...';
+ if (! empty($this->nfofiles)) {
+ $out[] = ' -nfo detected';
+ }
+ if (! empty($this->samplefiles)) {
+ $out[] = ' -sample detected';
+ }
+ if (! empty($this->mediafiles)) {
+ $out[] = ' -media detected';
+ }
+ if (! empty($this->audio)) {
+ $out[] = ' -audio detected';
+ }
- if (!empty($this->metadata))
- {
- $out[] = ' -metadata:';
- foreach($this->metadata as $mk=>$mv)
- $out[] = ' -'.$mk.': '.$mv;
- }
+ if (! empty($this->metadata)) {
+ $out[] = ' -metadata:';
+ foreach ($this->metadata as $mk=>$mv) {
+ $out[] = ' -'.$mk.': '.$mv;
+ }
+ }
- $out[] = ' -sngl: '.sizeof($this->segmentfiles);
+ $out[] = ' -sngl: '.sizeof($this->segmentfiles);
- $out[] = ' -pstr: '.$this->poster;
- $out[] = ' -grps: '.implode(', ', $this->groups);
- $out[] = ' -size: '.round(($this->filesize / 1048576), 2).' MB in '.$this->filecount.' Files';
- $out[] = ' -'.$this->rarcount.' rars';
- $out[] = ' -'.$this->parcount.' pars';
+ $out[] = ' -pstr: '.$this->poster;
+ $out[] = ' -grps: '.implode(', ', $this->groups);
+ $out[] = ' -size: '.round(($this->filesize / 1048576), 2).' MB in '.$this->filecount.' Files';
+ $out[] = ' -'.$this->rarcount.' rars';
+ $out[] = ' -'.$this->parcount.' pars';
$out[] = ' -'.$this->sfvcount.' sfvs';
- $out[] = ' -'.$this->zipcount.' zips';
- $out[] = ' -'.$this->videocount.' videos';
- $out[] = ' -'.$this->audiocount.' audios';
- $out[] = ' -cmpltn: '.$this->completion.'% ('.$this->segmentactual.'/'.$this->segmenttotal.')';
- $out[] = ' -pstd: '.date("Y-m-d H:i:s", $this->postedlast);
- $out[] = '';
- $out[] = '';
+ $out[] = ' -'.$this->zipcount.' zips';
+ $out[] = ' -'.$this->videocount.' videos';
+ $out[] = ' -'.$this->audiocount.' audios';
+ $out[] = ' -cmpltn: '.$this->completion.'% ('.$this->segmentactual.'/'.$this->segmenttotal.')';
+ $out[] = ' -pstd: '.date('Y-m-d H:i:s', $this->postedlast);
+ $out[] = '';
+ $out[] = '';
- return implode(PHP_EOL, $out);
- }
+ return implode(PHP_EOL, $out);
+ }
- private function isValidNzb($xmlObj)
- {
- if (!$xmlObj || strtolower($xmlObj->getName()) != 'nzb' || !isset($xmlObj->file))
- return false;
+ private function isValidNzb($xmlObj)
+ {
+ if (! $xmlObj || strtolower($xmlObj->getName()) != 'nzb' || ! isset($xmlObj->file)) {
+ return false;
+ }
return true;
- }
+ }
- private function parseNzb($xmlObj)
- {
- //Metadata
- if (isset($xmlObj->head->meta))
- {
- foreach($xmlObj->head->meta as $meta)
- {
- if (isset($meta->attributes()->type))
- {
- $metaKey = (string) $meta->attributes()->type;
- $this->metadata[$metaKey] = (string) $meta;
- }
- }
- }
+ private function parseNzb($xmlObj)
+ {
+ //Metadata
+ if (isset($xmlObj->head->meta)) {
+ foreach ($xmlObj->head->meta as $meta) {
+ if (isset($meta->attributes()->type)) {
+ $metaKey = (string) $meta->attributes()->type;
+ $this->metadata[$metaKey] = (string) $meta;
+ }
+ }
+ }
- //NZB GID = first segment of first file
- $gid = (string) $xmlObj->file->segments->segment;
- if (!empty($gid))
- $this->gid = md5($gid);
+ //NZB GID = first segment of first file
+ $gid = (string) $xmlObj->file->segments->segment;
+ if (! empty($gid)) {
+ $this->gid = md5($gid);
+ }
- foreach($xmlObj->file as $file)
- {
- $fileArr = [];
- $fileArr['subject'] = (string) $file->attributes()->subject;
- $fileArr['poster'] = (string) $file->attributes()->poster;
- $fileArr['posted'] = (int) $file->attributes()->date;
- $fileArr['groups'] = [];
- $fileArr['filesize'] = 0;
- $fileArr['segmenttotal'] = 0;
- $fileArr['segmentactual'] = 0;
- $fileArr['completion'] = 0;
- $fileArr['segments'] = [];
+ foreach ($xmlObj->file as $file) {
+ $fileArr = [];
+ $fileArr['subject'] = (string) $file->attributes()->subject;
+ $fileArr['poster'] = (string) $file->attributes()->poster;
+ $fileArr['posted'] = (int) $file->attributes()->date;
+ $fileArr['groups'] = [];
+ $fileArr['filesize'] = 0;
+ $fileArr['segmenttotal'] = 0;
+ $fileArr['segmentactual'] = 0;
+ $fileArr['completion'] = 0;
+ $fileArr['segments'] = [];
- //subject
- $subject = $fileArr['subject'];
+ //subject
+ $subject = $fileArr['subject'];
- //poster
- $this->poster = $fileArr['poster'];
+ //poster
+ $this->poster = $fileArr['poster'];
- //dates
- $date = $fileArr['posted'];
- if ($date > $this->postedlast || $this->postedlast == 0)
- $this->postedlast = $date;
+ //dates
+ $date = $fileArr['posted'];
+ if ($date > $this->postedlast || $this->postedlast == 0) {
+ $this->postedlast = $date;
+ }
- if ($date < $this->postedfirst || $this->postedfirst == 0)
- $this->postedfirst = $date;
+ if ($date < $this->postedfirst || $this->postedfirst == 0) {
+ $this->postedfirst = $date;
+ }
+ //groups
+ foreach ($file->groups->group as $group) {
+ $this->groups[] = (string) $group;
+ $fileArr['groups'][] = (string) $group;
+ }
- //groups
- foreach ($file->groups->group as $group)
- {
- $this->groups[] = (string) $group;
- $fileArr['groups'][] = (string) $group;
- }
+ //file segments
+ foreach ($file->segments->segment as $segment) {
+ $bytes = (int) $segment->attributes()->bytes;
+ $number = (int) $segment->attributes()->number;
- //file segments
- foreach($file->segments->segment as $segment)
- {
- $bytes = (int) $segment->attributes()->bytes;
- $number = (int) $segment->attributes()->number;
+ $this->filesize += $bytes;
+ $this->segmentactual++;
- $this->filesize += $bytes;
- $this->segmentactual++;
-
- $fileArr['filesize'] += $bytes;
- $fileArr['segmentactual']++;
- $fileArr['segments'][$number] = (string) $segment;
+ $fileArr['filesize'] += $bytes;
+ $fileArr['segmentactual']++;
+ $fileArr['segments'][$number] = (string) $segment;
$fileArr['segmentbytes'][$number] = $bytes;
- }
+ }
$pattern = '|\((\d+)[\/](\d+)\)|i';
preg_match_all($pattern, $subject, $matches, PREG_PATTERN_ORDER);
$matchcnt = sizeof($matches[0]);
$msgPart = $msgTotalParts = 0;
- for ($i=0; $i<$matchcnt; $i++)
- {
+ for ($i = 0; $i < $matchcnt; $i++) {
//not (int)'d here because of the preg_replace later on
$msgPart = $matches[1][$i];
$msgTotalParts = $matches[2][$i];
}
- if((int)$msgPart > 0 && (int)$msgTotalParts > 0)
- {
+ if ((int) $msgPart > 0 && (int) $msgTotalParts > 0) {
$this->segmenttotal += (int) $msgTotalParts;
$fileArr['segmenttotal'] = (int) $msgTotalParts;
- $fileArr['completion'] = number_format(($fileArr['segmentactual']/$fileArr['segmenttotal'])*100, 0);
+ $fileArr['completion'] = number_format(($fileArr['segmentactual'] / $fileArr['segmenttotal']) * 100, 0);
$fileArr['subject'] = utf8_encode(trim(preg_replace('|\('.$msgPart.'[\/]'.$msgTotalParts.'\)|i', '', $subject)));
}
- //file counts
- $this->filecount++;
+ //file counts
+ $this->filecount++;
- if ($fileArr['segmenttotal'] == 1)
- $this->segmentfiles[] = $fileArr;
+ if ($fileArr['segmenttotal'] == 1) {
+ $this->segmentfiles[] = $fileArr;
+ }
- if (preg_match($this->nfofileregex, $subject))
- $this->nfofiles[] = $fileArr;
+ if (preg_match($this->nfofileregex, $subject)) {
+ $this->nfofiles[] = $fileArr;
+ }
- if (preg_match($this->mediafileregex, $subject) && preg_match('/sample[\.\-]/i', $subject) && !preg_match('/\.par2|\.srs/i', $subject))
- $this->samplefiles[] = $fileArr;
+ if (preg_match($this->mediafileregex, $subject) && preg_match('/sample[\.\-]/i', $subject) && ! preg_match('/\.par2|\.srs/i', $subject)) {
+ $this->samplefiles[] = $fileArr;
+ }
- if (preg_match($this->mediafileregex, $subject) && !preg_match('/sample[\.\-]/i', $subject) && !preg_match('/\.par2|\.srs/i', $subject))
- {
- $this->mediafiles[] = $fileArr;
- $this->videocount++;
- }
+ if (preg_match($this->mediafileregex, $subject) && ! preg_match('/sample[\.\-]/i', $subject) && ! preg_match('/\.par2|\.srs/i', $subject)) {
+ $this->mediafiles[] = $fileArr;
+ $this->videocount++;
+ }
- if (preg_match('/\.(rar|r\d{2,3})(?!\.)/i', $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject))
- $this->rarcount++;
+ if (preg_match('/\.(rar|r\d{2,3})(?!\.)/i', $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) {
+ $this->rarcount++;
+ }
- if (preg_match($this->rarfileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject))
- $this->rarfiles[] = $fileArr;
+ if (preg_match($this->rarfileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) {
+ $this->rarfiles[] = $fileArr;
+ }
- if (preg_match($this->audiofileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject))
- {
- $this->audiofiles[] = $fileArr;
- $this->audiocount++;
- }
+ if (preg_match($this->audiofileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) {
+ $this->audiofiles[] = $fileArr;
+ $this->audiocount++;
+ }
- if (preg_match($this->imgfileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject))
- {
+ if (preg_match($this->imgfileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject)) {
$this->imgfiles[] = $fileArr;
$this->imgcount++;
}
- if (preg_match($this->srrfileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject))
- {
+ if (preg_match($this->srrfileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject)) {
$this->srrfiles[] = $fileArr;
$this->srrcount++;
}
- if (preg_match($this->txtfileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject))
- {
+ if (preg_match($this->txtfileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/iS', $subject)) {
$this->txtfiles[] = $fileArr;
$this->txtcount++;
}
- if (preg_match($this->sfvfileregex, $subject) && !preg_match('/\.(par2|vol\d+\+|nzb)/iS', $subject))
- {
+ if (preg_match($this->sfvfileregex, $subject) && ! preg_match('/\.(par2|vol\d+\+|nzb)/iS', $subject)) {
$this->sfvfiles[] = $fileArr;
$this->sfvcount++;
}
- if (preg_match('/\.par2(?!\.)/iS', $subject))
- {
+ if (preg_match('/\.par2(?!\.)/iS', $subject)) {
$this->parcount++;
- if (!preg_match('/(vol\d+\+|vol[_\.\s]\d)/iS', $subject) && $fileArr['segmenttotal'] < 3)
+ if (! preg_match('/(vol\d+\+|vol[_\.\s]\d)/iS', $subject) && $fileArr['segmenttotal'] < 3) {
$this->parfiles[] = $fileArr;
+ }
}
- if (preg_match('/\.zip(?!\.)/i', $subject) && !preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject))
- $this->zipcount++;
+ if (preg_match('/\.zip(?!\.)/i', $subject) && ! preg_match('/\.(par2|vol\d+\+|sfv|nzb)/i', $subject)) {
+ $this->zipcount++;
+ }
- if ($this->loadAllVars === true)
- $this->nzb[] = $fileArr;
- else
- $this->nzb[]['subject'] = $fileArr['subject'];
- }
+ if ($this->loadAllVars === true) {
+ $this->nzb[] = $fileArr;
+ } else {
+ $this->nzb[]['subject'] = $fileArr['subject'];
+ }
+ }
- $this->groups = array_unique($this->groups);
+ $this->groups = array_unique($this->groups);
- if ($this->segmenttotal > 0)
- $this->completion = number_format(($this->segmentactual/$this->segmenttotal)*100, 0);
+ if ($this->segmenttotal > 0) {
+ $this->completion = number_format(($this->segmentactual / $this->segmenttotal) * 100, 0);
+ }
- if (is_array($this->nzb) && !empty($this->nzb))
- $this->isLoaded = true;
+ if (is_array($this->nzb) && ! empty($this->nzb)) {
+ $this->isLoaded = true;
+ }
- return $this->isLoaded;
- }
+ return $this->isLoaded;
+ }
public function toNzb()
{
- if ($this->loadAllVars === false)
+ if ($this->loadAllVars === false) {
return false;
+ }
$nzb = "\n";
$nzb .= "\n";
$nzb .= "\n\n";
- if (!empty($this->metadata))
- {
+ if (! empty($this->metadata)) {
$nzb .= "\n";
- $out = [];
- foreach($this->metadata as $mk=>$mv)
+ $out = [];
+ foreach ($this->metadata as $mk=>$mv) {
$out[] = ' '.$mv."\n";
+ }
$nzb .= "\n";
}
- foreach($this->nzb as $postFile)
- {
- $nzb .= "\n";
+ foreach ($this->nzb as $postFile) {
+ $nzb .= '\n";
$nzb .= " \n";
- foreach($postFile['groups'] as $fileGroup)
- {
- $nzb .= " ".$fileGroup."\n";
+ foreach ($postFile['groups'] as $fileGroup) {
+ $nzb .= ' '.$fileGroup."\n";
}
$nzb .= " \n";
$nzb .= " \n";
- foreach($postFile['segments'] as $fileSegmentNum=>$fileSegment)
- {
- $nzb .= " ".Utility::htmlfmt($fileSegment)."\n";
+ foreach ($postFile['segments'] as $fileSegmentNum=>$fileSegment) {
+ $nzb .= ' '.Utility::htmlfmt($fileSegment)."\n";
}
$nzb .= " \n\n";
}
- $nzb .= "\n";
+ $nzb .= '\n";
return $nzb;
}
diff --git a/nntmux/NZBMultiGroup.php b/nntmux/NZBMultiGroup.php
index 7c638a6dd..44a6c3b39 100644
--- a/nntmux/NZBMultiGroup.php
+++ b/nntmux/NZBMultiGroup.php
@@ -1,4 +1,5 @@
_tableNames = [
+ /**
+ * Initiate class vars when writing NZB's.
+ *
+ *
+ * @param int $groupID
+ */
+ public function initiateForWrite($groupID)
+ {
+ $this->_tableNames = [
'cName' => 'multigroup_collections',
'bName' => 'multigroup_binaries',
'pName' => 'multigroup_parts',
];
- $this->setQueries();
- }
+ $this->setQueries();
+ }
}
diff --git a/nntmux/NZBVortex.php b/nntmux/NZBVortex.php
index 78cc0a8b9..7b648c930 100755
--- a/nntmux/NZBVortex.php
+++ b/nntmux/NZBVortex.php
@@ -1,29 +1,28 @@
session))
- {
+ if (is_null($this->session)) {
$this->getNonce();
$this->login();
}
}
/**
- * get text for state
+ * get text for state.
* @param int $code
* @return string
*/
public function getState($code = 0)
{
- $states = array
- (
+ $states = [
0 => 'Waiting',
1 => 'Downloading',
2 => 'Waiting for save',
@@ -48,23 +47,22 @@ final class NZBVortex
21 => 'Uncompress failed',
22 => 'Check failed, data corrupt',
23 => 'Move failed',
- 24 => 'Badly encoded download (uuencoded)'
- );
+ 24 => 'Badly encoded download (uuencoded)',
+ ];
return (isset($states[$code])) ?
$states[$code] : -1;
}
/**
- * get overview of NZB's in queue
+ * get overview of NZB's in queue.
* @return array
*/
public function getOverview()
{
- $params = array('sessionid' => $this->session);
+ $params = ['sessionid' => $this->session];
$response = $this->sendRequest(sprintf('app/webUpdate'), $params);
- foreach ($response['nzbs'] as &$nzb)
- {
+ foreach ($response['nzbs'] as &$nzb) {
$nzb['original_state'] = $nzb['state'];
$nzb['state'] = (1 == $nzb['isPaused']) ? 'Paused' : $this->getState($nzb['state']);
}
@@ -72,167 +70,148 @@ final class NZBVortex
return $response;
}
-
/**
- * add NZB to queue
+ * add NZB to queue.
* @param string $nzb
* @return void
*/
public function addQueue($nzb = '')
{
- if (!empty($nzb))
- {
+ if (! empty($nzb)) {
$page = new Page;
$user = new Users;
- $host = $page->serverurl;
- $data = $user->getById($user->currentUserId());
- $url = sprintf("%sgetnzb/%s.nzb&i=%s&r=%s", $host, $nzb, $data['id'], $data['rsstoken']);
+ $host = $page->serverurl;
+ $data = $user->getById($user->currentUserId());
+ $url = sprintf('%sgetnzb/%s.nzb&i=%s&r=%s', $host, $nzb, $data['id'], $data['rsstoken']);
- $params = array
- (
+ $params = [
'sessionid' => $this->session,
- 'url' => $url
- );
+ 'url' => $url,
+ ];
$response = $this->sendRequest('nzb/add', $params);
}
}
-
/**
- * resume NZB
+ * resume NZB.
* @param int $id
* @return void
*/
public function resume($id = 0)
{
- if ($id > 0)
- {
- # /nzb/(id)/resume
- $params = array('sessionid' => $this->session);
+ if ($id > 0) {
+ // /nzb/(id)/resume
+ $params = ['sessionid' => $this->session];
$response = $this->sendRequest(sprintf('nzb/%s/resume', $id), $params);
}
}
-
/**
- * pause NZB
+ * pause NZB.
* @param int $id
* @return void
*/
public function pause($id = 0)
{
- if ($id > 0)
- {
- # /nzb/(id)/pause
- $params = array('sessionid' => $this->session);
+ if ($id > 0) {
+ // /nzb/(id)/pause
+ $params = ['sessionid' => $this->session];
$response = $this->sendRequest(sprintf('nzb/%s/pause', $id), $params);
}
}
-
/**
- * move NZB up in queue
+ * move NZB up in queue.
* @param int $id
* @return void
*/
public function moveUp($id = 0)
{
- if ($id > 0)
- {
- # nzb/(nzbid)/moveup
- $params = array('sessionid' => $this->session);
+ if ($id > 0) {
+ // nzb/(nzbid)/moveup
+ $params = ['sessionid' => $this->session];
$response = $this->sendRequest(sprintf('nzb/%s/moveup', $id), $params);
}
}
-
/**
- * move NZB down in queue
+ * move NZB down in queue.
* @param int $id
* @return void
*/
public function moveDown($id = 0)
{
- if ($id > 0)
- {
- # nzb/(nzbid)/movedown
- $params = array('sessionid' => $this->session);
+ if ($id > 0) {
+ // nzb/(nzbid)/movedown
+ $params = ['sessionid' => $this->session];
$response = $this->sendRequest(sprintf('nzb/%s/movedown', $id), $params);
}
}
-
/**
- * move NZB to bottom of queue
+ * move NZB to bottom of queue.
* @param int $id
* @return void
*/
public function moveBottom($id = 0)
{
- if ($id > 0)
- {
- # nzb/(nzbid)/movebottom
- $params = array('sessionid' => $this->session);
+ if ($id > 0) {
+ // nzb/(nzbid)/movebottom
+ $params = ['sessionid' => $this->session];
$response = $this->sendRequest(sprintf('nzb/%s/movebottom', $id), $params);
}
}
-
/**
- * Remove a (finished/unfinished) NZB from queue and delete files
+ * Remove a (finished/unfinished) NZB from queue and delete files.
* @param int $id
* @return void
*/
public function delete($id = 0)
{
- if ($id > 0)
- {
- # nzb/(nzbid)/movebottom
- $params = array('sessionid' => $this->session);
+ if ($id > 0) {
+ // nzb/(nzbid)/movebottom
+ $params = ['sessionid' => $this->session];
$response = $this->sendRequest(sprintf('nzb/%s/cancelDelete', $id), $params);
}
}
-
/**
- * move NZB to top of queue
+ * move NZB to top of queue.
* @param int $id
* @return void
*/
public function moveTop($id = 0)
{
- if ($id > 0)
- {
- # nzb/(nzbid)/movebottom
- $params = array('sessionid' => $this->session);
+ if ($id > 0) {
+ // nzb/(nzbid)/movebottom
+ $params = ['sessionid' => $this->session];
$response = $this->sendRequest(sprintf('nzb/%s/movetop', $id), $params);
}
}
-
/**
- * get filelist for nzb
+ * get filelist for nzb.
* @param int $id
* @return array|bool
*/
public function getFilelist($id = 0)
{
- if ($id > 0)
- {
- # file/(nzbid)
- $params = array('sessionid' => $this->session);
+ if ($id > 0) {
+ // file/(nzbid)
+ $params = ['sessionid' => $this->session];
$response = $this->sendRequest(sprintf('file/%s', $id), $params);
+
return $response;
}
return false;
}
-
/**
- * get /auth/nonce
+ * get /auth/nonce.
* @return void
*/
protected function getNonce()
@@ -246,29 +225,30 @@ final class NZBVortex
*/
protected function login()
{
- $user = new Users();
- $data = $user->getById($user->currentUserId());
- $cnonce = generateUuid();
- $hash = hash('sha256', sprintf("%s:%s:%s", $this->nonce, $cnonce, $data['nzbvortex_api_key']), true);
- $hash = base64_encode($hash);
+ $user = new Users();
+ $data = $user->getById($user->currentUserId());
+ $cnonce = generateUuid();
+ $hash = hash('sha256', sprintf('%s:%s:%s', $this->nonce, $cnonce, $data['nzbvortex_api_key']), true);
+ $hash = base64_encode($hash);
- $params = array
- (
+ $params = [
'nonce' => $this->nonce,
'cnonce' => $cnonce,
- 'hash' => $hash
- );
+ 'hash' => $hash,
+ ];
$response = $this->sendRequest('auth/login', $params);
- if ('successful' == $response['loginResult'])
+ if ('successful' == $response['loginResult']) {
$this->session = $response['sessionID'];
+ }
- if ('failed' == $response['loginResult']) { }
+ if ('failed' == $response['loginResult']) {
+ }
}
/**
- * sendRequest()
+ * sendRequest().
*
* @param $path
* @param array $params
@@ -281,9 +261,9 @@ final class NZBVortex
$user = new Users;
$data = $user->getById($user->currentUserId());
- $url = sprintf('%s/api', $data['nzbvortex_server_url']);
+ $url = sprintf('%s/api', $data['nzbvortex_server_url']);
$params = http_build_query($params);
- $ch = curl_init(sprintf("%s/%s?%s", $url, $path, $params));
+ $ch = curl_init(sprintf('%s/%s?%s', $url, $path, $params));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
@@ -291,18 +271,17 @@ final class NZBVortex
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
- #curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
- #curl_setopt($ch, CURLOPT_PROXY, 'localhost:8888');
+ //curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
+ //curl_setopt($ch, CURLOPT_PROXY, 'localhost:8888');
$response = curl_exec($ch);
$response = json_decode($response, true);
- $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $error = curl_error($ch);
+ $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ $error = curl_error($ch);
curl_close($ch);
- switch ($status)
- {
+ switch ($status) {
case 0:
throw new \Exception(sprintf('Unable to connect. Is NZBVortex running? Is your API key correct? Is something blocking ports? (Err: %s)', $error));
break;
@@ -316,7 +295,7 @@ final class NZBVortex
break;
default:
- throw new \Exception(sprintf("%s (%s): %s", $path, $status, $response['result']));
+ throw new \Exception(sprintf('%s (%s): %s', $path, $status, $response['result']));
break;
}
}
diff --git a/nntmux/NameFixer.php b/nntmux/NameFixer.php
index e91c58fa3..6626149d4 100755
--- a/nntmux/NameFixer.php
+++ b/nntmux/NameFixer.php
@@ -1,152 +1,153 @@
true,
'Categorize' => null,
'ConsoleTools' => null,
@@ -155,43 +156,43 @@ class NameFixer
'Settings' => null,
'SphinxSearch' => null,
];
- $options += $defaults;
+ $options += $defaults;
- $this->echooutput = ($options['Echo'] && NN_ECHOCLI);
- $this->relid = $this->fixed = $this->checked = 0;
- $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB());
- $this->othercats = implode(',', Category::OTHERS_GROUP);
- $this->timeother = sprintf(' AND rel.adddate > (NOW() - INTERVAL 6 HOUR) AND rel.categories_id IN (%s) GROUP BY rel.id ORDER BY postdate DESC', $this->othercats);
- $this->timeall = ' AND rel.adddate > (NOW() - INTERVAL 6 HOUR) GROUP BY rel.id ORDER BY postdate DESC';
- $this->fullother = sprintf(' AND rel.categories_id IN (%s) GROUP BY rel.id', $this->othercats);
- $this->fullall = '';
- $this->_fileName = '';
- $this->done = $this->matched = false;
- $this->consoletools = ($options['ConsoleTools'] instanceof ConsoleTools ? $options['ConsoleTools'] : new ConsoleTools(['ColorCLI' => $this->pdo->log]));
- $this->category = ($options['Categorize'] instanceof Categorize ? $options['Categorize'] : new Categorize(['Settings' => $this->pdo]));
- $this->text = ($options['Misc'] instanceof Utility ? $options['Misc'] : new Utility());
- $this->_groups = ($options['Groups'] instanceof Groups ? $options['Groups'] : new Groups(['Settings' => $this->pdo]));
- $this->sphinx = ($options['SphinxSearch'] instanceof SphinxSearch ? $options['SphinxSearch'] : new SphinxSearch());
- }
+ $this->echooutput = ($options['Echo'] && NN_ECHOCLI);
+ $this->relid = $this->fixed = $this->checked = 0;
+ $this->pdo = ($options['Settings'] instanceof DB ? $options['Settings'] : new DB());
+ $this->othercats = implode(',', Category::OTHERS_GROUP);
+ $this->timeother = sprintf(' AND rel.adddate > (NOW() - INTERVAL 6 HOUR) AND rel.categories_id IN (%s) GROUP BY rel.id ORDER BY postdate DESC', $this->othercats);
+ $this->timeall = ' AND rel.adddate > (NOW() - INTERVAL 6 HOUR) GROUP BY rel.id ORDER BY postdate DESC';
+ $this->fullother = sprintf(' AND rel.categories_id IN (%s) GROUP BY rel.id', $this->othercats);
+ $this->fullall = '';
+ $this->_fileName = '';
+ $this->done = $this->matched = false;
+ $this->consoletools = ($options['ConsoleTools'] instanceof ConsoleTools ? $options['ConsoleTools'] : new ConsoleTools(['ColorCLI' => $this->pdo->log]));
+ $this->category = ($options['Categorize'] instanceof Categorize ? $options['Categorize'] : new Categorize(['Settings' => $this->pdo]));
+ $this->text = ($options['Misc'] instanceof Utility ? $options['Misc'] : new Utility());
+ $this->_groups = ($options['Groups'] instanceof Groups ? $options['Groups'] : new Groups(['Settings' => $this->pdo]));
+ $this->sphinx = ($options['SphinxSearch'] instanceof SphinxSearch ? $options['SphinxSearch'] : new SphinxSearch());
+ }
- /**
- * Attempts to fix release names using the NFO.
- *
- * @param int $time 1: 24 hours, 2: no time limit
- * @param boolean $echo 1: change the name, anything else: preview of what could have been changed.
- * @param int $cats 1: other categories, 2: all categories
- * @param $nameStatus
- * @param $show
- */
- public function fixNamesWithNfo($time, $echo, $cats, $nameStatus, $show): void
- {
- $this->_echoStartMessage($time, '.nfo files');
- $type = 'NFO, ';
+ /**
+ * Attempts to fix release names using the NFO.
+ *
+ * @param int $time 1: 24 hours, 2: no time limit
+ * @param bool $echo 1: change the name, anything else: preview of what could have been changed.
+ * @param int $cats 1: other categories, 2: all categories
+ * @param $nameStatus
+ * @param $show
+ */
+ public function fixNamesWithNfo($time, $echo, $cats, $nameStatus, $show): void
+ {
+ $this->_echoStartMessage($time, '.nfo files');
+ $type = 'NFO, ';
- // Only select releases we haven't checked here before
- $preId = false;
- if ($cats === 3) {
- $query = sprintf('
+ // Only select releases we haven't checked here before
+ $preId = false;
+ if ($cats === 3) {
+ $query = sprintf('
SELECT rel.id AS releases_id, rel.fromname
FROM releases rel
INNER JOIN release_nfos nfo ON (nfo.releases_id = rel.id)
@@ -199,10 +200,10 @@ class NameFixer
AND rel.predb_id = 0',
NZB::NZB_ADDED
);
- $cats = 2;
- $preId = true;
- } else {
- $query = sprintf('
+ $cats = 2;
+ $preId = true;
+ } else {
+ $query = sprintf('
SELECT rel.id AS releases_id, rel.fromname
FROM releases rel
INNER JOIN release_nfos nfo ON (nfo.releases_id = rel.id)
@@ -213,19 +214,19 @@ class NameFixer
Category::OTHER_MISC,
self::PROC_NFO_NONE
);
- }
+ }
- $releases = $this->_getReleases($time, $cats, $query);
+ $releases = $this->_getReleases($time, $cats, $query);
- if ($releases instanceof \Traversable) {
- $total = $releases->rowCount();
+ if ($releases instanceof \Traversable) {
+ $total = $releases->rowCount();
- if ($total > 0) {
- $this->_totalReleases = $total;
- echo ColorCLI::primary(number_format($total) . ' releases to process.');
+ if ($total > 0) {
+ $this->_totalReleases = $total;
+ echo ColorCLI::primary(number_format($total).' releases to process.');
- foreach ($releases as $rel) {
- $releaseRow = $this->pdo->queryOneRow(
+ foreach ($releases as $rel) {
+ $releaseRow = $this->pdo->queryOneRow(
sprintf('
SELECT nfo.releases_id AS nfoid, rel.groups_id, rel.fromname, rel.categories_id, rel.name, rel.searchname,
UNCOMPRESS(nfo) AS textstring, rel.id AS releases_id
@@ -236,42 +237,42 @@ class NameFixer
)
);
- $this->checked++;
+ $this->checked++;
- // Ignore encrypted NFOs.
- if (preg_match('/^=newz\[NZB\]=\w+/', $releaseRow['textstring'])) {
- $this->_updateSingleColumn('proc_nfo', self::PROC_NFO_DONE, $rel['releases_id']);
- continue;
- }
+ // Ignore encrypted NFOs.
+ if (preg_match('/^=newz\[NZB\]=\w+/', $releaseRow['textstring'])) {
+ $this->_updateSingleColumn('proc_nfo', self::PROC_NFO_DONE, $rel['releases_id']);
+ continue;
+ }
- $this->reset();
- $this->checkName($releaseRow, $echo, $type, $nameStatus, $show, $preId);
- $this->_echoRenamed($show);
- }
- $this->_echoFoundCount($echo, ' NFO\'s');
- } else {
- echo ColorCLI::info('Nothing to fix.');
- }
- }
- }
+ $this->reset();
+ $this->checkName($releaseRow, $echo, $type, $nameStatus, $show, $preId);
+ $this->_echoRenamed($show);
+ }
+ $this->_echoFoundCount($echo, ' NFO\'s');
+ } else {
+ echo ColorCLI::info('Nothing to fix.');
+ }
+ }
+ }
- /**
- * Attempts to fix release names using the File name.
- *
- * @param int $time 1: 24 hours, 2: no time limit
- * @param boolean $echo 1: change the name, anything else: preview of what could have been changed.
- * @param int $cats 1: other categories, 2: all categories
- * @param $nameStatus
- * @param $show
- */
- public function fixNamesWithFiles($time, $echo, $cats, $nameStatus, $show): void
- {
- $this->_echoStartMessage($time, 'file names');
- $type = 'Filenames, ';
+ /**
+ * Attempts to fix release names using the File name.
+ *
+ * @param int $time 1: 24 hours, 2: no time limit
+ * @param bool $echo 1: change the name, anything else: preview of what could have been changed.
+ * @param int $cats 1: other categories, 2: all categories
+ * @param $nameStatus
+ * @param $show
+ */
+ public function fixNamesWithFiles($time, $echo, $cats, $nameStatus, $show): void
+ {
+ $this->_echoStartMessage($time, 'file names');
+ $type = 'Filenames, ';
- $preId = false;
- if ($cats === 3) {
- $query = sprintf('
+ $preId = false;
+ if ($cats === 3) {
+ $query = sprintf('
SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id,
rf.releases_id AS fileid, rel.id AS releases_id
FROM releases rel
@@ -280,10 +281,10 @@ class NameFixer
AND predb_id = 0',
NZB::NZB_ADDED
);
- $cats = 2;
- $preId = true;
- } else {
- $query = sprintf('
+ $cats = 2;
+ $preId = true;
+ } else {
+ $query = sprintf('
SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id,
rf.releases_id AS fileid, rel.id AS releases_id
FROM releases rel
@@ -296,46 +297,45 @@ class NameFixer
Category::OTHER_HASHED,
self::PROC_FILES_NONE
);
- }
+ }
- $releases = $this->_getReleases($time, $cats, $query);
- if ($releases instanceof \Traversable) {
+ $releases = $this->_getReleases($time, $cats, $query);
+ if ($releases instanceof \Traversable) {
+ $total = $releases->rowCount();
+ if ($total > 0) {
+ $this->_totalReleases = $total;
+ echo ColorCLI::primary(number_format($total).' file names to process.');
- $total = $releases->rowCount();
- if ($total > 0) {
- $this->_totalReleases = $total;
- echo ColorCLI::primary(number_format($total) . ' file names to process.');
+ foreach ($releases as $release) {
+ $this->reset();
+ $this->checkName($release, $echo, $type, $nameStatus, $show, $preId);
+ $this->checked++;
+ $this->_echoRenamed($show);
+ }
- foreach ($releases as $release) {
- $this->reset();
- $this->checkName($release, $echo, $type, $nameStatus, $show, $preId);
- $this->checked++;
- $this->_echoRenamed($show);
- }
+ $this->_echoFoundCount($echo, ' files');
+ } else {
+ echo ColorCLI::info('Nothing to fix.');
+ }
+ }
+ }
- $this->_echoFoundCount($echo, ' files');
- } else {
- echo ColorCLI::info('Nothing to fix.');
- }
- }
- }
+ /**
+ * Attempts to fix release names using the File name.
+ *
+ * @param int $time 1: 24 hours, 2: no time limit
+ * @param bool $echo 1: change the name, anything else: preview of what could have been changed.
+ * @param int $cats 1: other categories, 2: all categories
+ * @param $nameStatus
+ * @param $show
+ */
+ public function fixXXXNamesWithFiles($time, $echo, $cats, $nameStatus, $show): void
+ {
+ $this->_echoStartMessage($time, 'file names');
+ $type = 'Filenames, ';
- /**
- * Attempts to fix release names using the File name.
- *
- * @param int $time 1: 24 hours, 2: no time limit
- * @param boolean $echo 1: change the name, anything else: preview of what could have been changed.
- * @param int $cats 1: other categories, 2: all categories
- * @param $nameStatus
- * @param $show
- */
- public function fixXXXNamesWithFiles($time, $echo, $cats, $nameStatus, $show): void
- {
- $this->_echoStartMessage($time, 'file names');
- $type = 'Filenames, ';
-
- if ($cats === 3) {
- $query = sprintf('
+ if ($cats === 3) {
+ $query = sprintf('
SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id,
rf.releases_id AS fileid, rel.id AS releases_id
FROM releases rel
@@ -344,9 +344,9 @@ class NameFixer
AND predb_id = 0',
NZB::NZB_ADDED
);
- $cats = 2;
- } else {
- $query = sprintf('
+ $cats = 2;
+ } else {
+ $query = sprintf('
SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id,
rf.releases_id AS fileid, rel.id AS releases_id
FROM releases rel
@@ -359,45 +359,44 @@ class NameFixer
Category::OTHER_HASHED,
$this->pdo->likeString('SDPORN', true, true)
);
- }
+ }
- $releases = $this->_getReleases($time, $cats, $query);
- if ($releases instanceof \Traversable) {
+ $releases = $this->_getReleases($time, $cats, $query);
+ if ($releases instanceof \Traversable) {
+ $total = $releases->rowCount();
+ if ($total > 0) {
+ $this->_totalReleases = $total;
+ echo ColorCLI::primary(number_format($total).' xxx file names to process.');
- $total = $releases->rowCount();
- if ($total > 0) {
- $this->_totalReleases = $total;
- echo ColorCLI::primary(number_format($total) . ' xxx file names to process.');
+ foreach ($releases as $release) {
+ $this->reset();
+ $this->xxxNameCheck($release, $echo, $type, $nameStatus, $show);
+ $this->checked++;
+ $this->_echoRenamed($show);
+ }
+ $this->_echoFoundCount($echo, ' files');
+ } else {
+ echo ColorCLI::info('Nothing to fix.');
+ }
+ }
+ }
- foreach ($releases as $release) {
- $this->reset();
- $this->xxxNameCheck($release, $echo, $type, $nameStatus, $show);
- $this->checked++;
- $this->_echoRenamed($show);
- }
- $this->_echoFoundCount($echo, ' files');
- } else {
- echo ColorCLI::info('Nothing to fix.');
- }
- }
- }
+ /**
+ * Attempts to fix release names using the File name.
+ *
+ * @param int $time 1: 24 hours, 2: no time limit
+ * @param bool $echo 1: change the name, anything else: preview of what could have been changed.
+ * @param int $cats 1: other categories, 2: all categories
+ * @param $nameStatus
+ * @param $show
+ */
+ public function fixNamesWithSrr($time, $echo, $cats, $nameStatus, $show): void
+ {
+ $this->_echoStartMessage($time, 'SRR file names');
+ $type = 'SRR, ';
- /**
- * Attempts to fix release names using the File name.
- *
- * @param int $time 1: 24 hours, 2: no time limit
- * @param boolean $echo 1: change the name, anything else: preview of what could have been changed.
- * @param int $cats 1: other categories, 2: all categories
- * @param $nameStatus
- * @param $show
- */
- public function fixNamesWithSrr($time, $echo, $cats, $nameStatus, $show): void
- {
- $this->_echoStartMessage($time, 'SRR file names');
- $type = 'SRR, ';
-
- if ($cats === 3) {
- $query = sprintf('
+ if ($cats === 3) {
+ $query = sprintf('
SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id,
rf.releases_id AS fileid, rel.id AS releases_id
FROM releases rel
@@ -406,9 +405,9 @@ class NameFixer
AND predb_id = 0',
NZB::NZB_ADDED
);
- $cats = 2;
- } else {
- $query = sprintf('
+ $cats = 2;
+ } else {
+ $query = sprintf('
SELECT rf.name AS textstring, rel.categories_id, rel.name, rel.searchname, rel.fromname, rel.groups_id,
rf.releases_id AS fileid, rel.id AS releases_id
FROM releases rel
@@ -423,54 +422,53 @@ class NameFixer
$this->pdo->likeString('.srr', true, false),
self::PROC_SRR_NONE
);
- }
+ }
- $releases = $this->_getReleases($time, $cats, $query);
- if ($releases instanceof \Traversable) {
+ $releases = $this->_getReleases($time, $cats, $query);
+ if ($releases instanceof \Traversable) {
+ $total = $releases->rowCount();
+ if ($total > 0) {
+ $this->_totalReleases = $total;
+ echo ColorCLI::primary(number_format($total).' srr file extensions to process.');
- $total = $releases->rowCount();
- if ($total > 0) {
- $this->_totalReleases = $total;
- echo ColorCLI::primary(number_format($total) . ' srr file extensions to process.');
+ foreach ($releases as $release) {
+ $this->reset();
+ $this->srrNameCheck($release, $echo, $type, $nameStatus, $show);
+ $this->checked++;
+ $this->_echoRenamed($show);
+ }
+ $this->_echoFoundCount($echo, ' files');
+ } else {
+ echo ColorCLI::info('Nothing to fix.');
+ }
+ }
+ }
- foreach ($releases as $release) {
- $this->reset();
- $this->srrNameCheck($release, $echo, $type, $nameStatus, $show);
- $this->checked++;
- $this->_echoRenamed($show);
- }
- $this->_echoFoundCount($echo, ' files');
- } else {
- echo ColorCLI::info('Nothing to fix.');
- }
- }
- }
+ /**
+ * Attempts to fix release names using the Par2 File.
+ *
+ * @param int $time 1: 24 hours, 2: no time limit
+ * @param int $echo 1: change the name, anything else: preview of what could have been changed.
+ * @param int $cats 1: other categories, 2: all categories
+ * @param $nameStatus
+ * @param $show
+ * @param NNTP $nntp
+ */
+ public function fixNamesWithPar2($time, $echo, $cats, $nameStatus, $show, $nntp): void
+ {
+ $this->_echoStartMessage($time, 'par2 files');
- /**
- * Attempts to fix release names using the Par2 File.
- *
- * @param int $time 1: 24 hours, 2: no time limit
- * @param int $echo 1: change the name, anything else: preview of what could have been changed.
- * @param int $cats 1: other categories, 2: all categories
- * @param $nameStatus
- * @param $show
- * @param NNTP $nntp
- */
- public function fixNamesWithPar2($time, $echo, $cats, $nameStatus, $show, $nntp): void
- {
- $this->_echoStartMessage($time, 'par2 files');
-
- if ($cats === 3) {
- $query = sprintf('
+ if ($cats === 3) {
+ $query = sprintf('
SELECT rel.id AS releases_id, rel.guid, rel.groups_id, rel.fromname
FROM releases rel
WHERE rel.nzbstatus = %d
AND rel.predb_id = 0',
NZB::NZB_ADDED
);
- $cats = 2;
- } else {
- $query = sprintf('
+ $cats = 2;
+ } else {
+ $query = sprintf('
SELECT rel.id AS releases_id, rel.guid, rel.groups_id, rel.fromname
FROM releases rel
WHERE rel.isrenamed = %d
@@ -479,61 +477,60 @@ class NameFixer
self::IS_RENAMED_NONE,
self::PROC_PAR2_NONE
);
- }
+ }
- $releases = $this->_getReleases($time, $cats, $query);
+ $releases = $this->_getReleases($time, $cats, $query);
- if ($releases instanceof \Traversable) {
+ if ($releases instanceof \Traversable) {
+ $total = $releases->rowCount();
+ if ($total > 0) {
+ $this->_totalReleases = $total;
- $total = $releases->rowCount();
- if ($total > 0) {
- $this->_totalReleases = $total;
-
- echo ColorCLI::primary(number_format($total) . ' releases to process.');
- $Nfo = new Nfo(['Echo' => $this->echooutput, 'Settings' => $this->pdo]);
- $nzbContents = new NZBContents(
+ echo ColorCLI::primary(number_format($total).' releases to process.');
+ $Nfo = new Nfo(['Echo' => $this->echooutput, 'Settings' => $this->pdo]);
+ $nzbContents = new NZBContents(
[
'Echo' => $this->echooutput,
'NNTP' => $nntp,
'Nfo' => $Nfo,
'Settings' => $this->pdo,
- 'PostProcess' => new PostProcess(['Settings' => $this->pdo, 'Nfo' => $Nfo])
+ 'PostProcess' => new PostProcess(['Settings' => $this->pdo, 'Nfo' => $Nfo]),
]
);
- foreach ($releases as $release) {
- if ($nzbContents->checkPAR2($release['guid'], $release['releases_id'], $release['groups_id'], $nameStatus, $show) === true) {
- $this->fixed++;
- }
+ foreach ($releases as $release) {
+ if ($nzbContents->checkPAR2($release['guid'], $release['releases_id'], $release['groups_id'], $nameStatus, $show) === true) {
+ $this->fixed++;
+ }
- $this->checked++;
- $this->_echoRenamed($show);
- }
- $this->_echoFoundCount($echo, ' files');
- } else {
- echo ColorCLI::alternate('Nothing to fix.');
- }
- }
- }
+ $this->checked++;
+ $this->_echoRenamed($show);
+ }
+ $this->_echoFoundCount($echo, ' files');
+ } else {
+ echo ColorCLI::alternate('Nothing to fix.');
+ }
+ }
+ }
- /**
- * Attempts to fix release names using the mediainfo xml Unique_ID.
- *
- * @param int $time 1: 24 hours, 2: no time limit
- * @param boolean $echo 1: change the name, anything else: preview of what could have been changed.
- * @param int $cats 1: other categories, 2: all categories
- * @param $nameStatus
- * @param $show
- */
- public function fixNamesWithMedia($time, $echo, $cats, $nameStatus, $show): void
- {
- $type = 'UID, ';
+ /**
+ * Attempts to fix release names using the mediainfo xml Unique_ID.
+ *
+ * @param int $time 1: 24 hours, 2: no time limit
+ * @param bool $echo 1: change the name, anything else: preview of what could have been changed.
+ * @param int $cats 1: other categories, 2: all categories
+ * @param $nameStatus
+ * @param $show
+ */
+ public function fixNamesWithMedia($time, $echo, $cats, $nameStatus, $show): void
+ {
+ $type = 'UID, ';
- $this->_echoStartMessage($time, 'mediainfo Unique_IDs');
+ $this->_echoStartMessage($time, 'mediainfo Unique_IDs');
- // Re-check all releases we haven't matched to a PreDB
- if ($cats === 3) {
- $query = sprintf('
+ // Re-check all releases we haven't matched to a PreDB
+ if ($cats === 3) {
+ $query = sprintf('
SELECT
rel.id AS releases_id, rel.size AS relsize, rel.groups_id, rel.fromname, rel.categories_id,
rel.name, rel.name AS textstring, rel.predb_id, rel.searchname,
@@ -545,10 +542,10 @@ class NameFixer
AND rel.predb_id = 0',
NZB::NZB_ADDED
);
- $cats = 2;
- // Otherwise check only releases we haven't renamed and checked uid before in Misc categories
- } else {
- $query = sprintf('
+ $cats = 2;
+ // Otherwise check only releases we haven't renamed and checked uid before in Misc categories
+ } else {
+ $query = sprintf('
SELECT
rel.id AS releases_id, rel.size AS relsize, rel.groups_id, rel.fromname, rel.categories_id,
rel.name, rel.name AS textstring, rel.predb_id, rel.searchname,
@@ -567,45 +564,45 @@ class NameFixer
Category::OTHER_HASHED,
self::PROC_UID_NONE
);
- }
+ }
- $releases = $this->_getReleases($time, $cats, $query);
- if ($releases instanceof \Traversable) {
- $total = $releases->rowCount();
- if ($total > 0) {
- $this->_totalReleases = $total;
- echo ColorCLI::primary(number_format($total) . ' unique ids to process.');
- foreach ($releases as $rel) {
- $this->checked++;
- $this->reset();
- $this->uidCheck($rel, $echo, $type, $nameStatus, $show);
- $this->_echoRenamed($show);
- }
- $this->_echoFoundCount($echo, ' UID\'s');
- } else {
- echo ColorCLI::info('Nothing to fix.');
- }
- }
- }
+ $releases = $this->_getReleases($time, $cats, $query);
+ if ($releases instanceof \Traversable) {
+ $total = $releases->rowCount();
+ if ($total > 0) {
+ $this->_totalReleases = $total;
+ echo ColorCLI::primary(number_format($total).' unique ids to process.');
+ foreach ($releases as $rel) {
+ $this->checked++;
+ $this->reset();
+ $this->uidCheck($rel, $echo, $type, $nameStatus, $show);
+ $this->_echoRenamed($show);
+ }
+ $this->_echoFoundCount($echo, ' UID\'s');
+ } else {
+ echo ColorCLI::info('Nothing to fix.');
+ }
+ }
+ }
- /**
- * Attempts to fix release names using the par2 hash_16K block.
- *
- * @param int $time 1: 24 hours, 2: no time limit
- * @param boolean $echo 1: change the name, anything else: preview of what could have been changed.
- * @param int $cats 1: other categories, 2: all categories
- * @param $nameStatus
- * @param $show
- */
- public function fixNamesWithParHash($time, $echo, $cats, $nameStatus, $show): void
- {
- $type = 'PAR2 hash, ';
+ /**
+ * Attempts to fix release names using the par2 hash_16K block.
+ *
+ * @param int $time 1: 24 hours, 2: no time limit
+ * @param bool $echo 1: change the name, anything else: preview of what could have been changed.
+ * @param int $cats 1: other categories, 2: all categories
+ * @param $nameStatus
+ * @param $show
+ */
+ public function fixNamesWithParHash($time, $echo, $cats, $nameStatus, $show): void
+ {
+ $type = 'PAR2 hash, ';
- $this->_echoStartMessage($time, 'PAR2 hash_16K');
+ $this->_echoStartMessage($time, 'PAR2 hash_16K');
- // Re-check all releases we haven't matched to a PreDB
- if ($cats === 3) {
- $query = sprintf('
+ // Re-check all releases we haven't matched to a PreDB
+ if ($cats === 3) {
+ $query = sprintf('
SELECT
rel.id AS releases_id, rel.size AS relsize, rel.groups_id, rel.fromname, rel.categories_id,
rel.name, rel.name AS textstring, rel.predb_id, rel.searchname,
@@ -616,10 +613,10 @@ class NameFixer
AND rel.predb_id = 0',
NZB::NZB_ADDED
);
- $cats = 2;
- // Otherwise check only releases we haven't renamed and checked their par2 hash_16K before in Misc categories
- } else {
- $query = sprintf('
+ $cats = 2;
+ // Otherwise check only releases we haven't renamed and checked their par2 hash_16K before in Misc categories
+ } else {
+ $query = sprintf('
SELECT
rel.id AS releases_id, rel.size AS relsize, rel.groups_id, rel.fromname, rel.categories_id,
rel.name, rel.name AS textstring, rel.predb_id, rel.searchname,
@@ -637,206 +634,205 @@ class NameFixer
Category::OTHER_HASHED,
self::PROC_HASH16K_NONE
);
- }
+ }
- $releases = $this->_getReleases($time, $cats, $query);
+ $releases = $this->_getReleases($time, $cats, $query);
- if ($releases instanceof \Traversable) {
- $total = $releases->rowCount();
- if ($total > 0) {
- $this->_totalReleases = $total;
- echo ColorCLI::primary(number_format($total) . ' hash_16K to process.');
- foreach ($releases as $rel) {
- $this->checked++;
- $this->reset();
- $this->hashCheck($rel, $echo, $type, $nameStatus, $show);
- $this->_echoRenamed($show);
- }
- $this->_echoFoundCount($echo, ' hashes');
- } else {
- echo ColorCLI::info('Nothing to fix.');
- }
- }
- }
+ if ($releases instanceof \Traversable) {
+ $total = $releases->rowCount();
+ if ($total > 0) {
+ $this->_totalReleases = $total;
+ echo ColorCLI::primary(number_format($total).' hash_16K to process.');
+ foreach ($releases as $rel) {
+ $this->checked++;
+ $this->reset();
+ $this->hashCheck($rel, $echo, $type, $nameStatus, $show);
+ $this->_echoRenamed($show);
+ }
+ $this->_echoFoundCount($echo, ' hashes');
+ } else {
+ echo ColorCLI::info('Nothing to fix.');
+ }
+ }
+ }
- /**
- * @param int $time 1: 24 hours, 2: no time limit
- * @param int $cats 1: other categories, 2: all categories
- * @param string $query Query to execute.
- *
- * @param string $limit limit defined by maxperrun
- *
- * @return bool|\PDOStatement False on failure, PDOStatement with query results on success.
- */
- protected function _getReleases($time, $cats, $query, $limit = '')
- {
- $releases = false;
- $queryLimit = ($limit === '') ? '' : ' LIMIT ' . $limit;
- // 24 hours, other cats
- if ($time === 1 && $cats === 1) {
- echo ColorCLI::header($query . $this->timeother . $queryLimit . ";\n");
- $releases = $this->pdo->queryDirect($query . $this->timeother . $queryLimit);
- } // 24 hours, all cats
- if ($time === 1 && $cats === 2) {
- echo ColorCLI::header($query . $this->timeall . $queryLimit . ";\n");
- $releases = $this->pdo->queryDirect($query . $this->timeall . $queryLimit);
- } //other cats
- if ($time === 2 && $cats === 1) {
- echo ColorCLI::header($query . $this->fullother . $queryLimit . ";\n");
- $releases = $this->pdo->queryDirect($query . $this->fullother . $queryLimit);
- } // all cats
- if ($time === 2 && $cats === 2) {
- echo ColorCLI::header($query . $this->fullall . $queryLimit . ";\n");
- $releases = $this->pdo->queryDirect($query . $this->fullall . $queryLimit);
- }
+ /**
+ * @param int $time 1: 24 hours, 2: no time limit
+ * @param int $cats 1: other categories, 2: all categories
+ * @param string $query Query to execute.
+ *
+ * @param string $limit limit defined by maxperrun
+ *
+ * @return bool|\PDOStatement False on failure, PDOStatement with query results on success.
+ */
+ protected function _getReleases($time, $cats, $query, $limit = '')
+ {
+ $releases = false;
+ $queryLimit = ($limit === '') ? '' : ' LIMIT '.$limit;
+ // 24 hours, other cats
+ if ($time === 1 && $cats === 1) {
+ echo ColorCLI::header($query.$this->timeother.$queryLimit.";\n");
+ $releases = $this->pdo->queryDirect($query.$this->timeother.$queryLimit);
+ } // 24 hours, all cats
+ if ($time === 1 && $cats === 2) {
+ echo ColorCLI::header($query.$this->timeall.$queryLimit.";\n");
+ $releases = $this->pdo->queryDirect($query.$this->timeall.$queryLimit);
+ } //other cats
+ if ($time === 2 && $cats === 1) {
+ echo ColorCLI::header($query.$this->fullother.$queryLimit.";\n");
+ $releases = $this->pdo->queryDirect($query.$this->fullother.$queryLimit);
+ } // all cats
+ if ($time === 2 && $cats === 2) {
+ echo ColorCLI::header($query.$this->fullall.$queryLimit.";\n");
+ $releases = $this->pdo->queryDirect($query.$this->fullall.$queryLimit);
+ }
- return $releases;
- }
+ return $releases;
+ }
- /**
- * Echo the amount of releases that found a new name.
- *
- * @param int $echo 1: change the name, anything else: preview of what could have been changed.
- * @param string $type The function type that found the name.
- */
- protected function _echoFoundCount($echo, $type): void
- {
- if ($echo === true) {
- echo ColorCLI::header(
- PHP_EOL .
- number_format($this->fixed) .
- ' releases have had their names changed out of: ' .
- number_format($this->checked) .
- $type . '.'
+ /**
+ * Echo the amount of releases that found a new name.
+ *
+ * @param int $echo 1: change the name, anything else: preview of what could have been changed.
+ * @param string $type The function type that found the name.
+ */
+ protected function _echoFoundCount($echo, $type): void
+ {
+ if ($echo === true) {
+ echo ColorCLI::header(
+ PHP_EOL.
+ number_format($this->fixed).
+ ' releases have had their names changed out of: '.
+ number_format($this->checked).
+ $type.'.'
);
- } else {
- echo ColorCLI::header(
- PHP_EOL .
- number_format($this->fixed) .
- ' releases could have their names changed. ' .
- number_format($this->checked) .
- $type . ' were checked.'
+ } else {
+ echo ColorCLI::header(
+ PHP_EOL.
+ number_format($this->fixed).
+ ' releases could have their names changed. '.
+ number_format($this->checked).
+ $type.' were checked.'
);
- }
- }
+ }
+ }
- /**
- * @param int $time 1: 24 hours, 2: no time limit
- * @param string $type The function type.
- */
- protected function _echoStartMessage($time, $type): void
- {
- echo ColorCLI::header(
+ /**
+ * @param int $time 1: 24 hours, 2: no time limit
+ * @param string $type The function type.
+ */
+ protected function _echoStartMessage($time, $type): void
+ {
+ echo ColorCLI::header(
sprintf(
'Fixing search names %s using %s.',
($time === 1 ? 'in the past 6 hours' : 'since the beginning'),
$type
)
);
+ }
- }
+ /**
+ * @param int $show
+ */
+ protected function _echoRenamed($show): void
+ {
+ if ($this->checked % 500 === 0 && $show === 1) {
+ echo ColorCLI::alternate(PHP_EOL.number_format($this->checked).' files processed.'.PHP_EOL);
+ }
- /**
- * @param int $show
- */
- protected function _echoRenamed($show): void
- {
- if ($this->checked % 500 === 0 && $show === 1) {
- echo ColorCLI::alternate(PHP_EOL . number_format($this->checked) . ' files processed.' . PHP_EOL);
- }
-
- if ($show === 2) {
- $this->consoletools->overWritePrimary(
- 'Renamed Releases: [' .
- number_format($this->fixed) .
- '] ' .
+ if ($show === 2) {
+ $this->consoletools->overWritePrimary(
+ 'Renamed Releases: ['.
+ number_format($this->fixed).
+ '] '.
$this->consoletools->percentString($this->checked, $this->_totalReleases)
);
- }
- }
+ }
+ }
- /**
- * Update the release with the new information.
- *
- * @param array $release
- * @param string $name
- * @param string $method
- * @param boolean $echo
- * @param string $type
- * @param int $nameStatus
- * @param int $show
- * @param int $preId
- */
- public function updateRelease($release, $name, $method, $echo, $type, int $nameStatus, int $show, int $preId = 0): void
- {
- $release['releases_id'] = $release['releases_id'] ?? $release['releaseid'];
- if ($this->relid !== (int)$release['releases_id']) {
- $releaseCleaning = new ReleaseCleaning($this->pdo);
- $newName = $releaseCleaning->fixerCleaner($name);
- if (strtolower($newName) !== strtolower($release['searchname'])) {
- $this->matched = true;
- $this->relid = (int)$release['releases_id'];
+ /**
+ * Update the release with the new information.
+ *
+ * @param array $release
+ * @param string $name
+ * @param string $method
+ * @param bool $echo
+ * @param string $type
+ * @param int $nameStatus
+ * @param int $show
+ * @param int $preId
+ */
+ public function updateRelease($release, $name, $method, $echo, $type, int $nameStatus, int $show, int $preId = 0): void
+ {
+ $release['releases_id'] = $release['releases_id'] ?? $release['releaseid'];
+ if ($this->relid !== (int) $release['releases_id']) {
+ $releaseCleaning = new ReleaseCleaning($this->pdo);
+ $newName = $releaseCleaning->fixerCleaner($name);
+ if (strtolower($newName) !== strtolower($release['searchname'])) {
+ $this->matched = true;
+ $this->relid = (int) $release['releases_id'];
- $determinedCategory = $this->category->determineCategory($release['groups_id'], $newName, !empty($release['fromname']) ? $release['fromname'] : '');
+ $determinedCategory = $this->category->determineCategory($release['groups_id'], $newName, ! empty($release['fromname']) ? $release['fromname'] : '');
- if ($type === 'PAR2, ') {
- $newName = ucwords($newName);
- if (preg_match('/(.+?)\.[a-z0-9]{2,3}(PAR2)?$/i', $name, $match)) {
- $newName = $match[1];
- }
- }
+ if ($type === 'PAR2, ') {
+ $newName = ucwords($newName);
+ if (preg_match('/(.+?)\.[a-z0-9]{2,3}(PAR2)?$/i', $name, $match)) {
+ $newName = $match[1];
+ }
+ }
- $this->fixed++;
+ $this->fixed++;
- if(!empty($release['fromname']) && (preg_match('/oz@lot[.]com/i', $release['fromname']) || preg_match('/anon@y[.]com/i', $release['fromname']))) {
- $newName = preg_replace('/(KTR|GUSH|BIUK|WEIRD)$/', 'SDCLiP', $newName);
- }
- $newName = explode("\\", $newName);
- $newName = preg_replace(['/^[-=_\.:\s]+/', '/[-=_\.:\s]+$/'], '', $newName[0]);
+ if (! empty($release['fromname']) && (preg_match('/oz@lot[.]com/i', $release['fromname']) || preg_match('/anon@y[.]com/i', $release['fromname']))) {
+ $newName = preg_replace('/(KTR|GUSH|BIUK|WEIRD)$/', 'SDCLiP', $newName);
+ }
+ $newName = explode('\\', $newName);
+ $newName = preg_replace(['/^[-=_\.:\s]+/', '/[-=_\.:\s]+$/'], '', $newName[0]);
- if ($this->echooutput === true && $show === 1) {
- $groupName = $this->_groups->getNameByID($release['groups_id']);
- $oldCatName = $this->category->getNameByID($release['categories_id']);
- $newCatName = $this->category->getNameByID($determinedCategory);
+ if ($this->echooutput === true && $show === 1) {
+ $groupName = $this->_groups->getNameByID($release['groups_id']);
+ $oldCatName = $this->category->getNameByID($release['categories_id']);
+ $newCatName = $this->category->getNameByID($determinedCategory);
- if ($type === 'PAR2, ') {
- echo PHP_EOL;
- }
+ if ($type === 'PAR2, ') {
+ echo PHP_EOL;
+ }
- echo
- ColorCLI::headerOver(PHP_EOL . 'New name: ') .
- ColorCLI::primary(substr($newName, 0, 299)) .
- ColorCLI::headerOver('Old name: ') .
- ColorCLI::primary($release['searchname']) .
- ColorCLI::headerOver('Use name: ') .
- ColorCLI::primary($release['name']) .
- ColorCLI::headerOver('New cat: ') .
- ColorCLI::primary($newCatName) .
- ColorCLI::headerOver('Old cat: ') .
- ColorCLI::primary($oldCatName) .
- ColorCLI::headerOver('Group: ') .
- ColorCLI::primary($groupName) .
- ColorCLI::headerOver('Method: ') .
- ColorCLI::primary($type . $method) .
- ColorCLI::headerOver('Releases ID: ') .
+ echo
+ ColorCLI::headerOver(PHP_EOL.'New name: ').
+ ColorCLI::primary(substr($newName, 0, 299)).
+ ColorCLI::headerOver('Old name: ').
+ ColorCLI::primary($release['searchname']).
+ ColorCLI::headerOver('Use name: ').
+ ColorCLI::primary($release['name']).
+ ColorCLI::headerOver('New cat: ').
+ ColorCLI::primary($newCatName).
+ ColorCLI::headerOver('Old cat: ').
+ ColorCLI::primary($oldCatName).
+ ColorCLI::headerOver('Group: ').
+ ColorCLI::primary($groupName).
+ ColorCLI::headerOver('Method: ').
+ ColorCLI::primary($type.$method).
+ ColorCLI::headerOver('Releases ID: ').
ColorCLI::primary($release['releases_id']);
- if (!empty($release['filename'])) {
- echo
- ColorCLI::headerOver('Filename: ') .
+ if (! empty($release['filename'])) {
+ echo
+ ColorCLI::headerOver('Filename: ').
ColorCLI::primary($release['filename']);
- }
+ }
- if ($type !== 'PAR2, ') {
- echo PHP_EOL;
- }
- }
+ if ($type !== 'PAR2, ') {
+ echo PHP_EOL;
+ }
+ }
- $newTitle = $this->pdo->escapeString(substr($newName, 0, 299));
+ $newTitle = $this->pdo->escapeString(substr($newName, 0, 299));
- if ($echo === true) {
- if ($nameStatus === 1) {
- $status = '';
- switch ($type) {
+ if ($echo === true) {
+ if ($nameStatus === 1) {
+ $status = '';
+ switch ($type) {
case 'NFO, ':
$status = 'isrenamed = 1, iscategorized = 1, proc_nfo = 1,';
break;
@@ -867,7 +863,7 @@ class NameFixer
$status = 'isrenamed = 1, iscategorized = 1, proc_srr = 1,';
break;
}
- $this->pdo->queryExec(
+ $this->pdo->queryExec(
sprintf('
UPDATE releases
SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL,
@@ -881,10 +877,10 @@ class NameFixer
$release['releases_id']
)
);
- $this->sphinx->updateRelease($release['releases_id'], $this->pdo);
- } else {
- $newTitle = $this->pdo->escapeString(substr($newName, 0, 299));
- $this->pdo->queryExec(
+ $this->sphinx->updateRelease($release['releases_id'], $this->pdo);
+ } else {
+ $newTitle = $this->pdo->escapeString(substr($newName, 0, 299));
+ $this->pdo->queryExec(
sprintf('
UPDATE releases
SET videos_id = 0, tv_episodes_id = 0, imdbid = NULL, musicinfo_id = NULL,
@@ -897,33 +893,32 @@ class NameFixer
$release['releases_id']
)
);
- $this->sphinx->updateRelease($release['releases_id'], $this->pdo);
- }
- }
- }
- }
- $this->done = true;
- }
+ $this->sphinx->updateRelease($release['releases_id'], $this->pdo);
+ }
+ }
+ }
+ }
+ $this->done = true;
+ }
- /**
- * Echo a updated release name to CLI.
- *
- * @param array $data
- * array(
- * 'new_name' => (string) The new release search name.
- * 'old_name' => (string) The old release search name.
- * 'new_category' => (string) The new category name or ID for the release.
- * 'old_category' => (string) The old category name or ID for the release.
- * 'group' => (string) The group name or ID of the release.
- * 'release_id' => (int) The ID of the release.
- * 'method' => (string) The method used to rename the release.
- * )
- *
- * @access public
- * @static
- * @void
- */
- public static function echoChangedReleaseName(array $data =
+ /**
+ * Echo a updated release name to CLI.
+ *
+ * @param array $data
+ * array(
+ * 'new_name' => (string) The new release search name.
+ * 'old_name' => (string) The old release search name.
+ * 'new_category' => (string) The new category name or ID for the release.
+ * 'old_category' => (string) The old category name or ID for the release.
+ * 'group' => (string) The group name or ID of the release.
+ * 'release_id' => (int) The ID of the release.
+ * 'method' => (string) The method used to rename the release.
+ * )
+ *
+ * @static
+ * @void
+ */
+ public static function echoChangedReleaseName(array $data =
[
'new_name' => '',
'old_name' => '',
@@ -931,89 +926,87 @@ class NameFixer
'old_category' => '',
'group' => '',
'releases_id' => 0,
- 'method' => ''
+ 'method' => '',
]
- ): void
- {
- echo
- PHP_EOL .
- ColorCLI::headerOver('New name: ') . ColorCLI::primaryOver($data['new_name']) . PHP_EOL .
- ColorCLI::headerOver('Old name: ') . ColorCLI::primaryOver($data['old_name']) . PHP_EOL .
- ColorCLI::headerOver('New category: ') . ColorCLI::primaryOver($data['new_category']) . PHP_EOL .
- ColorCLI::headerOver('Old category: ') . ColorCLI::primaryOver($data['old_category']) . PHP_EOL .
- ColorCLI::headerOver('Group: ') . ColorCLI::primaryOver($data['group']) . PHP_EOL .
- ColorCLI::headerOver('Releases ID: ') . ColorCLI::primaryOver($data['releases_id']) . PHP_EOL .
- ColorCLI::headerOver('Method: ') . ColorCLI::primaryOver($data['method']) . PHP_EOL;
- }
+ ): void {
+ echo
+ PHP_EOL.
+ ColorCLI::headerOver('New name: ').ColorCLI::primaryOver($data['new_name']).PHP_EOL.
+ ColorCLI::headerOver('Old name: ').ColorCLI::primaryOver($data['old_name']).PHP_EOL.
+ ColorCLI::headerOver('New category: ').ColorCLI::primaryOver($data['new_category']).PHP_EOL.
+ ColorCLI::headerOver('Old category: ').ColorCLI::primaryOver($data['old_category']).PHP_EOL.
+ ColorCLI::headerOver('Group: ').ColorCLI::primaryOver($data['group']).PHP_EOL.
+ ColorCLI::headerOver('Releases ID: ').ColorCLI::primaryOver($data['releases_id']).PHP_EOL.
+ ColorCLI::headerOver('Method: ').ColorCLI::primaryOver($data['method']).PHP_EOL;
+ }
- /**
- * Match a PreDB title to a release name or searchname using an exact full-text match
- * @param $pre
- * @param $echo
- * @param $namestatus
- * @param $echooutput
- * @param $show
- *
- * @return int
- */
- public function matchPredbFT($pre, $echo, $namestatus, $echooutput, $show): int
- {
- $matching = $total = 0;
+ /**
+ * Match a PreDB title to a release name or searchname using an exact full-text match.
+ * @param $pre
+ * @param $echo
+ * @param $namestatus
+ * @param $echooutput
+ * @param $show
+ *
+ * @return int
+ */
+ public function matchPredbFT($pre, $echo, $namestatus, $echooutput, $show): int
+ {
+ $matching = $total = 0;
- $join = $this->_preFTsearchQuery($pre['title']);
+ $join = $this->_preFTsearchQuery($pre['title']);
- if ($join === '') {
+ if ($join === '') {
+ return $matching;
+ }
- return $matching;
- }
-
- //Find release matches with fulltext and then identify exact matches with cleaned LIKE string
- $res = $this->pdo->queryDirect(
- sprintf("
+ //Find release matches with fulltext and then identify exact matches with cleaned LIKE string
+ $res = $this->pdo->queryDirect(
+ sprintf('
SELECT r.id AS releases_id, r.name, r.searchname,
r.fromname, r.groups_id, r.categories_id
FROM releases r
- %1\$s
- AND (r.name %2\$s OR r.searchname %2\$s)
+ %1$s
+ AND (r.name %2$s OR r.searchname %2$s)
AND r.predb_id = 0
- LIMIT 21",
+ LIMIT 21',
$join,
$this->pdo->likeString($pre['title'], true, true)
)
);
- if ($res !== false) {
- $total = $res->rowCount();
- }
+ if ($res !== false) {
+ $total = $res->rowCount();
+ }
- // Run if row count is positive, but do not run if row count exceeds 10 (as this is likely a failed title match)
- if ($total > 0 && $total <= 15 && $res instanceof \Traversable) {
- foreach ($res as $row) {
- if ($pre['title'] !== $row['searchname']) {
- $this->updateRelease($row, $pre['title'], $method = 'Title Match source: ' . $pre['source'], $echo, 'PreDB FT Exact, ', $namestatus, $show, $pre['predb_id']);
- $matching++;
- } else {
- $this->_updateSingleColumn('predb_id', $pre['predb_id'], $row['releases_id']);
- }
- }
- } elseif ($total >= 16) {
- $matching = -1;
- }
+ // Run if row count is positive, but do not run if row count exceeds 10 (as this is likely a failed title match)
+ if ($total > 0 && $total <= 15 && $res instanceof \Traversable) {
+ foreach ($res as $row) {
+ if ($pre['title'] !== $row['searchname']) {
+ $this->updateRelease($row, $pre['title'], $method = 'Title Match source: '.$pre['source'], $echo, 'PreDB FT Exact, ', $namestatus, $show, $pre['predb_id']);
+ $matching++;
+ } else {
+ $this->_updateSingleColumn('predb_id', $pre['predb_id'], $row['releases_id']);
+ }
+ }
+ } elseif ($total >= 16) {
+ $matching = -1;
+ }
- return $matching;
- }
+ return $matching;
+ }
- /**
- * @param $preTitle
- *
- * @return string
- */
- protected function _preFTsearchQuery($preTitle): string
- {
- $join = '';
+ /**
+ * @param $preTitle
+ *
+ * @return string
+ */
+ protected function _preFTsearchQuery($preTitle): string
+ {
+ $join = '';
- if (strlen($preTitle) >= 15 && preg_match(self::PREDB_REGEX, $preTitle)) {
- switch (NN_RELEASE_SEARCH_TYPE) {
+ if (strlen($preTitle) >= 15 && preg_match(self::PREDB_REGEX, $preTitle)) {
+ switch (NN_RELEASE_SEARCH_TYPE) {
case ReleaseSearch::SPHINX:
$titlematch = SphinxSearch::escapeString($preTitle);
$join .= sprintf(
@@ -1025,7 +1018,7 @@ class NameFixer
case ReleaseSearch::FULLTEXT:
//Remove all non-printable chars from PreDB title
preg_match_all('#[a-zA-Z0-9]{3,}#', $preTitle, $matches, PREG_PATTERN_ORDER);
- $titlematch = '+' . implode(' +', $matches[0]);
+ $titlematch = '+'.implode(' +', $matches[0]);
$join .= sprintf(
"INNER JOIN release_search_data rs ON rs.releases_id = r.id
WHERE
@@ -1039,39 +1032,40 @@ class NameFixer
$join .= 'WHERE 1=1 ';
break;
}
- }
- return $join;
- }
+ }
- /**
- * Retrieves releases and their file names to attempt PreDB matches
- * Runs in a limited mode based on arguments passed or a full mode broken into chunks of entire DB
- *
- * @param array $args The CLI script arguments
- */
- public function getPreFileNames(array $args = []): void
- {
- $n = PHP_EOL;
+ return $join;
+ }
- $show = (isset($args[2]) && $args[2] === 'show') ? 1 : 0;
+ /**
+ * Retrieves releases and their file names to attempt PreDB matches
+ * Runs in a limited mode based on arguments passed or a full mode broken into chunks of entire DB.
+ *
+ * @param array $args The CLI script arguments
+ */
+ public function getPreFileNames(array $args = []): void
+ {
+ $n = PHP_EOL;
- if (isset($args[1]) && is_numeric($args[1])) {
- $limit = 'LIMIT ' . $args[1];
- $orderby = 'ORDER BY r.id DESC';
- } else {
- $maxrelid = 0;
- $orderby = 'ORDER BY r.id ASC';
- $limit = 'LIMIT 1000000';
- }
+ $show = (isset($args[2]) && $args[2] === 'show') ? 1 : 0;
- echo ColorCLI::header(PHP_EOL . 'Match PreFiles ' . $args[1] . ' Started at ' . date('g:i:s'));
- echo ColorCLI::primary('Matching predb filename to cleaned release_files.name.' . PHP_EOL);
+ if (isset($args[1]) && is_numeric($args[1])) {
+ $limit = 'LIMIT '.$args[1];
+ $orderby = 'ORDER BY r.id DESC';
+ } else {
+ $maxrelid = 0;
+ $orderby = 'ORDER BY r.id ASC';
+ $limit = 'LIMIT 1000000';
+ }
- do {
- $counter = $counted = 0;
- $timestart = time();
+ echo ColorCLI::header(PHP_EOL.'Match PreFiles '.$args[1].' Started at '.date('g:i:s'));
+ echo ColorCLI::primary('Matching predb filename to cleaned release_files.name.'.PHP_EOL);
- $query = $this->pdo->queryDirect(
+ do {
+ $counter = $counted = 0;
+ $timestart = time();
+
+ $query = $this->pdo->queryDirect(
sprintf("
SELECT r.id AS releases_id, r.name, r.searchname,
r.fromname, r.groups_id, r.categories_id,
@@ -1089,67 +1083,67 @@ class NameFixer
)
);
- if ($query !== false) {
- $total = $query->rowCount();
+ if ($query !== false) {
+ $total = $query->rowCount();
- if ($total > 0 && $query instanceof \Traversable) {
- echo ColorCLI::header($n . number_format($total) . ' releases to process.');
+ if ($total > 0 && $query instanceof \Traversable) {
+ echo ColorCLI::header($n.number_format($total).' releases to process.');
- foreach ($query as $row) {
- $success = $this->matchPredbFiles($row, true, 1, true, $show);
- if ($success === 1) {
- $counted++;
- }
- if ($show === 0) {
- $this->consoletools->overWritePrimary('Renamed Releases: [' . number_format($counted) . '] ' . $this->consoletools->percentString(++$counter, $total));
- }
- if (isset($maxrelid) && $row['releases_id'] > $maxrelid) {
- $maxrelid = $row['releases_id'];
- }
- }
- echo ColorCLI::header($n . 'Renamed ' . number_format($counted) . ' releases in ' . $this->consoletools->convertTime(time() - $timestart) . '.');
- } else {
- echo ColorCLI::info($n . 'Nothing to do.');
- break;
- }
- } else {
- break;
- }
- } while (isset($maxrelid));
- }
+ foreach ($query as $row) {
+ $success = $this->matchPredbFiles($row, true, 1, true, $show);
+ if ($success === 1) {
+ $counted++;
+ }
+ if ($show === 0) {
+ $this->consoletools->overWritePrimary('Renamed Releases: ['.number_format($counted).'] '.$this->consoletools->percentString(++$counter, $total));
+ }
+ if (isset($maxrelid) && $row['releases_id'] > $maxrelid) {
+ $maxrelid = $row['releases_id'];
+ }
+ }
+ echo ColorCLI::header($n.'Renamed '.number_format($counted).' releases in '.$this->consoletools->convertTime(time() - $timestart).'.');
+ } else {
+ echo ColorCLI::info($n.'Nothing to do.');
+ break;
+ }
+ } else {
+ break;
+ }
+ } while (isset($maxrelid));
+ }
- /**
- * Match a release filename to a PreDB filename or title.
- *
- * @param $release
- * @param boolean $echo
- * @param integer $namestatus
- * @param boolean $echooutput
- * @param integer $show
- *
- * @return int
- */
- public function matchPredbFiles($release, $echo, $namestatus, $echooutput, $show): int
- {
- $matching = 0;
- $pre = false;
+ /**
+ * Match a release filename to a PreDB filename or title.
+ *
+ * @param $release
+ * @param bool $echo
+ * @param int $namestatus
+ * @param bool $echooutput
+ * @param int $show
+ *
+ * @return int
+ */
+ public function matchPredbFiles($release, $echo, $namestatus, $echooutput, $show): int
+ {
+ $matching = 0;
+ $pre = false;
- foreach(explode('||', $release['filename']) AS $key => $fileName) {
- $this->_fileName = $fileName;
- $this->_cleanMatchFiles();
- $preMatch = preg_match('/(\d{2}\.\d{2}\.\d{2})+[\w-.]+[\w]$/i', $this->_fileName, $match);
- if ($preMatch) {
- $result = $this->pdo->queryOneRow(sprintf("SELECT filename AS filename FROM predb WHERE MATCH(filename) AGAINST ('$match[0]' IN BOOLEAN MODE)"));
- $preFTmatch = preg_match('/(\d{2}\.\d{2}\.\d{2})+[\w-.]+[\w]$/i', $result['filename'], $match1);
- if ($preFTmatch) {
- if ($match[0] === $match1[0]) {
- $this->_fileName = $result['filename'];
- }
- }
- }
+ foreach (explode('||', $release['filename']) as $key => $fileName) {
+ $this->_fileName = $fileName;
+ $this->_cleanMatchFiles();
+ $preMatch = preg_match('/(\d{2}\.\d{2}\.\d{2})+[\w-.]+[\w]$/i', $this->_fileName, $match);
+ if ($preMatch) {
+ $result = $this->pdo->queryOneRow(sprintf("SELECT filename AS filename FROM predb WHERE MATCH(filename) AGAINST ('$match[0]' IN BOOLEAN MODE)"));
+ $preFTmatch = preg_match('/(\d{2}\.\d{2}\.\d{2})+[\w-.]+[\w]$/i', $result['filename'], $match1);
+ if ($preFTmatch) {
+ if ($match[0] === $match1[0]) {
+ $this->_fileName = $result['filename'];
+ }
+ }
+ }
- if ($this->_fileName !== '') {
- $pre = $this->pdo->queryOneRow(
+ if ($this->_fileName !== '') {
+ $pre = $this->pdo->queryOneRow(
sprintf('
SELECT id AS predb_id, title, source
FROM predb
@@ -1158,36 +1152,37 @@ class NameFixer
$this->pdo->escapeString($this->_fileName)
)
);
- }
+ }
- if (!empty($pre)) {
- $release['filename'] = $this->_fileName;
- if ($pre['title'] !== $release['searchname']) {
- $this->updateRelease($release, $pre['title'], $method = 'file matched source: ' . $pre['source'], $echo, 'PreDB file match, ', $namestatus, $show, $pre['predb_id']);
- } else {
- $this->_updateSingleColumn('predb_id', $pre['predb_id'], $release['releases_id']);
- }
- $matching++;
- break;
- }
- }
- return $matching;
- }
+ if (! empty($pre)) {
+ $release['filename'] = $this->_fileName;
+ if ($pre['title'] !== $release['searchname']) {
+ $this->updateRelease($release, $pre['title'], $method = 'file matched source: '.$pre['source'], $echo, 'PreDB file match, ', $namestatus, $show, $pre['predb_id']);
+ } else {
+ $this->_updateSingleColumn('predb_id', $pre['predb_id'], $release['releases_id']);
+ }
+ $matching++;
+ break;
+ }
+ }
- /**
- * Cleans file names for PreDB Match
- *
- *
- * @return string
- */
- protected function _cleanMatchFiles(): string
- {
+ return $matching;
+ }
+
+ /**
+ * Cleans file names for PreDB Match.
+ *
+ *
+ * @return string
+ */
+ protected function _cleanMatchFiles(): string
+ {
// first strip all non-printing chars from filename
- $this->_fileName = Utility::stripNonPrintingChars($this->_fileName);
+ $this->_fileName = Utility::stripNonPrintingChars($this->_fileName);
- if (strlen($this->_fileName) > 0 && strpos($this->_fileName, '.') !== 0) {
- switch (true) {
+ if (strlen($this->_fileName) > 0 && strpos($this->_fileName, '.') !== 0) {
+ switch (true) {
case strpos($this->_fileName, '.') !== false:
//some filenames start with a period that ends up creating bad matches so we don't process them
@@ -1215,37 +1210,38 @@ class NameFixer
$this->_fileName = preg_replace('/^\d{2}-/', '', $this->_fileName);
}
- return trim($this->_fileName);
- }
- return false;
- }
+ return trim($this->_fileName);
+ }
- /**
- * Match a Hash from the predb to a release.
- *
- * @param string $hash
- * @param $release
- * @param $echo
- * @param $namestatus
- * @param boolean $echooutput
- * @param $show
- *
- * @return int
- */
- public function matchPredbHash($hash, $release, $echo, $namestatus, $echooutput, $show): int
- {
- $pdo = $this->pdo;
- $matching = 0;
- $this->matched = false;
+ return false;
+ }
- // Determine MD5 or SHA1
- if (strlen($hash) === 40) {
- $hashtype = 'SHA1, ';
- } else {
- $hashtype = 'MD5, ';
- }
+ /**
+ * Match a Hash from the predb to a release.
+ *
+ * @param string $hash
+ * @param $release
+ * @param $echo
+ * @param $namestatus
+ * @param bool $echooutput
+ * @param $show
+ *
+ * @return int
+ */
+ public function matchPredbHash($hash, $release, $echo, $namestatus, $echooutput, $show): int
+ {
+ $pdo = $this->pdo;
+ $matching = 0;
+ $this->matched = false;
- $row = $pdo->queryOneRow(
+ // Determine MD5 or SHA1
+ if (strlen($hash) === 40) {
+ $hashtype = 'SHA1, ';
+ } else {
+ $hashtype = 'MD5, ';
+ }
+
+ $row = $pdo->queryOneRow(
sprintf('
SELECT p.id AS predb_id, p.title, p.source
FROM predb p INNER JOIN predb_hashes h ON h.predb_id = p.id
@@ -1255,49 +1251,48 @@ class NameFixer
)
);
- if ($row !== false) {
- if ($row['title'] !== $release['searchname']) {
- $this->updateRelease($release, $row['title'], $method = 'predb hash release name: ' . $row['source'], $echo, $hashtype, $namestatus, $show, $row['predb_id']);
- $matching++;
- }
- } else {
- $this->_updateSingleColumn('dehashstatus', $release['dehashstatus'] - 1, $release['releases_id']);
- }
+ if ($row !== false) {
+ if ($row['title'] !== $release['searchname']) {
+ $this->updateRelease($release, $row['title'], $method = 'predb hash release name: '.$row['source'], $echo, $hashtype, $namestatus, $show, $row['predb_id']);
+ $matching++;
+ }
+ } else {
+ $this->_updateSingleColumn('dehashstatus', $release['dehashstatus'] - 1, $release['releases_id']);
+ }
- return $matching;
- }
+ return $matching;
+ }
- /**
- * Check the array using regex for a clean name.
- *
- * @param $release
- * @param boolean $echo
- * @param string $type
- * @param $namestatus
- * @param $show
- * @param boolean $preid
- *
- * @return boolean
- */
- public function checkName($release, $echo, $type, $namestatus, $show, $preid = false): bool
- {
- // Get pre style name from releases.name
- if (preg_match_all(self::PREDB_REGEX, $release['textstring'], $matches) && !preg_match('/Source\s\:/i', $release['textstring'])) {
- foreach ($matches as $match) {
- foreach ($match as $val) {
- $title = $this->pdo->queryOneRow('SELECT title, id from predb WHERE title = ' . $this->pdo->escapeString(trim($val)));
- if ($title !== false) {
- $this->updateRelease($release, $title['title'], $method = 'preDB: Match', $echo, $type, $namestatus, $show, $title['id']);
- $preid = true;
- }
- }
- }
- }
+ /**
+ * Check the array using regex for a clean name.
+ *
+ * @param $release
+ * @param bool $echo
+ * @param string $type
+ * @param $namestatus
+ * @param $show
+ * @param bool $preid
+ *
+ * @return bool
+ */
+ public function checkName($release, $echo, $type, $namestatus, $show, $preid = false): bool
+ {
+ // Get pre style name from releases.name
+ if (preg_match_all(self::PREDB_REGEX, $release['textstring'], $matches) && ! preg_match('/Source\s\:/i', $release['textstring'])) {
+ foreach ($matches as $match) {
+ foreach ($match as $val) {
+ $title = $this->pdo->queryOneRow('SELECT title, id from predb WHERE title = '.$this->pdo->escapeString(trim($val)));
+ if ($title !== false) {
+ $this->updateRelease($release, $title['title'], $method = 'preDB: Match', $echo, $type, $namestatus, $show, $title['id']);
+ $preid = true;
+ }
+ }
+ }
+ }
- // if only processing for PreDB match skip to return
- if ($preid !== true) {
-
- switch ($type) {
+ // if only processing for PreDB match skip to return
+ if ($preid !== true) {
+ switch ($type) {
case 'PAR2, ':
$this->fileCheck($release, $echo, $type, $namestatus, $show);
break;
@@ -1327,9 +1322,9 @@ class NameFixer
$this->appCheck($release, $echo, $type, $namestatus, $show);
}
- // set NameFixer process flags after run
- if ($namestatus === 1 && $this->matched === false) {
- switch ($type) {
+ // set NameFixer process flags after run
+ if ($namestatus === 1 && $this->matched === false) {
+ switch ($type) {
case 'NFO, ':
$this->_updateSingleColumn('proc_nfo', self::PROC_NFO_DONE, $release['releases_id']);
break;
@@ -1349,24 +1344,24 @@ class NameFixer
$this->_updateSingleColumn('proc_uid', self::PROC_UID_DONE, $release['releases_id']);
break;
}
- }
- }
+ }
+ }
- return $this->matched;
- }
+ return $this->matched;
+ }
- /** This function updates a single variable column in releases
- * The first parameter is the column to update, the second is the value
- * The final parameter is the ID of the release to update
- *
- * @param string $column
- * @param integer $status
- * @param integer $id
- */
- public function _updateSingleColumn($column = '', $status = 0, $id = 0): void
- {
- if ($column !== '' && $id !== 0) {
- $this->pdo->queryExec(
+ /** This function updates a single variable column in releases
+ * The first parameter is the column to update, the second is the value
+ * The final parameter is the ID of the release to update.
+ *
+ * @param string $column
+ * @param int $status
+ * @param int $id
+ */
+ public function _updateSingleColumn($column = '', $status = 0, $id = 0): void
+ {
+ if ($column !== '' && $id !== 0) {
+ $this->pdo->queryExec(
sprintf('
UPDATE releases
SET %s = %s
@@ -1376,226 +1371,220 @@ class NameFixer
$id
)
);
- }
- }
+ }
+ }
- /**
- * Look for a TV name.
- *
- * @param $release
- * @param boolean $echo
- * @param string $type
- * @param $namestatus
- * @param $show
- */
- public function tvCheck($release, $echo, $type, $namestatus, $show): void
- {
- $result = [];
+ /**
+ * Look for a TV name.
+ *
+ * @param $release
+ * @param bool $echo
+ * @param string $type
+ * @param $namestatus
+ * @param $show
+ */
+ public function tvCheck($release, $echo, $type, $namestatus, $show): void
+ {
+ $result = [];
- if ($this->done === false && $this->relid !== (int)$release['releases_id']) {
+ if ($this->done === false && $this->relid !== (int) $release['releases_id']) {
+ if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|(?updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.source.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[-\w.\',;& ]+((19|20)\d\d)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.year.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[-\w.\',;& ]+(480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.resolution.source.vcodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.source.vcodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.acodec.source.res.vcodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -]((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.year.###(season/episode).source.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w(19|20)\d\d[._ -]\d{2}[._ -]\d{2}[._ -](IndyCar|NBA|NCW(T|Y)S|NNS|NSCS?)([._ -](19|20)\d\d)?[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'tvCheck: Sports', $echo, $type, $namestatus, $show);
+ }
+ }
+ }
- if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|(?updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.source.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[-\w.\',;& ]+((19|20)\d\d)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.year.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[-\w.\',;& ]+(480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.Text.resolution.source.vcodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.source.vcodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.SxxExx.acodec.source.res.vcodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -]((s\d{1,2}[._ -]?[bde]\d{1,2})|\d{1,2}x\d{2}|ep[._ -]?\d{2})[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'tvCheck: Title.year.###(season/episode).source.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w(19|20)\d\d[._ -]\d{2}[._ -]\d{2}[._ -](IndyCar|NBA|NCW(T|Y)S|NNS|NSCS?)([._ -](19|20)\d\d)?[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'tvCheck: Sports', $echo, $type, $namestatus, $show);
- }
- }
- }
+ /**
+ * Look for a movie name.
+ *
+ * @param $release
+ * @param bool $echo
+ * @param string $type
+ * @param $namestatus
+ * @param $show
+ */
+ public function movieCheck($release, $echo, $type, $namestatus, $show): void
+ {
+ $result = [];
- /**
- * Look for a movie name.
- *
- * @param $release
- * @param boolean $echo
- * @param string $type
- * @param $namestatus
- * @param $show
- */
- public function movieCheck($release, $echo, $type, $namestatus, $show): void
- {
- $result = [];
+ if ($this->done === false && $this->relid !== (int) $release['releases_id']) {
+ if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[-\w.\',;& ]+(480|720|1080)[ip][._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.Text.res.vcod.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[._ -](480|720|1080)[ip][-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.vcodec.res.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.vcodec.acodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+(Brazilian|Chinese|Croatian|Danish|Deutsch|Dutch|Estonian|English|Finnish|Flemish|Francais|French|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.language.acodec.source.vcodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.source.acodec.vcodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.source.vcodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.resolution.acodec.vcodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.acodec.vcodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BR(RIP)?|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -][-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.res.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -][-\w.\',;& ]+[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BR(RIP)?|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.eptitle.source.vcodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+(480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.resolution.source.acodec.vcodec.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+(480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[-\w.\',;& ]+(BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -]((19|20)\d\d)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.resolution.acodec.eptitle.source.year.group', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+(Brazilian|Chinese|Croatian|Danish|Deutsch|Dutch|Estonian|English|Finnish|Flemish|Francais|French|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)[._ -]((19|20)\d\d)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.language.year.acodec.src', $echo, $type, $namestatus, $show);
+ }
+ }
+ }
- if ($this->done === false && $this->relid !== (int)$release['releases_id']) {
+ /**
+ * Look for a game name.
+ *
+ * @param $release
+ * @param bool $echo
+ * @param string $type
+ * @param $namestatus
+ * @param $show
+ */
+ public function gameCheck($release, $echo, $type, $namestatus, $show): void
+ {
+ $result = [];
- if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[-\w.\',;& ]+(480|720|1080)[ip][._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.Text.res.vcod.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[._ -](480|720|1080)[ip][-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.vcodec.res.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.vcodec.acodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+(Brazilian|Chinese|Croatian|Danish|Deutsch|Dutch|Estonian|English|Finnish|Flemish|Francais|French|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.language.acodec.source.vcodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.source.acodec.vcodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.source.vcodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.resolution.acodec.vcodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -](480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.resolution.acodec.vcodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/[-\w.\',;& ]+((19|20)\d\d)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BR(RIP)?|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](480|720|1080)[ip][._ -][-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.source.res.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+((19|20)\d\d)[._ -][-\w.\',;& ]+[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BR(RIP)?|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.year.eptitle.source.vcodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+(480|720|1080)[ip][._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](DivX|[HX][._ -]?264|MPEG2|XviD(HD)?|WMV)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.resolution.source.acodec.vcodec.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+(480|720|1080)[ip][._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[-\w.\',;& ]+(BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[._ -]((19|20)\d\d)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.resolution.acodec.eptitle.source.year.group', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+(Brazilian|Chinese|Croatian|Danish|Deutsch|Dutch|Estonian|English|Finnish|Flemish|Francais|French|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)[._ -]((19|20)\d\d)[._ -](AAC( LC)?|AC-?3|DD5([._ -]1)?|(A_)?DTS-?(HD)?|Dolby( ?TrueHD)?|MP3|TrueHD)[._ -](BD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'movieCheck: Title.language.year.acodec.src', $echo, $type, $namestatus, $show);
- }
- }
- }
+ if ($this->done === false && $this->relid !== (int) $release['releases_id']) {
+ if (preg_match('/\w[-\w.\',;& ]+(ASIA|DLC|EUR|GOTY|JPN|KOR|MULTI\d{1}|NTSCU?|PAL|RF|Region[._ -]?Free|USA|XBLA)[._ -](DLC[._ -]Complete|FRENCH|GERMAN|MULTI\d{1}|PROPER|PSN|READ[._ -]?NFO|UMD)?[._ -]?(GC|NDS|NGC|PS3|PSP|WII|XBOX(360)?)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'gameCheck: Videogames 1', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+(GC|NDS|NGC|PS3|WII|XBOX(360)?)[._ -](DUPLEX|iNSOMNi|OneUp|STRANGE|SWAG|SKY)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'gameCheck: Videogames 2', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[\w.\',;-].+-OUTLAWS/i', $release['textstring'], $result)) {
+ $result = str_replace('OUTLAWS', 'PC GAME OUTLAWS', $result['0']);
+ $this->updateRelease($release, $result['0'], $method = 'gameCheck: PC Games -OUTLAWS', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[\w.\',;-].+\-ALiAS/i', $release['textstring'], $result)) {
+ $newresult = str_replace('-ALiAS', ' PC GAME ALiAS', $result['0']);
+ $this->updateRelease($release, $newresult, $method = 'gameCheck: PC Games -ALiAS', $echo, $type, $namestatus, $show);
+ }
+ }
+ }
- /**
- * Look for a game name.
- *
- * @param $release
- * @param boolean $echo
- * @param string $type
- * @param $namestatus
- * @param $show
- */
- public function gameCheck($release, $echo, $type, $namestatus, $show): void
- {
- $result = [];
+ /**
+ * Look for a app name.
+ *
+ * @param $release
+ * @param bool $echo
+ * @param string $type
+ * @param $namestatus
+ * @param $show
+ */
+ public function appCheck($release, $echo, $type, $namestatus, $show): void
+ {
+ $result = [];
- if ($this->done === false && $this->relid !== (int)$release['releases_id']) {
+ if ($this->done === false && $this->relid !== (int) $release['releases_id']) {
+ if (preg_match('/\w[-\w.\',;& ]+(\d{1,10}|Linux|UNIX)[._ -](RPM)?[._ -]?(X64)?[._ -]?(Incl)[._ -](Keygen)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'appCheck: Apps 1', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/\w[-\w.\',;& ]+\d{1,8}[._ -](winall-freeware)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['0'], $method = 'appCheck: Apps 2', $echo, $type, $namestatus, $show);
+ }
+ }
+ }
- if (preg_match('/\w[-\w.\',;& ]+(ASIA|DLC|EUR|GOTY|JPN|KOR|MULTI\d{1}|NTSCU?|PAL|RF|Region[._ -]?Free|USA|XBLA)[._ -](DLC[._ -]Complete|FRENCH|GERMAN|MULTI\d{1}|PROPER|PSN|READ[._ -]?NFO|UMD)?[._ -]?(GC|NDS|NGC|PS3|PSP|WII|XBOX(360)?)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'gameCheck: Videogames 1', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+(GC|NDS|NGC|PS3|WII|XBOX(360)?)[._ -](DUPLEX|iNSOMNi|OneUp|STRANGE|SWAG|SKY)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'gameCheck: Videogames 2', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[\w.\',;-].+-OUTLAWS/i', $release['textstring'], $result)) {
- $result = str_replace('OUTLAWS', 'PC GAME OUTLAWS', $result['0']);
- $this->updateRelease($release, $result['0'], $method = 'gameCheck: PC Games -OUTLAWS', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[\w.\',;-].+\-ALiAS/i', $release['textstring'], $result)) {
- $newresult = str_replace('-ALiAS', ' PC GAME ALiAS', $result['0']);
- $this->updateRelease($release, $newresult, $method = 'gameCheck: PC Games -ALiAS', $echo, $type, $namestatus, $show);
- }
- }
- }
+ /*
+ * Just for NFOS.
+ */
- /**
- * Look for a app name.
- *
- * @param $release
- * @param boolean $echo
- * @param string $type
- * @param $namestatus
- * @param $show
- */
- public function appCheck($release, $echo, $type, $namestatus, $show): void
- {
- $result = [];
+ /**
+ * TV.
+ *
+ * @param $release
+ * @param bool $echo
+ * @param string $type
+ * @param $namestatus
+ * @param $show
+ */
+ public function nfoCheckTV($release, $echo, $type, $namestatus, $show): void
+ {
+ $result = [];
- if ($this->done === false && $this->relid !== (int)$release['releases_id']) {
+ if ($this->done === false && $this->relid !== (int) $release['releases_id']) {
+ if (preg_match('/:\s*.*[\\\\\/]([A-Z0-9].+?S\d+[.-_ ]?[ED]\d+.+?)\.\w{2,}\s+/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['1'], $method = 'nfoCheck: Generic TV 1', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/(?:(\:\s{1,}))(.+?S\d{1,3}[.-_ ]?[ED]\d{1,3}.+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic TV 2', $echo, $type, $namestatus, $show);
+ }
+ }
+ }
- if (preg_match('/\w[-\w.\',;& ]+(\d{1,10}|Linux|UNIX)[._ -](RPM)?[._ -]?(X64)?[._ -]?(Incl)[._ -](Keygen)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'appCheck: Apps 1', $echo, $type, $namestatus, $show);
- } else if (preg_match('/\w[-\w.\',;& ]+\d{1,8}[._ -](winall-freeware)[-\w.\',;& ]+\w/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['0'], $method = 'appCheck: Apps 2', $echo, $type, $namestatus, $show);
- }
- }
- }
+ /**
+ * Movies.
+ *
+ * @param $release
+ * @param bool $echo
+ * @param string $type
+ * @param $namestatus
+ * @param $show
+ */
+ public function nfoCheckMov($release, $echo, $type, $namestatus, $show): void
+ {
+ $result = [];
- /*
- * Just for NFOS.
- */
+ if ($this->done === false && $this->relid !== (int) $release['releases_id']) {
+ if (preg_match('/(?:((?!Source\s)\:\s{1,}))(.+?(19|20)\d\d.+?(BDRip|bluray|DVD(R|Rip)?|XVID).+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 1', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/(?:(\s{2,}))((?!Source).+?[\.\-_ ](19|20)\d\d.+?(BDRip|bluray|DVD(R|Rip)?|XVID).+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 2', $echo, $type, $namestatus, $show);
+ } elseif (preg_match('/(?:(\s{2,}))(.+?[\.\-_ ](NTSC|MULTi).+?(MULTi|DVDR)[\.\-_ ].+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) {
+ $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 3', $echo, $type, $namestatus, $show);
+ }
+ }
+ }
- /**
- * TV.
- *
- * @param $release
- * @param boolean $echo
- * @param string $type
- * @param $namestatus
- * @param $show
- */
- public function nfoCheckTV($release, $echo, $type, $namestatus, $show): void
- {
- $result = [];
+ /**
+ * @param $release
+ * @param bool $echo
+ * @param string $type
+ * @param $namestatus
+ * @param $show
+ */
+ public function nfoCheckMus($release, $echo, $type, $namestatus, $show): void
+ {
+ $result = [];
- if ($this->done === false && $this->relid !== (int)$release['releases_id']) {
+ if ($this->done === false && $this->relid !== (int) $release['releases_id'] && preg_match('/(?:\s{2,})(.+?-FM-\d{2}-\d{2})/i', $release['textstring'], $result)) {
+ $newname = str_replace('-FM-', '-FM-Radio-MP3-', $result['1']);
+ $this->updateRelease($release, $newname, $method = 'nfoCheck: Music FM RADIO', $echo, $type, $namestatus, $show);
+ }
+ }
- if (preg_match('/:\s*.*[\\\\\/]([A-Z0-9].+?S\d+[.-_ ]?[ED]\d+.+?)\.\w{2,}\s+/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['1'], $method = 'nfoCheck: Generic TV 1', $echo, $type, $namestatus, $show);
- } else if (preg_match('/(?:(\:\s{1,}))(.+?S\d{1,3}[.-_ ]?[ED]\d{1,3}.+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic TV 2', $echo, $type, $namestatus, $show);
- }
- }
- }
+ /**
+ * Title (year).
+ *
+ * @param $release
+ * @param bool $echo
+ * @param string $type
+ * @param $namestatus
+ * @param $show
+ */
+ public function nfoCheckTY($release, $echo, $type, $namestatus, $show): void
+ {
+ $result = [];
- /**
- * Movies.
- *
- * @param $release
- * @param boolean $echo
- * @param string $type
- * @param $namestatus
- * @param $show
- */
- public function nfoCheckMov($release, $echo, $type, $namestatus, $show): void
- {
- $result = [];
-
- if ($this->done === false && $this->relid !== (int)$release['releases_id']) {
-
- if (preg_match('/(?:((?!Source\s)\:\s{1,}))(.+?(19|20)\d\d.+?(BDRip|bluray|DVD(R|Rip)?|XVID).+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 1', $echo, $type, $namestatus, $show);
- } else if (preg_match('/(?:(\s{2,}))((?!Source).+?[\.\-_ ](19|20)\d\d.+?(BDRip|bluray|DVD(R|Rip)?|XVID).+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 2', $echo, $type, $namestatus, $show);
- } else if (preg_match('/(?:(\s{2,}))(.+?[\.\-_ ](NTSC|MULTi).+?(MULTi|DVDR)[\.\-_ ].+?)(\s{2,}|\r|\n)/i', $release['textstring'], $result)) {
- $this->updateRelease($release, $result['2'], $method = 'nfoCheck: Generic Movies 3', $echo, $type, $namestatus, $show);
- }
- }
- }
-
- /**
- * @param $release
- * @param boolean $echo
- * @param string $type
- * @param $namestatus
- * @param $show
- */
- public function nfoCheckMus($release, $echo, $type, $namestatus, $show): void
- {
- $result = [];
-
- if ($this->done === false && $this->relid !== (int)$release['releases_id'] && preg_match('/(?:\s{2,})(.+?-FM-\d{2}-\d{2})/i', $release['textstring'], $result)) {
- $newname = str_replace('-FM-', '-FM-Radio-MP3-', $result['1']);
- $this->updateRelease($release, $newname, $method = 'nfoCheck: Music FM RADIO', $echo, $type, $namestatus, $show);
- }
- }
-
- /**
- * Title (year)
- *
- * @param $release
- * @param boolean $echo
- * @param string $type
- * @param $namestatus
- * @param $show
- */
- public function nfoCheckTY($release, $echo, $type, $namestatus, $show): void
- {
- $result = [];
-
- if ($this->done === false && $this->relid !== (int)$release['releases_id']) {
- if (preg_match('/(\w[-\w`~!@#$%^&*()_+={}|"<>?\[\]\\;\',.\/ ]+\s?\((19|20)\d\d\))/i', $release['textstring'], $result) && !preg_match('/\.pdf|Audio ?Book/i', $release['textstring'])) {
- $releasename = $result[0];
- if (preg_match('/(idiomas|lang|language|langue|sprache).*?\b(?PBrazilian|Chinese|Croatian|Danish|DE|Deutsch|Dutch|Estonian|ES|English|Englisch|Finnish|Flemish|Francais|French|FR|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)\b/i', $release['textstring'], $result)) {
- switch ($result['lang']) {
+ if ($this->done === false && $this->relid !== (int) $release['releases_id']) {
+ if (preg_match('/(\w[-\w`~!@#$%^&*()_+={}|"<>?\[\]\\;\',.\/ ]+\s?\((19|20)\d\d\))/i', $release['textstring'], $result) && ! preg_match('/\.pdf|Audio ?Book/i', $release['textstring'])) {
+ $releasename = $result[0];
+ if (preg_match('/(idiomas|lang|language|langue|sprache).*?\b(?PBrazilian|Chinese|Croatian|Danish|DE|Deutsch|Dutch|Estonian|ES|English|Englisch|Finnish|Flemish|Francais|French|FR|German|Greek|Hebrew|Icelandic|Italian|Japenese|Japan|Japanese|Korean|Latin|Nordic|Norwegian|Polish|Portuguese|Russian|Serbian|Slovenian|Swedish|Spanisch|Spanish|Thai|Turkish)\b/i', $release['textstring'], $result)) {
+ switch ($result['lang']) {
case 'DE':
$result['lang'] = 'DUTCH';
break;
@@ -1611,11 +1600,11 @@ class NameFixer
default:
break;
}
- $releasename = $releasename . '.' . $result['lang'];
- }
+ $releasename = $releasename.'.'.$result['lang'];
+ }
- if (preg_match('/(frame size|(video )?res(olution)?|video).*?(?P(272|336|480|494|528|608|\(?640|688|704|720x480|810|816|820|1 ?080|1280( \@)?|1 ?920(x1080)?))/i', $release['textstring'], $result)) {
- switch ($result['res']) {
+ if (preg_match('/(frame size|(video )?res(olution)?|video).*?(?P(272|336|480|494|528|608|\(?640|688|704|720x480|810|816|820|1 ?080|1280( \@)?|1 ?920(x1080)?))/i', $release['textstring'], $result)) {
+ switch ($result['res']) {
case '272':
case '336':
case '480':
@@ -1645,9 +1634,9 @@ class NameFixer
break;
}
- $releasename = $releasename . '.' . $result['res'];
- } else if (preg_match('/(largeur|width).*?(?P(\(?640|688|704|720|1280( \@)?|1 ?920))/i', $release['textstring'], $result)) {
- switch ($result['res']) {
+ $releasename = $releasename.'.'.$result['res'];
+ } elseif (preg_match('/(largeur|width).*?(?P(\(?640|688|704|720|1280( \@)?|1 ?920))/i', $release['textstring'], $result)) {
+ switch ($result['res']) {
case '640':
case '(640':
case '688':
@@ -1665,12 +1654,11 @@ class NameFixer
break;
}
- $releasename = $releasename . '.' . $result['res'];
- }
+ $releasename = $releasename.'.'.$result['res'];
+ }
- if (preg_match('/source.*?\b(?PBD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)\b/i', $release['textstring'], $result)) {
-
- switch ($result['source']) {
+ if (preg_match('/source.*?\b(?PBD(-?(25|50|RIP))?|Blu-?Ray ?(3D)?|BRRIP|CAM(RIP)?|DBrip|DTV|DVD\-?(5|9|(R(IP)?|scr(eener)?))?|[HPS]D?(RIP|TV(RIP)?)?|NTSC|PAL|R5|Ripped |S?VCD|scr(eener)?|SAT(RIP)?|TS|VHS(RIP)?|VOD|WEB-DL)\b/i', $release['textstring'], $result)) {
+ switch ($result['source']) {
case 'BD':
$result['source'] = 'Bluray.x264';
break;
@@ -1693,9 +1681,9 @@ class NameFixer
$result['source'] = 'DVDRIP';
}
- $releasename = $releasename . '.' . $result['source'];
- } else if (preg_match('/(codec( (name|code))?|(original )?format|res(olution)|video( (codec|format|res))?|tv system|type|writing library).*?\b(?P