]> git.mxchange.org Git - friendica.git/blob - src/Model/Tag.php
Merge remote-tracking branch 'upstream/develop' into notification-uri-id
[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\DBA;
29 use Friendica\DI;
30 use Friendica\Util\Strings;
31
32 /**
33  * Class Tag
34  *
35  * This Model class handles tag table interactions.
36  * This tables stores relevant tags related to posts, like hashtags and mentions.
37  */
38 class Tag
39 {
40         const UNKNOWN  = 0;
41         const HASHTAG  = 1;
42         const MENTION  = 2;
43         /**
44          * An implicit mention is a mention in a comment body that is redundant with the threading information.
45          */
46         const IMPLICIT_MENTION  = 8;
47         /**
48          * An exclusive mention transfers the ownership of the post to the target account, usually a forum.
49          */
50         const EXCLUSIVE_MENTION = 9;
51
52         const TAG_CHARACTER = [
53                 self::HASHTAG           => '#',
54                 self::MENTION           => '@',
55                 self::IMPLICIT_MENTION  => '%',
56                 self::EXCLUSIVE_MENTION => '!',
57         ];
58
59         /**
60          * Store tag/mention elements
61          *
62          * @param integer $uriid
63          * @param integer $type
64          * @param string  $name
65          * @param string  $url
66          * @param boolean $probing
67          */
68         public static function store(int $uriid, int $type, string $name, string $url = '', $probing = true)
69         {
70                 if ($type == self::HASHTAG) {
71                         // Remove some common "garbarge" from tags
72                         $name = trim($name, "\x00..\x20\xFF#!@,;.:'/?!^°$%".'"');
73
74                         $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
75                         if (count($tags) > 1) {
76                                 foreach ($tags as $tag) {
77                                         self::store($uriid, $type, $tag, $url, $probing);
78                                 }
79                                 return;
80                         }
81                 }
82
83                 if (empty($name)) {
84                         return;
85                 }
86
87                 $cid = 0;
88                 $tagid = 0;
89
90                 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
91                         if (empty($url)) {
92                                 // No mention without a contact url
93                                 return;
94                         }
95
96                         if (!$probing) {
97                                 $condition = ['nurl' => Strings::normaliseLink($url), 'uid' => 0, 'deleted' => false];
98                                 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
99                                 if (DBA::isResult($contact)) {
100                                         $cid = $contact['id'];
101                                         Logger::info('Got id for contact url', ['cid' => $cid, 'url' => $url]);
102                                 }
103
104                                 if (empty($cid)) {
105                                         $ssl_url = str_replace('http://', 'https://', $url);
106                                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, 0];
107                                         $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
108                                         if (DBA::isResult($contact)) {
109                                                 $cid = $contact['id'];
110                                                 Logger::info('Got id for contact alias', ['cid' => $cid, 'url' => $url]);
111                                         }
112                                 }
113                         } else {
114                                 $cid = Contact::getIdForURL($url, 0, true);
115                                 Logger::info('Got id by probing', ['cid' => $cid, 'url' => $url]);
116                         }
117
118                         if (empty($cid)) {
119                                 // The contact wasn't found in the system (most likely some dead account)
120                                 // We ensure that we only store a single entry by overwriting the previous name
121                                 Logger::info('Contact not found, updating tag', ['url' => $url, 'name' => $name]);
122                                 DBA::update('tag', ['name' => substr($name, 0, 96)], ['url' => $url]);
123                         }
124                 }
125
126                 if (empty($cid)) {
127                         $fields = ['name' => substr($name, 0, 96), 'url' => ''];
128
129                         if (($type != self::HASHTAG) && !empty($url) && ($url != $name)) {
130                                 $fields['url'] = strtolower($url);
131                         }
132
133                         $tag = DBA::selectFirst('tag', ['id'], $fields);
134                         if (!DBA::isResult($tag)) {
135                                 DBA::insert('tag', $fields, true);
136                                 $tagid = DBA::lastInsertId();
137                         } else {
138                                 $tagid = $tag['id'];
139                         }
140
141                         if (empty($tagid)) {
142                                 Logger::error('No tag id created', $fields);
143                                 return;
144                         }
145                 }
146
147                 $fields = ['uri-id' => $uriid, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
148
149                 if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
150                         $condition = $fields;
151                         $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION];
152                         if (DBA::exists('post-tag', $condition)) {
153                                 Logger::info('Tag already exists', $fields);
154                                 return;
155                         }
156                 }
157
158                 DBA::insert('post-tag', $fields, true);
159
160                 Logger::info('Stored tag/mention', ['uri-id' => $uriid, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
161         }
162
163         /**
164          * Store tag/mention elements
165          *
166          * @param integer $uriid
167          * @param string $hash
168          * @param string $name
169          * @param string $url
170          * @param boolean $probing
171          */
172         public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
173         {
174                 $type = self::getTypeForHash($hash);
175                 if ($type == self::UNKNOWN) {
176                         return;
177                 }
178
179                 self::store($uriid, $type, $name, $url, $probing);
180         }
181
182         /**
183          * Store tags and mentions from the body
184          * 
185          * @param integer $uriid   URI-Id
186          * @param string  $body    Body of the post
187          * @param string  $tags    Accepted tags
188          * @param boolean $probing Perform a probing for contacts, adding them if needed
189          */
190         public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
191         {
192                 if (is_null($tags)) {
193                         $tags =  self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
194                 }
195
196                 Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
197
198                 if (!preg_match_all("/([" . $tags . "])\[url\=([^\[\]]*)\]([^\[\]]*)\[\/url\]/ism", $body, $result, PREG_SET_ORDER)) {
199                         return;
200                 }
201
202                 Logger::info('Found tags', ['uri-id' => $uriid, 'hash' => $tags, 'result' => $result]);
203
204                 foreach ($result as $tag) {
205                         self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing);
206                 }
207         }
208
209         /**
210          * Store raw tags (not encapsulated in links) from the body
211          * This function is needed in the intermediate phase.
212          * Later we can call item::setHashtags in advance to have all tags converted.
213          * 
214          * @param integer $uriid URI-Id
215          * @param string  $body   Body of the post
216          */
217         public static function storeRawTagsFromBody(int $uriid, string $body)
218         {
219                 Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]);
220
221                 $result = BBCode::getTags($body);
222                 if (empty($result)) {
223                         return;
224                 }
225
226                 Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
227
228                 foreach ($result as $tag) {
229                         if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
230                                 continue;
231                         }
232                         self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1));
233                 }
234         }
235
236         /**
237          * Checks for stored hashtags and mentions for the given post
238          *
239          * @param integer $uriid
240          * @return bool
241          */
242         public static function existsForPost(int $uriid)
243         {
244                 return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION]]);
245         }
246
247         /**
248          * Remove tag/mention
249          *
250          * @param integer $uriid
251          * @param integer $type
252          * @param string $name
253          * @param string $url
254          */
255         public static function remove(int $uriid, int $type, string $name, string $url = '')
256         {
257                 $condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url];
258                 if ($type == self::HASHTAG) {
259                         $condition['name'] = $name;
260                 }
261
262                 $tag = DBA::selectFirst('tag-view', ['tid', 'cid'], $condition);
263                 if (!DBA::isResult($tag)) {
264                         return;
265                 }
266
267                 Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
268                 DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
269         }
270
271         /**
272          * Remove tag/mention
273          *
274          * @param integer $uriid
275          * @param string $hash
276          * @param string $name
277          * @param string $url
278          */
279         public static function removeByHash(int $uriid, string $hash, string $name, string $url = '')
280         {
281                 $type = self::getTypeForHash($hash);
282                 if ($type == self::UNKNOWN) {
283                         return;
284                 }
285
286                 self::remove($uriid, $type, $name, $url);
287         }
288
289         /**
290          * Get the type for the given hash
291          *
292          * @param string $hash
293          * @return integer type
294          */
295         private static function getTypeForHash(string $hash)
296         {
297                 if ($hash == self::TAG_CHARACTER[self::MENTION]) {
298                         return self::MENTION;
299                 } elseif ($hash == self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]) {
300                         return self::EXCLUSIVE_MENTION;
301                 } elseif ($hash == self::TAG_CHARACTER[self::IMPLICIT_MENTION]) {
302                         return self::IMPLICIT_MENTION;
303                 } elseif ($hash == self::TAG_CHARACTER[self::HASHTAG]) {
304                         return self::HASHTAG;
305                 } else {
306                         return self::UNKNOWN;
307                 }
308         }
309
310         /**
311          * Retrieves the terms from the provided type(s) associated with the provided item ID.
312          *
313          * @param int       $item_id
314          * @param int|array $type
315          * @return array
316          * @throws \Exception
317          */
318         public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::IMPLICIT_MENTION, self::EXCLUSIVE_MENTION])
319         {
320                 $condition = ['uri-id' => $uri_id, 'type' => $type];
321                 return DBA::selectToArray('tag-view', ['type', 'name', 'url'], $condition);
322         }
323
324         /**
325          * Sorts an item's tags into mentions, hashtags and other tags. Generate personalized URLs by user and modify the
326          * provided item's body with them.
327          *
328          * @param array $item
329          * @return array
330          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
331          * @throws \ImagickException
332          */
333         public static function populateFromItem(&$item)
334         {
335                 $return = [
336                         'tags' => [],
337                         'hashtags' => [],
338                         'mentions' => [],
339                         'implicit_mentions' => [],
340                 ];
341
342                 $searchpath = DI::baseUrl() . "/search?tag=";
343
344                 $taglist = DBA::select('tag-view', ['type', 'name', 'url'],
345                         ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
346                 while ($tag = DBA::fetch($taglist)) {
347                         if ($tag['url'] == '') {
348                                 $tag['url'] = $searchpath . rawurlencode($tag['name']);
349                         }
350
351                         $orig_tag = $tag['url'];
352
353                         $prefix = self::TAG_CHARACTER[$tag['type']];
354                         switch($tag['type']) {
355                                 case self::HASHTAG:
356                                         if ($orig_tag != $tag['url']) {
357                                                 $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']);
358                                         }
359
360                                         $return['hashtags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
361                                         $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
362                                         break;
363                                 case self::MENTION:
364                                 case self::EXCLUSIVE_MENTION:
365                                                 $tag['url'] = Contact::magicLink($tag['url']);
366                                         $return['mentions'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
367                                         $return['tags'][] = $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a>';
368                                         break;
369                                 case self::IMPLICIT_MENTION:
370                                         $return['implicit_mentions'][] = $prefix . $tag['name'];
371                                         break;
372                         }
373                 }
374                 DBA::close($taglist);
375
376                 return $return;
377         }
378
379         /**
380          * Search posts for given tag
381          *
382          * @param string $search
383          * @param integer $uid
384          * @param integer $start
385          * @param integer $limit
386          * @return array with URI-ID
387          */
388         public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100)
389         {
390                 $condition = ["`name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $search, $uid];
391                 $params = [
392                         'order' => ['uri-id' => true],
393                         'group_by' => ['uri-id'],
394                         'limit' => [$start, $limit]
395                 ];
396
397                 $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
398
399                 $uriids = [];
400                 while ($tag = DBA::fetch($tags)) {
401                         $uriids[] = $tag['uri-id'];
402                 }
403                 DBA::close($tags);
404
405                 return $uriids;
406         }
407
408         /**
409          * Returns a list of the most frequent global hashtags over the given period
410          *
411          * @param int $period Period in hours to consider posts
412          * @return array
413          * @throws \Exception
414          */
415         public static function getGlobalTrendingHashtags(int $period, $limit = 10)
416         {
417                 $tags = DI::cache()->get('global_trending_tags');
418
419                 if (empty($tags)) {
420                         $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
421                                 FROM `tag-search-view`
422                                 WHERE `private` = ? AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
423                                 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
424                                 Item::PUBLIC, $period, $limit);
425
426                         if (DBA::isResult($tagsStmt)) {
427                                 $tags = DBA::toArray($tagsStmt);
428                                 DI::cache()->set('global_trending_tags', $tags, Duration::HOUR);
429                         }
430                 }
431
432                 return $tags ?: [];
433         }
434
435         /**
436          * Returns a list of the most frequent local hashtags over the given period
437          *
438          * @param int $period Period in hours to consider posts
439          * @return array
440          * @throws \Exception
441          */
442         public static function getLocalTrendingHashtags(int $period, $limit = 10)
443         {
444                 $tags = DI::cache()->get('local_trending_tags');
445
446                 if (empty($tags)) {
447                         $tagsStmt = DBA::p("SELECT `name` AS `term`, COUNT(*) AS `score`
448                                 FROM `tag-search-view`
449                                 WHERE `private` = ? AND `wall` AND `origin` AND `received` > DATE_SUB(NOW(), INTERVAL ? HOUR)
450                                 GROUP BY `term` ORDER BY `score` DESC LIMIT ?",
451                                 Item::PUBLIC, $period, $limit);
452
453                         if (DBA::isResult($tagsStmt)) {
454                                 $tags = DBA::toArray($tagsStmt);
455                                 DI::cache()->set('local_trending_tags', $tags, Duration::HOUR);
456                         }
457                 }
458
459                 return $tags ?: [];
460         }
461
462         /**
463          * Check if the provided tag is of one of the provided term types.
464          *
465          * @param string $tag
466          * @param int    ...$types
467          * @return bool
468          */
469         public static function isType($tag, ...$types)
470         {
471                 $tag_chars = [];
472                 foreach ($types as $type) {
473                         if (array_key_exists($type, self::TAG_CHARACTER)) {
474                                 $tag_chars[] = self::TAG_CHARACTER[$type];
475                         }
476                 }
477
478                 return Strings::startsWith($tag, $tag_chars);
479         }       
480 }