]> git.mxchange.org Git - friendica.git/blob - src/Content/Item.php
Use the uri-id to fetch the contact
[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                 $matches = null;
360                 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
361                         foreach ($matches as $mtch) {
362                                 if (!strpos($mtch[1], 'zrl=')) {
363                                         $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
364                                 }
365                         }
366                 }
367 */
368                 // add sparkle links to appropriate permalinks
369                 // Only create a redirection to a magic link when logged in
370                 if (!empty($item['plink']) && Session::isAuthenticated() && $item['private'] == ModelItem::PRIVATE) {
371                         $author = ['uid' => 0, 'id' => $item['author-id'],
372                                 'network' => $item['author-network'], 'url' => $item['author-link']];
373                         $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
374                 }
375                 $this->profiler->stopRecording();
376         }
377
378         public function photoMenu($item, string $formSecurityToken)
379         {
380                 $this->profiler->startRecording('rendering');
381                 $sub_link = '';
382                 $poke_link = '';
383                 $contact_url = '';
384                 $pm_url = '';
385                 $status_link = '';
386                 $photos_link = '';
387                 $posts_link = '';
388                 $block_link = '';
389                 $ignore_link = '';
390
391                 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
392                         $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
393                 }
394
395                 $author = ['uid' => 0, 'id' => $item['author-id'],
396                         'network' => $item['author-network'], 'url' => $item['author-link']];
397                 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
398                 $sparkle = (strpos($profile_link, 'redir/') === 0);
399
400                 $cid = 0;
401                 $pcid = $item['author-id'];
402                 $network = '';
403                 $rel = 0;
404                 $condition = ['uid' => local_user(), 'uri-id' => $item['author-uri-id']];
405                 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
406                 if (DBA::isResult($contact)) {
407                         $cid = $contact['id'];
408                         $network = $contact['network'];
409                         $rel = $contact['rel'];
410                 }
411
412                 if ($sparkle) {
413                         $status_link = $profile_link . '/status';
414                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
415                         $profile_link = $profile_link . '/profile';
416                 }
417
418                 if (!empty($pcid)) {
419                         $contact_url = 'contact/' . $pcid;
420                         $posts_link  = $contact_url . '/posts';
421                         $block_link  = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
422                         $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
423                 }
424
425                 if ($cid && !$item['self']) {
426                         $contact_url = 'contact/' . $cid;
427                         $poke_link   = $contact_url . '/poke';
428                         $posts_link  = $contact_url . '/posts';
429
430                         if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
431                                 $pm_url = 'message/new/' . $cid;
432                         }
433                 }
434
435                 if (local_user()) {
436                         $menu = [
437                                 $this->l10n->t('Follow Thread') => $sub_link,
438                                 $this->l10n->t('View Status') => $status_link,
439                                 $this->l10n->t('View Profile') => $profile_link,
440                                 $this->l10n->t('View Photos') => $photos_link,
441                                 $this->l10n->t('Network Posts') => $posts_link,
442                                 $this->l10n->t('View Contact') => $contact_url,
443                                 $this->l10n->t('Send PM') => $pm_url,
444                                 $this->l10n->t('Block') => $block_link,
445                                 $this->l10n->t('Ignore') => $ignore_link
446                         ];
447
448                         if (!empty($item['language'])) {
449                                 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ModelItem::getLanguageMessage($item) . '\');';
450                         }
451
452                         if ($network == Protocol::DFRN) {
453                                 $menu[$this->l10n->t("Poke")] = $poke_link;
454                         }
455
456                         if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
457                                 in_array($item['network'], Protocol::FEDERATED)) {
458                                 $menu[$this->l10n->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
459                         }
460                 } else {
461                         $menu = [$this->l10n->t('View Profile') => $item['author-link']];
462                 }
463
464                 $args = ['item' => $item, 'menu' => $menu];
465
466                 Hook::callAll('item_photo_menu', $args);
467
468                 $menu = $args['menu'];
469
470                 $o = '';
471                 foreach ($menu as $k => $v) {
472                         if (strpos($v, 'javascript:') === 0) {
473                                 $v = substr($v, 11);
474                                 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
475                         } elseif ($v) {
476                                 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
477                         }
478                 }
479                 $this->profiler->stopRecording();
480                 return $o;
481         }
482
483         public function visibleActivity($item) {
484
485                 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
486                         return false;
487                 }
488
489                 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
490                 if ($this->activity->match($item['verb'], Activity::FOLLOW) &&
491                         $item['object-type'] === Activity\ObjectType::NOTE &&
492                         empty($item['self']) &&
493                         $item['uid'] == local_user()) {
494                         return false;
495                 }
496
497                 return true;
498         }
499
500         public function expandTags(array $item, bool $setPermissions = false)
501         {
502                 // Look for any tags and linkify them
503                 $item['inform'] = '';
504                 $private_forum  = false;
505                 $private_id     = null;
506                 $only_to_forum  = false;
507                 $forum_contact  = [];
508                 $receivers      = [];
509
510                 // Convert mentions in the body to a unified format
511                 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
512
513                 // Search for forum mentions
514                 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
515                         $contact = Contact::getByURLForUser($tag[2], $item['uid']);
516
517                         $receivers[] = $contact['id'];
518
519                         if (!empty($item['inform'])) {
520                                 $item['inform'] .= ',';
521                         }
522                         $item['inform'] .= 'cid:' . $contact['id'];
523
524                         if (($item['gravity'] == GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
525                                 continue;
526                         }
527
528                         if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
529                                 $private_forum = $contact['prv'];
530                                 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
531                                 $private_id = $contact['id'];
532                                 $forum_contact = $contact;
533                                 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
534                         } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
535                                 $private_forum = false;
536                                 $only_to_forum = true;
537                                 $private_id = $contact['id'];
538                                 $forum_contact = $contact;
539                                 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
540                         } else {
541                                 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
542                         }
543                 }
544                 Logger::info('Got inform', ['inform' => $item['inform']]);
545
546                 if (($item['gravity'] == GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
547                         // we tagged a forum in a top level post. Now we change the post
548                         $item['private'] = $private_forum ? ModelItem::PRIVATE : ModelItem::UNLISTED;
549
550                         if ($only_to_forum) {
551                                 $item['postopts'] = '';
552                         }
553
554                         $item['deny_cid'] = '';
555                         $item['deny_gid'] = '';
556
557                         if ($private_forum) {
558                                 $item['allow_cid'] = '<' . $private_id . '>';
559                                 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
560                         } else {
561                                 $item['allow_cid'] = '';
562                                 $item['allow_gid'] = '';
563                         }
564                 } elseif ($setPermissions && ($item['gravity'] == GRAVITY_PARENT)) {
565                         if (empty($receivers)) {
566                                 // For security reasons direct posts without any receiver will be posts to yourself
567                                 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
568                                 $receivers[] = $self['id'];
569                         }
570
571                         $item['private']   = ModelItem::PRIVATE;
572                         $item['allow_cid'] = '';
573                         $item['allow_gid'] = '';
574                         $item['deny_cid']  = '';
575                         $item['deny_gid']  = '';
576
577                         foreach ($receivers as $receiver) {
578                                 $item['allow_cid'] .= '<' . $receiver . '>';
579                         }
580                 }
581                 return $item;
582         }
583 }