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