]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
Merge branch 'bug/phpinfo-accessible-hotfix' into 2020.09-rc
[friendica.git] / src / Object / Post.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\Tag;
37 use Friendica\Model\User;
38 use Friendica\Protocol\Activity;
39 use Friendica\Util\Crypto;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Strings;
42 use Friendica\Util\Temporal;
43
44 /**
45  * An item
46  */
47 class Post
48 {
49         private $data = [];
50         private $template = null;
51         private $available_templates = [
52                 'wall' => 'wall_thread.tpl',
53                 'wall2wall' => 'wallwall_thread.tpl'
54         ];
55         private $comment_box_template = 'comment_item.tpl';
56         private $toplevel = false;
57         private $writable = false;
58         /**
59          * @var Post[]
60          */
61         private $children = [];
62         private $parent = null;
63
64         /**
65          * @var Thread
66          */
67         private $thread = null;
68         private $redirect_url = null;
69         private $owner_url = '';
70         private $owner_photo = '';
71         private $owner_name = '';
72         private $wall_to_wall = false;
73         private $threaded = false;
74         private $visiting = false;
75
76         /**
77          * Constructor
78          *
79          * @param array $data data array
80          * @throws \Exception
81          */
82         public function __construct(array $data)
83         {
84                 $this->data = $data;
85                 $this->setTemplate('wall');
86                 $this->toplevel = $this->getId() == $this->getDataValue('parent');
87
88                 if (!empty(Session::getUserIDForVisitorContactID($this->getDataValue('contact-id')))) {
89                         $this->visiting = true;
90                 }
91
92                 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
93                 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
94                         'network' => $this->getDataValue('author-network'),
95                         'url' => $this->getDataValue('author-link')];
96                 $this->redirect_url = Contact::magicLinkByContact($author);
97                 if (!$this->isToplevel()) {
98                         $this->threaded = true;
99                 }
100
101                 // Prepare the children
102                 if (!empty($data['children'])) {
103                         foreach ($data['children'] as $item) {
104                                 // Only add will be displayed
105                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
106                                         continue;
107                                 } elseif (!visible_activity($item)) {
108                                         continue;
109                                 }
110
111                                 // You can always comment on Diaspora and OStatus items
112                                 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (local_user() == $item['uid'])) {
113                                         $item['writable'] = true;
114                                 }
115
116                                 $item['pagedrop'] = $data['pagedrop'];
117                                 $child = new Post($item);
118                                 $this->addChild($child);
119                         }
120                 }
121         }
122
123         /**
124          * Get data in a form usable by a conversation template
125          *
126          * @param array   $conv_responses conversation responses
127          * @param integer $thread_level   default = 1
128          *
129          * @return mixed The data requested on success
130          *               false on failure
131          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
132          * @throws \ImagickException
133          */
134         public function getTemplateData(array $conv_responses, $thread_level = 1)
135         {
136                 $a = DI::app();
137
138                 $item = $this->getData();
139                 $edited = false;
140                 // If the time between "created" and "edited" differs we add
141                 // a notice that the post was edited.
142                 // Note: In some networks reshared items seem to have (sometimes) a difference
143                 // between creation time and edit time of a second. Thats why we add the notice
144                 // only if the difference is more than 1 second.
145                 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
146                         $edited = [
147                                 'label'    => DI::l10n()->t('This entry was edited'),
148                                 'date'     => DateTimeFormat::local($item['edited'], 'r'),
149                                 'relative' => Temporal::getRelativeDate($item['edited'])
150                         ];
151                 }
152                 $sparkle = '';
153                 $buttons = [
154                         'like'    => null,
155                         'dislike' => null,
156                         'share'   => null,
157                 ];
158                 $dropping = false;
159                 $pinned = '';
160                 $pin = false;
161                 $star = false;
162                 $ignore = false;
163                 $ispinned = "unpinned";
164                 $isstarred = "unstarred";
165                 $indent = '';
166                 $shiny = '';
167                 $osparkle = '';
168                 $total_children = $this->countDescendants();
169
170                 $conv = $this->getThread();
171
172                 $lock = ((($item['private'] == Item::PRIVATE) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
173                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
174                         ? DI::l10n()->t('Private Message')
175                         : false);
176
177                 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != Item::PRIVATE;
178
179                 $edpost = false;
180
181                 if (local_user()) {
182                         if (Strings::compareLink($a->contact['url'], $item['author-link'])) {
183                                 if ($item["event-id"] != 0) {
184                                         $edpost = ["events/event/" . $item['event-id'], DI::l10n()->t("Edit")];
185                                 } else {
186                                         $edpost = ["editpost/" . $item['id'], DI::l10n()->t("Edit")];
187                                 }
188                         }
189                         $dropping = in_array($item['uid'], [0, local_user()]);
190                 }
191
192                 // Editing on items of not subscribed users isn't currently possible
193                 // There are some issues on editing that prevent this.
194                 // But also it is an issue of the supported protocols that doesn't allow editing at all.
195                 if ($item['uid'] == 0) {
196                         $edpost = false;
197                 }
198
199                 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
200                         $dropping = true;
201                 }
202
203                 $origin = $item['origin'];
204
205                 if (!$origin) {
206                         /// @todo This shouldn't be done as query here, but better during the data creation.
207                         // it is now done here, since during the RC phase we shouldn't make to intense changes.
208                         $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
209                         if (DBA::isResult($parent)) {
210                                 $origin = $parent['origin'];
211                         }
212                 } elseif ($item['pinned']) {
213                         $pinned = DI::l10n()->t('pinned item');
214                 }
215
216                 if ($origin && ($item['gravity'] != GRAVITY_PARENT) && ($item['network'] == Protocol::ACTIVITYPUB)) {
217                         // ActivityPub doesn't allow removal of remote comments
218                         $delete = DI::l10n()->t('Delete locally');
219                 } else {
220                         // Showing the one or the other text, depending upon if we can only hide it or really delete it.
221                         $delete = $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally');
222                 }
223
224                 $drop = [
225                         'dropping' => $dropping,
226                         'pagedrop' => $item['pagedrop'],
227                         'select'   => DI::l10n()->t('Select'),
228                         'delete'   => $delete,
229                 ];
230
231                 if (!local_user()) {
232                         $drop = false;
233                 }
234
235                 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? DI::l10n()->t("save to folder") : false);
236
237                 $profile_name = $item['author-name'];
238                 if (!empty($item['author-link']) && empty($item['author-name'])) {
239                         $profile_name = $item['author-link'];
240                 }
241
242                 $author = ['uid' => 0, 'id' => $item['author-id'],
243                         'network' => $item['author-network'], 'url' => $item['author-link']];
244
245                 if (Session::isAuthenticated()) {
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 = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
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'] . '-self'] ?? 0,
278                                 'output' => !empty($conv_responses[$verb][$item['uri']]) ? format_like($conv_responses[$verb][$item['uri']], $conv_responses[$verb][$item['uri'] . '-l'], $verb, $item['uri']) : '',
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                                 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
298                                 if (DBA::isResult($thread)) {
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'   => $thread['ignored'] ? "hidden" : "",
304                                                 'classundo' => $thread['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('Share this'), DI::l10n()->t('share')];
349                         }
350                 }
351
352                 $comment = $this->getCommentBox($indent);
353
354                 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
355                         $shiny = 'shiny';
356                 }
357
358                 localize_item($item);
359
360                 $body = Item::prepareBody($item, true);
361
362                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
363
364                 $body_e       = $body;
365                 $text_e       = strip_tags($body);
366                 $name_e       = $profile_name;
367
368                 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
369                         $title_e = ucfirst($item['content-warning']);
370                 } else {
371                         $title_e = $item['title'];
372                 }
373
374                 $location_e   = $location;
375                 $owner_name_e = $this->getOwnerName();
376
377                 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
378                         $buttons['dislike'] = false;
379                 }
380
381                 // Disable features that aren't available in several networks
382                 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
383                         if ($buttons["dislike"]) {
384                                 $buttons["dislike"] = false;
385                         }
386
387                         $isevent = false;
388                         $tagger = '';
389                 }
390
391                 if ($buttons["like"] && in_array($item["network"], [Protocol::FEED, Protocol::MAIL])) {
392                         $buttons["like"] = false;
393                 }
394
395                 $tags = Tag::populateFromItem($item);
396
397                 $ago = Temporal::getRelativeDate($item['created']);
398                 $ago_received = Temporal::getRelativeDate($item['received']);
399                 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
400                         $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
401                 }
402
403                 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
404                 if (($item['network'] != Protocol::DIASPORA) && empty($comment) && !empty(Session::get('remote_comment'))) {
405                         $remote_comment = [DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('remote comment'),
406                                 str_replace('{uri}', urlencode($item['uri']), Session::get('remote_comment'))];
407                 } else {
408                         $remote_comment = '';
409                 }
410
411                 $direction = [];
412                 if (!empty($item['direction'])) {
413                         $direction = $item['direction'];
414                 } elseif (DI::config()->get('debug', 'show_direction')) {
415                         $conversation = DBA::selectFirst('conversation', ['direction'], ['item-uri' => $item['uri']]);
416                         if (!empty($conversation['direction']) && in_array($conversation['direction'], [1, 2])) {
417                                 $title = [1 => DI::l10n()->t('Pushed'), 2 => DI::l10n()->t('Pulled')];
418                                 $direction = ['direction' => $conversation['direction'], 'title' => $title[$conversation['direction']]];
419                         }
420                 }
421
422                 $tmp_item = [
423                         'template'        => $this->getTemplate(),
424                         'type'            => implode("", array_slice(explode("/", $item['verb']), -1)),
425                         'suppress_tags'   => DI::config()->get('system', 'suppress_tags'),
426                         'tags'            => $tags['tags'],
427                         'hashtags'        => $tags['hashtags'],
428                         'mentions'        => $tags['mentions'],
429                         'implicit_mentions' => $tags['implicit_mentions'],
430                         'txt_cats'        => DI::l10n()->t('Categories:'),
431                         'txt_folders'     => DI::l10n()->t('Filed under:'),
432                         'has_cats'        => ((count($categories)) ? 'true' : ''),
433                         'has_folders'     => ((count($folders)) ? 'true' : ''),
434                         'categories'      => $categories,
435                         'folders'         => $folders,
436                         'body'            => $body_e,
437                         'text'            => $text_e,
438                         'id'              => $this->getId(),
439                         'guid'            => urlencode($item['guid']),
440                         'isevent'         => $isevent,
441                         'attend'          => $attend,
442                         'linktitle'       => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
443                         'olinktitle'      => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
444                         'to'              => DI::l10n()->t('to'),
445                         'via'             => DI::l10n()->t('via'),
446                         'wall'            => DI::l10n()->t('Wall-to-Wall'),
447                         'vwall'           => DI::l10n()->t('via Wall-To-Wall:'),
448                         'profile_url'     => $profile_link,
449                         'item_photo_menu' => item_photo_menu($item),
450                         'name'            => $name_e,
451                         'thumb'           => DI::baseUrl()->remove($item['author-avatar']),
452                         'osparkle'        => $osparkle,
453                         'sparkle'         => $sparkle,
454                         'title'           => $title_e,
455                         'localtime'       => DateTimeFormat::local($item['created'], 'r'),
456                         'ago'             => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
457                         'app'             => $item['app'],
458                         'created'         => $ago,
459                         'lock'            => $lock,
460                         'location'        => $location_e,
461                         'indent'          => $indent,
462                         'shiny'           => $shiny,
463                         'owner_self'      => $item['author-link'] == Session::get('my_url'),
464                         'owner_url'       => $this->getOwnerUrl(),
465                         'owner_photo'     => DI::baseUrl()->remove($item['owner-avatar']),
466                         'owner_name'      => $owner_name_e,
467                         'plink'           => Item::getPlink($item),
468                         'edpost'          => $edpost,
469                         'ispinned'        => $ispinned,
470                         'pin'             => $pin,
471                         'pinned'          => $pinned,
472                         'isstarred'       => $isstarred,
473                         'star'            => $star,
474                         'ignore'          => $ignore,
475                         'tagger'          => $tagger,
476                         'filer'           => $filer,
477                         'drop'            => $drop,
478                         'vote'            => $buttons,
479                         'like'            => $responses['like']['output'],
480                         'dislike'         => $responses['dislike']['output'],
481                         'responses'       => $responses,
482                         'switchcomment'   => DI::l10n()->t('Comment'),
483                         'reply_label'     => DI::l10n()->t('Reply to %s', $name_e),
484                         'comment'         => $comment,
485                         'remote_comment'  => $remote_comment,
486                         'menu'            => DI::l10n()->t('More'),
487                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
488                         'wait'            => DI::l10n()->t('Please wait'),
489                         'thread_level'    => $thread_level,
490                         'edited'          => $edited,
491                         'network'         => $item["network"],
492                         'network_name'    => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
493                         'network_icon'    => ContactSelector::networkToIcon($item['network'], $item['author-link']),
494                         'received'        => $item['received'],
495                         'commented'       => $item['commented'],
496                         'created_date'    => $item['created'],
497                         'uriid'           => $item['uri-id'],
498                         'return'          => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
499                         'direction'       => $direction,
500                         'delivery'        => [
501                                 'queue_count'       => $item['delivery_queue_count'],
502                                 'queue_done'        => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
503                                 'notifier_pending'  => DI::l10n()->t('Notifier task is pending'),
504                                 'delivery_pending'  => DI::l10n()->t('Delivery to remote servers is pending'),
505                                 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
506                                 'delivery_almost'   => DI::l10n()->t('Delivery to remote servers is mostly done'),
507                                 'delivery_done'     => DI::l10n()->t('Delivery to remote servers is done'),
508                         ],
509                 ];
510
511                 $arr = ['item' => $item, 'output' => $tmp_item];
512                 Hook::callAll('display_item', $arr);
513
514                 $result = $arr['output'];
515
516                 $result['children'] = [];
517                 $children = $this->getChildren();
518                 $nb_children = count($children);
519                 if ($nb_children > 0) {
520                         foreach ($children as $child) {
521                                 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
522                         }
523
524                         // Collapse
525                         if (($nb_children > 2) || ($thread_level > 1)) {
526                                 $result['children'][0]['comment_firstcollapsed'] = true;
527                                 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
528                                 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
529                                 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
530                                 if ($thread_level > 1) {
531                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
532                                 } else {
533                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
534                                 }
535                         }
536                 }
537
538                 if ($this->isToplevel()) {
539                         $result['total_comments_num'] = "$total_children";
540                         $result['total_comments_text'] = DI::l10n()->tt('comment', 'comments', $total_children);
541                 }
542
543                 $result['private'] = $item['private'];
544                 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
545
546                 if ($this->isThreaded()) {
547                         $result['flatten'] = false;
548                         $result['threaded'] = true;
549                 } else {
550                         $result['flatten'] = true;
551                         $result['threaded'] = false;
552                 }
553
554                 return $result;
555         }
556
557         /**
558          * @return integer
559          */
560         public function getId()
561         {
562                 return $this->getDataValue('id');
563         }
564
565         /**
566          * @return boolean
567          */
568         public function isThreaded()
569         {
570                 return $this->threaded;
571         }
572
573         /**
574          * Add a child item
575          *
576          * @param Post $item The child item to add
577          *
578          * @return mixed
579          * @throws \Exception
580          */
581         public function addChild(Post $item)
582         {
583                 $item_id = $item->getId();
584                 if (!$item_id) {
585                         Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
586                         return false;
587                 } elseif ($this->getChild($item->getId())) {
588                         Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
589                         return false;
590                 }
591
592                 $activity = DI::activity();
593
594                 /*
595                  * Only add what will be displayed
596                  */
597                 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
598                         return false;
599                 } elseif ($activity->match($item->getDataValue('verb'), Activity::LIKE) ||
600                           $activity->match($item->getDataValue('verb'), Activity::DISLIKE)) {
601                         return false;
602                 }
603
604                 $item->setParent($this);
605                 $this->children[] = $item;
606
607                 return end($this->children);
608         }
609
610         /**
611          * Get a child by its ID
612          *
613          * @param integer $id The child id
614          *
615          * @return mixed
616          */
617         public function getChild($id)
618         {
619                 foreach ($this->getChildren() as $child) {
620                         if ($child->getId() == $id) {
621                                 return $child;
622                         }
623                 }
624
625                 return null;
626         }
627
628         /**
629          * Get all our children
630          *
631          * @return Post[]
632          */
633         public function getChildren()
634         {
635                 return $this->children;
636         }
637
638         /**
639          * Set our parent
640          *
641          * @param Post $item The item to set as parent
642          *
643          * @return void
644          */
645         protected function setParent(Post $item)
646         {
647                 $parent = $this->getParent();
648                 if ($parent) {
649                         $parent->removeChild($this);
650                 }
651
652                 $this->parent = $item;
653                 $this->setThread($item->getThread());
654         }
655
656         /**
657          * Remove our parent
658          *
659          * @return void
660          */
661         protected function removeParent()
662         {
663                 $this->parent = null;
664                 $this->thread = null;
665         }
666
667         /**
668          * Remove a child
669          *
670          * @param Post $item The child to be removed
671          *
672          * @return boolean Success or failure
673          * @throws \Exception
674          */
675         public function removeChild(Post $item)
676         {
677                 $id = $item->getId();
678                 foreach ($this->getChildren() as $key => $child) {
679                         if ($child->getId() == $id) {
680                                 $child->removeParent();
681                                 unset($this->children[$key]);
682                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
683                                 $this->children = array_values($this->children);
684                                 return true;
685                         }
686                 }
687                 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
688                 return false;
689         }
690
691         /**
692          * Get parent item
693          *
694          * @return object
695          */
696         protected function getParent()
697         {
698                 return $this->parent;
699         }
700
701         /**
702          * Set conversation thread
703          *
704          * @param Thread $thread
705          *
706          * @return void
707          */
708         public function setThread(Thread $thread = null)
709         {
710                 $this->thread = $thread;
711
712                 // Set it on our children too
713                 foreach ($this->getChildren() as $child) {
714                         $child->setThread($thread);
715                 }
716         }
717
718         /**
719          * Get conversation
720          *
721          * @return Thread
722          */
723         public function getThread()
724         {
725                 return $this->thread;
726         }
727
728         /**
729          * Get raw data
730          *
731          * We shouldn't need this
732          *
733          * @return array
734          */
735         public function getData()
736         {
737                 return $this->data;
738         }
739
740         /**
741          * Get a data value
742          *
743          * @param string $name key
744          *
745          * @return mixed value on success
746          *               false on failure
747          */
748         public function getDataValue($name)
749         {
750                 if (!isset($this->data[$name])) {
751                         // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
752                         return false;
753                 }
754
755                 return $this->data[$name];
756         }
757
758         /**
759          * Set template
760          *
761          * @param string $name template name
762          * @return bool
763          * @throws \Exception
764          */
765         private function setTemplate($name)
766         {
767                 if (empty($this->available_templates[$name])) {
768                         Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
769                         return false;
770                 }
771
772                 $this->template = $this->available_templates[$name];
773
774                 return true;
775         }
776
777         /**
778          * Get template
779          *
780          * @return object
781          */
782         private function getTemplate()
783         {
784                 return $this->template;
785         }
786
787         /**
788          * Check if this is a toplevel post
789          *
790          * @return boolean
791          */
792         private function isToplevel()
793         {
794                 return $this->toplevel;
795         }
796
797         /**
798          * Check if this is writable
799          *
800          * @return boolean
801          */
802         private function isWritable()
803         {
804                 $conv = $this->getThread();
805
806                 if ($conv) {
807                         // This will allow us to comment on wall-to-wall items owned by our friends
808                         // and community forums even if somebody else wrote the post.
809                         // bug #517 - this fixes for conversation owner
810                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
811                                 return true;
812                         }
813
814                         // this fixes for visitors
815                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
816                 }
817                 return $this->writable;
818         }
819
820         /**
821          * Count the total of our descendants
822          *
823          * @return integer
824          */
825         private function countDescendants()
826         {
827                 $children = $this->getChildren();
828                 $total = count($children);
829                 if ($total > 0) {
830                         foreach ($children as $child) {
831                                 $total += $child->countDescendants();
832                         }
833                 }
834
835                 return $total;
836         }
837
838         /**
839          * Get the template for the comment box
840          *
841          * @return string
842          */
843         private function getCommentBoxTemplate()
844         {
845                 return $this->comment_box_template;
846         }
847
848         /**
849          * Get default text for the comment box
850          *
851          * @return string
852          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
853          */
854         private function getDefaultText()
855         {
856                 $a = DI::app();
857
858                 if (!local_user()) {
859                         return '';
860                 }
861
862                 $owner = User::getOwnerDataById($a->user['uid']);
863
864                 if (!Feature::isEnabled(local_user(), 'explicit_mentions')) {
865                         return '';
866                 }
867
868                 $item = Item::selectFirst(['author-addr', 'uri-id'], ['id' => $this->getId()]);
869                 if (!DBA::isResult($item) || empty($item['author-addr'])) {
870                         // Should not happen
871                         return '';
872                 }
873
874                 if ($item['author-addr'] != $owner['addr']) {
875                         $text = '@' . $item['author-addr'] . ' ';
876                 } else {
877                         $text = '';
878                 }
879
880                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
881                 foreach ($terms as $term) {
882                         $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
883                         if (!empty($profile['addr']) && ((($profile['contact-type'] ?? '') ?: Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
884                                 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])) {
885                                 $text .= '@' . $profile['addr'] . ' ';
886                         }
887                 }
888
889                 return $text;
890         }
891
892         /**
893          * Get the comment box
894          *
895          * @param string $indent Indent value
896          *
897          * @return mixed The comment box string (empty if no comment box)
898          *               false on failure
899          * @throws \Exception
900          */
901         private function getCommentBox($indent)
902         {
903                 $a = DI::app();
904
905                 $comment_box = '';
906                 $conv = $this->getThread();
907                 $ww = '';
908                 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
909                         $ww = 'ww';
910                 }
911
912                 if ($conv->isWritable() && $this->isWritable()) {
913                         $qcomment = null;
914
915                         /*
916                          * Hmmm, code depending on the presence of a particular addon?
917                          * This should be better if done by a hook
918                          */
919                         if (Addon::isEnabled('qcomment')) {
920                                 $qc = ((local_user()) ? DI::pConfig()->get(local_user(), 'qcomment', 'words') : null);
921                                 $qcomment = (($qc) ? explode("\n", $qc) : null);
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                                 '$ww'          => $conv->getMode() === 'network' ? $ww : '',
964                                 '$rand_num'    => Crypto::randomDigits(12)
965                         ]);
966                 }
967
968                 return $comment_box;
969         }
970
971         /**
972          * @return string
973          */
974         private function getRedirectUrl()
975         {
976                 return $this->redirect_url;
977         }
978
979         /**
980          * Check if we are a wall to wall item and set the relevant properties
981          *
982          * @return void
983          * @throws \Exception
984          */
985         protected function checkWallToWall()
986         {
987                 $a = DI::app();
988                 $conv = $this->getThread();
989                 $this->wall_to_wall = false;
990
991                 if ($this->isToplevel()) {
992                         if ($conv->getMode() !== 'profile') {
993                                 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
994                                         // On the network page, I am the owner. On the display page it will be the profile owner.
995                                         // This will have been stored in $a->page_contact by our calling page.
996                                         // Put this person as the wall owner of the wall-to-wall notice.
997
998                                         $this->owner_url = Contact::magicLink($a->page_contact['url']);
999                                         $this->owner_photo = $a->page_contact['thumb'];
1000                                         $this->owner_name = $a->page_contact['name'];
1001                                         $this->wall_to_wall = true;
1002                                 } elseif ($this->getDataValue('owner-link')) {
1003                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1004                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1005                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1006
1007                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1008                                                 // The author url doesn't match the owner (typically the contact)
1009                                                 // and also doesn't match the contact alias.
1010                                                 // The name match is a hack to catch several weird cases where URLs are
1011                                                 // all over the park. It can be tricked, but this prevents you from
1012                                                 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1013                                                 // well that it's the same Bob Smith.
1014                                                 // But it could be somebody else with the same name. It just isn't highly likely.
1015
1016
1017                                                 $this->owner_photo = $this->getDataValue('owner-avatar');
1018                                                 $this->owner_name = $this->getDataValue('owner-name');
1019                                                 $this->wall_to_wall = true;
1020
1021                                                 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
1022                                                         'network' => $this->getDataValue('owner-network'),
1023                                                         'url' => $this->getDataValue('owner-link')];
1024                                                 $this->owner_url = Contact::magicLinkByContact($owner);
1025                                         }
1026                                 }
1027                         }
1028                 }
1029
1030                 if (!$this->wall_to_wall) {
1031                         $this->setTemplate('wall');
1032                         $this->owner_url = '';
1033                         $this->owner_photo = '';
1034                         $this->owner_name = '';
1035                 }
1036         }
1037
1038         /**
1039          * @return boolean
1040          */
1041         private function isWallToWall()
1042         {
1043                 return $this->wall_to_wall;
1044         }
1045
1046         /**
1047          * @return string
1048          */
1049         private function getOwnerUrl()
1050         {
1051                 return $this->owner_url;
1052         }
1053
1054         /**
1055          * @return string
1056          */
1057         private function getOwnerName()
1058         {
1059                 return $this->owner_name;
1060         }
1061
1062         /**
1063          * @return boolean
1064          */
1065         private function isVisiting()
1066         {
1067                 return $this->visiting;
1068         }
1069 }