Completed
Push — master ( 8555c7...3d8b58 )
by Angus
02:42
created

MangaFox::handleCustomFollow()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 11
nc 1
nop 3
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
ccs 0
cts 14
cp 0
crap 2
1
<?php declare(strict_types=1); defined('BASEPATH') OR exit('No direct script access allowed');
2
3
class MangaFox extends Base_Site_Model {
4
	public $titleFormat   = '/^[a-z0-9_]+$/';
5
	public $chapterFormat = '/^(?:v[0-9a-zA-Z]+\/)?c[0-9\.]+$/';
6
7
	public function getFullTitleURL(string $title_url) : string {
8
		return "http://mangafox.me/manga/{$title_url}/";
9
	}
10
11
	public function getChapterData(string $title_url, string $chapter) : array {
12
		return [
13
			'url'    => "http://mangafox.me/manga/{$title_url}/{$chapter}/1.html",
14
			'number' => $chapter
15
		];
16
	}
17
18
	public function getTitleData(string $title_url, bool $firstGet = FALSE) {
19
		$titleData = [];
20
21
		$fullURL = $this->getFullTitleURL($title_url);
22
		$content = $this->get_content($fullURL);
23
24
		$data = $this->parseTitleDataDOM(
25
			$content,
0 ignored issues
show
Security Bug introduced by
It seems like $content defined by $this->get_content($fullURL) on line 22 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...
26
			$title_url,
27
			"//title",
28
			"//body/div[@id='page']/div[@class='left']/div[@id='chapters']/ul[1]/li[1]",
29
			"div/span[@class='date']",
30
			"div/h3/a"
31
		);
32
		if($data) {
33
			$titleData['title'] = html_entity_decode(explode(' Manga - Read ', $data['nodes_title']->textContent)[0]);
34
35
			$link = preg_replace('/^(.*\/)(?:[0-9]+\.html)?$/', '$1', (string) $data['nodes_chapter']->getAttribute('href'));
36
			$chapterURLSegments = explode('/', $link);
37
			$titleData['latest_chapter'] = $chapterURLSegments[5] . (isset($chapterURLSegments[6]) && !empty($chapterURLSegments[6]) ? "/{$chapterURLSegments[6]}" : "");
38
			$titleData['last_updated'] =  date("Y-m-d H:i:s", strtotime((string) $data['nodes_latest']->nodeValue));
39
40
			if($firstGet) {
41
				$this->doCustomFollow($content['body']);
42
			}
43
		}
44
45
		return (!empty($titleData) ? $titleData : NULL);
46
	}
47
48
	//FIXME: This entire thing feels like an awful implementation....BUT IT WORKS FOR NOW.
49
	public function handleCustomFollow(callable $callback, string $data = "", array $extra = []) {
50
		preg_match('/var sid=(?<id>[0-9]+);/', $data, $matches);
51
52
		$formData = [
53
			'action' => 'add',
54
			'sid'    => $matches['id']
55
		];
56
57
		$cookies = [
58
			"mfvb_userid={$this->config->item('mangafox_userid')}",
59
			"mfvb_password={$this->config->item('mangafox_password')}",
60
			"bmsort=last_chapter"
61
		];
62
		$content = $this->get_content('http://mangafox.me/ajax/bookmark.php', implode("; ", $cookies), "", TRUE, TRUE, $formData);
63
64
		$callback($content, $matches['id']);
65
	}
66
	public function doCustomUpdate() {
67
		$titleDataList = [];
68
69
		$cookies = [
70
			"mfvb_userid={$this->config->item('mangafox_userid')}",
71
			"mfvb_password={$this->config->item('mangafox_password')}",
72
			"bmsort=last_chapter",
73
			"bmorder=za"
74
		];
75
		$content = $this->get_content('http://mangafox.me/bookmark/?status=currentreading&sort=last_chapter&order=za', implode("; ", $cookies), "", TRUE);
76
77
		if(!is_array($content)) {
78
			log_message('error', "{$this->site} /bookmark | Failed to grab URL (See above curl error)");
79
		} else {
80
			$headers     = $content['headers'];
0 ignored issues
show
Unused Code introduced by
$headers is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
81
			$status_code = $content['status_code'];
82
			$data        = $content['body'];
83
84
			if(!($status_code >= 200 && $status_code < 300)) {
85
				log_message('error', "{$this->site} /bookmark | Bad Status Code ({$status_code})");
86
			} else if(empty($data)) {
87
				log_message('error', "{$this->site} /bookmark | Data is empty? (Status code: {$status_code})");
88
			} else {
89
				$data = preg_replace('/^[\s\S]+<ul id="bmlist">/', '<ul id="bmlist">', $data);
90
				$data = preg_replace('/<!-- end of bookmark -->[\s\S]+$/', '<!-- end of bookmark -->', $data);
91
92
				$dom = new DOMDocument();
93
				libxml_use_internal_errors(TRUE);
94
				$dom->loadHTML($data);
95
				libxml_use_internal_errors(FALSE);
96
97
				$xpath      = new DOMXPath($dom);
98
				$nodes_rows = $xpath->query("//ul[@id='bmlist']/li/div[@class='series_grp' and h2[@class='title']/span[@class='updatedch'] and dl]");
99
				if($nodes_rows->length > 0) {
100
					foreach($nodes_rows as $row) {
101
						$titleData = [];
102
103
						$nodes_title   = $xpath->query("h2[@class='title']/a[contains(@class, 'title')]", $row);
104
						$nodes_chapter = $xpath->query("dl/dt[1]/a[@class='chapter']", $row);
105
						$nodes_latest  = $xpath->query("dl/dt[1]/em/span[@class='timing']", $row);
106
107
						if($nodes_title->length === 1 && $nodes_chapter->length === 1 && $nodes_latest->length === 1) {
108
							$title = $nodes_title->item(0);
109
110
							$titleData['title'] = trim($title->textContent);
111
112
113
							$link = preg_replace('/^(.*\/)(?:[0-9]+\.html)?$/', '$1', (string) $nodes_chapter->item(0)->getAttribute('href'));
114
							$chapterURLSegments = explode('/', $link);
115
							$titleData['latest_chapter'] = $chapterURLSegments[5] . (isset($chapterURLSegments[6]) && !empty($chapterURLSegments[6]) ? "/{$chapterURLSegments[6]}" : "");
116
117
							$titleData['last_updated'] =  date("Y-m-d H:i:s", strtotime((string) $nodes_latest->item(0)->nodeValue));
118
119
							$title_url = explode('/', $title->getAttribute('href'))[4];
120
							$titleDataList[$title_url] = $titleData;
121
						} else {
122
							log_message('error', "{$this->site}/Custom | Invalid amount of nodes (TITLE: {$nodes_title->length} | CHAPTER: {$nodes_chapter->length}) | LATEST: {$nodes_latest->length})");
123
						}
124
					}
125
				} else {
126
					log_message('error', '{$this->site} | Following list is empty?');
127
				}
128
			}
129
		}
130
		return $titleDataList;
131
	}
132
	public function doCustomCheck(string $oldChapterString, string $newChapterString) {
133
		$status = FALSE;
134
135
		$oldChapterSegments = explode('/', $oldChapterString);
136
		$newChapterSegments = explode('/', $newChapterString);
137
138
		//Although it's rare, it's possible for new chapters to have a different amount of segments to the oldChapter (or vice versa).
139
		//Since this can cause errors, we just throw a fail.
140
		$count = count($newChapterSegments);
141 View Code Duplication
		if($count === count($oldChapterSegments)) {
142
			if($count === 2) {
143
				//FIXME: This feels like a mess.
144
				$oldVolume = substr(array_shift($oldChapterSegments), 1);
145
				$newVolume = substr(array_shift($newChapterSegments), 1);
146
147
				if(in_array($oldVolume, ['TBD', 'TBA', 'NA', 'LMT'])) $oldVolume = 999;
148
				if(in_array($newVolume, ['TBD', 'TBA', 'NA', 'LMT'])) $newVolume = 999;
149
150
				$oldVolume = floatval($oldVolume);
151
				$newVolume = floatval($newVolume);
152
			} else {
153
				$oldVolume = 0;
154
				$newVolume = 0;
155
			}
156
			$oldChapter = floatval(substr(array_shift($oldChapterSegments), 1));
157
			$newChapter = floatval(substr(array_shift($newChapterSegments), 1));
158
159
			if($newVolume > $oldVolume) {
160
				//$newVolume is higher, no need to check chapter.
161
				$status = TRUE;
162
			} elseif($newChapter > $oldChapter) {
163
				//$newVolume isn't higher, but chapter is.
164
				$status = TRUE;
165
			}
166
		}
167
168
		return $status;
169
	}
170
}
171