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