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