]> git.mxchange.org Git - friendica.git/blob - src/Content/Item.php
Merge remote-tracking branch 'upstream/develop' into user-contact
[friendica.git] / src / Content / Item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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 string  $inform      a comma-seperated string containing everybody to inform
139          * @param integer $profile_uid the user id to replace the tag for (0 = anyone)
140          * @param string  $tag         the tag to replace
141          * @param string  $network     The network of the post
142          *
143          * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
144          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
145          * @throws \ImagickException
146          */
147         public static function replaceTag(&$body, &$inform, $profile_uid, $tag, $network = '')
148         {
149                 $replaced = false;
150
151                 //is it a person tag?
152                 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
153                         $tag_type = substr($tag, 0, 1);
154                         //is it already replaced?
155                         if (strpos($tag, '[url=')) {
156                                 return $replaced;
157                         }
158
159                         //get the person's name
160                         $name = substr($tag, 1);
161
162                         // Sometimes the tag detection doesn't seem to work right
163                         // This is some workaround
164                         $nameparts = explode(' ', $name);
165                         $name = $nameparts[0];
166
167                         // Try to detect the contact in various ways
168                         if (strpos($name, 'http://') || strpos($name, '@')) {
169                                 $contact = Contact::getByURLForUser($name, $profile_uid);
170                         } else {
171                                 $contact = false;
172                                 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
173
174                                 if (strrpos($name, '+')) {
175                                         // Is it in format @nick+number?
176                                         $tagcid = intval(substr($name, strrpos($name, '+') + 1));
177                                         $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
178                                 }
179
180                                 // select someone by nick in the current network
181                                 if (!DBA::isResult($contact) && ($network != '')) {
182                                         $condition = ["`nick` = ? AND `network` = ? AND `uid` = ?",
183                                                 $name, $network, $profile_uid];
184                                         $contact = DBA::selectFirst('contact', $fields, $condition);
185                                 }
186
187                                 // select someone by attag in the current network
188                                 if (!DBA::isResult($contact) && ($network != '')) {
189                                         $condition = ["`attag` = ? AND `network` = ? AND `uid` = ?",
190                                                 $name, $network, $profile_uid];
191                                         $contact = DBA::selectFirst('contact', $fields, $condition);
192                                 }
193
194                                 //select someone by name in the current network
195                                 if (!DBA::isResult($contact) && ($network != '')) {
196                                         $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
197                                         $contact = DBA::selectFirst('contact', $fields, $condition);
198                                 }
199
200                                 // select someone by nick in any network
201                                 if (!DBA::isResult($contact)) {
202                                         $condition = ["`nick` = ? AND `uid` = ?", $name, $profile_uid];
203                                         $contact = DBA::selectFirst('contact', $fields, $condition);
204                                 }
205
206                                 // select someone by attag in any network
207                                 if (!DBA::isResult($contact)) {
208                                         $condition = ["`attag` = ? AND `uid` = ?", $name, $profile_uid];
209                                         $contact = DBA::selectFirst('contact', $fields, $condition);
210                                 }
211
212                                 // select someone by name in any network
213                                 if (!DBA::isResult($contact)) {
214                                         $condition = ['name' => $name, 'uid' => $profile_uid];
215                                         $contact = DBA::selectFirst('contact', $fields, $condition);
216                                 }
217                         }
218
219                         // Check if $contact has been successfully loaded
220                         if (DBA::isResult($contact)) {
221                                 if (strlen($inform) && (isset($contact['notify']) || isset($contact['id']))) {
222                                         $inform .= ',';
223                                 }
224
225                                 if (isset($contact['id'])) {
226                                         $inform .= 'cid:' . $contact['id'];
227                                 } elseif (isset($contact['notify'])) {
228                                         $inform  .= $contact['notify'];
229                                 }
230
231                                 $profile = $contact['url'];
232                                 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
233                         }
234
235                         //if there is an url for this persons profile
236                         if (isset($profile) && ($newname != '')) {
237                                 $replaced = true;
238                                 // create profile link
239                                 $profile = str_replace(',', '%2c', $profile);
240                                 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
241                                 $body = str_replace($tag_type . $name, $newtag, $body);
242                         }
243                 }
244
245                 return ['replaced' => $replaced, 'contact' => $contact];
246         }
247
248         /**
249          * Render actions localized
250          *
251          * @param $item
252          * @throws ImagickException
253          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254          */
255         public function localize(&$item)
256         {
257                 $this->profiler->startRecording('rendering');
258                 /// @todo The following functionality needs to be cleaned up.
259                 if (!empty($item['verb'])) {
260                         $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
261
262                         if (stristr($item['verb'], Activity::POKE)) {
263                                 $verb = urldecode(substr($item['verb'], strpos($item['verb'],'#') + 1));
264                                 if (!$verb) {
265                                         $this->profiler->stopRecording();
266                                         return;
267                                 }
268                                 if ($item['object-type'] == "" || $item['object-type'] !== Activity\ObjectType::PERSON) {
269                                         $this->profiler->stopRecording();
270                                         return;
271                                 }
272
273                                 $obj = XML::parseString($xmlhead . $item['object']);
274
275                                 $Bname = $obj->title;
276                                 $Blink = $obj->id;
277                                 $Bphoto = "";
278
279                                 foreach ($obj->link as $l) {
280                                         $atts = $l->attributes();
281                                         switch ($atts['rel']) {
282                                                 case "alternate": $Blink = $atts['href'];
283                                                 case "photo": $Bphoto = $atts['href'];
284                                         }
285                                 }
286
287                                 $author = ['uid' => 0, 'id' => $item['author-id'],
288                                         'network' => $item['author-network'], 'url' => $item['author-link']];
289                                 $A = '[url=' . Contact::magicLinkByContact($author) . ']' . $item['author-name'] . '[/url]';
290
291                                 if (!empty($Blink)) {
292                                         $B = '[url=' . Contact::magicLink($Blink) . ']' . $Bname . '[/url]';
293                                 } else {
294                                         $B = '';
295                                 }
296
297                                 if ($Bphoto != "" && !empty($Blink)) {
298                                         $Bphoto = '[url=' . Contact::magicLink($Blink) . '][img=80x80]' . $Bphoto . '[/img][/url]';
299                                 }
300
301                                 /*
302                                 * we can't have a translation string with three positions but no distinguishable text
303                                 * So here is the translate string.
304                                 */
305                                 $txt = $this->l10n->t('%1$s poked %2$s');
306
307                                 // now translate the verb
308                                 $poked_t = trim(sprintf($txt, '', ''));
309                                 $txt = str_replace($poked_t, $this->l10n->t($verb), $txt);
310
311                                 // then do the sprintf on the translation string
312
313                                 $item['body'] = sprintf($txt, $A, $B) . "\n\n\n" . $Bphoto;
314
315                         }
316
317                         if ($this->activity->match($item['verb'], Activity::TAG)) {
318                                 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
319                                         'verb', 'object-type', 'resource-id', 'body', 'plink'];
320                                 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
321                                 if (!DBA::isResult($obj)) {
322                                         $this->profiler->stopRecording();
323                                         return;
324                                 }
325
326                                 $author_arr = ['uid' => 0, 'id' => $item['author-id'],
327                                         'network' => $item['author-network'], 'url' => $item['author-link']];
328                                 $author  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
329
330                                 $author_arr = ['uid' => 0, 'id' => $obj['author-id'],
331                                         'network' => $obj['author-network'], 'url' => $obj['author-link']];
332                                 $objauthor  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
333
334                                 switch ($obj['verb']) {
335                                         case Activity::POST:
336                                                 switch ($obj['object-type']) {
337                                                         case Activity\ObjectType::EVENT:
338                                                                 $post_type = $this->l10n->t('event');
339                                                                 break;
340                                                         default:
341                                                                 $post_type = $this->l10n->t('status');
342                                                 }
343                                                 break;
344                                         default:
345                                                 if ($obj['resource-id']) {
346                                                         $post_type = $this->l10n->t('photo');
347                                                         $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
348                                                         $rr['plink'] = $m[1];
349                                                 } else {
350                                                         $post_type = $this->l10n->t('status');
351                                                 }
352                                                 // Let's break everthing ... ;-)
353                                                 break;
354                                 }
355                                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
356
357                                 $parsedobj = XML::parseString($xmlhead . $item['object']);
358
359                                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
360                                 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
361                         }
362                 }
363
364                 $matches = null;
365                 if (preg_match_all('/@\[url=(.*?)\]/is', $item['body'], $matches, PREG_SET_ORDER)) {
366                         foreach ($matches as $mtch) {
367                                 if (!strpos($mtch[1], 'zrl=')) {
368                                         $item['body'] = str_replace($mtch[0], '@[url=' . Contact::magicLink($mtch[1]) . ']', $item['body']);
369                                 }
370                         }
371                 }
372
373                 // add sparkle links to appropriate permalinks
374                 // Only create a redirection to a magic link when logged in
375                 if (!empty($item['plink']) && Session::isAuthenticated() && $item['private'] == ModelItem::PRIVATE) {
376                         $author = ['uid' => 0, 'id' => $item['author-id'],
377                                 'network' => $item['author-network'], 'url' => $item['author-link']];
378                         $item['plink'] = Contact::magicLinkByContact($author, $item['plink']);
379                 }
380                 $this->profiler->stopRecording();
381         }
382
383         public function photoMenu($item, string $formSecurityToken)
384         {
385                 $this->profiler->startRecording('rendering');
386                 $sub_link = '';
387                 $poke_link = '';
388                 $contact_url = '';
389                 $pm_url = '';
390                 $status_link = '';
391                 $photos_link = '';
392                 $posts_link = '';
393                 $block_link = '';
394                 $ignore_link = '';
395
396                 if (local_user() && local_user() == $item['uid'] && $item['gravity'] == GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
397                         $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
398                 }
399
400                 $author = ['uid' => 0, 'id' => $item['author-id'],
401                         'network' => $item['author-network'], 'url' => $item['author-link']];
402                 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
403                 $sparkle = (strpos($profile_link, 'redir/') === 0);
404
405                 $cid = 0;
406                 $pcid = $item['author-id'];
407                 $network = '';
408                 $rel = 0;
409                 $condition = ['uid' => local_user(), 'nurl' => Strings::normaliseLink($item['author-link'])];
410                 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
411                 if (DBA::isResult($contact)) {
412                         $cid = $contact['id'];
413                         $network = $contact['network'];
414                         $rel = $contact['rel'];
415                 }
416
417                 if ($sparkle) {
418                         $status_link = $profile_link . '/status';
419                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
420                         $profile_link = $profile_link . '/profile';
421                 }
422
423                 if (!empty($pcid)) {
424                         $contact_url = 'contact/' . $pcid;
425                         $posts_link  = $contact_url . '/posts';
426                         $block_link  = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
427                         $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
428                 }
429
430                 if ($cid && !$item['self']) {
431                         $contact_url = 'contact/' . $cid;
432                         $poke_link   = $contact_url . '/poke';
433                         $posts_link  = $contact_url . '/posts';
434
435                         if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
436                                 $pm_url = 'message/new/' . $cid;
437                         }
438                 }
439
440                 if (local_user()) {
441                         $menu = [
442                                 $this->l10n->t('Follow Thread') => $sub_link,
443                                 $this->l10n->t('View Status') => $status_link,
444                                 $this->l10n->t('View Profile') => $profile_link,
445                                 $this->l10n->t('View Photos') => $photos_link,
446                                 $this->l10n->t('Network Posts') => $posts_link,
447                                 $this->l10n->t('View Contact') => $contact_url,
448                                 $this->l10n->t('Send PM') => $pm_url,
449                                 $this->l10n->t('Block') => $block_link,
450                                 $this->l10n->t('Ignore') => $ignore_link
451                         ];
452
453                         if (!empty($item['language'])) {
454                                 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ModelItem::getLanguageMessage($item) . '\');';
455                         }
456
457                         if ($network == Protocol::DFRN) {
458                                 $menu[$this->l10n->t("Poke")] = $poke_link;
459                         }
460
461                         if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
462                                 in_array($item['network'], Protocol::FEDERATED)) {
463                                 $menu[$this->l10n->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
464                         }
465                 } else {
466                         $menu = [$this->l10n->t('View Profile') => $item['author-link']];
467                 }
468
469                 $args = ['item' => $item, 'menu' => $menu];
470
471                 Hook::callAll('item_photo_menu', $args);
472
473                 $menu = $args['menu'];
474
475                 $o = '';
476                 foreach ($menu as $k => $v) {
477                         if (strpos($v, 'javascript:') === 0) {
478                                 $v = substr($v, 11);
479                                 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
480                         } elseif ($v) {
481                                 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
482                         }
483                 }
484                 $this->profiler->stopRecording();
485                 return $o;
486         }
487
488         public function visibleActivity($item) {
489
490                 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
491                         return false;
492                 }
493         
494                 // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
495                 if ($this->activity->match($item['verb'], Activity::FOLLOW) &&
496                         $item['object-type'] === Activity\ObjectType::NOTE &&
497                         empty($item['self']) &&
498                         $item['uid'] == local_user()) {
499                         return false;
500                 }
501         
502                 return true;
503         }
504 }