]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
253b4b4f18a42d467b0e286e3e5909b895bf06f6
[friendica.git] / src / Object / Post.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\Object;
23
24 use Friendica\Content\ContactSelector;
25 use Friendica\Content\Feature;
26 use Friendica\Core\Addon;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Session;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Post as PostModel;
37 use Friendica\Model\Tag;
38 use Friendica\Model\User;
39 use Friendica\Protocol\Activity;
40 use Friendica\Util\Crypto;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Proxy;
43 use Friendica\Util\Strings;
44 use Friendica\Util\Temporal;
45
46 /**
47  * An item
48  */
49 class Post
50 {
51         private $data = [];
52         private $template = null;
53         private $available_templates = [
54                 'wall' => 'wall_thread.tpl',
55                 'wall2wall' => 'wallwall_thread.tpl'
56         ];
57         private $comment_box_template = 'comment_item.tpl';
58         private $toplevel = false;
59         private $writable = false;
60         /**
61          * @var Post[]
62          */
63         private $children = [];
64         private $parent = null;
65
66         /**
67          * @var Thread
68          */
69         private $thread = null;
70         private $redirect_url = null;
71         private $owner_url = '';
72         private $owner_name = '';
73         private $wall_to_wall = false;
74         private $threaded = false;
75         private $visiting = false;
76
77         /**
78          * Constructor
79          *
80          * @param array $data data array
81          * @throws \Exception
82          */
83         public function __construct(array $data)
84         {
85                 $this->data = $data;
86                 $this->setTemplate('wall');
87                 $this->toplevel = $this->getId() == $this->getDataValue('parent');
88
89                 if (!empty(Session::getUserIDForVisitorContactID($this->getDataValue('contact-id')))) {
90                         $this->visiting = true;
91                 }
92
93                 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
94                 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
95                         'network' => $this->getDataValue('author-network'),
96                         'url' => $this->getDataValue('author-link')];
97                 $this->redirect_url = Contact::magicLinkByContact($author);
98                 if (!$this->isToplevel()) {
99                         $this->threaded = true;
100                 }
101
102                 // Prepare the children
103                 if (!empty($data['children'])) {
104                         foreach ($data['children'] as $item) {
105                                 // Only add will be displayed
106                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
107                                         continue;
108                                 } elseif (!DI::contentItem()->visibleActivity($item)) {
109                                         continue;
110                                 }
111
112                                 // You can always comment on Diaspora and OStatus items
113                                 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (local_user() == $item['uid'])) {
114                                         $item['writable'] = true;
115                                 }
116
117                                 $item['pagedrop'] = $data['pagedrop'];
118                                 $child = new Post($item);
119                                 $this->addChild($child);
120                         }
121                 }
122         }
123
124         /**
125          * Fetch the privacy of the post
126          *
127          * @param array $item 
128          * @return string 
129          */
130         private function fetchPrivacy(array $item):string
131         {
132                 switch ($item['private']) {
133                         case Item::PRIVATE:
134                                 $output = DI::l10n()->t('Private Message');
135                                 break;
136                         case Item::PUBLIC:
137                                 $output = DI::l10n()->t('Public Message');
138                                 break;
139                         case Item::UNLISTED:
140                                 $output = DI::l10n()->t('Unlisted Message');
141                                 break;
142                 }
143
144                 return $output;
145         }
146
147         /**
148          * Get data in a form usable by a conversation template
149          *
150          * @param array   $conv_responses conversation responses
151          * @param string $formSecurityToken A security Token to avoid CSF attacks
152          * @param integer $thread_level   default = 1
153          *
154          * @return mixed The data requested on success
155          *               false on failure
156          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
157          * @throws \ImagickException
158          */
159         public function getTemplateData(array $conv_responses, string $formSecurityToken, $thread_level = 1)
160         {
161                 $item = $this->getData();
162                 $edited = false;
163                 // If the time between "created" and "edited" differs we add
164                 // a notice that the post was edited.
165                 // Note: In some networks reshared items seem to have (sometimes) a difference
166                 // between creation time and edit time of a second. Thats why we add the notice
167                 // only if the difference is more than 1 second.
168                 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
169                         $edited = [
170                                 'label'    => DI::l10n()->t('This entry was edited'),
171                                 'date'     => DateTimeFormat::local($item['edited'], 'r'),
172                                 'relative' => Temporal::getRelativeDate($item['edited'])
173                         ];
174                 }
175                 $sparkle = '';
176                 $buttons = [
177                         'like'     => null,
178                         'dislike'  => null,
179                         'share'    => null,
180                         'announce' => null,
181                 ];
182                 $dropping = false;
183                 $pinned = '';
184                 $pin = false;
185                 $star = false;
186                 $ignore = false;
187                 $ispinned = "unpinned";
188                 $isstarred = "unstarred";
189                 $indent = '';
190                 $shiny = '';
191                 $osparkle = '';
192                 $total_children = $this->countDescendants();
193
194                 $conv = $this->getThread();
195
196                 $privacy   = $this->fetchPrivacy($item);
197                 $lock      = ($item['private'] == Item::PRIVATE) ? $privacy : false;
198                 $connector = !in_array($item['network'], Protocol::NATIVE_SUPPORT) ? DI::l10n()->t('Connector Message') : false;
199
200                 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != Item::PRIVATE;
201                 $announceable = $shareable && in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::TWITTER]);
202
203                 // On Diaspora only toplevel posts can be reshared
204                 if ($announceable && ($item['network'] == Protocol::DIASPORA) && ($item['gravity'] != GRAVITY_PARENT)) {
205                         $announceable = false;
206                 }
207
208                 $edpost = false;
209
210                 if (local_user()) {
211                         if (Strings::compareLink(Session::get('my_url'), $item['author-link'])) {
212                                 if ($item["event-id"] != 0) {
213                                         $edpost = ["events/event/" . $item['event-id'], DI::l10n()->t("Edit")];
214                                 } else {
215                                         $edpost = ["editpost/" . $item['id'], DI::l10n()->t("Edit")];
216                                 }
217                         }
218                         $dropping = in_array($item['uid'], [0, local_user()]);
219                 }
220
221                 // Editing on items of not subscribed users isn't currently possible
222                 // There are some issues on editing that prevent this.
223                 // But also it is an issue of the supported protocols that doesn't allow editing at all.
224                 if ($item['uid'] == 0) {
225                         $edpost = false;
226                 }
227
228                 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
229                         $dropping = true;
230                 }
231
232                 $origin = $item['origin'] || $item['parent-origin'];
233
234                 if ($item['pinned']) {
235                         $pinned = DI::l10n()->t('Pinned item');
236                 }
237
238                 // Showing the one or the other text, depending upon if we can only hide it or really delete it.
239                 $delete = $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally');
240
241                 $drop = false;
242                 $block = false;
243                 if (local_user()) {
244                         $drop = [
245                                 'dropping' => $dropping,
246                                 'pagedrop' => $item['pagedrop'],
247                                 'select' => DI::l10n()->t('Select'),
248                                 'delete' => $delete,
249                         ];
250                 }
251
252                 if (!$item['self']) {
253                         $block = [
254                                 'blocking' => true,
255                                 'block'   => DI::l10n()->t('Block %s', $item['author-name']),
256                                 'author_id'   => $item['author-id'],
257                         ];
258                 }
259
260                 $filer = local_user() ? DI::l10n()->t('Save to folder') : false;
261
262                 $profile_name = $item['author-name'];
263                 if (!empty($item['author-link']) && empty($item['author-name'])) {
264                         $profile_name = $item['author-link'];
265                 }
266
267                 if (Session::isAuthenticated()) {
268                         $author = ['uid' => 0, 'id' => $item['author-id'],
269                                 'network' => $item['author-network'], 'url' => $item['author-link']];
270                         $profile_link = Contact::magicLinkByContact($author);
271                 } else {
272                         $profile_link = $item['author-link'];
273                 }
274
275                 if (strpos($profile_link, 'redir/') === 0) {
276                         $sparkle = ' sparkle';
277                 }
278
279                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
280                 Hook::callAll('render_location', $locate);
281                 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
282
283                 // process action responses - e.g. like/dislike/attend/agree/whatever
284                 $response_verbs = ['like', 'dislike', 'announce'];
285
286                 $isevent = false;
287                 $attend = [];
288                 if ($item['object-type'] === Activity\ObjectType::EVENT) {
289                         $response_verbs[] = 'attendyes';
290                         $response_verbs[] = 'attendno';
291                         $response_verbs[] = 'attendmaybe';
292                         if ($conv->isWritable()) {
293                                 $isevent = true;
294                                 $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')];
295                         }
296                 }
297
298                 $responses = [];
299                 foreach ($response_verbs as $value => $verb) {
300                         $responses[$verb] = [
301                                 'self'   => $conv_responses[$verb][$item['uri-id']]['self'] ?? 0,
302                                 'output' => !empty($conv_responses[$verb][$item['uri-id']]) ? DI::conversation()->formatActivity($conv_responses[$verb][$item['uri-id']]['links'], $verb, $item['uri-id']) : '',
303                         ];
304                 }
305
306                 /*
307                  * We should avoid doing this all the time, but it depends on the conversation mode
308                  * And the conv mode may change when we change the conv, or it changes its mode
309                  * Maybe we should establish a way to be notified about conversation changes
310                  */
311                 $this->checkWallToWall();
312
313                 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
314                         $osparkle = ' sparkle';
315                 }
316
317                 $tagger = '';
318
319                 if ($this->isToplevel()) {
320                         if (local_user()) {
321                                 $ignored = PostModel\ThreadUser::getIgnored($item['uri-id'], local_user());
322                                 if ($item['mention'] || $ignored) {
323                                         $ignore = [
324                                                 'do'        => DI::l10n()->t('Ignore thread'),
325                                                 'undo'      => DI::l10n()->t('Unignore thread'),
326                                                 'toggle'    => DI::l10n()->t('Toggle ignore status'),
327                                                 'classdo'   => $ignored ? "hidden" : "",
328                                                 'classundo' => $ignored ? "" : "hidden",
329                                                 'ignored'   => DI::l10n()->t('Ignored'),
330                                         ];
331                                 }
332
333                                 $isstarred = (($item['starred']) ? "starred" : "unstarred");
334
335                                 $star = [
336                                         'do'        => DI::l10n()->t('Add star'),
337                                         'undo'      => DI::l10n()->t('Remove star'),
338                                         'toggle'    => DI::l10n()->t('Toggle star status'),
339                                         'classdo'   => $item['starred'] ? "hidden" : "",
340                                         'classundo' => $item['starred'] ? "" : "hidden",
341                                         'starred'   => DI::l10n()->t('Starred'),
342                                 ];
343
344                                 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
345                                         if ($origin) {
346                                                 $ispinned = ($item['pinned'] ? 'pinned' : 'unpinned');
347
348                                                 $pin = [
349                                                         'do'        => DI::l10n()->t('Pin'),
350                                                         'undo'      => DI::l10n()->t('Unpin'),
351                                                         'toggle'    => DI::l10n()->t('Toggle pin status'),
352                                                         'classdo'   => $item['pinned'] ? 'hidden' : '',
353                                                         'classundo' => $item['pinned'] ? '' : 'hidden',
354                                                         'pinned'   => DI::l10n()->t('Pinned'),
355                                                 ];
356                                         }
357
358                                         $tagger = [
359                                                 'add'   => DI::l10n()->t('Add tag'),
360                                                 'class' => "",
361                                         ];
362                                 }
363                         }
364                 } else {
365                         $indent = 'comment';
366                 }
367
368                 if ($conv->isWritable()) {
369                         $buttons['like']    = [DI::l10n()->t("I like this \x28toggle\x29")      , DI::l10n()->t('Like')];
370                         $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t('Dislike')];
371                         if ($shareable) {
372                                 $buttons['share'] = [DI::l10n()->t('Quote share this'), DI::l10n()->t('Quote Share')];
373                         }
374                         if ($announceable) {
375                                 $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')];
376                                 $buttons['unannounce'] = [DI::l10n()->t('Cancel your Reshare'), DI::l10n()->t('Unshare')];
377                         }
378                 }
379
380                 $comment_html = $this->getCommentBox($indent);
381
382                 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
383                         $shiny = 'shiny';
384                 }
385
386                 DI::contentItem()->localize($item);
387
388                 $body_html = Item::prepareBody($item, true);
389
390                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item, local_user());
391
392                 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
393                         $title = ucfirst($item['content-warning']);
394                 } else {
395                         $title = $item['title'];
396                 }
397
398                 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
399                         $buttons['dislike'] = false;
400                 }
401
402                 // Disable features that aren't available in several networks
403                 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
404                         if ($buttons["dislike"]) {
405                                 $buttons["dislike"] = false;
406                         }
407
408                         $isevent = false;
409                         $tagger = '';
410                 }
411
412                 if ($buttons["like"] && in_array($item["network"], [Protocol::FEED, Protocol::MAIL])) {
413                         $buttons["like"] = false;
414                 }
415
416                 $tags = Tag::populateFromItem($item);
417
418                 $ago = Temporal::getRelativeDate($item['created']);
419                 $ago_received = Temporal::getRelativeDate($item['received']);
420                 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
421                         $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
422                 }
423
424                 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
425                 if (!local_user() && ($item['network'] != Protocol::DIASPORA) && !empty(Session::get('remote_comment'))) {
426                         $remote_comment = [DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('Remote comment'),
427                                 str_replace('{uri}', urlencode($item['uri']), Session::get('remote_comment'))];
428
429                         // Ensure to either display the remote comment or the local activities
430                         $buttons = [];
431                         $comment_html = '';
432                 } else {
433                         $remote_comment = '';
434                 }
435
436                 $direction = [];
437                 if (!empty($item['direction'])) {
438                         $direction = $item['direction'];
439                 }
440
441                 $languages = [];
442                 if (!empty($item['language'])) {
443                         $languages = [DI::l10n()->t('Languages'), Item::getLanguageMessage($item)];
444                 }
445
446                 $tmp_item = [
447                         'template'        => $this->getTemplate(),
448                         'type'            => implode("", array_slice(explode("/", $item['verb']), -1)),
449                         'comment_firstcollapsed' => false,
450                         'comment_lastcollapsed' => false,
451                         'suppress_tags'   => DI::config()->get('system', 'suppress_tags'),
452                         'tags'            => $tags['tags'],
453                         'hashtags'        => $tags['hashtags'],
454                         'mentions'        => $tags['mentions'],
455                         'implicit_mentions' => $tags['implicit_mentions'],
456                         'txt_cats'        => DI::l10n()->t('Categories:'),
457                         'txt_folders'     => DI::l10n()->t('Filed under:'),
458                         'has_cats'        => ((count($categories)) ? 'true' : ''),
459                         'has_folders'     => ((count($folders)) ? 'true' : ''),
460                         'categories'      => $categories,
461                         'folders'         => $folders,
462                         'body_html'       => $body_html,
463                         'text'            => strip_tags($body_html),
464                         'id'              => $this->getId(),
465                         'guid'            => urlencode($item['guid']),
466                         'isevent'         => $isevent,
467                         'attend'          => $attend,
468                         'linktitle'       => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
469                         'olinktitle'      => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
470                         'to'              => DI::l10n()->t('to'),
471                         'via'             => DI::l10n()->t('via'),
472                         'wall'            => DI::l10n()->t('Wall-to-Wall'),
473                         'vwall'           => DI::l10n()->t('via Wall-To-Wall:'),
474                         'profile_url'     => $profile_link,
475                         'name'            => $profile_name,
476                         'item_photo_menu_html' => DI::contentItem()->photoMenu($item, $formSecurityToken),
477                         'thumb'           => DI::baseUrl()->remove(Contact::getAvatarUrlForUrl($item['author-link'], $item['uid'], Proxy::SIZE_THUMB)),
478                         'osparkle'        => $osparkle,
479                         'sparkle'         => $sparkle,
480                         'title'           => $title,
481                         'localtime'       => DateTimeFormat::local($item['created'], 'r'),
482                         'ago'             => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
483                         'app'             => $item['app'],
484                         'created'         => $ago,
485                         'lock'            => $lock,
486                         'private'         => $item['private'],
487                         'privacy'         => $privacy,
488                         'connector'       => $connector,
489                         'location_html'   => $location_html,
490                         'indent'          => $indent,
491                         'shiny'           => $shiny,
492                         'owner_self'      => $item['author-link'] == Session::get('my_url'),
493                         'owner_url'       => $this->getOwnerUrl(),
494                         'owner_photo'     => DI::baseUrl()->remove(Contact::getAvatarUrlForUrl($item['owner-link'], $item['uid'], Proxy::SIZE_THUMB)),
495                         'owner_name'      => $this->getOwnerName(),
496                         'plink'           => Item::getPlink($item),
497                         'browsershare'    => DI::l10n()->t('Share'),
498                         'edpost'          => $edpost,
499                         'ispinned'        => $ispinned,
500                         'pin'             => $pin,
501                         'pinned'          => $pinned,
502                         'isstarred'       => $isstarred,
503                         'star'            => $star,
504                         'ignore'          => $ignore,
505                         'tagger'          => $tagger,
506                         'filer'           => $filer,
507                         'language'        => $languages,
508                         'drop'            => $drop,
509                         'block'           => $block,
510                         'vote'            => $buttons,
511                         'like_html'       => $responses['like']['output'],
512                         'dislike_html'    => $responses['dislike']['output'],
513                         'responses'       => $responses,
514                         'switchcomment'   => DI::l10n()->t('Comment'),
515                         'reply_label'     => DI::l10n()->t('Reply to %s', $profile_name),
516                         'comment_html'    => $comment_html,
517                         'remote_comment'  => $remote_comment,
518                         'menu'            => DI::l10n()->t('More'),
519                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
520                         'wait'            => DI::l10n()->t('Please wait'),
521                         'thread_level'    => $thread_level,
522                         'edited'          => $edited,
523                         'network'         => $item["network"],
524                         'network_name'    => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
525                         'network_icon'    => ContactSelector::networkToIcon($item['network'], $item['author-link']),
526                         'received'        => $item['received'],
527                         'commented'       => $item['commented'],
528                         'created_date'    => $item['created'],
529                         'uriid'           => $item['uri-id'],
530                         'return'          => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
531                         'direction'       => $direction,
532                         'reshared'        => $item['reshared'] ?? '',
533                         'delivery'        => [
534                                 'queue_count'       => $item['delivery_queue_count'],
535                                 'queue_done'        => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
536                                 'notifier_pending'  => DI::l10n()->t('Notifier task is pending'),
537                                 'delivery_pending'  => DI::l10n()->t('Delivery to remote servers is pending'),
538                                 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
539                                 'delivery_almost'   => DI::l10n()->t('Delivery to remote servers is mostly done'),
540                                 'delivery_done'     => DI::l10n()->t('Delivery to remote servers is done'),
541                         ],
542                 ];
543
544                 $arr = ['item' => $item, 'output' => $tmp_item];
545                 Hook::callAll('display_item', $arr);
546
547                 $result = $arr['output'];
548
549                 $result['children'] = [];
550                 $children = $this->getChildren();
551                 $nb_children = count($children);
552                 if ($nb_children > 0) {
553                         foreach ($children as $child) {
554                                 $result['children'][] = $child->getTemplateData($conv_responses, $formSecurityToken, $thread_level + 1);
555                         }
556
557                         // Collapse
558                         if (($nb_children > 2) || ($thread_level > 1)) {
559                                 $result['children'][0]['comment_firstcollapsed'] = true;
560                                 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
561                                 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
562                                 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
563                                 if ($thread_level > 1) {
564                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
565                                 } else {
566                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
567                                 }
568                         }
569                 }
570
571                 $result['total_comments_num'] = $this->isToplevel() ? $total_children : 0;
572
573                 $result['private'] = $item['private'];
574                 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
575
576                 if ($this->isThreaded()) {
577                         $result['flatten'] = false;
578                         $result['threaded'] = true;
579                 } else {
580                         $result['flatten'] = true;
581                         $result['threaded'] = false;
582                 }
583
584                 return $result;
585         }
586
587         /**
588          * @return integer
589          */
590         public function getId()
591         {
592                 return $this->getDataValue('id');
593         }
594
595         /**
596          * @return boolean
597          */
598         public function isThreaded()
599         {
600                 return $this->threaded;
601         }
602
603         /**
604          * Add a child item
605          *
606          * @param Post $item The child item to add
607          *
608          * @return mixed
609          * @throws \Exception
610          */
611         public function addChild(Post $item)
612         {
613                 $item_id = $item->getId();
614                 if (!$item_id) {
615                         Logger::info('[ERROR] Post::addChild : Item has no ID!!');
616                         return false;
617                 } elseif ($this->getChild($item->getId())) {
618                         Logger::info('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').');
619                         return false;
620                 }
621
622                 $activity = DI::activity();
623
624                 /*
625                  * Only add what will be displayed
626                  */
627                 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
628                         return false;
629                 } elseif ($activity->match($item->getDataValue('verb'), Activity::LIKE) ||
630                           $activity->match($item->getDataValue('verb'), Activity::DISLIKE)) {
631                         return false;
632                 }
633
634                 $item->setParent($this);
635                 $this->children[] = $item;
636
637                 return end($this->children);
638         }
639
640         /**
641          * Get a child by its ID
642          *
643          * @param integer $id The child id
644          *
645          * @return mixed
646          */
647         public function getChild($id)
648         {
649                 foreach ($this->getChildren() as $child) {
650                         if ($child->getId() == $id) {
651                                 return $child;
652                         }
653                 }
654
655                 return null;
656         }
657
658         /**
659          * Get all our children
660          *
661          * @return Post[]
662          */
663         public function getChildren()
664         {
665                 return $this->children;
666         }
667
668         /**
669          * Set our parent
670          *
671          * @param Post $item The item to set as parent
672          *
673          * @return void
674          */
675         protected function setParent(Post $item)
676         {
677                 $parent = $this->getParent();
678                 if ($parent) {
679                         $parent->removeChild($this);
680                 }
681
682                 $this->parent = $item;
683                 $this->setThread($item->getThread());
684         }
685
686         /**
687          * Remove our parent
688          *
689          * @return void
690          */
691         protected function removeParent()
692         {
693                 $this->parent = null;
694                 $this->thread = null;
695         }
696
697         /**
698          * Remove a child
699          *
700          * @param Post $item The child to be removed
701          *
702          * @return boolean Success or failure
703          * @throws \Exception
704          */
705         public function removeChild(Post $item)
706         {
707                 $id = $item->getId();
708                 foreach ($this->getChildren() as $key => $child) {
709                         if ($child->getId() == $id) {
710                                 $child->removeParent();
711                                 unset($this->children[$key]);
712                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
713                                 $this->children = array_values($this->children);
714                                 return true;
715                         }
716                 }
717                 Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').');
718                 return false;
719         }
720
721         /**
722          * Get parent item
723          *
724          * @return object
725          */
726         protected function getParent()
727         {
728                 return $this->parent;
729         }
730
731         /**
732          * Set conversation thread
733          *
734          * @param Thread $thread
735          *
736          * @return void
737          */
738         public function setThread(Thread $thread = null)
739         {
740                 $this->thread = $thread;
741
742                 // Set it on our children too
743                 foreach ($this->getChildren() as $child) {
744                         $child->setThread($thread);
745                 }
746         }
747
748         /**
749          * Get conversation
750          *
751          * @return Thread
752          */
753         public function getThread()
754         {
755                 return $this->thread;
756         }
757
758         /**
759          * Get raw data
760          *
761          * We shouldn't need this
762          *
763          * @return array
764          */
765         public function getData()
766         {
767                 return $this->data;
768         }
769
770         /**
771          * Get a data value
772          *
773          * @param string $name key
774          *
775          * @return mixed value on success
776          *               false on failure
777          */
778         public function getDataValue($name)
779         {
780                 if (!isset($this->data[$name])) {
781                         // Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".');
782                         return false;
783                 }
784
785                 return $this->data[$name];
786         }
787
788         /**
789          * Set template
790          *
791          * @param string $name template name
792          * @return bool
793          * @throws \Exception
794          */
795         private function setTemplate($name)
796         {
797                 if (empty($this->available_templates[$name])) {
798                         Logger::info('[ERROR] Item::setTemplate : Template not available ("' . $name . '").');
799                         return false;
800                 }
801
802                 $this->template = $this->available_templates[$name];
803
804                 return true;
805         }
806
807         /**
808          * Get template
809          *
810          * @return object
811          */
812         private function getTemplate()
813         {
814                 return $this->template;
815         }
816
817         /**
818          * Check if this is a toplevel post
819          *
820          * @return boolean
821          */
822         private function isToplevel()
823         {
824                 return $this->toplevel;
825         }
826
827         /**
828          * Check if this is writable
829          *
830          * @return boolean
831          */
832         private function isWritable()
833         {
834                 $conv = $this->getThread();
835
836                 if ($conv) {
837                         // This will allow us to comment on wall-to-wall items owned by our friends
838                         // and community forums even if somebody else wrote the post.
839                         // bug #517 - this fixes for conversation owner
840                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
841                                 return true;
842                         }
843
844                         // this fixes for visitors
845                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
846                 }
847                 return $this->writable;
848         }
849
850         /**
851          * Count the total of our descendants
852          *
853          * @return integer
854          */
855         private function countDescendants()
856         {
857                 $children = $this->getChildren();
858                 $total = count($children);
859                 if ($total > 0) {
860                         foreach ($children as $child) {
861                                 $total += $child->countDescendants();
862                         }
863                 }
864
865                 return $total;
866         }
867
868         /**
869          * Get the template for the comment box
870          *
871          * @return string
872          */
873         private function getCommentBoxTemplate()
874         {
875                 return $this->comment_box_template;
876         }
877
878         /**
879          * Get default text for the comment box
880          *
881          * @return string
882          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
883          */
884         private function getDefaultText()
885         {
886                 $a = DI::app();
887
888                 if (!local_user()) {
889                         return '';
890                 }
891
892                 $owner = User::getOwnerDataById($a->getLoggedInUserId());
893
894                 $item = PostModel::selectFirst(['author-addr', 'uri-id', 'network', 'gravity', 'content-warning'], ['id' => $this->getId()]);
895                 if (!DBA::isResult($item) || empty($item['author-addr'])) {
896                         // Should not happen
897                         return '';
898                 }
899
900                 if (!empty($item['content-warning']) && Feature::isEnabled(local_user(), 'add_abstract')) {
901                         $text = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $item['content-warning'] . "[/abstract]\n";
902                 } else {
903                         $text = '';
904                 }
905
906                 if (!Feature::isEnabled(local_user(), 'explicit_mentions')) {
907                         return $text;
908                 }
909
910                 if (($item['author-addr'] != $owner['addr']) && (($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], [Protocol::DIASPORA]))) {
911                         $text .= '@' . $item['author-addr'] . ' ';
912                 }
913
914                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
915                 foreach ($terms as $term) {
916                         if (!$term['url']) {
917                                 DI::logger()->warning('Mention term with no URL', ['term' => $term]);
918                                 continue;
919                         }
920
921                         $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
922                         if (!empty($profile['addr']) && (($profile['contact-type'] ?? Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
923                                 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])) {
924                                 $text .= '@' . $profile['addr'] . ' ';
925                         }
926                 }
927
928                 return $text;
929         }
930
931         /**
932          * Get the comment box
933          *
934          * @param string $indent Indent value
935          *
936          * @return mixed The comment box string (empty if no comment box)
937          *               false on failure
938          * @throws \Exception
939          */
940         private function getCommentBox($indent)
941         {
942                 $a = DI::app();
943
944                 $comment_box = '';
945                 $conv = $this->getThread();
946
947                 if ($conv->isWritable() && $this->isWritable()) {
948                         /*
949                          * Hmmm, code depending on the presence of a particular addon?
950                          * This should be better if done by a hook
951                          */
952                         $qcomment = null;
953                         if (Addon::isEnabled('qcomment')) {
954                                 $words = DI::pConfig()->get(local_user(), 'qcomment', 'words');
955                                 $qcomment = $words ? explode("\n", $words) : [];
956                         }
957
958                         // Fetch the user id from the parent when the owner user is empty
959                         $uid = $conv->getProfileOwner();
960                         $parent_uid = $this->getDataValue('uid');
961
962                         $contact = Contact::getById($a->getContactId());
963
964                         $default_text = $this->getDefaultText();
965
966                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
967                                 $uid = $parent_uid;
968                         }
969
970                         $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
971                         $comment_box = Renderer::replaceMacros($template, [
972                                 '$return_path' => DI::args()->getQueryString(),
973                                 '$threaded'    => $this->isThreaded(),
974                                 '$jsreload'    => '',
975                                 '$wall'        => ($conv->getMode() === 'profile'),
976                                 '$id'          => $this->getId(),
977                                 '$parent'      => $this->getId(),
978                                 '$qcomment'    => $qcomment,
979                                 '$default'     => $default_text,
980                                 '$profile_uid' => $uid,
981                                 '$mylink'      => DI::baseUrl()->remove($contact['url'] ?? ''),
982                                 '$mytitle'     => DI::l10n()->t('This is you'),
983                                 '$myphoto'     => DI::baseUrl()->remove($contact['thumb'] ?? ''),
984                                 '$comment'     => DI::l10n()->t('Comment'),
985                                 '$submit'      => DI::l10n()->t('Submit'),
986                                 '$loading'     => DI::l10n()->t('Loading...'),
987                                 '$edbold'      => DI::l10n()->t('Bold'),
988                                 '$editalic'    => DI::l10n()->t('Italic'),
989                                 '$eduline'     => DI::l10n()->t('Underline'),
990                                 '$edquote'     => DI::l10n()->t('Quote'),
991                                 '$edcode'      => DI::l10n()->t('Code'),
992                                 '$edimg'       => DI::l10n()->t('Image'),
993                                 '$edurl'       => DI::l10n()->t('Link'),
994                                 '$edattach'    => DI::l10n()->t('Link or Media'),
995                                 '$prompttext'  => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
996                                 '$preview'     => DI::l10n()->t('Preview'),
997                                 '$indent'      => $indent,
998                                 '$rand_num'    => Crypto::randomDigits(12)
999                         ]);
1000                 }
1001
1002                 return $comment_box;
1003         }
1004
1005         /**
1006          * @return string
1007          */
1008         private function getRedirectUrl()
1009         {
1010                 return $this->redirect_url;
1011         }
1012
1013         /**
1014          * Check if we are a wall to wall item and set the relevant properties
1015          *
1016          * @return void
1017          * @throws \Exception
1018          */
1019         protected function checkWallToWall()
1020         {
1021                 $a = DI::app();
1022                 $conv = $this->getThread();
1023                 $this->wall_to_wall = false;
1024
1025                 if ($this->isToplevel()) {
1026                         if ($conv->getMode() !== 'profile') {
1027                                 if ($this->getDataValue('owner-link')) {
1028                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1029                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1030                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1031
1032                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1033                                                 // The author url doesn't match the owner (typically the contact)
1034                                                 // and also doesn't match the contact alias.
1035                                                 // The name match is a hack to catch several weird cases where URLs are
1036                                                 // all over the park. It can be tricked, but this prevents you from
1037                                                 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1038                                                 // well that it's the same Bob Smith.
1039                                                 // But it could be somebody else with the same name. It just isn't highly likely.
1040
1041
1042                                                 $this->owner_name = $this->getDataValue('owner-name');
1043                                                 $this->wall_to_wall = true;
1044
1045                                                 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
1046                                                         'network' => $this->getDataValue('owner-network'),
1047                                                         'url' => $this->getDataValue('owner-link')];
1048                                                 $this->owner_url = Contact::magicLinkByContact($owner);
1049                                         }
1050                                 }
1051                         }
1052                 }
1053
1054                 if (!$this->wall_to_wall) {
1055                         $this->setTemplate('wall');
1056                         $this->owner_url = '';
1057                         $this->owner_name = '';
1058                 }
1059         }
1060
1061         /**
1062          * @return boolean
1063          */
1064         private function isWallToWall()
1065         {
1066                 return $this->wall_to_wall;
1067         }
1068
1069         /**
1070          * @return string
1071          */
1072         private function getOwnerUrl()
1073         {
1074                 return $this->owner_url;
1075         }
1076
1077         /**
1078          * @return string
1079          */
1080         private function getOwnerName()
1081         {
1082                 return $this->owner_name;
1083         }
1084
1085         /**
1086          * @return boolean
1087          */
1088         private function isVisiting()
1089         {
1090                 return $this->visiting;
1091         }
1092 }