Completed
Pull Request — master (#294)
by
unknown
02:38
created

Bookmarks::addBookmark()   B

Complexity

Conditions 7
Paths 14

Size

Total Lines 64
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 11.3705

Importance

Changes 0
Metric Value
cc 7
eloc 45
nc 14
nop 7
dl 0
loc 64
ccs 26
cts 47
cp 0.5532
crap 11.3705
rs 7.2058
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * ownCloud - bookmarks plugin
5
 *
6
 * @author Arthur Schiwon
7
 * @copyright 2011 Arthur Schiwon [email protected]
8
 *
9
 * This library is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
11
 * License as published by the Free Software Foundation; either
12
 * version 3 of the License, or any later version.
13
 *
14
 * This library is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public
20
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
/**
24
 * This class manages bookmarks
25
 */
26
27
namespace OCA\Bookmarks\Controller\Lib;
28
29
use GuzzleHttp\Exception\ClientException;
30
use \OCP\IDb;
31
32
class Bookmarks {
33
34
	/**
35
	 * @brief Finds all tags for bookmarks
36
	 * @param string $userId UserId
37
	 * @param IDb $db Database Interface
38
	 * @param filterTags array of tag to look for if empty then every tag
39
	 * @param offset integer offset
40
	 * @param limit integer of item to return
41
	 * @return Found Tags
42
	 */
43 1
	public static function findTags($userId, IDb $db, $filterTags = array(), $offset = 0, $limit = -1) {
44 1
		$params = array_merge($filterTags, $filterTags);
45 1
		array_unshift($params, $userId);
46 1
		$not_in = '';
47 1
		if (!empty($filterTags)) {
48
			$exist_clause = " AND	exists (select 1 from `*PREFIX*bookmarks_tags`
49
				`t2` where `t2`.`bookmark_id` = `t`.`bookmark_id` and `tag` = ?) ";
50
51
			$not_in = ' AND `tag` not in (' . implode(',', array_fill(0, count($filterTags), '?')) . ')' .
52
					str_repeat($exist_clause, count($filterTags));
53
		}
54
		$sql = 'SELECT tag, count(*) as nbr from *PREFIX*bookmarks_tags t ' .
55 1
				' WHERE EXISTS( SELECT 1 from *PREFIX*bookmarks bm where  t.bookmark_id  = bm.id and user_id = ?) ' .
56 1
				$not_in .
57 1
				' GROUP BY `tag` ORDER BY `nbr` DESC ';
58
59 1
		$query = $db->prepareQuery($sql, $limit, $offset);
60 1
		$tags = $query->execute($params)->fetchAll();
61 1
		return $tags;
62
	}
63
64
	/**
65
	 * @brief Finds Bookmark with certain ID
66
	 * @param int $id BookmarkId
67
	 * @param string $userId UserId
68
	 * @param IDb $db Database Interface
69
	 * @return array Specific Bookmark
70
	 */
71 2
	public static function findUniqueBookmark($id, $userId, IDb $db) {
72 2
		$CONFIG_DBTYPE = \OCP\Config::getSystemValue('dbtype', 'sqlite');
73 2
		if ($CONFIG_DBTYPE == 'pgsql') {
74
			$group_fct = 'array_agg(`tag`)';
75
		} else {
76 2
			$group_fct = 'GROUP_CONCAT(`tag`)';
77
		}
78
		$sql = "SELECT *, (select $group_fct from `*PREFIX*bookmarks_tags` where `bookmark_id` = `b`.`id`) as `tags`
79
				FROM `*PREFIX*bookmarks` `b`
80 2
				WHERE `user_id` = ? AND `id` = ?";
81 2
		$query = $db->prepareQuery($sql);
82 2
		$result = $query->execute(array($userId, $id))->fetchRow();
83 2
		$result['tags'] = explode(',', $result['tags']);
84 2
		return $result;
85
	}
86
87
	/**
88
	 * @brief Check if an URL is bookmarked
89
	 * @param string $url Url of a possible bookmark
90
	 * @param string $userId UserId
91
	 * @param IDb $db Database Interface
92
	 * @return boolean if the url is already bookmarked
93
	 */
94 1
	public static function bookmarkExists($url, $userId, IDb $db) {
95 1
		$enc_url = htmlspecialchars_decode($url);
96 1
		$sql = "SELECT id from `*PREFIX*bookmarks` where `url` = ? and `user_id` = ?";
97 1
		$query = $db->prepareQuery($sql);
98 1
		$result = $query->execute(array($enc_url, $userId))->fetchRow();
99 1
		if ($result) {
100 1
			return $result['id'];
101
		} else {
102 1
			return false;
103
		}
104
	}
105
106
	/**
107
	 * @brief Finds all bookmarks, matching the filter
108
	 * @param string $userid UserId
109
	 * @param IDb $db Database Interface
110
	 * @param int $offset offset
111
	 * @param string $sqlSortColumn result with this column
112
	 * @param string|array $filters filters can be: empty -> no filter, a string -> filter this, a string array -> filter for all strings
113
	 * @param bool $filterTagOnly true, filter affects only tags, else filter affects url, title and tags
114
	 * @param int $limit limit of items to return (default 10) if -1 or false then all items are returned
115
	 * @param bool $public check if only public bookmarks should be returned
116
	 * @param array $requestedAttributes select all the attributes that should be returned. default is * + tags
117
	 * @param string $tagFilterConjunction select wether the filterTagOnly should filter with an AND or an OR  conjunction
118
	 * @return Collection of specified bookmarks
119
	 */
120 3
	public static function findBookmarks(
121
	$userid, IDb $db, $offset, $sqlSortColumn, $filters, $filterTagOnly, $limit = 10, $public = false, $requestedAttributes = null, $tagFilterConjunction = "and") {
122
123 3
		$CONFIG_DBTYPE = \OCP\Config::getSystemValue('dbtype', 'sqlite');
124 3
		if (is_string($filters)) {
125
			$filters = array($filters);
126
		}
127
128 3
		$toSelect = '*';
129 3
		$tableAttributes = array('id', 'url', 'title', 'user_id', 'description',
130 3
			'public', 'added', 'lastmodified', 'clickcount',);
131
132 3
		$returnTags = true;
133
134 3
		if ($requestedAttributes != null) {
135
136 1
			$key = array_search('tags', $requestedAttributes);
137 1
			if ($key == false) {
138 1
				$returnTags = false;
139 1
			} else {
140
				unset($requestedAttributes[$key]);
141
			}
142
143 1
			$toSelect = implode(",", array_intersect($tableAttributes, $requestedAttributes));
144 1
		}
145
146 3
		if ($CONFIG_DBTYPE == 'pgsql') {
147
			$sql = "SELECT " . $toSelect . " FROM (SELECT *, (select array_to_string(array_agg(`tag`),',')
148
				from `*PREFIX*bookmarks_tags` where `bookmark_id` = `b2`.`id`) as `tags`
149
				FROM `*PREFIX*bookmarks` `b2`
150
				WHERE `user_id` = ? ) as `b` WHERE true ";
151
		} else {
152 3
			$sql = "SELECT " . $toSelect . ", (SELECT GROUP_CONCAT(`tag`) from `*PREFIX*bookmarks_tags`
153
				WHERE `bookmark_id` = `b`.`id`) as `tags`
154
				FROM `*PREFIX*bookmarks` `b`
155 3
				WHERE `user_id` = ? ";
156
		}
157
158 3
		$params = array($userid);
159
160 3
		if ($public) {
161 1
			$sql .= ' AND public = 1 ';
162 1
		}
163
164 3
		if (count($filters) > 0) {
165 2
			Bookmarks::findBookmarksBuildFilter($sql, $params, $filters, $filterTagOnly, $tagFilterConjunction, $CONFIG_DBTYPE);
166 2
		}
167
168 3
		if (!in_array($sqlSortColumn, $tableAttributes)) {
169 1
			$sqlSortColumn = 'lastmodified';
170 1
		}
171 3
		$sql .= " ORDER BY " . $sqlSortColumn . " DESC ";
172 3
		if ($limit == -1 || $limit === false) {
173 3
			$limit = null;
174 3
			$offset = null;
175 3
		}
176
177 3
		$query = $db->prepareQuery($sql, $limit, $offset);
178 3
		$results = $query->execute($params)->fetchAll();
179 3
		$bookmarks = array();
180 3
		foreach ($results as $result) {
181 3
			if ($returnTags) {
182 2
				$result['tags'] = explode(',', $result['tags']);
183 2
			} else {
184 1
				unset($result['tags']);
185
			}
186 3
			$bookmarks[] = $result;
187 3
		}
188 3
		return $bookmarks;
189
	}
190
191 2
	private static function findBookmarksBuildFilter(&$sql, &$params, $filters, $filterTagOnly, $tagFilterConjunction, $CONFIG_DBTYPE) {
192 2
		$tagOrSearch = false;
193 2
		$connectWord = 'AND';
194
195 2
		if ($tagFilterConjunction == 'or') {
196 1
			$tagOrSearch = true;
197 1
			$connectWord = 'OR';
198 1
		}
199
200 2
		if ($filterTagOnly) {
201 2
			if ($tagOrSearch) {
202 1
				$sql .= 'AND (';
203 1
			} else {
204 1
				$sql .= 'AND';
205
			}
206
			$exist_clause = " exists (SELECT `id` FROM  `*PREFIX*bookmarks_tags`
207 2
				`t2` WHERE `t2`.`bookmark_id` = `b`.`id` AND `tag` = ?) ";
208 2
			$sql .= str_repeat($exist_clause . $connectWord, count($filters));
209 2
			if ($tagOrSearch) {
210 1
				$sql = rtrim($sql, 'OR');
211 1
				$sql .= ')';
212 1
			} else {
213 1
				$sql = rtrim($sql, 'AND');
214
			}
215 2
			$params = array_merge($params, $filters);
216 2
		} else {
217
			if ($CONFIG_DBTYPE == 'mysql') { //Dirty hack to allow usage of alias in where
218
				$sql .= ' HAVING true ';
219
			}
220
			foreach ($filters as $filter) {
221
				if ($CONFIG_DBTYPE == 'mysql') {
222
					$sql .= ' AND lower( concat(url,title,description,IFNULL(tags,\'\') )) like ? ';
223
				} else {
224
					$sql .= ' AND lower(url || title || description || ifnull(tags,\'\') ) like ? ';
225
				}
226
				$params[] = '%' . strtolower($filter) . '%';
227
			}
228
		}
229 2
	}
230
231
	/**
232
	 * @brief Delete bookmark with specific id
233
	 * @param string $userId UserId
234
	 * @param IDb $db Database Interface
235
	 * @param int $id Bookmark ID to delete
236
	 * @return boolean Success of operation
237
	 */
238 1
	public static function deleteUrl($userId, IDb $db, $id) {
239 1
		$user = $userId;
240
241 1
		$query = $db->prepareQuery("
242
				SELECT `id` FROM `*PREFIX*bookmarks`
243
				WHERE `id` = ?
244
				AND `user_id` = ?
245 1
				");
246
247 1
		$result = $query->execute(array($id, $user));
248 1
		$id = $result->fetchOne();
249 1
		if ($id === false) {
250
			return false;
251
		}
252
253 1
		$query = $db->prepareQuery("
254
			DELETE FROM `*PREFIX*bookmarks`
255
			WHERE `id` = ?
256 1
			");
257
258 1
		$query->execute(array($id));
259
260 1
		$query = $db->prepareQuery("
261
			DELETE FROM `*PREFIX*bookmarks_tags`
262
			WHERE `bookmark_id` = ?
263 1
			");
264
265 1
		$query->execute(array($id));
266 1
		\OC_Hook::emit('\OCA\Bookmarks', 'post_delete', array('id' => $id));
267
		
268 1
		return true;
269
	}
270
271
	/**
272
	 * @brief Rename a tag
273
	 * @param string $userId UserId
274
	 * @param IDb $db Database Interface
275
	 * @param string $old Old Tag Name
276
	 * @param string $new New Tag Name
277
	 * @return boolean Success of operation
278
	 */
279
	public static function renameTag($userId, IDb $db, $old, $new) {
280
		$user_id = $userId;
281
		$CONFIG_DBTYPE = \OCP\Config::getSystemValue('dbtype', 'sqlite');
282
283
284
		if ($CONFIG_DBTYPE == 'sqlite' or $CONFIG_DBTYPE == 'sqlite3') {
285
			// Update tags to the new label unless it already exists a tag like this
286
			$query = $db->prepareQuery("
287
				UPDATE OR REPLACE `*PREFIX*bookmarks_tags`
288
				SET `tag` = ?
289
				WHERE `tag` = ?
290
				AND exists( select `b`.`id` from `*PREFIX*bookmarks` `b`
291
				WHERE `b`.`user_id` = ? AND `bookmark_id` = `b`.`id`)
292
			");
293
294
			$params = array(
295
				$new,
296
				$old,
297
				$user_id,
298
			);
299
300
			$query->execute($params);
301
		} else {
302
303
			// Remove potentialy duplicated tags
304
			$query = $db->prepareQuery("
305
			DELETE FROM `*PREFIX*bookmarks_tags` as `tgs` WHERE `tgs`.`tag` = ?
306
			AND exists( SELECT `id` FROM `*PREFIX*bookmarks` WHERE `user_id` = ?
307
			AND `tgs`.`bookmark_id` = `id`)
308
			AND exists( SELECT `t`.`tag` FROM `*PREFIX*bookmarks_tags` `t` where `t`.`tag` = ?
309
			AND `tgs`.`bookmark_id` = `t`.`bookmark_id`)");
310
311
			$params = array(
312
				$new,
313
				$user_id,
314
				$new
315
			);
316
317
			$query->execute($params);
318
319
320
			// Update tags to the new label unless it already exists a tag like this
321
			$query = $db->prepareQuery("
322
			UPDATE `*PREFIX*bookmarks_tags`
323
			SET `tag` = ?
324
			WHERE `tag` = ?
325
			AND exists( SELECT `b`.`id` FROM `*PREFIX*bookmarks` `b`
326
			WHERE `b`.`user_id` = ? AND `bookmark_id` = `b`.`id`)
327
			");
328
329
			$params = array(
330
				$new,
331
				$old,
332
				$user_id
333
			);
334
335
			$query->execute($params);
336
		}
337
338
339
		return true;
340
	}
341
342
	/**
343
	 * @brief Delete a tag
344
	 * @param string $userid UserId
345
	 * @param IDb $db Database Interface
346
	 * @param string $old Tag Name to delete
347
	 * @return boolean Success of operation
348
	 */
349
	public static function deleteTag($userid, IDb $db, $old) {
350
351
		// Update the record
352
		$query = $db->prepareQuery("
353
		DELETE FROM `*PREFIX*bookmarks_tags`
354
		WHERE `tag` = ?
355
		AND exists( SELECT `id` FROM `*PREFIX*bookmarks` WHERE `user_id` = ? AND `bookmark_id` = `id`)
356
		");
357
358
		$params = array(
359
			$old,
360
			$userid,
361
		);
362
363
		$result = $query->execute($params);
364
		return $result;
365
	}
366
367
	/**
368
	 * Edit a bookmark
369
	 * @param string $userid UserId
370
	 * @param IDb $db Database Interface
371
	 * @param int $id The id of the bookmark to edit
372
	 * @param string $url The url to set
373
	 * @param string $title Name of the bookmark
374
	 * @param array $tags Simple array of tags to qualify the bookmark (different tags are taken from values)
375
	 * @param string $description A longer description about the bookmark
376
	 * @param boolean $is_public True if the bookmark is publishable to not registered users
377
	 * @return null
378
	 */
379 1
	public static function editBookmark($userid, IDb $db, $id, $url, $title, $tags = array(), $description = '', $is_public = false) {
380
381 1
		$is_public = $is_public ? 1 : 0;
382 1
		$user_id = $userid;
383
384
		// Update the record
385 1
		$query = $db->prepareQuery("
386
		UPDATE `*PREFIX*bookmarks` SET
387
			`url` = ?, `title` = ?, `public` = ?, `description` = ?,
388
			`lastmodified` = UNIX_TIMESTAMP()
389
		WHERE `id` = ?
390
		AND `user_id` = ?
391 1
		");
392
393
		$params = array(
394 1
			htmlspecialchars_decode($url),
395 1
			htmlspecialchars_decode($title),
396 1
			$is_public,
397 1
			htmlspecialchars_decode($description),
398 1
			$id,
399 1
			$user_id,
400 1
		);
401
402 1
		$result = $query->execute($params);
403
404
		// Abort the operation if bookmark couldn't be set
405
		// (probably because the user is not allowed to edit this bookmark)
406 1
		if ($result == 0)
407 1
			exit();
408
409
410
		// Remove old tags
411 1
		$sql = "DELETE FROM `*PREFIX*bookmarks_tags`  WHERE `bookmark_id` = ?";
412 1
		$query = $db->prepareQuery($sql);
413 1
		$query->execute(array($id));
414
415
		// Add New Tags
416 1
		self::addTags($db, $id, $tags);
417
418 1
		return $id;
419
	}
420
421
	/**
422
	 * Add a bookmark
423
	 * @param string $userid UserId
424
	 * @param IDb $db Database Interface
425
	 * @param string $url
426
	 * @param string $title Name of the bookmark
427
	 * @param array $tags Simple array of tags to qualify the bookmark (different tags are taken from values)
428
	 * @param string $description A longer description about the bookmark
429
	 * @param boolean $public True if the bookmark is publishable to not registered users
0 ignored issues
show
Documentation introduced by
There is no parameter named $public. Did you maybe mean $is_public?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
430
	 * @return int The id of the bookmark created
431
	 */
432 8
	public static function addBookmark($userid, IDb $db, $url, $title, $tags = array(), $description = '', $is_public = false) {
433 8
		$public = $is_public ? 1 : 0;
434 8
		$url_without_prefix = trim(substr($url, strpos($url, "://") + 3)); // Removes everything from the url before the "://" pattern (included)
435 8
		if($url_without_prefix === '') {
436
			throw new \InvalidArgumentException('Bookmark URL is missing');
437
		}
438 8
		$enc_url_noprefix = htmlspecialchars_decode($url_without_prefix);
439 8
		$enc_url = htmlspecialchars_decode($url);
440
441 8
		$title = mb_substr($title, 0, 4096);
442 8
		$description = mb_substr($description, 0, 4096);
443
444
		// Change lastmodified date if the record if already exists
445 8
		$sql = "SELECT * from  `*PREFIX*bookmarks` WHERE `url` like ? AND `user_id` = ?";
446 8
		$query = $db->prepareQuery($sql, 1);
447 8
		$result = $query->execute(array('%'.$enc_url_noprefix, $userid)); // Find url in the db independantly from its protocol
448 8
		if ($row = $result->fetchRow()) {
449
			$params = array();
450
			$title_str = '';
451
			if (trim($title) != '') { // Do we replace the old title
452
				$title_str = ' , title = ?';
453
				$params[] = $title;
454
			}
455
			$desc_str = '';
456
			if (trim($description) != '') { // Do we replace the old description
457
				$desc_str = ' , description = ?';
458
				$params[] = $description;
459
			}
460
			$sql = "UPDATE `*PREFIX*bookmarks` SET `lastmodified` = "
461
					. "UNIX_TIMESTAMP() $title_str $desc_str , `url` = ? WHERE `url` like ? and `user_id` = ?";
462
			$params[] = $enc_url;
463
			$params[] = '%'.$enc_url_noprefix;
464
			$params[] = $userid;
465
			$query = $db->prepareQuery($sql);
466
			$query->execute($params);
467
			
468
			\OC_Hook::emit('\OCA\Bookmarks', 'post_edit', array('id' => $row['id']));
469
				
470
			return $row['id'];
471
		} else {
472 8
			$query = $db->prepareQuery("
473
			INSERT INTO `*PREFIX*bookmarks`
474
			(`url`, `title`, `user_id`, `public`, `added`, `lastmodified`, `description`)
475
			VALUES (?, ?, ?, ?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), ?)
476 8
			");
477
478
			$params = array(
479 8
				$enc_url,
480 8
				htmlspecialchars_decode($title),
481 8
				$userid,
482 8
				$public,
483 8
				$description,
484 8
			);
485 8
			$query->execute($params);
486
487 8
			$b_id = $db->getInsertId('*PREFIX*bookmarks');
488
489 8
			if ($b_id !== false) {
490 8
				\OC_Hook::emit('\OCA\Bookmarks', 'post_add', array('id' => $b_id));
491 8
			    self::addTags($db, $b_id, $tags);
492 8
				return $b_id;
493
			}
494
		}
495
	}
496
497
	/**
498
	 * @brief Add a set of tags for a bookmark
499
	 * @param IDb $db Database Interface
500
	 * @param int $bookmarkID The bookmark reference
501
	 * @param array $tags Set of tags to add to the bookmark
502
	 * @return null
503
	 * */
504 8
	private static function addTags(IDb $db, $bookmarkID, $tags) {
505 8
		$sql = 'INSERT INTO `*PREFIX*bookmarks_tags` (`bookmark_id`, `tag`) select ?, ? ';
506 8
		$dbtype = \OCP\Config::getSystemValue('dbtype', 'sqlite');
507
508 8
		if ($dbtype === 'mysql') {
509
			$sql .= 'from dual ';
510
		}
511 8
		$sql .= 'where not exists(select * from `*PREFIX*bookmarks_tags` where `bookmark_id` = ? and `tag` = ?)';
512
513 8
		$query = $db->prepareQuery($sql);
514 8
		foreach ($tags as $tag) {
515 8
			$tag = trim($tag);
516 8
			if (empty($tag)) {
517
				//avoid saving white spaces
518
				continue;
519
			}
520 8
			$params = array($bookmarkID, $tag, $bookmarkID, $tag);
521 8
			$query->execute($params);
522 8
		}
523 8
	}
524
525
	/**
526
	 * @brief Import Bookmarks from html formatted file
527
	 * @param string $user User imported Bookmarks should belong to
528
	 * @param IDb $db Database Interface
529
	 * @param string $file Content to import
530
	 * @return null
531
	 * */
532
	public static function importFile($user, IDb $db, $file) {
533
		libxml_use_internal_errors(true);
534
		$dom = new \domDocument();
535
536
		$dom->loadHTMLFile($file);
537
		$links = $dom->getElementsByTagName('a');
538
539
		$l = \OC::$server->getL10NFactory()->get('bookmarks');
540
		$errors = [];
541
542
		// Reintroduce transaction here!?
543
		foreach ($links as $link) {
544
			/* @var \DOMElement $link */
545
			$title = $link->nodeValue;
546
			$ref = $link->getAttribute("href");
547
			$tag_str = '';
548
			if ($link->hasAttribute("tags"))
549
				$tag_str = $link->getAttribute("tags");
550
			$tags = explode(',', $tag_str);
551
552
			$desc_str = '';
553
			if ($link->hasAttribute("description"))
554
				$desc_str = $link->getAttribute("description");
555
			try {
556
				self::addBookmark($user, $db, $ref, $title, $tags, $desc_str);
557
			} catch (\InvalidArgumentException $e) {
558
				\OC::$server->getLogger()->logException($e, ['app' => 'bookmarks']);
559
				$errors[] =  $l->t('Failed to import one bookmark, because: ') . $e->getMessage();
560
			}
561
		}
562
563
		return $errors;
564
	}
565
566
	/**
567
	 * @brief Load Url and receive Metadata (Title)
568
	 * @param string $url Url to load and analyze
569
	 * @return array Metadata for url;
570
	 * @throws \Exception|ClientException
571
	 */
572 1
	public static function getURLMetadata($url) {
573
		
574 1
		$metadata = array();
575 1
		$metadata['url'] = $url;
576 1
		$page = "";
577
		
578
		try {
579 1
			$request = \OC::$server->getHTTPClientService()->newClient()->get($url);
580 1
			$page = $request->getBody();
581 1
			$contentType = $request->getHeader('Content-Type');
582 1
		} catch (ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
583
			$errorCode = $e->getCode();
584
			if(!($errorCode >= 401 && $errorCode <= 403)) {
585
				// whitelist Unauthorized, Forbidden and Paid pages
586
				throw $e;
587
			}
588
		} catch (\Exception $e) {
589
			throw $e;
590
		}
591
		
592
		//Check for encoding of site.
593
		//If not UTF-8 convert it.
594 1
		$encoding = array();
595 1
		preg_match('#.+?/.+?;\\s?charset\\s?=\\s?(.+)#i', $contentType, $encoding);
0 ignored issues
show
Bug introduced by
The variable $contentType 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...
596 1
		if(empty($encoding)) {
597 1
			preg_match('/charset="?(.*?)["|;]/i', $page, $encoding);
598 1
		}
599
600 1
		if (isset($encoding[1])) {
601 1
			$decodeFrom = strtoupper($encoding[1]);
602 1
		} else {
603
			$decodeFrom = 'UTF-8';
604
		}
605
606 1
		if ($page) {
607
608 1
			if ($decodeFrom != 'UTF-8') {
609 1
				$page = iconv($decodeFrom, "UTF-8", $page);
610 1
			}
611
612 1
			preg_match("/<title>(.*)<\/title>/si", $page, $match);
613
			
614 1
			if (isset($match[1])) {
615 1
				$metadata['title'] = html_entity_decode($match[1]);
616 1
			}
617 1
		}
618
		
619 1
		return $metadata;
620
	}
621
622
	/**
623
	 * @brief Seperate Url String at comma charachter
624
	 * @param $line String of Tags
625
	 * @return array Array of Tags
626
	 * */
627
	public static function analyzeTagRequest($line) {
628
		$tags = explode(',', $line);
629
		$filterTag = array();
630
		foreach ($tags as $tag) {
631
			if (trim($tag) != '')
632
				$filterTag[] = trim($tag);
633
		}
634
		return $filterTag;
635
	}
636
637
}
638