]> git.mxchange.org Git - friendica.git/blob - src/Content/Item.php
Merge remote-tracking branch 'upstream/2022.05-rc' into performance
[friendica.git] / src / Content / Item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
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\Content;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Core\Hook;
26 use Friendica\Core\L10n;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Session;
30 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Group;
33 use Friendica\Model\Item as ModelItem;
34 use Friendica\Model\Tag;
35 use Friendica\Model\Post;
36 use Friendica\Protocol\Activity;
37 use Friendica\Util\Profiler;
38 use Friendica\Util\Strings;
39 use Friendica\Util\XML;
40
41 /**
42  * A content helper class for displaying items
43  */
44 class Item
45 {
46         /** @var Activity */
47         private $activity;
48         /** @var L10n */
49         private $l10n;
50         /** @var Profiler */
51         private $profiler;
52
53         public function __construct(Profiler $profiler, Activity $activity, L10n $l10n)
54         {
55                 $this->profiler = $profiler;
56                 $this->activity = $activity;
57                 $this->l10n   = $l10n;
58         }
59
60         /**
61          * Return array with details for categories and folders for an item
62          *
63          * @param array $item
64          * @param int   $uid
65          * @return [array, array]
66          *
67          * [
68          *      [ // categories array
69          *          {
70          *               'name': 'category name',
71          *               'removeurl': 'url to remove this category',
72          *               'first': 'is the first in this array? true/false',
73          *               'last': 'is the last in this array? true/false',
74          *           } ,
75          *           ....
76          *       ],
77          *       [ //folders array
78          *                      {
79          *               'name': 'folder name',
80          *               'removeurl': 'url to remove this folder',
81          *               'first': 'is the first in this array? true/false',
82          *               'last': 'is the last in this array? true/false',
83          *           } ,
84          *           ....
85          *       ]
86          *  ]
87          */
88         public function determineCategoriesTerms(array $item, int $uid = 0)
89         {
90                 $categories = [];
91                 $folders = [];
92                 $first = true;
93
94                 $uid = $item['uid'] ?: $uid;
95
96                 if (!Post\Category::existsForURIId($item['uri-id'], $uid)) {
97                         return [$categories, $folders];
98                 }
99
100                 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::CATEGORY) as $savedFolderName) {
101                         if (!empty($item['author-link'])) {
102                                 $url = $item['author-link'] . "?category=" . rawurlencode($savedFolderName);
103                         } else {
104                                 $url = '#';
105                         }
106                         $categories[] = [
107                                 'name' => $savedFolderName,
108                                 'url' => $url,
109                                 'removeurl' => local_user() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
110                                 'first' => $first,
111                                 'last' => false
112                         ];
113                         $first = false;
114                 }
115
116                 if (count($categories)) {
117                         $categories[count($categories) - 1]['last'] = true;
118                 }
119
120                 if (local_user() == $uid) {
121                         foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
122                                 $folders[] = [
123                                         'name' => $savedFolderName,
124                                         'url' => "#",
125                                         'removeurl' => local_user() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
126                                         'first' => $first,
127                                         'last' => false
128                                 ];
129                                 $first = false;
130                         }
131                 }
132
133                 if (count($folders)) {
134                         $folders[count($folders) - 1]['last'] = true;
135                 }
136
137                 return [$categories, $folders];
138         }
139
140         /**
141          * This function removes the tag $tag from the text $body and replaces it with
142          * the appropriate link.
143          *
144          * @param string  $body        the text to replace the tag in
145          * @param integer $profile_uid the user id to replace the tag for (0 = anyone)
146          * @param string  $tag         the tag to replace
147          * @param string  $network     The network of the post
148          *
149          * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
150          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
151          * @throws \ImagickException
152          */
153         public static function replaceTag(&$body, $profile_uid, $tag, $network = '')
154         {
155                 $replaced = false;
156
157                 //is it a person tag?
158                 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
159                         $tag_type = substr($tag, 0, 1);
160                         //is it already replaced?
161                         if (strpos($tag, '[url=')) {
162                                 return $replaced;
163                         }
164
165                         //get the person's name
166                         $name = substr($tag, 1);
167
168                         // Sometimes the tag detection doesn't seem to work right
169                         // This is some workaround
170                         $nameparts = explode(' ', $name);
171                         $name = $nameparts[0];
172
173                         // Try to detect the contact in various ways
174                         if (strpos($name, 'http://') || strpos($name, '@')) {
175                                 $contact = Contact::getByURLForUser($name, $profile_uid);
176                         } else {
177                                 $contact = false;
178                                 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
179
180                                 if (strrpos($name, '+')) {
181                                         // Is it in format @nick+number?
182                                         $tagcid = intval(substr($name, strrpos($name, '+') + 1));
183                                         $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
184                                 }
185
186                                 // select someone by nick in the current network
187                                 if (!DBA::isResult($contact) && ($network != '')) {
188                                         $condition = ["`nick` = ? AND `network` = ? AND `uid` = ?",
189                                                 $name, $network, $profile_uid];
190                                         $contact = DBA::selectFirst('contact', $fields, $condition);
191                                 }
192
193                                 // select someone by attag in the current network
194                                 if (!DBA::isResult($contact) && ($network != '')) {
195                                         $condition = ["`attag` = ? AND `network` = ? AND `uid` = ?",
196                                                 $name, $network, $profile_uid];
197                                         $contact = DBA::selectFirst('contact', $fields, $condition);
198                                 }
199
200                                 //select someone by name in the current network
201                                 if (!DBA::isResult($contact) && ($network != '')) {
202                                         $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
203                                         $contact = DBA::selectFirst('contact', $fields, $condition);
204                                 }
205
206                                 // select someone by nick in any network
207                                 if (!DBA::isResult($contact)) {
208                                         $condition = ["`nick` = ? AND `uid` = ?", $name, $profile_uid];
209                                         $contact = DBA::selectFirst('contact', $fields, $condition);
210                                 }
211
212                                 // select someone by attag in any network
213                                 if (!DBA::isResult($contact)) {
214                                         $condition = ["`attag` = ? AND `uid` = ?", $name, $profile_uid];
215                                         $contact = DBA::selectFirst('contact', $fields, $condition);
216                                 }
217
218                                 // select someone by name in any network
219                                 if (!DBA::isResult($contact)) {
220                                         $condition = ['name' => $name, 'uid' => $profile_uid];
221                                         $contact = DBA::selectFirst('contact', $fields, $condition);
222                                 }
223                         }
224
225                         // Check if $contact has been successfully loaded
226                         if (DBA::isResult($contact)) {
227                                 $profile = $contact['url'];
228                                 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
229                         }
230
231                         //if there is an url for this persons profile
232                         if (isset($profile) && ($newname != '')) {
233                                 $replaced = true;
234                                 // create profile link
235                                 $profile = str_replace(',', '%2c', $profile);
236                                 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
237                                 $body = str_replace($tag_type . $name, $newtag, $body);
238                         }
239                 }
240
241                 return ['replaced' => $replaced, 'contact' => $contact];
242         }
243
244         /**
245          * Render actions localized
246          *
247          * @param $item
248          * @throws ImagickException
249          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250          */
251         public function localize(&$item)
252         {
253                 $this->profiler->startRecording('rendering');
254                 /// @todo The following functionality needs to be cleaned up.
255                 if (!empty($item['verb'])) {
256                         $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
257
258                         if (stristr($item['verb'], Activity::POKE)) {
259                                 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
260                                 if (!$verb) {
261                                         $this->profiler->stopRecording();
262                                         return;
263                                 }
264                                 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
265                                         $this->profiler->stopRecording();
266                                         return;
267                                 }
268
269                                 $obj = XML::parseString($xmlhead . $item['object']);
270
271                                 $Bname = $obj->title;
272                                 $Blink = $obj->id;
273                                 $Bphoto = "";
274
275                                 foreach ($obj->link as $l) {
276                                         $atts = $l->attributes();
277                                         switch ($atts['rel']) {
278                                                 case "alternate": $Blink = $atts['href'];
279                                                 case "photo": $Bphoto = $atts['href'];
280                                         }
281                                 }
282
283                                 $author = ['uid' => 0, 'id' => $item['author-id'],
284                                         'network' => $item['author-network'], 'url' => $item['author-link']];
285                                 $A = '[url=' . Contact::magicLinkByContact($author) . ']' . $item['author-name'] . '[/url]';
286
287                                 if (!empty($Blink)) {
288                                         $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
289                                 } else {
290                                         $B = '';
291                                 }
292
293                                 if ($Bphoto != "" && !empty($Blink)) {
294                                         $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
295                                 }
296
297                                 /*
298                                 * we can't have a translation string with three positions but no distinguishable text
299                                 * So here is the translate string.
300                                 */
301                                 $txt = $this->l10n->t('%1$s poked %2$s');
302
303                                 // now translate the verb
304                                 $poked_t = trim(sprintf($txt, '', ''));
305                                 $txt = str_replace($poked_t, $this->l10n->t($verb), $txt);
306
307                                 // then do the sprintf on the translation string
308
309                                 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
310
311                         }
312
313                         if ($this->activity->match($item['verb'], Activity::TAG)) {
314                                 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
315                                         'verb', 'object-type', 'resource-id', 'body', 'plink'];
316                                 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
317                                 if (!DBA::isResult($obj)) {
318                                         $this->profiler->stopRecording();
319                                         return;
320                                 }
321
322                                 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
323                                         'network' => $item['author-network'], 'url' => $item['author-link']];
324                                 $author  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
325
326                                 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
327                                         'network' => $obj['author-network'], 'url' => $obj['author-link']];
328                                 $objauthor  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
329
330                                 switch ($obj['verb']) {
331                                         case Activity::POST:
332                                                 switch ($obj['object-type']) {
333                                                         case Activity\ObjectType::EVENT:
334                                                                 $post_type = $this->l10n->t('event');
335                                                                 break;
336                                                         default:
337                                                                 $post_type = $this->l10n->t('status');
338                                                 }
339                                                 break;
340                                         default:
341                                                 if ($obj['resource-id']) {
342                                                         $post_type = $this->l10n->t('photo');
343                                                         $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
344                                                         $rr['plink'] = $m[1];
345                                                 } else {
346                                                         $post_type = $this->l10n->t('status');
347                                                 }
348                                                 // Let's break everthing ... ;-)
349                                                 break;
350                                 }
351                                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
352
353                                 $parsedobj = XML::parseString($xmlhead . $item['object']);
354
355                                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
356                                 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
357                         }
358                 }
359 /*
360                 $matches = null;
361                 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
362                         foreach ($matches as $mtch) {
363                                 if (!strpos($mtch[1], 'zrl=')) {
364                                         $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
365                                 }
366                         }
367                 }
368 */
369                 // add sparkle links to appropriate permalinks
370                 // Only create a redirection to a magic link when logged in
371                 if (!empty($item['plink']) && Session::isAuthenticated() && $item['private'] == ModelItem::PRIVATE) {
372                         $author = ['uid' => 0, 'id' => $item['author-id'],
373                                 'network' => $item['author-network'], 'url' => $item['author-link']];
374                         $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
375                 }
376                 $this->profiler->stopRecording();
377         }
378
379         public function photoMenu($item, string $formSecurityToken)
380         {
381                 $this->profiler->startRecording('rendering');
382                 $sub_link = '';
383                 $poke_link = '';
384                 $contact_url = '';
385                 $pm_url = '';
386                 $status_link = '';
387                 $photos_link = '';
388                 $posts_link = '';
389                 $block_link = '';
390                 $ignore_link = '';
391
392                 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
393                         $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
394                 }
395
396                 $author = ['uid' => 0, 'id' => $item['author-id'],
397                         'network' => $item['author-network'], 'url' => $item['author-link']];
398                 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
399                 $sparkle = (strpos($profile_link, 'redir/') === 0);
400
401                 $cid = 0;
402                 $pcid = $item['author-id'];
403                 $network = '';
404                 $rel = 0;
405                 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
406                 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
407                 if (DBA::isResult($contact)) {
408                         $cid = $contact['id'];
409                         $network = $contact['network'];
410                         $rel = $contact['rel'];
411                 }
412
413                 if ($sparkle) {
414                         $status_link = $profile_link . '/status';
415                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
416                         $profile_link = $profile_link . '/profile';
417                 }
418
419                 if (!empty($pcid)) {
420                         $contact_url = 'contact/' . $pcid;
421                         $posts_link  = $contact_url . '/posts';
422                         $block_link  = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
423                         $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
424                 }
425
426                 if ($cid && !$item['self']) {
427                         $contact_url = 'contact/' . $cid;
428                         $poke_link   = $contact_url . '/poke';
429                         $posts_link  = $contact_url . '/posts';
430
431                         if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
432                                 $pm_url = 'message/new/' . $cid;
433                         }
434                 }
435
436                 if (local_user()) {
437                         $menu = [
438                                 $this->l10n->t('Follow Thread') => $sub_link,
439                                 $this->l10n->t('View Status') => $status_link,
440                                 $this->l10n->t('View Profile') => $profile_link,
441                                 $this->l10n->t('View Photos') => $photos_link,
442                                 $this->l10n->t('Network Posts') => $posts_link,
443                                 $this->l10n->t('View Contact') => $contact_url,
444                                 $this->l10n->t('Send PM') => $pm_url,
445                                 $this->l10n->t('Block') => $block_link,
446                                 $this->l10n->t('Ignore') => $ignore_link
447                         ];
448
449                         if (!empty($item['language'])) {
450                                 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ModelItem::getLanguageMessage($item) . '\');';
451                         }
452
453                         if ($network == Protocol::DFRN) {
454                                 $menu[$this->l10n->t("Poke")] = $poke_link;
455                         }
456
457                         if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
458                                 in_array($item['network'], Protocol::FEDERATED)) {
459                                 $menu[$this->l10n->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
460                         }
461                 } else {
462                         $menu = [$this->l10n->t('View Profile') => $item['author-link']];
463                 }
464
465                 $args = ['item' => $item, 'menu' => $menu];
466
467                 Hook::callAll('item_photo_menu', $args);
468
469                 $menu = $args['menu'];
470
471                 $o = '';
472                 foreach ($menu as $k => $v) {
473                         if (strpos($v, 'javascript:') === 0) {
474                                 $v = substr($v, 11);
475                                 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
476                         } elseif ($v) {
477                                 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
478                         }
479                 }
480                 $this->profiler->stopRecording();
481                 return $o;
482         }
483
484         public function visibleActivity($item) {
485
486                 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
487                         return false;
488                 }
489
490                 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
491                 if ($this->activity->match($item['verb'], Activity::FOLLOW) &&
492                         $item['object-type'] === Activity\ObjectType::NOTE &&
493                         empty($item['self']) &&
494                         $item['uid'] == local_user()) {
495                         return false;
496                 }
497
498                 return true;
499         }
500
501         public function expandTags(array $item, bool $setPermissions = false)
502         {
503                 // Look for any tags and linkify them
504                 $item['inform'] = '';
505                 $private_forum  = false;
506                 $private_id     = null;
507                 $only_to_forum  = false;
508                 $forum_contact  = [];
509                 $receivers      = [];
510
511                 // Convert mentions in the body to a unified format
512                 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
513
514                 // Search for forum mentions
515                 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
516                         $contact = Contact::getByURLForUser($tag[2], $item['uid']);
517
518                         $receivers[] = $contact['id'];
519
520                         if (!empty($item['inform'])) {
521                                 $item['inform'] .= ',';
522                         }
523                         $item['inform'] .= 'cid:' . $contact['id'];
524
525                         if (($item['gravity'] == GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
526                                 continue;
527                         }
528
529                         if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
530                                 $private_forum = $contact['prv'];
531                                 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
532                                 $private_id = $contact['id'];
533                                 $forum_contact = $contact;
534                                 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
535                         } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
536                                 $private_forum = false;
537                                 $only_to_forum = true;
538                                 $private_id = $contact['id'];
539                                 $forum_contact = $contact;
540                                 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
541                         } else {
542                                 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
543                         }
544                 }
545                 Logger::info('Got inform', ['inform' => $item['inform']]);
546
547                 if (($item['gravity'] == GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
548                         // we tagged a forum in a top level post. Now we change the post
549                         $item['private'] = $private_forum ? ModelItem::PRIVATE : ModelItem::UNLISTED;
550
551                         if ($only_to_forum) {
552                                 $item['postopts'] = '';
553                         }
554
555                         $item['deny_cid'] = '';
556                         $item['deny_gid'] = '';
557
558                         if ($private_forum) {
559                                 $item['allow_cid'] = '<' . $private_id . '>';
560                                 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
561                         } else {
562                                 $item['allow_cid'] = '';
563                                 $item['allow_gid'] = '';
564                         }
565                 } elseif ($setPermissions && ($item['gravity'] == GRAVITY_PARENT)) {
566                         if (empty($receivers)) {
567                                 // For security reasons direct posts without any receiver will be posts to yourself
568                                 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
569                                 $receivers[] = $self['id'];
570                         }
571
572                         $item['private']   = ModelItem::PRIVATE;
573                         $item['allow_cid'] = '';
574                         $item['allow_gid'] = '';
575                         $item['deny_cid']  = '';
576                         $item['deny_gid']  = '';
577
578                         foreach ($receivers as $receiver) {
579                                 $item['allow_cid'] .= '<' . $receiver . '>';
580                         }
581                 }
582                 return $item;
583         }
584 }