Completed
Push — master ( 9156a4...0ac3a5 )
by Angus
04:44
created

Base_Site_Model::getChapterData()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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