Completed
Push — master ( 256588...d4b7ca )
by Angus
02:50
created

Base_Site_Model::handleCustomFollow()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 3
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
ccs 0
cts 5
cp 0
crap 6
1
<?php declare(strict_types=1); defined('BASEPATH') OR exit('No direct script access allowed');
2
3
/**
4
 * Class Tracker_Sites_Model
5
 */
6
class Tracker_Sites_Model extends CI_Model {
7 127
	public function __construct() {
8 127
		parent::__construct();
9 127
	}
10
11
	public function __get($name) {
12
		//TODO: Is this a good idea? There wasn't a good consensus on if this is good practice or not..
13
		//      It's probably a minor speed reduction, but that isn't much of an issue.
14
		//      An alternate solution would simply have a function which generates a PHP file with code to load each model. Similar to: https://github.com/shish/shimmie2/blob/834bc740a4eeef751f546979e6400fd089db64f8/core/util.inc.php#L1422
15
		$validClasses = [
16
			'Base_Site_Model',
17
			'Base_FoolSlide_Site_Model',
18
			'Base_myMangaReaderCMS_Site_Model',
19
			'Base_GlossyBright_Site_Model',
20
			'Base_Roku_Site_Model'
21
		];
22
		if(!class_exists($name) || !(in_array(get_parent_class($name), $validClasses))) {
23
			return get_instance()->{$name};
24
		} else {
25
			$this->loadSite($name);
26
			return $this->{$name};
27
		}
28
	}
29
30
	private function loadSite(string $siteName) : void {
31
		$this->{$siteName} = new $siteName();
32
	}
33
}
34
35
abstract class Base_Site_Model extends CI_Model {
36
	public $site          = '';
37
	public $titleFormat   = '//';
38
	public $chapterFormat = '//';
39
	public $hasCloudFlare = FALSE;
40
	public $userAgent     = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2824.0 Safari/537.36';
41
42
	public $baseURL = '';
43
44
	/**
45
	 * 0: No custom updater.
46
	 * 1: Uses following page.
47
	 * 2: Uses latest releases page.
48
	 */
49
	public $customType = 0;
50
51
	public $canHaveNoChapters = FALSE;
52
53 16
	public function __construct() {
54 16
		parent::__construct();
55
56 16
		$this->load->database();
57
58 16
		$this->site = get_class($this);
59 16
	}
60
61
	/**
62
	 * Generates URL to the title page of the requested series.
63
	 *
64
	 * NOTE: In some cases, we are required to store more data in the title_string than is needed to generate the URL. (Namely as the title_string is our unique identifier for that series)
65
	 *       When storing additional data, we use ':--:' as a delimiter to separate the data. Make sure to handle this as needed.
66
	 *
67
	 * Example:
68
	 *    return "http://mangafox.me/manga/{$title_url}/";
69
	 *
70
	 * Example (with extra data):
71
	 *    $title_parts = explode(':--:', title_url);
72
	 *    return "https://bato.to/comic/_/comics/-r".$title_parts[0];
73
	 *
74
	 * @param string $title_url
75
	 * @return string
76
	 */
77
	abstract public function getFullTitleURL(string $title_url) : string;
78
79
	/**
80
	 * Generates chapter data from given $title_url and $chapter.
81
	 *
82
	 * Chapter must be in a (v[0-9]+/)?c[0-9]+(\..+)? format.
83
	 *
84
	 * NOTE: In some cases, we are required to store the chapter number, and the segment required to generate the chapter URL separately.
85
	 *       Much like when generating the title URL, we use ':--:' as a delimiter to separate the data. Make sure to handle this as needed.
86
	 *
87
	 * Example:
88
	 *     return [
89
	 *        'url'    => $this->getFullTitleURL($title_url).'/'.$chapter,
90
	 *        'number' => "c{$chapter}"
91
	 *    ];
92
	 *
93
	 * @param string $title_url
94
	 * @param string $chapter
95
	 * @return array [url, number]
96
	 */
97
	abstract public function getChapterData(string $title_url, string $chapter) : array;
98
99
	/**
100
	 * Used to get the latest chapter of given $title_url.
101
	 *
102
	 * This <should> utilize both get_content and parseTitleDataDOM functions when possible, as these can both reduce a lot of the code required to set this up.
103
	 *
104
	 * $titleData params must be set accordingly:
105
	 * * `title` should always be used with html_entity_decode.
106
	 * * `latest_chapter` must match $this->chapterFormat.
107
	 * * `last_updated` should always be in date("Y-m-d H:i:s") format.
108
	 * * `followed` should never be set within via getTitleData, with the exception of via a array_merge with doCustomFollow.
109
	 *
110
	 * $firstGet is set to true when the series is first added to the DB, and is used to follow the series on given site (if possible).
111
	 *
112
	 * @param string $title_url
113
	 * @param bool   $firstGet
114
	 * @return array|null [title,latest_chapter,last_updated,followed?]
115
	 */
116
	abstract public function getTitleData(string $title_url, bool $firstGet = FALSE) : ?array;
117
118
	/**
119
	 * Validates given $title_url against titleFormat.
120
	 *
121
	 * Failure to match against titleFormat will stop the series from being added to the DB.
122
	 *
123
	 * @param string $title_url
124
	 * @return bool
125
	 */
126 2
	final public function isValidTitleURL(string $title_url) : bool {
127 2
		$success = (bool) preg_match($this->titleFormat, $title_url);
128 2
		if(!$success) log_message('error', "Invalid Title URL ({$this->site}): {$title_url}");
129 2
		return $success;
130
	}
131
132
	/**
133
	 * Validates given $chapter against chapterFormat.
134
	 *
135
	 * Failure to match against chapterFormat will stop the chapter being updated.
136
	 *
137
	 * @param string $chapter
138
	 * @return bool
139
	 */
140 2
	final public function isValidChapter(string $chapter) : bool {
141 2
		$success = (bool) preg_match($this->chapterFormat, $chapter);
142 2
		if(!$success) log_message('error', "Invalid Chapter ({$this->site}): {$chapter}");
143 2
		return $success;
144
	}
145
146
	/**
147
	 * Used by getTitleData (& similar functions) to get the requested page data.
148
	 *
149
	 * @param string $url
150
	 * @param string $cookie_string
151
	 * @param string $cookiejar_path
152
	 * @param bool   $follow_redirect
153
	 * @param bool   $isPost
154
	 * @param array  $postFields
155
	 *
156
	 * @return array|bool
157
	 */
158
	final protected function get_content(string $url, string $cookie_string = "", string $cookiejar_path = "", bool $follow_redirect = FALSE, bool $isPost = FALSE, array $postFields = []) {
159
		$refresh = TRUE; //For sites that have CloudFlare, we want to loop get_content again.
160
		$loops   = 0;
161
		while($refresh && $loops < 2) {
162
			$refresh = FALSE;
163
			$loops++;
164
165
			$ch = curl_init();
166
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
167
			curl_setopt($ch, CURLOPT_ENCODING , "gzip");
168
			//curl_setopt($ch, CURLOPT_VERBOSE, 1);
169
			curl_setopt($ch, CURLOPT_HEADER, 1);
170
171
			if($follow_redirect)        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
172
173
			if($cookies = $this->cache->get("cloudflare_{$this->site}")) {
174
				$cookie_string .= "; {$cookies}";
175
			}
176
177
			if(!empty($cookie_string))  curl_setopt($ch, CURLOPT_COOKIE, $cookie_string);
178
			if(!empty($cookiejar_path)) curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiejar_path);
179
180
			//Some sites check the useragent for stuff, use a pre-defined user-agent to avoid stuff.
181
			curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
182
183
			//NOTE: This is required for SSL URLs for now. Without it we tend to get error code 60.
184
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //FIXME: This isn't safe, but it allows us to grab SSL URLs
185
186
			curl_setopt($ch, CURLOPT_URL, $url);
187
188
			if($isPost) {
189
				curl_setopt($ch,CURLOPT_POST, count($postFields));
190
				curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($postFields));
191
			}
192
193
			$response = curl_exec($ch);
194
195
			$this->Tracker->admin->incrementRequests();
196
197
			if($response === FALSE) {
198
				log_message('error', "curl failed with error: ".curl_errno($ch)." | ".curl_error($ch));
199
				//FIXME: We don't always account for FALSE return
200
				return FALSE;
201
			}
202
203
			$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
204
			$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
205
			$headers     = http_parse_headers(substr($response, 0, $header_size));
206
			$body        = substr($response, $header_size);
207
			curl_close($ch);
208
209
			if($status_code === 503) $refresh = $this->handleCloudFlare($url, $body);
210
		}
211
212
		return [
213
			'headers'     => $headers,
0 ignored issues
show
Bug introduced by
The variable $headers does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
214
			'status_code' => $status_code,
0 ignored issues
show
Bug introduced by
The variable $status_code does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
215
			'body'        => $body
0 ignored issues
show
Bug introduced by
The variable $body does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
216
		];
217
	}
218
219
	final private function handleCloudFlare(string $url, string $body) : bool {
220
		$refresh = FALSE;
221
222
		if((strpos($body, 'DDoS protection by Cloudflare') !== FALSE) || (strpos($body, '<input type="hidden" id="jschl-answer" name="jschl_answer"/>') !== FALSE)) {
223
			//print "Cloudflare detected? Grabbing Cookies.\n";
224
			if(!$this->hasCloudFlare) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
225
				//TODO: Site appears to have enabled CloudFlare, disable it and contact admin.
226
				//      We'll continue to bypass CloudFlare as this may occur in a loop.
227
			}
228
229
			$urlData = [
230
				'url'        => $url,
231
				'user_agent' => $this->userAgent
232
			];
233
			//TODO: shell_exec seems bad since the URLs "could" be user inputted? Better way of doing this?
234
			$result = shell_exec('python '.APPPATH.'../_scripts/get_cloudflare_cookie.py '.escapeshellarg(json_encode($urlData)));
235
			$cookieData = json_decode($result, TRUE);
236
237
			$this->cache->save("cloudflare_{$this->site}", $cookieData['cookies'],  31536000 /* 1 year, or until we renew it */);
238
			log_message('debug', "Saving CloudFlare Cookies for {$this->site}");
239
240
			$refresh = TRUE;
241
		} else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
242
			//Either site doesn't have CloudFlare or we have bypassed it. Either is good!
243
		}
244
		return $refresh;
245
	}
246
247
	/**
248
	 * Used by getTitleData to get the title, latest_chapter & last_updated data from the data returned by get_content.
249
	 *
250
	 * parseTitleDataDOM checks if the data returned by get_content is valid via a few simple checks.
251
	 * * If the request was actually successful, had a valid status code & data wasn't empty. We also do an additional check on an optional $failure_string param, which will throw a failure if it's matched.
252
	 *
253
	 * Data is cleaned by cleanTitleDataDOM prior to being passed to DOMDocument.
254
	 *
255
	 * All $node_* params must be XPath to the requested node, and must only return 1 result. Anything else will throw a failure.
256
	 *
257
	 * @param array  $content
258
	 * @param string $title_url
259
	 * @param string $node_title_string
260
	 * @param string $node_row_string
261
	 * @param string $node_latest_string
262
	 * @param string $node_chapter_string
263
	 * @param string $failure_string
264
	 * @param string $no_chapters_string
265
	 * @return DOMElement[]|false [nodes_title,nodes_chapter,nodes_latest]
266
	 */
267
	final protected function parseTitleDataDOM(
268
		$content, string $title_url,
269
		string $node_title_string, string $node_row_string,
270
		string $node_latest_string, string $node_chapter_string,
271
		string $failure_string = "", string $no_chapters_string = "") {
272
273
		if(!is_array($content)) {
274
			log_message('error', "{$this->site} : {$title_url} | Failed to grab URL (See above curl error)");
275
		} else {
276
			list('headers' => $headers, 'status_code' => $status_code, 'body' => $data) = $content;
0 ignored issues
show
Unused Code introduced by
The assignment to $headers is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
277
278
			if(!($status_code >= 200 && $status_code < 300)) {
279
				log_message('error', "{$this->site} : {$title_url} | Bad Status Code ({$status_code})");
280
			} else if(empty($data)) {
281
				log_message('error', "{$this->site} : {$title_url} | Data is empty? (Status code: {$status_code})");
282
			} else if($failure_string !== "" && strpos($data, $failure_string) !== FALSE) {
283
				log_message('error', "{$this->site} : {$title_url} | Failure string matched");
284
			} else {
285
				$data = $this->cleanTitleDataDOM($data); //This allows us to clean the DOM prior to parsing. It's faster to grab the only part we need THEN parse it.
286
287
				$dom = new DOMDocument();
288
				libxml_use_internal_errors(TRUE);
289
				$dom->loadHTML('<?xml encoding="utf-8" ?>' . $data);
290
				libxml_use_internal_errors(FALSE);
291
292
				$xpath = new DOMXPath($dom);
293
				$nodes_title = $xpath->query($node_title_string);
294
				$nodes_row   = $xpath->query($node_row_string);
295
				if($nodes_title->length === 1) {
296
					if($nodes_row->length === 1) {
297
						$firstRow      = $nodes_row->item(0);
298
						$nodes_latest  = $xpath->query($node_latest_string,  $firstRow);
299
300
						if($node_chapter_string !== '') {
301
							$nodes_chapter = $xpath->query($node_chapter_string, $firstRow);
302
						} else {
303
							$nodes_chapter = $nodes_row;
304
						}
305
306
						if($nodes_latest->length === 1 && $nodes_chapter->length === 1) {
307
							return [
308
								'nodes_title'   => $nodes_title->item(0),
309
								'nodes_latest'  => $nodes_latest->item(0),
310
								'nodes_chapter' => $nodes_chapter->item(0)
311
							];
312
						} else {
313
							log_message('error', "{$this->site} : {$title_url} | Invalid amount of nodes (LATEST: {$nodes_latest->length} | CHAPTER: {$nodes_chapter->length})");
314
						}
315
					} elseif($this->canHaveNoChapters && !empty($no_chapters_string) && strpos($data, $no_chapters_string) !== FALSE) {
316
						return [
317
							'nodes_title' => $nodes_title->item(0)
318
						];
319
					} else {
320
						log_message('error', "{$this->site} : {$title_url} | Invalid amount of nodes (ROW: {$nodes_row->length})");
321
					}
322
				} else {
323
					log_message('error', "{$this->site} : {$title_url} | Invalid amount of nodes (TITLE: {$nodes_title->length})");
324
				}
325
			}
326
		}
327
328
		return FALSE;
329
	}
330
331
	/**
332
	 * Used by parseTitleDataDOM to clean the data prior to passing it to DOMDocument & DOMXPath.
333
	 * This is mostly done as an (assumed) speed improvement due to the reduced amount of DOM to parse, or simply just making it easier to parse with XPath.
334
	 *
335
	 * @param string $data
336
	 * @return string
337
	 */
338
	public function cleanTitleDataDOM(string $data) : string {
339
		return $data;
340
	}
341
342
	/**
343
	 * Used to follow a series on given site if supported.
344
	 *
345
	 * This is called by getTitleData if $firstGet is true (which occurs when the series is first being added to the DB).
346
	 *
347
	 * Most of the actual following is done by handleCustomFollow.
348
	 *
349
	 * @param string $data
350
	 * @param array  $extra
351
	 * @return array
352
	 */
353
	final public function doCustomFollow(string $data = "", array $extra = []) : array {
354
		$titleData = [];
355
		$this->handleCustomFollow(function($content, $id, closure $successCallback = NULL) use(&$titleData) {
356
			if(is_array($content)) {
357
				if(array_key_exists('status_code', $content)) {
358
					$statusCode = $content['status_code'];
359
					if($statusCode === 200) {
360
						$isCallable = is_callable($successCallback);
361
						if(($isCallable && $successCallback($content['body'])) || !$isCallable) {
362
							$titleData['followed'] = 'Y';
363
364
							log_message('info', "doCustomFollow succeeded for {$id}");
365
						} else {
366
							log_message('error', "doCustomFollow failed (Invalid response?) for {$id}");
367
						}
368
					} else {
369
						log_message('error', "doCustomFollow failed (Invalid status code ({$statusCode})) for {$id}");
370
					}
371
				} else {
372
					log_message('error', "doCustomFollow failed (Missing status code?) for {$id}");
373
				}
374
			} else {
375
				log_message('error', "doCustomFollow failed (Failed request) for {$id}");
376
			}
377
		}, $data, $extra);
378
		return $titleData;
379
	}
380
381
	/**
382
	 * Used by doCustomFollow to handle following series on sites.
383
	 *
384
	 * Uses get_content to get data.
385
	 *
386
	 * $callback must return ($content, $id, closure $successCallback = NULL).
387
	 * * $content is simply just the get_content data.
388
	 * * $id is the dbID. This should be passed by the $extra arr.
389
	 * * $successCallback is an optional success check to make sure the series was properly followed.
390
	 *
391
	 * @param callable $callback
392
	 * @param string   $data
393
	 * @param array    $extra
394
	 */
395
	public function handleCustomFollow(callable $callback, string $data = "", array $extra = []) {
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
396
		if($this->customType === 2) {
397
			$content = ['status_code' => 200];
398
			$callback($content, $extra['id']);
399
		}
400
	}
401
402
	/**
403
	 * Used to check the sites following page for new updates (if supported).
404
	 * This should work much like getTitleData, but instead checks the following page.
405
	 *
406
	 * This must return an array containing arrays of each of the chapters data.
407
	 */
408
	public function doCustomUpdate() {}
409
410
	/**
411
	 * Used by the custom updater to check if a chapter looks newer than the current one.
412
	 *
413
	 * This calls doCustomCheckCompare which handles the majority of the checking.
414
	 * NOTE: Depending on the site, you may need to call getChapterData to get the chapter number to be used with this.
415
	 *
416
	 * @param string $oldChapterString
417
	 * @param string $newChapterString
418
	 * @return bool
419
	 */
420
	public function doCustomCheck(string $oldChapterString, string $newChapterString) : bool {
421
		$oldChapterSegments = explode('/', $this->getChapterData('', $oldChapterString)['number']);
422
		$newChapterSegments = explode('/', $this->getChapterData('', $newChapterString)['number']);
423
424
		$status = $this->doCustomCheckCompare($oldChapterSegments, $newChapterSegments);
425
426
		return $status;
427
	}
428
429
	/**
430
	 * Used by doCustomCheck to check if a chapter looks newer than the current one.
431
	 * Chapter must be in a (v[0-9]+/)?c[0-9]+(\..+)? format.
432
	 *
433
	 * To avoid issues with the occasional off case, this will only ever return true if we are 100% sure that the new chapter is newer than the old one.
434
	 *
435
	 * @param array $oldChapterSegments
436
	 * @param array $newChapterSegments
437
	 * @return bool
438
	 */
439 12
	final public function doCustomCheckCompare(array $oldChapterSegments, array $newChapterSegments) : bool {
440
		//NOTE: We only need to check against the new chapter here, as that is what is used for confirming update.
441 12
		$status = FALSE;
442
443
		//Make sure we have a volume element
444 12
		if(count($oldChapterSegments) === 1) array_unshift($oldChapterSegments, 'v0');
445 12
		if(count($newChapterSegments) === 1) array_unshift($newChapterSegments, 'v0');
446
447 12
		$oldCount = count($oldChapterSegments);
448 12
		$newCount = count($newChapterSegments);
449 12
		if($newCount === $oldCount) {
450
			//Make sure chapter format looks correct.
451
			//NOTE: We only need to check newCount as we know oldCount is the same count.
452 12
			if($newCount === 2) {
453
				//FIXME: Can we loop this?
454 12
				$oldVolume = substr(array_shift($oldChapterSegments), 1);
455 12
				$newVolume = substr(array_shift($newChapterSegments), 1);
456
457
				//Forcing volume to 0 as TBD might not be the latest (although it can be, but that is covered by other checks)
458 12
				if(in_array($oldVolume, ['TBD', 'TBA', 'NA', 'LMT'])) $oldVolume = 0;
459 12
				if(in_array($newVolume, ['TBD', 'TBA', 'NA', 'LMT'])) $newVolume = 0;
460
461 12
				$oldVolume = floatval($oldVolume);
462 12
				$newVolume = floatval($newVolume);
463
			} else {
464
				$oldVolume = 0;
465
				$newVolume = 0;
466
			}
467 12
			$oldChapter = floatval(substr(array_shift($oldChapterSegments), 1));
468 12
			$newChapter = floatval(substr(array_shift($newChapterSegments), 1));
469
470 12
			if($newChapter > $oldChapter && ($oldChapter >= 10 && $newChapter >= 10)) {
471
				//$newChapter is higher than $oldChapter AND $oldChapter and $newChapter are both more than 10
472
				//This is intended to cover the /majority/ of valid updates, as we technically shouldn't have to check volumes.
473
474 4
				$status = TRUE;
475 8
			} elseif($newVolume > $oldVolume && ($oldChapter < 10 && $newChapter < 10)) {
476
				//This is pretty much just to match a one-off case where the site doesn't properly increment chapter numbers across volumes, and instead does something like: v1/c1..v1/c5, v2/c1..v1/c5 (and so on).
477 1
				$status = TRUE;
478 7
			} elseif($newVolume > $oldVolume && $newChapter >= $oldChapter) {
479
				//$newVolume is higher, and chapter is higher so no need to check chapter.
480 2
				$status = TRUE;
481 5
			} elseif($newChapter > $oldChapter) {
482
				//$newVolume isn't higher, but chapter is.
483
				$status = TRUE;
484
			}
485
		}
486
487 12
		return $status;
488
	}
489
}
490
491
abstract class Base_FoolSlide_Site_Model extends Base_Site_Model {
492
	public $titleFormat   = '/^[a-z0-9_-]+$/';
493
	public $chapterFormat = '/^(?:en(?:-us)?|pt|es)\/[0-9]+(?:\/[0-9]+(?:\/[0-9]+(?:\/[0-9]+)?)?)?$/';
494
	public $customType    = 2;
495
496
	public function getFullTitleURL(string $title_url) : string {
497
		return "{$this->baseURL}/series/{$title_url}";
498
	}
499
500
	public function getChapterData(string $title_url, string $chapter) : array {
501
		$chapter_parts = explode('/', $chapter); //returns #LANG#/#VOLUME#/#CHAPTER#/#CHAPTER_EXTRA#(/#PAGE#/)
502
		return [
503
			'url'    => $this->getChapterURL($title_url, $chapter),
504
			'number' => ($chapter_parts[1] !== '0' ? "v{$chapter_parts[1]}/" : '') . "c{$chapter_parts[2]}" . (isset($chapter_parts[3]) ? ".{$chapter_parts[3]}" : '')/*)*/
505
		];
506
	}
507
	public function getChapterURL(string $title_url, string $chapter) : string {
508
		return "{$this->baseURL}/read/{$title_url}/{$chapter}/";
509
	}
510
511
	public function getTitleData(string $title_url, bool $firstGet = FALSE) : ?array {
512
		$titleData = [];
513
514
		$jsonURL = $this->getJSONTitleURL($title_url);
515
		if($content = $this->get_content($jsonURL)) {
516
			$json = json_decode($content['body'], TRUE);
517
			if($json && isset($json['chapters']) && count($json['chapters']) > 0) {
518
				$titleData['title'] = trim($json['comic']['name']);
519
520
				//FoolSlide title API doesn't appear to let you sort (yet every other API method which has chapters does, so we need to sort ourselves..
521
				usort($json['chapters'], function($a, $b) {
522
					return floatval("{$b['chapter']['chapter']}.{$b['chapter']['subchapter']}") <=> floatval("{$a['chapter']['chapter']}.{$a['chapter']['subchapter']}");
523
				});
524
				$latestChapter = reset($json['chapters'])['chapter'];
525
526
				$latestChapterString = "{$latestChapter['language']}/{$latestChapter['volume']}/{$latestChapter['chapter']}";
527
				if($latestChapter['subchapter'] !== '0') {
528
					$latestChapterString .= "/{$latestChapter['subchapter']}";
529
				}
530
				$titleData['latest_chapter'] = $latestChapterString;
531
532
				//No need to use date() here since this is already formatted as such.
533
				$titleData['last_updated'] = ($latestChapter['updated'] !== '0000-00-00 00:00:00' ? $latestChapter['updated'] : $latestChapter['created']);
534
			}
535
		}
536
537
		return (!empty($titleData) ? $titleData : NULL);
538
	}
539
540
	public function doCustomUpdate() {
541
		$titleDataList = [];
542
543
		$jsonURL = $this->getJSONUpdateURL();
544
		if(($content = $this->get_content($jsonURL)) && $content['status_code'] == 200) {
545
			if(($json = json_decode($content['body'], TRUE)) && isset($json['chapters'])) {
546
				//This should fix edge cases where chapters are uploaded in bulk in the wrong order (HelveticaScans does this with Mousou Telepathy).
547
				usort($json['chapters'], function($a, $b) {
548
					$a_date = new DateTime($a['chapter']['updated'] !== '0000-00-00 00:00:00' ? $a['chapter']['updated'] : $a['chapter']['created']);
549
					$b_date = new DateTime($b['chapter']['updated'] !== '0000-00-00 00:00:00' ? $b['chapter']['updated'] : $b['chapter']['created']);
550
					return $b_date <=> $a_date;
551
				});
552
553
				$parsedTitles = [];
554
				foreach($json['chapters'] as $chapterData) {
555
					if(!in_array($chapterData['comic']['stub'], $parsedTitles)) {
556
						$parsedTitles[] = $chapterData['comic']['stub'];
557
558
						$titleData = [];
559
						$titleData['title'] = trim($chapterData['comic']['name']);
560
561
						$latestChapter = $chapterData['chapter'];
562
563
						$latestChapterString = "en/{$latestChapter['volume']}/{$latestChapter['chapter']}";
564
						if($latestChapter['subchapter'] !== '0') {
565
							$latestChapterString .= "/{$latestChapter['subchapter']}";
566
						}
567
						$titleData['latest_chapter'] = $latestChapterString;
568
569
						//No need to use date() here since this is already formatted as such.
570
						$titleData['last_updated'] = ($latestChapter['updated'] !== '0000-00-00 00:00:00' ? $latestChapter['updated'] : $latestChapter['created']);
571
572
						$titleDataList[$chapterData['comic']['stub']] = $titleData;
573
					} else {
574
						//We already have title data for this title.
575
						continue;
576
					}
577
				}
578
			} else {
579
				log_message('error', "{$this->site} - Custom updating failed (no chapters arg?) for {$this->baseURL}.");
580
			}
581
		} else {
582
			log_message('error', "{$this->site} - Custom updating failed for {$this->baseURL}.");
583
		}
584
585
		return $titleDataList;
586
	}
587
588
	public function getJSONTitleURL(string $title_url) : string {
589
		return "{$this->baseURL}/api/reader/comic/stub/{$title_url}/format/json";
590
	}
591
	public function getJSONUpdateURL() : string {
592
		return "{$this->baseURL}/api/reader/chapters/orderby/desc_created/format/json";
593
	}
594
}
595
596
abstract class Base_myMangaReaderCMS_Site_Model extends Base_Site_Model {
597
	public $titleFormat   = '/^[a-zA-Z0-9_-]+$/';
598
	public $chapterFormat = '/^(?:oneshot|(?:chapter-)?[0-9\.]+)$/';
599
	public $customType    = 2;
600
601
	public function getFullTitleURL(string $title_url) : string {
602
		return "{$this->baseURL}/manga/{$title_url}";
603
	}
604
605
	public function getChapterData(string $title_url, string $chapter) : array {
606
		$chapterN = (ctype_digit($chapter) ? "c${chapter}" : $chapter);
607
		return [
608
			'url'    => $this->getChapterURL($title_url, $chapter),
609
			'number' => $chapterN
610
		];
611
	}
612
	public function getChapterURL(string $title_url, string $chapter) : string {
613
		return $this->getFullTitleURL($title_url).'/'.$chapter;
614
	}
615
616
	public function getTitleData(string $title_url, bool $firstGet = FALSE) : ?array {
617
		$titleData = [];
618
619
		$fullURL = $this->getFullTitleURL($title_url);
620
621
		$content = $this->get_content($fullURL);
622
623
		$data = $this->parseTitleDataDOM(
624
			$content,
0 ignored issues
show
Security Bug introduced by
It seems like $content defined by $this->get_content($fullURL) on line 621 can also be of type false; however, Base_Site_Model::parseTitleDataDOM() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
625
			$title_url,
626
			"(//h2[@class='widget-title'])[1]",
627
			"//ul[contains(@class, 'chapters')]/li[not(contains(@class, 'btn'))][1]",
628
			"div[contains(@class, 'action')]/div[@class='date-chapter-title-rtl']",
629
			"h5/a[1] | h3/a[1]",
630
			"Whoops, looks like something went wrong."
631
		);
632
		if($data) {
633
			$titleData['title'] = trim($data['nodes_title']->textContent);
634
635
			$segments = explode('/', (string) $data['nodes_chapter']->getAttribute('href'));
636
			$needle = array_search('manga', array_reverse($segments, TRUE)) + 2;
637
			$titleData['latest_chapter'] = $segments[$needle];
638
639
			$dateString = $data['nodes_latest']->nodeValue;
640
			$titleData['last_updated'] = date("Y-m-d H:i:s", strtotime(preg_replace('/ (-|\[A\]).*$/', '', $dateString)));
641
		}
642
643
		return (!empty($titleData) ? $titleData : NULL);
644
	}
645
646
	public function doCustomUpdate() {
647
		$titleDataList = [];
648
649
		$updateURL = "{$this->baseURL}/latest-release";
650
		if(($content = $this->get_content($updateURL)) && $content['status_code'] == 200) {
651
			$data = $content['body'];
652
653
			$data = preg_replace('/^[\s\S]+<dl>/', '<dl>', $data);
654
			$data = preg_replace('/<\/dl>[\s\S]+$/', '</dl>', $data);
655
656
			$dom = new DOMDocument();
657
			libxml_use_internal_errors(TRUE);
658
			$dom->loadHTML($data);
659
			libxml_use_internal_errors(FALSE);
660
661
			$xpath      = new DOMXPath($dom);
662
			$nodes_rows = $xpath->query("//dl/dd | //div[@class='mangalist']/div[@class='manga-item']");
663
			if($nodes_rows->length > 0) {
664
				foreach($nodes_rows as $row) {
665
					$titleData = [];
666
667
					$nodes_title   = $xpath->query("div[@class='events ']/div[@class='events-body']/h3[@class='events-heading']/a | h3/a", $row);
668
					$nodes_chapter = $xpath->query("(div[@class='events '][1]/div[@class='events-body'][1] | div[@class='manga-chapter'][1])/h6[@class='events-subtitle'][1]/a[1]", $row);
669
					$nodes_latest  = $xpath->query("div[@class='time'] | small", $row);
670
671
					if($nodes_title->length === 1 && $nodes_chapter->length === 1 && $nodes_latest->length === 1) {
672
						$title = $nodes_title->item(0);
673
674
						preg_match('/(?<url>[^\/]+(?=\/$|$))/', $title->getAttribute('href'), $title_url_arr);
675
						$title_url = $title_url_arr['url'];
676
677
						if(!array_key_exists($title_url, $titleDataList)) {
678
							$titleData['title'] = trim($title->textContent);
679
680
							$chapter = $nodes_chapter->item(0);
681
							preg_match('/(?<chapter>[^\/]+(?=\/$|$))/', $chapter->getAttribute('href'), $chapter_arr);
682
							$titleData['latest_chapter'] = $chapter_arr['chapter'];
683
684
							$dateString = str_replace('/', '-', trim($nodes_latest->item(0)->nodeValue)); //NOTE: We replace slashes here as it stops strtotime interpreting the date as US date format.
685
							if($dateString == 'T') {
686
								$dateString = date("Y-m-d",now());
687
							}
688
							$titleData['last_updated'] = date("Y-m-d H:i:s", strtotime($dateString . ' 00:00'));
689
690
							$titleDataList[$title_url] = $titleData;
691
						}
692
					} else {
693
						log_message('error', "{$this->site}/Custom | Invalid amount of nodes (TITLE: {$nodes_title->length} | CHAPTER: {$nodes_chapter->length}) | LATEST: {$nodes_latest->length})");
694
					}
695
				}
696
			} else {
697
				log_message('error', "{$this->site} | Following list is empty?");
698
			}
699
		} else {
700
			log_message('error', "{$this->site} - Custom updating failed for {$this->baseURL}.");
701
		}
702
703
		return $titleDataList;
704
	}
705
}
706
707
abstract class Base_GlossyBright_Site_Model extends Base_Site_Model {
708
	public $titleFormat   = '/^[a-zA-Z0-9_-]+$/';
709
	public $chapterFormat = '/^[0-9\.]+$/';
710
711
	public $customType    = 2;
712
713
	public function getFullTitleURL(string $title_url) : string {
714
		return "{$this->baseURL}/{$title_url}";
715
	}
716
717
	public function getChapterData(string $title_url, string $chapter) : array {
718
		return [
719
			'url'    => $this->getFullTitleURL($title_url).'/'.$chapter.'/',
720
			'number' => "c{$chapter}"
721
		];
722
	}
723
724
	public function getTitleData(string $title_url, bool $firstGet = FALSE) : ?array {
725
		$titleData = [];
726
727
		$fullURL = "{$this->baseURL}/manga-rss/{$title_url}";
728
		$content = $this->get_content($fullURL);
729
		$data    = $this->parseTitleDataDOM(
730
			$content,
0 ignored issues
show
Security Bug introduced by
It seems like $content defined by $this->get_content($fullURL) on line 728 can also be of type false; however, Base_Site_Model::parseTitleDataDOM() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
731
			$title_url,
732
			"//rss/channel/image/title",
733
			"//rss/channel/item[1]",
734
			"pubdate",
735
			"title"
736
		);
737
		if($data) {
738
			$titleData['title'] = preg_replace('/^Recent chapters of (.*?) manga$/', '$1', trim($data['nodes_title']->textContent));
739
740
			//For whatever reason, DOMDocument breaks the <link> element we need to grab the chapter, so we have to grab it elsewhere.
741
			$titleData['latest_chapter'] = preg_replace('/^.*? - ([0-9\.]+) - .*?$/', '$1', trim($data['nodes_chapter']->textContent));
742
743
			$titleData['last_updated'] =  date("Y-m-d H:i:s", strtotime((string) $data['nodes_latest']->textContent));
744
		}
745
746
		return (!empty($titleData) ? $titleData : NULL);
747
	}
748
749
	public function doCustomUpdate() {
750
		$titleDataList = [];
751
752
		$baseURLRegex = str_replace('.', '\\.', parse_url($this->baseURL, PHP_URL_HOST));
753
		if(($content = $this->get_content($this->baseURL)) && $content['status_code'] == 200) {
754
			$data = $content['body'];
755
756
			$dom = new DOMDocument();
757
			libxml_use_internal_errors(TRUE);
758
			$dom->loadHTML($data);
759
			libxml_use_internal_errors(FALSE);
760
761
			$xpath      = new DOMXPath($dom);
762
			$nodes_rows = $xpath->query("//table[@id='wpm_mng_lst']/tr/td | //*[@id='wpm_mng_lst']/li/div");
763
			if($nodes_rows->length > 0) {
764
				foreach($nodes_rows as $row) {
765
					$titleData = [];
766
767
					$nodes_title   = $xpath->query("a[2]", $row);
768
					$nodes_chapter = $xpath->query("a[2]", $row);
769
					$nodes_latest  = $xpath->query("b | text()[last()]", $row);
770
771
					if($nodes_title->length === 1 && $nodes_chapter->length === 1 && $nodes_latest->length === 1) {
772
						$title   = $nodes_title->item(0);
773
						$chapter = $nodes_chapter->item(0);
774
775
						preg_match('/'.$baseURLRegex.'\/(?<url>.*?)\//', $title->getAttribute('href'), $title_url_arr);
776
						$title_url = $title_url_arr['url'];
777
778
						if(!array_key_exists($title_url, $titleDataList)) {
779
							$titleData['title'] = trim($title->getAttribute('title'));
780
781
							preg_match('/(?<chapter>[^\/]+(?=\/$|$))/', $chapter->getAttribute('href'), $chapter_arr);
782
							$titleData['latest_chapter'] = $chapter_arr['chapter'];
783
784
							$dateString = trim($nodes_latest->item(0)->textContent);
785
							switch($dateString) {
786
								case 'Today':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
787
									$dateString = date("Y-m-d", now());
788
									break;
789
790
								case 'Yesterday':
791
									$dateString = date("Y-m-d", strtotime("-1 days"));
792
									break;
793
794
								default:
795
									//Do nothing
796
									break;
797
							}
798
							$titleData['last_updated'] = date("Y-m-d H:i:s", strtotime($dateString));
799
800
							$titleDataList[$title_url] = $titleData;
801
						}
802
					} else {
803
						log_message('error', "{$this->site}/Custom | Invalid amount of nodes (TITLE: {$nodes_title->length} | CHAPTER: {$nodes_chapter->length}) | LATEST: {$nodes_latest->length})");
804
					}
805
				}
806
			} else {
807
				log_message('error', "{$this->site} | Following list is empty?");
808
			}
809
		} else {
810
			log_message('error', "{$this->site} - Custom updating failed.");
811
		}
812
813
		return $titleDataList;
814
	}
815
}
816
817
abstract class Base_Roku_Site_Model extends Base_Site_Model {
818
	public $titleFormat   = '/^[a-zA-Z0-9-]+$/';
819
	public $chapterFormat = '/^[0-9\.]+$/';
820
821
	public $customType    = 2;
822
823
	public function getFullTitleURL(string $title_url) : string {
824
		return "{$this->baseURL}/series/{$title_url}";
825
	}
826
	public function getChapterData(string $title_url, string $chapter) : array {
827
		return [
828
			'url'    => "{$this->baseURL}/read/{$title_url}/{$chapter}",
829
			'number' => "c{$chapter}"
830
		];
831
	}
832
	public function getTitleData(string $title_url, bool $firstGet = FALSE) : ?array {
833
		$titleData = [];
834
		$fullURL = $this->getFullTitleURL($title_url);
835
		$content = $this->get_content($fullURL);
836
		$data = $this->parseTitleDataDOM(
837
			$content,
0 ignored issues
show
Security Bug introduced by
It seems like $content defined by $this->get_content($fullURL) on line 835 can also be of type false; however, Base_Site_Model::parseTitleDataDOM() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
838
			$title_url,
839
			"//div[@id='activity']/descendant::div[@class='media'][1]/descendant::div[@class='media-body']/h2/text()",
840
			"//ul[contains(@class, 'media-list')]/li[@class='media'][1]/a",
841
			"div[@class='media-body']/span[@class='text-muted']",
842
			""
843
		);
844
		if($data) {
845
			$titleData['title'] = trim(preg_replace('/ Added on .*$/','', $data['nodes_title']->textContent));
846
			$titleData['latest_chapter'] = preg_replace('/^.*\/([0-9\.]+)$/', '$1', (string) $data['nodes_chapter']->getAttribute('href'));
847
848
			$dateString = preg_replace('/^Added (?:on )?/', '',$data['nodes_latest']->textContent);
849
			$titleData['last_updated'] =  date("Y-m-d H:i:s", strtotime($dateString));
850
		}
851
		return (!empty($titleData) ? $titleData : NULL);
852
	}
853
854
855
	public function doCustomUpdate() {
856
		$titleDataList = [];
857
858
		$updateURL = "{$this->baseURL}/latest";
859
		if(($content = $this->get_content($updateURL)) && $content['status_code'] == 200) {
860
			$data = $content['body'];
861
862
			$dom = new DOMDocument();
863
			libxml_use_internal_errors(TRUE);
864
			$dom->loadHTML($data);
865
			libxml_use_internal_errors(FALSE);
866
867
			$xpath      = new DOMXPath($dom);
868
			$nodes_rows = $xpath->query("//div[@class='content-wrapper']/div[@class='row']/div/div");
869
			if($nodes_rows->length > 0) {
870
				foreach($nodes_rows as $row) {
871
					$titleData = [];
872
873
					$nodes_title   = $xpath->query("div[@class='caption']/h6/a", $row);
874
					$nodes_chapter = $xpath->query("div[@class='panel-footer no-padding']/a", $row);
875
					$nodes_latest  = $xpath->query("div[@class='caption']/text()", $row);
876
877
					if($nodes_title->length === 1 && $nodes_chapter->length === 1 && $nodes_latest->length === 1) {
878
						$title = $nodes_title->item(0);
879
880
						preg_match('/(?<url>[^\/]+(?=\/$|$))/', $title->getAttribute('href'), $title_url_arr);
881
						$title_url = $title_url_arr['url'];
882
883
						if(!array_key_exists($title_url, $titleDataList)) {
884
							$titleData['title'] = trim($title->textContent);
885
886
							$chapter = $nodes_chapter->item(0);
887
							preg_match('/(?<chapter>[^\/]+(?=\/$|$))/', $chapter->getAttribute('href'), $chapter_arr);
888
							$titleData['latest_chapter'] = $chapter_arr['chapter'];
889
890
							$dateString = trim(str_replace('Added ', '', $nodes_latest->item(0)->textContent));
891
							$titleData['last_updated'] = date("Y-m-d H:i:s", strtotime($dateString));
892
893
							$titleDataList[$title_url] = $titleData;
894
						}
895
					} else {
896
						log_message('error', "{$this->site}/Custom | Invalid amount of nodes (TITLE: {$nodes_title->length} | CHAPTER: {$nodes_chapter->length}) | LATEST: {$nodes_latest->length})");
897
					}
898
				}
899
			} else {
900
				log_message('error', "{$this->site} | Following list is empty?");
901
			}
902
		} else {
903
			log_message('error', "{$this->site} - Custom updating failed.");
904
		}
905
906
		return $titleDataList;
907
	}
908
}
909