]> git.mxchange.org Git - friendica.git/blob - src/Content/Item.php
ca60139eaf9982dde17c57b00007753b93256e61
[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\Database\DBA;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Group;
32 use Friendica\Model\Item as ModelItem;
33 use Friendica\Model\Photo;
34 use Friendica\Model\Tag;
35 use Friendica\Model\Post;
36 use Friendica\Protocol\Activity;
37 use Friendica\Util\Profiler;
38 use Friendica\Util\Proxy;
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): array
89         {
90                 $categories = [];
91                 $folders = [];
92                 $first = true;
93
94                 $uid = $item['uid'] ?: $uid;
95
96                 if (empty($item['has-categories'])) {
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 int    $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] or "false" on if already replaced
150          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
151          * @throws \ImagickException
152          */
153         public static function replaceTag(string &$body, int $profile_uid, string $tag, string $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 array $item
248          * @return void
249          * @throws ImagickException
250          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251          */
252         public function localize(array &$item)
253         {
254                 $this->profiler->startRecording('rendering');
255                 /// @todo The following functionality needs to be cleaned up.
256                 if (!empty($item['verb'])) {
257                         $xmlhead = '<?xml version="1.0" encoding="UTF-8" ?>';
258
259                         if ($this->activity->match($item['verb'], Activity::TAG)) {
260                                 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
261                                         'verb', 'object-type', 'resource-id', 'body', 'plink'];
262                                 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
263                                 if (!DBA::isResult($obj)) {
264                                         $this->profiler->stopRecording();
265                                         return;
266                                 }
267
268                                 $author_arr = [
269                                         'uid' => 0,
270                                         'id' => $item['author-id'],
271                                         'network' => $item['author-network'],
272                                         'url' => $item['author-link'],
273                                 ];
274                                 $author  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
275
276                                 $author_arr = [
277                                         'uid' => 0,
278                                         'id' => $obj['author-id'],
279                                         'network' => $obj['author-network'],
280                                         'url' => $obj['author-link'],
281                                 ];
282                                 $objauthor  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
283
284                                 switch ($obj['verb']) {
285                                         case Activity::POST:
286                                                 switch ($obj['object-type']) {
287                                                         case Activity\ObjectType::EVENT:
288                                                                 $post_type = $this->l10n->t('event');
289                                                                 break;
290                                                         default:
291                                                                 $post_type = $this->l10n->t('status');
292                                                 }
293                                                 break;
294
295                                         default:
296                                                 if ($obj['resource-id']) {
297                                                         $post_type = $this->l10n->t('photo');
298                                                         $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
299                                                         $rr['plink'] = $m[1];
300                                                 } else {
301                                                         $post_type = $this->l10n->t('status');
302                                                 }
303                                                 // Let's break everthing ... ;-)
304                                                 break;
305                                 }
306                                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
307
308                                 $parsedobj = XML::parseString($xmlhead . $item['object']);
309
310                                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
311                                 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
312                         }
313                 }
314
315                 $this->profiler->stopRecording();
316         }
317
318         /**
319          * Renders photo menu based on item
320          *
321          * @param array $item
322          * @param string $formSecurityToken
323          * @return string
324          */
325         public function photoMenu(array $item, string $formSecurityToken): string
326         {
327                 $this->profiler->startRecording('rendering');
328                 $sub_link = $contact_url = $pm_url = $status_link = '';
329                 $photos_link = $posts_link = $block_link = $ignore_link = '';
330
331                 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
332                         $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
333                 }
334
335                 $author = [
336                         'uid' => 0,
337                         'id' => $item['author-id'],
338                         'network' => $item['author-network'],
339                         'url' => $item['author-link'],
340                 ];
341                 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
342                 $sparkle = (strpos($profile_link, 'redir/') === 0);
343
344                 $cid = 0;
345                 $pcid = $item['author-id'];
346                 $network = '';
347                 $rel = 0;
348                 $condition = ['uid' => local_user(), 'uri-id' => $item['author-uri-id']];
349                 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
350                 if (DBA::isResult($contact)) {
351                         $cid = $contact['id'];
352                         $network = $contact['network'];
353                         $rel = $contact['rel'];
354                 }
355
356                 if ($sparkle) {
357                         $status_link = $profile_link . '/status';
358                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
359                         $profile_link = $profile_link . '/profile';
360                 }
361
362                 if (!empty($pcid)) {
363                         $contact_url = 'contact/' . $pcid;
364                         $posts_link  = $contact_url . '/posts';
365                         $block_link  = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
366                         $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
367                 }
368
369                 if ($cid && !$item['self']) {
370                         $contact_url = 'contact/' . $cid;
371                         $posts_link  = $contact_url . '/posts';
372
373                         if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
374                                 $pm_url = 'message/new/' . $cid;
375                         }
376                 }
377
378                 if (local_user()) {
379                         $menu = [
380                                 $this->l10n->t('Follow Thread') => $sub_link,
381                                 $this->l10n->t('View Status') => $status_link,
382                                 $this->l10n->t('View Profile') => $profile_link,
383                                 $this->l10n->t('View Photos') => $photos_link,
384                                 $this->l10n->t('Network Posts') => $posts_link,
385                                 $this->l10n->t('View Contact') => $contact_url,
386                                 $this->l10n->t('Send PM') => $pm_url,
387                                 $this->l10n->t('Block') => $block_link,
388                                 $this->l10n->t('Ignore') => $ignore_link
389                         ];
390
391                         if (!empty($item['language'])) {
392                                 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ModelItem::getLanguageMessage($item) . '\');';
393                         }
394
395                         if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
396                                 in_array($item['network'], Protocol::FEDERATED)) {
397                                 $menu[$this->l10n->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
398                         }
399                 } else {
400                         $menu = [$this->l10n->t('View Profile') => $item['author-link']];
401                 }
402
403                 $args = ['item' => $item, 'menu' => $menu];
404
405                 Hook::callAll('item_photo_menu', $args);
406
407                 $menu = $args['menu'];
408
409                 $o = '';
410                 foreach ($menu as $k => $v) {
411                         if (strpos($v, 'javascript:') === 0) {
412                                 $v = substr($v, 11);
413                                 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
414                         } elseif ($v) {
415                                 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
416                         }
417                 }
418                 $this->profiler->stopRecording();
419                 return $o;
420         }
421
422         /**
423          * Checks if the activity is visible to current user
424          *
425          * @param array $item Activity item
426          * @return bool Whether the item is visible to the user
427          */
428         public function isVisibleActivity(array $item): bool
429         {
430                 // Empty verb or hidden?
431                 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
432                         return false;
433                 }
434
435                 // Check conditions
436                 return (!($this->activity->match($item['verb'], Activity::FOLLOW) &&
437                         $item['object-type'] === Activity\ObjectType::NOTE &&
438                         empty($item['self']) &&
439                         $item['uid'] == local_user())
440                 );
441         }
442
443         public function expandTags(array $item, bool $setPermissions = false): array
444         {
445                 // Look for any tags and linkify them
446                 $item['inform'] = '';
447                 $private_forum  = false;
448                 $private_id     = null;
449                 $only_to_forum  = false;
450                 $forum_contact  = [];
451                 $receivers      = [];
452
453                 // Convert mentions in the body to a unified format
454                 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
455
456                 // Search for forum mentions
457                 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
458                         $contact = Contact::getByURLForUser($tag[2], $item['uid']);
459                         if (empty($contact)) {
460                                 continue;
461                         }
462
463                         $receivers[] = $contact['id'];
464
465                         if (!empty($item['inform'])) {
466                                 $item['inform'] .= ',';
467                         }
468                         $item['inform'] .= 'cid:' . $contact['id'];
469
470                         if (($item['gravity'] == GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
471                                 continue;
472                         }
473
474                         if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
475                                 $private_forum = $contact['prv'];
476                                 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
477                                 $private_id = $contact['id'];
478                                 $forum_contact = $contact;
479                                 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
480                         } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
481                                 $private_forum = false;
482                                 $only_to_forum = true;
483                                 $private_id = $contact['id'];
484                                 $forum_contact = $contact;
485                                 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
486                         } else {
487                                 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
488                         }
489                 }
490                 Logger::info('Got inform', ['inform' => $item['inform']]);
491
492                 if (($item['gravity'] == GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
493                         // we tagged a forum in a top level post. Now we change the post
494                         $item['private'] = $private_forum ? ModelItem::PRIVATE : ModelItem::UNLISTED;
495
496                         if ($only_to_forum) {
497                                 $item['postopts'] = '';
498                         }
499
500                         $item['deny_cid'] = '';
501                         $item['deny_gid'] = '';
502
503                         if ($private_forum) {
504                                 $item['allow_cid'] = '<' . $private_id . '>';
505                                 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
506                         } else {
507                                 $item['allow_cid'] = '';
508                                 $item['allow_gid'] = '';
509                         }
510                 } elseif ($setPermissions && ($item['gravity'] == GRAVITY_PARENT)) {
511                         if (empty($receivers)) {
512                                 // For security reasons direct posts without any receiver will be posts to yourself
513                                 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
514                                 $receivers[] = $self['id'];
515                         }
516
517                         $item['private']   = ModelItem::PRIVATE;
518                         $item['allow_cid'] = '';
519                         $item['allow_gid'] = '';
520                         $item['deny_cid']  = '';
521                         $item['deny_gid']  = '';
522
523                         foreach ($receivers as $receiver) {
524                                 $item['allow_cid'] .= '<' . $receiver . '>';
525                         }
526                 }
527                 return $item;
528         }
529
530         public function getAuthorAvatar(array $item): string
531         {
532                 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
533                         $author_avatar  = $item['contact-id'];
534                         $author_updated = '';
535                         $author_thumb   = $item['contact-avatar'];
536                 } else {
537                         $author_avatar  = $item['author-id'];
538                         $author_updated = $item['author-updated'];
539                         $author_thumb   = $item['author-avatar'];
540                 }
541
542
543                 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
544                         $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
545                 }
546
547                 return $author_thumb;
548         }
549
550         public function getOwnerAvatar(array $item): string
551         {
552                 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
553                         $owner_avatar  = $item['contact-id'];
554                         $owner_updated = '';
555                         $owner_thumb   = $item['contact-avatar'];
556                 } else {
557                         $owner_avatar   = $item['owner-id'];
558                         $owner_updated  = $item['owner-updated'];
559                         $owner_thumb    = $item['owner-avatar'];
560                 }
561
562                 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
563                         $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
564                 }
565
566                 return $owner_thumb;
567         }
568 }