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