Completed
Push — master ( ba305b...98989a )
by Angus
03:47
created

Base_Site_Model::handleCloudFlare()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 14
nc 3
nop 2
dl 0
loc 27
ccs 0
cts 12
cp 0
crap 20
rs 8.5806
c 0
b 0
f 0
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 = "", callable $extraCall = NULL) {
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
							$returnData = [
308
								'nodes_title'   => $nodes_title->item(0),
309
								'nodes_latest'  => $nodes_latest->item(0),
310
								'nodes_chapter' => $nodes_chapter->item(0)
311
							];
312
313
							$extraCall($xpath, $returnData);
314
315
							return $returnData;
316
						} else {
317
							log_message('error', "{$this->site} : {$title_url} | Invalid amount of nodes (LATEST: {$nodes_latest->length} | CHAPTER: {$nodes_chapter->length})");
318
						}
319
					} elseif($this->canHaveNoChapters && !empty($no_chapters_string) && strpos($data, $no_chapters_string) !== FALSE) {
320
						return [
321
							'nodes_title' => $nodes_title->item(0)
322
						];
323
					} else {
324
						log_message('error', "{$this->site} : {$title_url} | Invalid amount of nodes (ROW: {$nodes_row->length})");
325
					}
326
				} else {
327
					log_message('error', "{$this->site} : {$title_url} | Invalid amount of nodes (TITLE: {$nodes_title->length})");
328
				}
329
			}
330
		}
331
332
		return FALSE;
333
	}
334
335
	/**
336
	 * Used by parseTitleDataDOM to clean the data prior to passing it to DOMDocument & DOMXPath.
337
	 * 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.
338
	 *
339
	 * @param string $data
340
	 * @return string
341
	 */
342
	public function cleanTitleDataDOM(string $data) : string {
343
		return $data;
344
	}
345
346
	/**
347
	 * Used to follow a series on given site if supported.
348
	 *
349
	 * This is called by getTitleData if $firstGet is true (which occurs when the series is first being added to the DB).
350
	 *
351
	 * Most of the actual following is done by handleCustomFollow.
352
	 *
353
	 * @param string $data
354
	 * @param array  $extra
355
	 * @return array
356
	 */
357
	final public function doCustomFollow(string $data = "", array $extra = []) : array {
358
		$titleData = [];
359
		$this->handleCustomFollow(function($content, $id, closure $successCallback = NULL) use(&$titleData) {
360
			if(is_array($content)) {
361
				if(array_key_exists('status_code', $content)) {
362
					$statusCode = $content['status_code'];
363
					if($statusCode === 200) {
364
						$isCallable = is_callable($successCallback);
365
						if(($isCallable && $successCallback($content['body'])) || !$isCallable) {
366
							$titleData['followed'] = 'Y';
367
368
							log_message('info', "doCustomFollow succeeded for {$id}");
369
						} else {
370
							log_message('error', "doCustomFollow failed (Invalid response?) for {$id}");
371
						}
372
					} else {
373
						log_message('error', "doCustomFollow failed (Invalid status code ({$statusCode})) for {$id}");
374
					}
375
				} else {
376
					log_message('error', "doCustomFollow failed (Missing status code?) for {$id}");
377
				}
378
			} else {
379
				log_message('error', "doCustomFollow failed (Failed request) for {$id}");
380
			}
381
		}, $data, $extra);
382
		return $titleData;
383
	}
384
385
	/**
386
	 * Used by doCustomFollow to handle following series on sites.
387
	 *
388
	 * Uses get_content to get data.
389
	 *
390
	 * $callback must return ($content, $id, closure $successCallback = NULL).
391
	 * * $content is simply just the get_content data.
392
	 * * $id is the dbID. This should be passed by the $extra arr.
393
	 * * $successCallback is an optional success check to make sure the series was properly followed.
394
	 *
395
	 * @param callable $callback
396
	 * @param string   $data
397
	 * @param array    $extra
398
	 */
399
	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...
400
		if($this->customType === 2) {
401
			$content = ['status_code' => 200];
402
			$callback($content, $extra['id']);
403
		}
404
	}
405
406
	/**
407
	 * Used to check the sites following page for new updates (if supported).
408
	 * This should work much like getTitleData, but instead checks the following page.
409
	 *
410
	 * This must return an array containing arrays of each of the chapters data.
411
	 */
412
	public function doCustomUpdate() {}
413
414
	/**
415
	 * Used by the custom updater to check if a chapter looks newer than the current one.
416
	 *
417
	 * This calls doCustomCheckCompare which handles the majority of the checking.
418
	 * NOTE: Depending on the site, you may need to call getChapterData to get the chapter number to be used with this.
419
	 *
420
	 * @param string $oldChapterString
421
	 * @param string $newChapterString
422
	 * @return bool
423
	 */
424
	public function doCustomCheck(?string $oldChapterString, string $newChapterString) : bool {
425
		if(!is_null($oldChapterString)) {
426
			$oldChapterSegments = explode('/', $this->getChapterData('', $oldChapterString)['number']);
427
			$newChapterSegments = explode('/', $this->getChapterData('', $newChapterString)['number']);
428
429
			$status = $this->doCustomCheckCompare($oldChapterSegments, $newChapterSegments);
430
		} else {
431
			$status = TRUE;
432
		}
433
434
		return $status;
435
	}
436
437
	/**
438
	 * Used by doCustomCheck to check if a chapter looks newer than the current one.
439
	 * Chapter must be in a (v[0-9]+/)?c[0-9]+(\..+)? format.
440
	 *
441
	 * 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.
442
	 *
443
	 * @param array $oldChapterSegments
444
	 * @param array $newChapterSegments
445
	 * @return bool
446
	 */
447 12
	final public function doCustomCheckCompare(array $oldChapterSegments, array $newChapterSegments) : bool {
448
		//NOTE: We only need to check against the new chapter here, as that is what is used for confirming update.
449 12
		$status = FALSE;
450
451
		//Make sure we have a volume element
452 12
		if(count($oldChapterSegments) === 1) array_unshift($oldChapterSegments, 'v0');
453 12
		if(count($newChapterSegments) === 1) array_unshift($newChapterSegments, 'v0');
454
455 12
		$oldCount = count($oldChapterSegments);
456 12
		$newCount = count($newChapterSegments);
457 12
		if($newCount === $oldCount) {
458
			//Make sure chapter format looks correct.
459
			//NOTE: We only need to check newCount as we know oldCount is the same count.
460 12
			if($newCount === 2) {
461
				//FIXME: Can we loop this?
462 12
				$oldVolume = substr(array_shift($oldChapterSegments), 1);
463 12
				$newVolume = substr(array_shift($newChapterSegments), 1);
464
465
				//Forcing volume to 0 as TBD might not be the latest (although it can be, but that is covered by other checks)
466 12
				if(in_array($oldVolume, ['TBD', 'TBA', 'NA', 'LMT'])) $oldVolume = 0;
467 12
				if(in_array($newVolume, ['TBD', 'TBA', 'NA', 'LMT'])) $newVolume = 0;
468
469 12
				$oldVolume = floatval($oldVolume);
470 12
				$newVolume = floatval($newVolume);
471
			} else {
472
				$oldVolume = 0;
473
				$newVolume = 0;
474
			}
475 12
			$oldChapter = floatval(substr(array_shift($oldChapterSegments), 1));
476 12
			$newChapter = floatval(substr(array_shift($newChapterSegments), 1));
477
478 12
			if($newChapter > $oldChapter && ($oldChapter >= 10 && $newChapter >= 10)) {
479
				//$newChapter is higher than $oldChapter AND $oldChapter and $newChapter are both more than 10
480
				//This is intended to cover the /majority/ of valid updates, as we technically shouldn't have to check volumes.
481
482 4
				$status = TRUE;
483 8
			} elseif($newVolume > $oldVolume && ($oldChapter < 10 && $newChapter < 10)) {
484
				//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).
485 1
				$status = TRUE;
486 7
			} elseif($newVolume > $oldVolume && $newChapter >= $oldChapter) {
487
				//$newVolume is higher, and chapter is higher so no need to check chapter.
488 2
				$status = TRUE;
489 5
			} elseif($newChapter > $oldChapter) {
490
				//$newVolume isn't higher, but chapter is.
491
				$status = TRUE;
492
			}
493
		}
494
495 12
		return $status;
496
	}
497
}
498
499
abstract class Base_FoolSlide_Site_Model extends Base_Site_Model {
500
	public $titleFormat   = '/^[a-z0-9_-]+$/';
501
	public $chapterFormat = '/^(?:en(?:-us)?|pt|es)\/[0-9]+(?:\/[0-9]+(?:\/[0-9]+(?:\/[0-9]+)?)?)?$/';
502
	public $customType    = 2;
503
504
	public function getFullTitleURL(string $title_url) : string {
505
		return "{$this->baseURL}/series/{$title_url}";
506
	}
507
508
	public function getChapterData(string $title_url, string $chapter) : array {
509
		$chapter_parts = explode('/', $chapter); //returns #LANG#/#VOLUME#/#CHAPTER#/#CHAPTER_EXTRA#(/#PAGE#/)
510
		return [
511
			'url'    => $this->getChapterURL($title_url, $chapter),
512
			'number' => ($chapter_parts[1] !== '0' ? "v{$chapter_parts[1]}/" : '') . "c{$chapter_parts[2]}" . (isset($chapter_parts[3]) ? ".{$chapter_parts[3]}" : '')/*)*/
513
		];
514
	}
515
	public function getChapterURL(string $title_url, string $chapter) : string {
516
		return "{$this->baseURL}/read/{$title_url}/{$chapter}/";
517
	}
518
519
	public function getTitleData(string $title_url, bool $firstGet = FALSE) : ?array {
520
		$titleData = [];
521
522
		$jsonURL = $this->getJSONTitleURL($title_url);
523
		if($content = $this->get_content($jsonURL)) {
524
			$json = json_decode($content['body'], TRUE);
525
			if($json && isset($json['chapters']) && count($json['chapters']) > 0) {
526
				$titleData['title'] = trim($json['comic']['name']);
527
528
				//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..
529
				usort($json['chapters'], function($a, $b) {
530
					return floatval("{$b['chapter']['chapter']}.{$b['chapter']['subchapter']}") <=> floatval("{$a['chapter']['chapter']}.{$a['chapter']['subchapter']}");
531
				});
532
				$latestChapter = reset($json['chapters'])['chapter'];
533
534
				$latestChapterString = "{$latestChapter['language']}/{$latestChapter['volume']}/{$latestChapter['chapter']}";
535
				if($latestChapter['subchapter'] !== '0') {
536
					$latestChapterString .= "/{$latestChapter['subchapter']}";
537
				}
538
				$titleData['latest_chapter'] = $latestChapterString;
539
540
				//No need to use date() here since this is already formatted as such.
541
				$titleData['last_updated'] = ($latestChapter['updated'] !== '0000-00-00 00:00:00' ? $latestChapter['updated'] : $latestChapter['created']);
542
			}
543
		}
544
545
		return (!empty($titleData) ? $titleData : NULL);
546
	}
547
548
	public function doCustomUpdate() {
549
		$titleDataList = [];
550
551
		$jsonURL = $this->getJSONUpdateURL();
552
		if(($content = $this->get_content($jsonURL)) && $content['status_code'] == 200) {
553
			if(($json = json_decode($content['body'], TRUE)) && isset($json['chapters'])) {
554
				//This should fix edge cases where chapters are uploaded in bulk in the wrong order (HelveticaScans does this with Mousou Telepathy).
555
				usort($json['chapters'], function($a, $b) {
556
					$a_date = new DateTime($a['chapter']['updated'] !== '0000-00-00 00:00:00' ? $a['chapter']['updated'] : $a['chapter']['created']);
557
					$b_date = new DateTime($b['chapter']['updated'] !== '0000-00-00 00:00:00' ? $b['chapter']['updated'] : $b['chapter']['created']);
558
					return $b_date <=> $a_date;
559
				});
560
561
				$parsedTitles = [];
562
				foreach($json['chapters'] as $chapterData) {
563
					if(!in_array($chapterData['comic']['stub'], $parsedTitles)) {
564
						$parsedTitles[] = $chapterData['comic']['stub'];
565
566
						$titleData = [];
567
						$titleData['title'] = trim($chapterData['comic']['name']);
568
569
						$latestChapter = $chapterData['chapter'];
570
571
						$latestChapterString = "en/{$latestChapter['volume']}/{$latestChapter['chapter']}";
572
						if($latestChapter['subchapter'] !== '0') {
573
							$latestChapterString .= "/{$latestChapter['subchapter']}";
574
						}
575
						$titleData['latest_chapter'] = $latestChapterString;
576
577
						//No need to use date() here since this is already formatted as such.
578
						$titleData['last_updated'] = ($latestChapter['updated'] !== '0000-00-00 00:00:00' ? $latestChapter['updated'] : $latestChapter['created']);
579
580
						$titleDataList[$chapterData['comic']['stub']] = $titleData;
581
					} else {
582
						//We already have title data for this title.
583
						continue;
584
					}
585
				}
586
			} else {
587
				log_message('error', "{$this->site} - Custom updating failed (no chapters arg?) for {$this->baseURL}.");
588
			}
589
		} else {
590
			log_message('error', "{$this->site} - Custom updating failed for {$this->baseURL}.");
591
		}
592
593
		return $titleDataList;
594
	}
595
596
	public function getJSONTitleURL(string $title_url) : string {
597
		return "{$this->baseURL}/api/reader/comic/stub/{$title_url}/format/json";
598
	}
599
	public function getJSONUpdateURL() : string {
600
		return "{$this->baseURL}/api/reader/chapters/orderby/desc_created/format/json";
601
	}
602
}
603
604
abstract class Base_myMangaReaderCMS_Site_Model extends Base_Site_Model {
605
	public $titleFormat   = '/^[a-zA-Z0-9_-]+$/';
606
	public $chapterFormat = '/^(?:oneshot|(?:chapter-)?[0-9\.]+)$/';
607
	public $customType    = 2;
608
609
	public function getFullTitleURL(string $title_url) : string {
610
		return "{$this->baseURL}/manga/{$title_url}";
611
	}
612
613
	public function getChapterData(string $title_url, string $chapter) : array {
614
		$chapterN = (ctype_digit($chapter) ? "c${chapter}" : $chapter);
615
		return [
616
			'url'    => $this->getChapterURL($title_url, $chapter),
617
			'number' => $chapterN
618
		];
619
	}
620
	public function getChapterURL(string $title_url, string $chapter) : string {
621
		return $this->getFullTitleURL($title_url).'/'.$chapter;
622
	}
623
624
	public function getTitleData(string $title_url, bool $firstGet = FALSE) : ?array {
625
		$titleData = [];
626
627
		$fullURL = $this->getFullTitleURL($title_url);
628
629
		$content = $this->get_content($fullURL);
630
631
		$data = $this->parseTitleDataDOM(
632
			$content,
0 ignored issues
show
Security Bug introduced by
It seems like $content defined by $this->get_content($fullURL) on line 629 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...
633
			$title_url,
634
			"(//h2[@class='widget-title'])[1]",
635
			"//ul[contains(@class, 'chapters')]/li[not(contains(@class, 'btn'))][1]",
636
			"div[contains(@class, 'action')]/div[@class='date-chapter-title-rtl']",
637
			"h5/a[1] | h3/a[1]",
638
			"Whoops, looks like something went wrong."
639
		);
640
		if($data) {
641
			$titleData['title'] = trim($data['nodes_title']->textContent);
642
643
			$segments = explode('/', (string) $data['nodes_chapter']->getAttribute('href'));
644
			$needle = array_search('manga', array_reverse($segments, TRUE)) + 2;
645
			$titleData['latest_chapter'] = $segments[$needle];
646
647
			$dateString = $data['nodes_latest']->nodeValue;
648
			$titleData['last_updated'] = date("Y-m-d H:i:s", strtotime(preg_replace('/ (-|\[A\]).*$/', '', $dateString)));
649
		}
650
651
		return (!empty($titleData) ? $titleData : NULL);
652
	}
653
654
	public function doCustomUpdate() {
655
		$titleDataList = [];
656
657
		$updateURL = "{$this->baseURL}/latest-release";
658
		if(($content = $this->get_content($updateURL)) && $content['status_code'] == 200) {
659
			$data = $content['body'];
660
661
			$data = preg_replace('/^[\s\S]+<dl>/', '<dl>', $data);
662
			$data = preg_replace('/<\/dl>[\s\S]+$/', '</dl>', $data);
663
664
			$dom = new DOMDocument();
665
			libxml_use_internal_errors(TRUE);
666
			$dom->loadHTML($data);
667
			libxml_use_internal_errors(FALSE);
668
669
			$xpath      = new DOMXPath($dom);
670
			$nodes_rows = $xpath->query("//dl/dd | //div[@class='mangalist']/div[@class='manga-item']");
671
			if($nodes_rows->length > 0) {
672
				foreach($nodes_rows as $row) {
673
					$titleData = [];
674
675
					$nodes_title   = $xpath->query("div[@class='events ']/div[@class='events-body']/h3[@class='events-heading']/a | h3/a", $row);
676
					$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);
677
					$nodes_latest  = $xpath->query("div[@class='time'] | small", $row);
678
679
					if($nodes_title->length === 1 && $nodes_chapter->length === 1 && $nodes_latest->length === 1) {
680
						$title = $nodes_title->item(0);
681
682
						preg_match('/(?<url>[^\/]+(?=\/$|$))/', $title->getAttribute('href'), $title_url_arr);
683
						$title_url = $title_url_arr['url'];
684
685
						if(!array_key_exists($title_url, $titleDataList)) {
686
							$titleData['title'] = trim($title->textContent);
687
688
							$chapter = $nodes_chapter->item(0);
689
							preg_match('/(?<chapter>[^\/]+(?=\/$|$))/', $chapter->getAttribute('href'), $chapter_arr);
690
							$titleData['latest_chapter'] = $chapter_arr['chapter'];
691
692
							$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.
693
							if($dateString == 'T') {
694
								$dateString = date("Y-m-d",now());
695
							}
696
							$titleData['last_updated'] = date("Y-m-d H:i:s", strtotime($dateString . ' 00:00'));
697
698
							$titleDataList[$title_url] = $titleData;
699
						}
700
					} else {
701
						log_message('error', "{$this->site}/Custom | Invalid amount of nodes (TITLE: {$nodes_title->length} | CHAPTER: {$nodes_chapter->length}) | LATEST: {$nodes_latest->length})");
702
					}
703
				}
704
			} else {
705
				log_message('error', "{$this->site} | Following list is empty?");
706
			}
707
		} else {
708
			log_message('error', "{$this->site} - Custom updating failed for {$this->baseURL}.");
709
		}
710
711
		return $titleDataList;
712
	}
713
}
714
715
abstract class Base_GlossyBright_Site_Model extends Base_Site_Model {
716
	public $titleFormat   = '/^[a-zA-Z0-9_-]+$/';
717
	public $chapterFormat = '/^[0-9\.]+$/';
718
719
	public $customType    = 2;
720
721
	public function getFullTitleURL(string $title_url) : string {
722
		return "{$this->baseURL}/{$title_url}";
723
	}
724
725
	public function getChapterData(string $title_url, string $chapter) : array {
726
		return [
727
			'url'    => $this->getFullTitleURL($title_url).'/'.$chapter.'/',
728
			'number' => "c{$chapter}"
729
		];
730
	}
731
732
	public function getTitleData(string $title_url, bool $firstGet = FALSE) : ?array {
733
		$titleData = [];
734
735
		$fullURL = "{$this->baseURL}/manga-rss/{$title_url}";
736
		$content = $this->get_content($fullURL);
737
		$data    = $this->parseTitleDataDOM(
738
			$content,
0 ignored issues
show
Security Bug introduced by
It seems like $content defined by $this->get_content($fullURL) on line 736 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...
739
			$title_url,
740
			"//rss/channel/image/title",
741
			"//rss/channel/item[1]",
742
			"pubdate",
743
			"title"
744
		);
745
		if($data) {
746
			$titleData['title'] = preg_replace('/^Recent chapters of (.*?) manga$/', '$1', trim($data['nodes_title']->textContent));
747
748
			//For whatever reason, DOMDocument breaks the <link> element we need to grab the chapter, so we have to grab it elsewhere.
749
			$titleData['latest_chapter'] = preg_replace('/^.*? - ([0-9\.]+) - .*?$/', '$1', trim($data['nodes_chapter']->textContent));
750
751
			$titleData['last_updated'] =  date("Y-m-d H:i:s", strtotime((string) $data['nodes_latest']->textContent));
752
		}
753
754
		return (!empty($titleData) ? $titleData : NULL);
755
	}
756
757
	public function doCustomUpdate() {
758
		$titleDataList = [];
759
760
		$baseURLRegex = str_replace('.', '\\.', parse_url($this->baseURL, PHP_URL_HOST));
761
		if(($content = $this->get_content($this->baseURL)) && $content['status_code'] == 200) {
762
			$data = $content['body'];
763
764
			$dom = new DOMDocument();
765
			libxml_use_internal_errors(TRUE);
766
			$dom->loadHTML($data);
767
			libxml_use_internal_errors(FALSE);
768
769
			$xpath      = new DOMXPath($dom);
770
			$nodes_rows = $xpath->query("//table[@id='wpm_mng_lst']/tr/td | //*[@id='wpm_mng_lst']/li/div");
771
			if($nodes_rows->length > 0) {
772
				foreach($nodes_rows as $row) {
773
					$titleData = [];
774
775
					$nodes_title   = $xpath->query("a[2]", $row);
776
					$nodes_chapter = $xpath->query("a[2]", $row);
777
					$nodes_latest  = $xpath->query("b", $row);
778
779
					if($nodes_latest->length === 0) {
780
						$nodes_latest = $xpath->query('text()[last()]', $row);
781
					}
782
783
					if($nodes_title->length === 1 && $nodes_chapter->length === 1 && $nodes_latest->length === 1) {
784
						$title   = $nodes_title->item(0);
785
						$chapter = $nodes_chapter->item(0);
786
787
						preg_match('/'.$baseURLRegex.'\/(?<url>.*?)\//', $title->getAttribute('href'), $title_url_arr);
788
						$title_url = $title_url_arr['url'];
789
790
						if(!array_key_exists($title_url, $titleDataList)) {
791
							$titleData['title'] = trim($title->getAttribute('title'));
792
793
							preg_match('/(?<chapter>[^\/]+(?=\/$|$))/', $chapter->getAttribute('href'), $chapter_arr);
794
							$titleData['latest_chapter'] = $chapter_arr['chapter'];
795
796
							$dateString = trim($nodes_latest->item(0)->textContent);
797
							switch($dateString) {
798
								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...
799
									$dateString = date("Y-m-d", now());
800
									break;
801
802
								case 'Yesterday':
803
									$dateString = date("Y-m-d", strtotime("-1 days"));
804
									break;
805
806
								default:
807
									//Do nothing
808
									break;
809
							}
810
							$titleData['last_updated'] = date("Y-m-d H:i:s", strtotime($dateString));
811
812
							$titleDataList[$title_url] = $titleData;
813
						}
814
					} else {
815
						log_message('error', "{$this->site}/Custom | Invalid amount of nodes (TITLE: {$nodes_title->length} | CHAPTER: {$nodes_chapter->length}) | LATEST: {$nodes_latest->length})");
816
					}
817
				}
818
			} else {
819
				log_message('error', "{$this->site} | Following list is empty?");
820
			}
821
		} else {
822
			log_message('error', "{$this->site} - Custom updating failed.");
823
		}
824
825
		return $titleDataList;
826
	}
827
}
828
829
abstract class Base_Roku_Site_Model extends Base_Site_Model {
830
	public $titleFormat   = '/^[a-zA-Z0-9-]+$/';
831
	public $chapterFormat = '/^[0-9\.]+$/';
832
833
	public $customType    = 2;
834
835
	public function getFullTitleURL(string $title_url) : string {
836
		return "{$this->baseURL}/series/{$title_url}";
837
	}
838
	public function getChapterData(string $title_url, string $chapter) : array {
839
		return [
840
			'url'    => "{$this->baseURL}/read/{$title_url}/{$chapter}",
841
			'number' => "c{$chapter}"
842
		];
843
	}
844
	public function getTitleData(string $title_url, bool $firstGet = FALSE) : ?array {
845
		$titleData = [];
846
		$fullURL = $this->getFullTitleURL($title_url);
847
		$content = $this->get_content($fullURL);
848
		$data = $this->parseTitleDataDOM(
849
			$content,
0 ignored issues
show
Security Bug introduced by
It seems like $content defined by $this->get_content($fullURL) on line 847 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...
850
			$title_url,
851
			"//div[@id='activity']/descendant::div[@class='media'][1]/descendant::div[@class='media-body']/h2/text()",
852
			"//ul[contains(@class, 'media-list')]/li[@class='media'][1]/a",
853
			"div[@class='media-body']/span[@class='text-muted']",
854
			""
855
		);
856
		if($data) {
857
			$titleData['title'] = trim(preg_replace('/ Added on .*$/','', $data['nodes_title']->textContent));
858
			$titleData['latest_chapter'] = preg_replace('/^.*\/([0-9\.]+)$/', '$1', (string) $data['nodes_chapter']->getAttribute('href'));
859
860
			$dateString = preg_replace('/^Added (?:on )?/', '',$data['nodes_latest']->textContent);
861
			$titleData['last_updated'] =  date("Y-m-d H:i:s", strtotime($dateString));
862
		}
863
		return (!empty($titleData) ? $titleData : NULL);
864
	}
865
866
867
	public function doCustomUpdate() {
868
		$titleDataList = [];
869
870
		$updateURL = "{$this->baseURL}/latest";
871
		if(($content = $this->get_content($updateURL)) && $content['status_code'] == 200) {
872
			$data = $content['body'];
873
874
			$dom = new DOMDocument();
875
			libxml_use_internal_errors(TRUE);
876
			$dom->loadHTML($data);
877
			libxml_use_internal_errors(FALSE);
878
879
			$xpath      = new DOMXPath($dom);
880
			$nodes_rows = $xpath->query("//div[@class='content-wrapper']/div[@class='row']/div/div");
881
			if($nodes_rows->length > 0) {
882
				foreach($nodes_rows as $row) {
883
					$titleData = [];
884
885
					$nodes_title   = $xpath->query("div[@class='caption']/h6/a", $row);
886
					$nodes_chapter = $xpath->query("div[@class='panel-footer no-padding']/a", $row);
887
					$nodes_latest  = $xpath->query("div[@class='caption']/text()", $row);
888
889
					if($nodes_title->length === 1 && $nodes_chapter->length === 1 && $nodes_latest->length === 1) {
890
						$title = $nodes_title->item(0);
891
892
						preg_match('/(?<url>[^\/]+(?=\/$|$))/', $title->getAttribute('href'), $title_url_arr);
893
						$title_url = $title_url_arr['url'];
894
895
						if(!array_key_exists($title_url, $titleDataList)) {
896
							$titleData['title'] = trim($title->textContent);
897
898
							$chapter = $nodes_chapter->item(0);
899
							preg_match('/(?<chapter>[^\/]+(?=\/$|$))/', $chapter->getAttribute('href'), $chapter_arr);
900
							$titleData['latest_chapter'] = $chapter_arr['chapter'];
901
902
							$dateString = trim(str_replace('Added ', '', $nodes_latest->item(0)->textContent));
903
							$titleData['last_updated'] = date("Y-m-d H:i:s", strtotime($dateString));
904
905
							$titleDataList[$title_url] = $titleData;
906
						}
907
					} else {
908
						log_message('error', "{$this->site}/Custom | Invalid amount of nodes (TITLE: {$nodes_title->length} | CHAPTER: {$nodes_chapter->length}) | LATEST: {$nodes_latest->length})");
909
					}
910
				}
911
			} else {
912
				log_message('error', "{$this->site} | Following list is empty?");
913
			}
914
		} else {
915
			log_message('error', "{$this->site} - Custom updating failed.");
916
		}
917
918
		return $titleDataList;
919
	}
920
}
921