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