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