]> git.mxchange.org Git - friendica.git/blob - src/Model/Tag.php
Merge pull request #9635 from MrPetovan/bug/notices
[friendica.git] / src / Model / Tag.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Core\Cache\Duration;
26 use Friendica\Core\Logger;
27 use Friendica\Core\System;
28 use Friendica\Database\Database;
29 use Friendica\Database\DBA;
30 use Friendica\DI;
31 use Friendica\Util\Strings;
32
33 /**
34  * Class Tag
35  *
36  * This Model class handles tag table interactions.
37  * This tables stores relevant tags related to posts, like hashtags and mentions.
38  */
39 class Tag
40 {
41         const UNKNOWN  = 0;
42         const HASHTAG  = 1;
43         const MENTION  = 2;
44         /**
45          * An implicit mention is a mention in a comment body that is redundant with the threading information.
46          */
47         const IMPLICIT_MENTION  = 8;
48         /**
49          * An exclusive mention transfers the ownership of the post to the target account, usually a forum.
50          */
51         const EXCLUSIVE_MENTION = 9;
52
53         const TAG_CHARACTER = [
54                 self::HASHTAG           => '#',
55                 self::MENTION           => '@',
56                 self::IMPLICIT_MENTION  => '%',
57                 self::EXCLUSIVE_MENTION => '!',
58         ];
59
60         /**
61          * Store tag/mention elements
62          *
63          * @param integer $uriid
64          * @param integer $type
65          * @param string  $name
66          * @param string  $url
67          * @param boolean $probing
68          */
69         public static function store(int $uriid, int $type, string $name, string $url = '', $probing = true)
70         {
71                 if ($type == self::HASHTAG) {
72                         // Remove some common "garbarge" from tags
73                         $name = trim($name, "\x00..\x20\xFF#!@,;.:'/?!^°$%".'"');
74
75                         $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
76                         if (count($tags) > 1) {
77                                 foreach ($tags as $tag) {
78                                         self::store($uriid, $type, $tag, $url, $probing);
79                                 }
80                                 return;
81                         }
82                 }
83
84                 if (empty($name)) {
85                         return;
86                 }
87
88                 $cid = 0;
89                 $tagid = 0;
90
91                 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
92                         if (empty($url)) {
93                                 // No mention without a contact url
94                                 return;
95                         }
96
97                         if ((substr($url, 0, 7) == 'https//') || (substr($url, 0, 6) == 'http//')) {
98                                 Logger::notice('Wrong scheme in url', ['url' => $url, 'callstack' => System::callstack(20)]);
99                         }
100
101                         if (!$probing) {
102                                 $condition = ['nurl' => Strings::normaliseLink($url), 'uid' => 0, 'deleted' => false];
103                                 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
104                                 if (DBA::isResult($contact)) {
105                                         $cid = $contact['id'];
106                                         Logger::info('Got id for contact url', ['cid' => $cid, 'url' => $url]);
107                                 }
108
109                                 if (empty($cid)) {
110                                         $ssl_url = str_replace('http://', 'https://', $url);
111                                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, 0];
112                                         $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
113                                         if (DBA::isResult($contact)) {
114                                                 $cid = $contact['id'];
115                                                 Logger::info('Got id for contact alias', ['cid' => $cid, 'url' => $url]);
116                                         }
117                                 }
118                         } else {
119                                 $cid = Contact::getIdForURL($url, 0, false);
120                                 Logger::info('Got id by probing', ['cid' => $cid, 'url' => $url]);
121                         }
122
123                         if (empty($cid)) {
124                                 // The contact wasn't found in the system (most likely some dead account)
125                                 // We ensure that we only store a single entry by overwriting the previous name
126                                 Logger::info('Contact not found, updating tag', ['url' => $url, 'name' => $name]);
127                                 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url]);
128                         }
129                 }
130
131                 if (empty($cid)) {
132                         if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
133                                 $url = strtolower($url);
134                         } else {
135                                 $url = '';
136                         }
137
138                         $tagid = self::getID($name, $url);
139                         if (empty($tagid)) {
140                                 return;
141                         }
142                 }
143
144                 $fields = ['uri-id' => $uriid, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
145
146                 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
147                         $condition = $fields;
148                         $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION];
149                         if (DBA::exists('post-tag', $condition)) {
150                                 Logger::info('Tag already exists', $fields);
151                                 return;
152                         }
153                 }
154
155                 DBA::insert('post-tag', $fields, Database::INSERT_IGNORE);
156
157                 Logger::info('Stored tag/mention', ['uri-id' => $uriid, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
158         }
159
160         /**
161          * Get a tag id for a given tag name and url
162          *
163          * @param string $name
164          * @param string $url
165          * @return void
166          */
167         public static function getID(string $name, string $url = '')
168         {
169                 $fields = ['name' => substr($name, 0, 96), 'url' => $url];
170
171                 $tag = DBA::selectFirst('tag', ['id'], $fields);
172                 if (DBA::isResult($tag)) {
173                         return $tag['id'];
174                 }
175
176                 DBA::insert('tag', $fields, Database::INSERT_IGNORE);
177                 $tid = DBA::lastInsertId();
178                 if (!empty($tid)) {
179                         return $tid;
180                 }
181
182                 Logger::error('No tag id created', $fields);
183                 return 0;
184         }
185
186         /**
187          * Store tag/mention elements
188          *
189          * @param integer $uriid
190          * @param string $hash
191          * @param string $name
192          * @param string $url
193          * @param boolean $probing
194          */
195         public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
196         {
197                 $type = self::getTypeForHash($hash);
198                 if ($type == self::UNKNOWN) {
199                         return;
200                 }
201
202                 self::store($uriid, $type, $name, $url, $probing);
203         }
204
205         /**
206          * Store tags and mentions from the body
207          * 
208          * @param integer $uriid   URI-Id
209          * @param string  $body    Body of the post
210          * @param string  $tags    Accepted tags
211          * @param boolean $probing Perform a probing for contacts, adding them if needed
212          */
213         public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
214         {
215                 if (is_null($tags)) {
216                         $tags =  self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
217                 }
218
219                 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
220
221                 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
222                         return;
223                 }
224
225                 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
226
227                 foreach ($result as $tag) {
228                         self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
229                 }
230         }
231
232         /**
233          * Store raw tags (not encapsulated in links) from the body
234          * This function is needed in the intermediate phase.
235          * Later we can call item::setHashtags in advance to have all tags converted.
236          * 
237          * @param integer $uriid URI-Id
238          * @param string  $body   Body of the post
239          */
240         public static function storeRawTagsFromBody(int $uriid, string $body)
241         {
242                 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
243
244                 $result = BBCode::getTags($body);
245                 if (empty($result)) {
246                         return;
247                 }
248
249                 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
250
251                 foreach ($result as $tag) {
252                         if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
253                                 continue;
254                         }
255                         self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
256                 }
257         }
258
259         /**
260          * Checks for stored hashtags and mentions for the given post
261          *
262          * @param integer $uriid
263          * @return bool
264          */
265         public static function existsForPost(int $uriid)
266         {
267                 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION]]);
268         }
269
270         /**
271          * Remove tag/mention
272          *
273          * @param integer $uriid
274          * @param integer $type
275          * @param string $name
276          * @param string $url
277          */
278         public static function remove(int $uriid, int $type, string $name, string $url = '')
279         {
280                 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
281                 if ($type == self::HASHTAG) {
282                         $condition['name'] = $name;
283                 }
284
285                 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
286                 if (!DBA::isResult($tag)) {
287                         return;
288                 }
289
290                 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
291                 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
292         }
293
294         /**
295          * Remove tag/mention
296          *
297          * @param integer $uriid
298          * @param string $hash
299          * @param string $name
300          * @param string $url
301          */
302         public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
303         {
304                 $type = self::getTypeForHash($hash);
305                 if ($type == self::UNKNOWN) {
306                         return;
307                 }
308
309                 self::remove($uriid, $type, $name, $url);
310         }
311
312         /**
313          * Get the type for the given hash
314          *
315          * @param string $hash
316          * @return integer type
317          */
318         private static function getTypeForHash(string $hash)
319         {
320                 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
321                         return self::MENTION;
322                 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
323                         return self::EXCLUSIVE_MENTION;
324                 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
325                         return self::IMPLICIT_MENTION;
326                 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
327                         return self::HASHTAG;
328                 } else {
329                         return self::UNKNOWN;
330                 }
331         }
332
333         /**
334          * Create implicit mentions for a given post
335          *
336          * @param integer $uri_id
337          * @param integer $parent_uri_id
338          */
339         public static function createImplicitMentions(int $uri_id, int $parent_uri_id)
340         {
341                 // Always mention the direct parent author
342                 $parent = Item::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]);
343                 self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
344
345                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
346                         return;
347                 }
348
349                 $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parent_uri_id]);
350                 while ($tag = DBA::fetch($tags)) {
351                         self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
352                 }
353                 DBA::close($tags);
354         }
355
356         /**
357          * Retrieves the terms from the provided type(s) associated with the provided item ID.
358          *
359          * @param int       $item_id
360          * @param int|array $type
361          * @return array
362          * @throws \Exception
363          */
364         public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
365         {
366                 $condition = ['uri-id' => $uri_id, 'type' => $type];
367                 return DBA::selectToArray('tag-view', ['type', 'name', 'url'], $condition);
368         }
369
370         /**
371          * Return a string with all tags and mentions
372          *
373          * @param integer $uri_id
374          * @param array   $type
375          * @return string tags and mentions
376          * @throws \Exception
377          */
378         public static function getCSVByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
379         {
380                 $tag_list = [];
381                 $tags = self::getByURIId($uri_id, $type);
382                 foreach ($tags as $tag) {
383                         $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
384                 }
385
386                 return implode(',', $tag_list);
387         }
388
389         /**
390          * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
391          * provided item's body with them.
392          *
393          * @param array $item
394          * @return array
395          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
396          * @throws \ImagickException
397          */
398         public static function populateFromItem(&$item)
399         {
400                 $return = [
401                         'tags' => [],
402                         'hashtags' => [],
403                         'mentions' => [],
404                         'implicit_mentions' => [],
405                 ];
406
407                 $searchpath = DI::baseUrl() . "/search?tag=";
408
409                 $taglist = DBA::select('tag-view', ['type', 'name', 'url'],
410                         ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
411                 while ($tag = DBA::fetch($taglist)) {
412                         if ($tag['url'] == '') {
413                                 $tag['url'] = $searchpath . rawurlencode($tag['name']);
414                         }
415
416                         $orig_tag = $tag['url'];
417
418                         $prefix = self::TAG_CHARACTER[$tag['type']];
419                         switch($tag['type']) {
420                                 case self::HASHTAG:
421                                         if ($orig_tag != $tag['url']) {
422                                                 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
423                                         }
424
425                                         $return['hashtags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
426                                         $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
427                                         break;
428                                 case self::MENTION:
429                                 case self::EXCLUSIVE_MENTION:
430                                                 $tag['url'] = Contact::magicLink($tag['url']);
431                                         $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
432                                         $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
433                                         break;
434                                 case self::IMPLICIT_MENTION:
435                                         $return['implicit_mentions'][] = $prefix . $tag['name'];
436                                         break;
437                         }
438                 }
439                 DBA::close($taglist);
440
441                 return $return;
442         }
443
444         /**
445          * Counts posts for given tag
446          *
447          * @param string $search
448          * @param integer $uid
449          * @return integer number of posts
450          */
451         public static function countByTag(string $search, int $uid = 0)
452         {
453                 $condition = ["`name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $search, $uid];
454                 $params = ['group_by' => ['uri-id']];
455
456                 return DBA::count('tag-search-view', $condition, $params);
457         }
458
459         /**
460          * Search posts for given tag
461          *
462          * @param string $search
463          * @param integer $uid
464          * @param integer $start
465          * @param integer $limit
466          * @param integer $last_uriid
467          * @return array with URI-ID
468          */
469         public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
470         {
471                 $condition = ["`name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $search, $uid];
472
473                 if (!empty($last_uriid)) {
474                         $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
475                 }
476
477                 $params = [
478                         'order' => ['uri-id' => true],
479                         'group_by' => ['uri-id'],
480                         'limit' => [$start, $limit]
481                 ];
482
483                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
484
485                 $uriids = [];
486                 while ($tag = DBA::fetch($tags)) {
487                         $uriids[] = $tag['uri-id'];
488                 }
489                 DBA::close($tags);
490
491                 return $uriids;
492         }
493
494         /**
495          * Returns a list of the most frequent global hashtags over the given period
496          *
497          * @param int $period Period in hours to consider posts
498          * @param int $limit  Number of returned tags
499          * @return array
500          * @throws \Exception
501          */
502         public static function getGlobalTrendingHashtags(int $period, $limit = 10)
503         {
504                 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
505                 if (!empty($tags)) {
506                         return $tags;
507                 } else {
508                         return self::setGlobalTrendingHashtags($period, $limit);
509                 }
510         }
511
512         /**
513          * Creates a list of the most frequent global hashtags over the given period
514          *
515          * @param int $period Period in hours to consider posts
516          * @param int $limit  Number of returned tags
517          * @return array
518          * @throws \Exception
519          */
520         public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
521         {
522                 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
523                         FROM `tag-search-view`
524                         WHERE `private` = ? AND `uid` = ? AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
525                         GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
526                         Item::PUBLIC, 0, $period, $limit);
527
528                 if (DBA::isResult($tagsStmt)) {
529                         $tags = DBA::toArray($tagsStmt);
530                         DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
531                         return $tags;
532                 }
533
534                 return [];
535         }
536
537         /**
538          * Returns a list of the most frequent local hashtags over the given period
539          *
540          * @param int $period Period in hours to consider posts
541          * @param int $limit  Number of returned tags
542          * @return array
543          * @throws \Exception
544          */
545         public static function getLocalTrendingHashtags(int $period, $limit = 10)
546         {
547                 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
548                 if (!empty($tags)) {
549                         return $tags;
550                 } else {
551                         return self::setLocalTrendingHashtags($period, $limit);
552                 }
553         }
554
555         /**
556          * Returns a list of the most frequent local hashtags over the given period
557          *
558          * @param int $period Period in hours to consider posts
559          * @param int $limit  Number of returned tags
560          * @return array
561          * @throws \Exception
562          */
563         public static function setLocalTrendingHashtags(int $period, int $limit = 10)
564         {
565                 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
566                         FROM `tag-search-view`
567                         WHERE `private` = ? AND `wall` AND `origin` AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
568                         GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
569                         Item::PUBLIC, $period, $limit);
570
571                 if (DBA::isResult($tagsStmt)) {
572                         $tags = DBA::toArray($tagsStmt);
573                         DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
574                         return $tags;
575                 }
576
577                 return [];
578         }
579
580         /**
581          * Check if the provided tag is of one of the provided term types.
582          *
583          * @param string $tag
584          * @param int    ...$types
585          * @return bool
586          */
587         public static function isType($tag, ...$types)
588         {
589                 $tag_chars = [];
590                 foreach ($types as $type) {
591                         if (array_key_exists($type, self::TAG_CHARACTER)) {
592                                 $tag_chars[] = self::TAG_CHARACTER[$type];
593                         }
594                 }
595
596                 return Strings::startsWithChars($tag, $tag_chars);
597         }
598
599         /**
600          * Fetch user who subscribed to the given tag
601          *
602          * @param string $tag
603          * @return array User list
604          */
605         private static function getUIDListByTag(string $tag)
606         {
607                 $uids = [];
608                 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
609                 while ($search = DBA::fetch($searches)) {
610                         $uids[] = $search['uid'];
611                 }
612                 DBA::close($searches);
613
614                 return $uids;
615         }
616
617         /**
618          * Fetch user who subscribed to the tags of the given item
619          *
620          * @param integer $uri_id
621          * @return array User list
622          */
623         public static function getUIDListByURIId(int $uri_id)
624         {
625                 $uids = [];
626                 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
627
628                 foreach ($tags as $tag) {
629                         $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
630                 }
631
632                 return array_unique($uids);
633         }
634 }