post/thread views are renamed, search bugs fixed
[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', 'cid'],
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                                         if (!empty($tag['cid'])) {
432                                                 $tag['url'] = Contact::magicLinkById($tag['cid']);
433                                         } else {
434                                                 $tag['url'] = Contact::magicLink($tag['url']);
435                                         }
436                                         $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
437                                         $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
438                                         break;
439                                 case self::IMPLICIT_MENTION:
440                                         $return['implicit_mentions'][] = $prefix . $tag['name'];
441                                         break;
442                         }
443                 }
444                 DBA::close($taglist);
445
446                 return $return;
447         }
448
449         /**
450          * Counts posts for given tag
451          *
452          * @param string $search
453          * @param integer $uid
454          * @return integer number of posts
455          */
456         public static function countByTag(string $search, int $uid = 0)
457         {
458                 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
459                         AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
460                         $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
461
462                 return DBA::count('tag-search-view', $condition);
463         }
464
465         /**
466          * Search posts for given tag
467          *
468          * @param string $search
469          * @param integer $uid
470          * @param integer $start
471          * @param integer $limit
472          * @param integer $last_uriid
473          * @return array with URI-ID
474          */
475         public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0)
476         {
477                 $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
478                         AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
479                         $search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
480
481                 if (!empty($last_uriid)) {
482                         $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
483                 }
484
485                 $params = [
486                         'order' => ['uri-id' => true],
487                         'limit' => [$start, $limit]
488                 ];
489
490                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
491
492                 $uriids = [];
493                 while ($tag = DBA::fetch($tags)) {
494                         $uriids[] = $tag['uri-id'];
495                 }
496                 DBA::close($tags);
497
498                 return $uriids;
499         }
500
501         /**
502          * Returns a list of the most frequent global hashtags over the given period
503          *
504          * @param int $period Period in hours to consider posts
505          * @param int $limit  Number of returned tags
506          * @return array
507          * @throws \Exception
508          */
509         public static function getGlobalTrendingHashtags(int $period, $limit = 10)
510         {
511                 $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
512                 if (!empty($tags)) {
513                         return $tags;
514                 } else {
515                         return self::setGlobalTrendingHashtags($period, $limit);
516                 }
517         }
518
519         /**
520          * Creates a list of the most frequent global hashtags over the given period
521          *
522          * @param int $period Period in hours to consider posts
523          * @param int $limit  Number of returned tags
524          * @return array
525          * @throws \Exception
526          */
527         public static function setGlobalTrendingHashtags(int $period, int $limit = 10)
528         {
529                 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
530                         FROM `tag-search-view`
531                         WHERE `private` = ? AND `uid` = ? AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
532                         GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
533                         Item::PUBLIC, 0, $period, $limit);
534
535                 if (DBA::isResult($tagsStmt)) {
536                         $tags = DBA::toArray($tagsStmt);
537                         DI::cache()->set('global_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
538                         return $tags;
539                 }
540
541                 return [];
542         }
543
544         /**
545          * Returns a list of the most frequent local hashtags over the given period
546          *
547          * @param int $period Period in hours to consider posts
548          * @param int $limit  Number of returned tags
549          * @return array
550          * @throws \Exception
551          */
552         public static function getLocalTrendingHashtags(int $period, $limit = 10)
553         {
554                 $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
555                 if (!empty($tags)) {
556                         return $tags;
557                 } else {
558                         return self::setLocalTrendingHashtags($period, $limit);
559                 }
560         }
561
562         /**
563          * Returns a list of the most frequent local hashtags over the given period
564          *
565          * @param int $period Period in hours to consider posts
566          * @param int $limit  Number of returned tags
567          * @return array
568          * @throws \Exception
569          */
570         public static function setLocalTrendingHashtags(int $period, int $limit = 10)
571         {
572                 $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
573                         FROM `tag-search-view`
574                         WHERE `private` = ? AND `wall` AND `origin` AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
575                         GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
576                         Item::PUBLIC, $period, $limit);
577
578                 if (DBA::isResult($tagsStmt)) {
579                         $tags = DBA::toArray($tagsStmt);
580                         DI::cache()->set('local_trending_tags-' . $period . '-' . $limit, $tags, Duration::DAY);
581                         return $tags;
582                 }
583
584                 return [];
585         }
586
587         /**
588          * Check if the provided tag is of one of the provided term types.
589          *
590          * @param string $tag
591          * @param int    ...$types
592          * @return bool
593          */
594         public static function isType($tag, ...$types)
595         {
596                 $tag_chars = [];
597                 foreach ($types as $type) {
598                         if (array_key_exists($type, self::TAG_CHARACTER)) {
599                                 $tag_chars[] = self::TAG_CHARACTER[$type];
600                         }
601                 }
602
603                 return Strings::startsWithChars($tag, $tag_chars);
604         }
605
606         /**
607          * Fetch user who subscribed to the given tag
608          *
609          * @param string $tag
610          * @return array User list
611          */
612         private static function getUIDListByTag(string $tag)
613         {
614                 $uids = [];
615                 $searches = DBA::select('search', ['uid'], ['term' => $tag]);
616                 while ($search = DBA::fetch($searches)) {
617                         $uids[] = $search['uid'];
618                 }
619                 DBA::close($searches);
620
621                 return $uids;
622         }
623
624         /**
625          * Fetch user who subscribed to the tags of the given item
626          *
627          * @param integer $uri_id
628          * @return array User list
629          */
630         public static function getUIDListByURIId(int $uri_id)
631         {
632                 $uids = [];
633                 $tags = self::getByURIId($uri_id, [self::HASHTAG]);
634
635                 foreach ($tags as $tag) {
636                         $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));
637                 }
638
639                 return array_unique($uids);
640         }
641 }