]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
Issue 8605: "show less" now displays "show less"
[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                         'announce' => null,
158                 ];
159                 $dropping = false;
160                 $pinned = '';
161                 $pin = false;
162                 $star = false;
163                 $ignore = false;
164                 $ispinned = "unpinned";
165                 $isstarred = "unstarred";
166                 $indent = '';
167                 $shiny = '';
168                 $osparkle = '';
169                 $total_children = $this->countDescendants();
170
171                 $conv = $this->getThread();
172
173                 $lock = ((($item['private'] == Item::PRIVATE) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
174                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
175                         ? DI::l10n()->t('Private Message')
176                         : false);
177
178                 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != Item::PRIVATE;
179                 $announceable = $shareable && in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::TWITTER]);
180
181                 // On Diaspora only toplevel posts can be reshared
182                 if ($announceable && ($item['network'] == Protocol::DIASPORA) && ($item['gravity'] != GRAVITY_PARENT)) {
183                         $announceable = false;
184                 }
185
186                 $edpost = false;
187
188                 if (local_user()) {
189                         if (Strings::compareLink($a->contact['url'], $item['author-link'])) {
190                                 if ($item["event-id"] != 0) {
191                                         $edpost = ["events/event/" . $item['event-id'], DI::l10n()->t("Edit")];
192                                 } else {
193                                         $edpost = ["editpost/" . $item['id'], DI::l10n()->t("Edit")];
194                                 }
195                         }
196                         $dropping = in_array($item['uid'], [0, local_user()]);
197                 }
198
199                 // Editing on items of not subscribed users isn't currently possible
200                 // There are some issues on editing that prevent this.
201                 // But also it is an issue of the supported protocols that doesn't allow editing at all.
202                 if ($item['uid'] == 0) {
203                         $edpost = false;
204                 }
205
206                 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
207                         $dropping = true;
208                 }
209
210                 $origin = $item['origin'];
211
212                 if (!$origin) {
213                         /// @todo This shouldn't be done as query here, but better during the data creation.
214                         // it is now done here, since during the RC phase we shouldn't make to intense changes.
215                         $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
216                         if (DBA::isResult($parent)) {
217                                 $origin = $parent['origin'];
218                         }
219                 } elseif ($item['pinned']) {
220                         $pinned = DI::l10n()->t('pinned item');
221                 }
222
223                 if ($origin && ($item['gravity'] != GRAVITY_PARENT) && ($item['network'] == Protocol::ACTIVITYPUB)) {
224                         // ActivityPub doesn't allow removal of remote comments
225                         $delete = DI::l10n()->t('Delete locally');
226                 } else {
227                         // Showing the one or the other text, depending upon if we can only hide it or really delete it.
228                         $delete = $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally');
229                 }
230
231                 $drop = false;
232                 if (local_user()) {
233                         $drop = [
234                                 'dropping' => $dropping,
235                                 'pagedrop' => $item['pagedrop'],
236                                 'select'   => DI::l10n()->t('Select'),
237                                 'delete'   => $delete,
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                 $author = ['uid' => 0, 'id' => $item['author-id'],
249                         'network' => $item['author-network'], 'url' => $item['author-link']];
250
251                 if (Session::isAuthenticated()) {
252                         $profile_link = Contact::magicLinkByContact($author);
253                 } else {
254                         $profile_link = $item['author-link'];
255                 }
256
257                 if (strpos($profile_link, 'redir/') === 0) {
258                         $sparkle = ' sparkle';
259                 }
260
261                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
262                 Hook::callAll('render_location', $locate);
263                 $location_html = $locate['html'] ?: Strings::escapeHtml($locate['location'] ?: $locate['coord'] ?: '');
264
265                 // process action responses - e.g. like/dislike/attend/agree/whatever
266                 $response_verbs = ['like', 'dislike', 'announce'];
267
268                 $isevent = false;
269                 $attend = [];
270                 if ($item['object-type'] === Activity\ObjectType::EVENT) {
271                         $response_verbs[] = 'attendyes';
272                         $response_verbs[] = 'attendno';
273                         $response_verbs[] = 'attendmaybe';
274                         if ($conv->isWritable()) {
275                                 $isevent = true;
276                                 $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')];
277                         }
278                 }
279
280                 $responses = [];
281                 foreach ($response_verbs as $value => $verb) {
282                         $responses[$verb] = [
283                                 'self'   => $conv_responses[$verb][$item['uri']]['self'] ?? 0,
284                                 'output' => !empty($conv_responses[$verb][$item['uri']]) ? format_activity($conv_responses[$verb][$item['uri']]['links'], $verb, $item['uri']) : '',
285                         ];
286                 }
287
288                 /*
289                  * We should avoid doing this all the time, but it depends on the conversation mode
290                  * And the conv mode may change when we change the conv, or it changes its mode
291                  * Maybe we should establish a way to be notified about conversation changes
292                  */
293                 $this->checkWallToWall();
294
295                 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
296                         $osparkle = ' sparkle';
297                 }
298
299                 $tagger = '';
300
301                 if ($this->isToplevel()) {
302                         if(local_user()) {
303                                 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
304                                 if (DBA::isResult($thread)) {
305                                         $ignore = [
306                                                 'do'        => DI::l10n()->t("ignore thread"),
307                                                 'undo'      => DI::l10n()->t("unignore thread"),
308                                                 'toggle'    => DI::l10n()->t("toggle ignore status"),
309                                                 'classdo'   => $thread['ignored'] ? "hidden" : "",
310                                                 'classundo' => $thread['ignored'] ? "" : "hidden",
311                                                 'ignored'   => DI::l10n()->t('ignored'),
312                                         ];
313                                 }
314
315                                 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
316                                         if ($origin) {
317                                                 $ispinned = ($item['pinned'] ? 'pinned' : 'unpinned');
318
319                                                 $pin = [
320                                                         'do'        => DI::l10n()->t('pin'),
321                                                         'undo'      => DI::l10n()->t('unpin'),
322                                                         'toggle'    => DI::l10n()->t('toggle pin status'),
323                                                         'classdo'   => $item['pinned'] ? 'hidden' : '',
324                                                         'classundo' => $item['pinned'] ? '' : 'hidden',
325                                                         'pinned'   => DI::l10n()->t('pinned'),
326                                                 ];
327                                         }
328
329                                         $isstarred = (($item['starred']) ? "starred" : "unstarred");
330
331                                         $star = [
332                                                 'do'        => DI::l10n()->t("add star"),
333                                                 'undo'      => DI::l10n()->t("remove star"),
334                                                 'toggle'    => DI::l10n()->t("toggle star status"),
335                                                 'classdo'   => $item['starred'] ? "hidden" : "",
336                                                 'classundo' => $item['starred'] ? "" : "hidden",
337                                                 'starred'   => DI::l10n()->t('starred'),
338                                         ];
339
340                                         $tagger = [
341                                                 'add'   => DI::l10n()->t("add tag"),
342                                                 'class' => "",
343                                         ];
344                                 }
345                         }
346                 } else {
347                         $indent = 'comment';
348                 }
349
350                 if ($conv->isWritable()) {
351                         $buttons['like']    = [DI::l10n()->t("I like this \x28toggle\x29")      , DI::l10n()->t("like")];
352                         $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t("dislike")];
353                         if ($shareable) {
354                                 $buttons['share'] = [DI::l10n()->t('Quote and share this'), DI::l10n()->t('Quote Share')];
355                         }
356                         if ($announceable) {
357                                 $buttons['announce'] = [DI::l10n()->t('Share this'), DI::l10n()->t('Share')];
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                         'vote'            => $buttons,
487                         'like_html'       => $responses['like']['output'],
488                         'dislike_html'    => $responses['dislike']['output'],
489                         'responses'       => $responses,
490                         'switchcomment'   => DI::l10n()->t('Comment'),
491                         'reply_label'     => DI::l10n()->t('Reply to %s', $profile_name),
492                         'comment_html'    => $comment_html,
493                         'remote_comment'  => $remote_comment,
494                         'menu'            => DI::l10n()->t('More'),
495                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
496                         'wait'            => DI::l10n()->t('Please wait'),
497                         'thread_level'    => $thread_level,
498                         'edited'          => $edited,
499                         'network'         => $item["network"],
500                         'network_name'    => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
501                         'network_icon'    => ContactSelector::networkToIcon($item['network'], $item['author-link']),
502                         'received'        => $item['received'],
503                         'commented'       => $item['commented'],
504                         'created_date'    => $item['created'],
505                         'uriid'           => $item['uri-id'],
506                         'return'          => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
507                         'direction'       => $direction,
508                         'reshared'        => $item['reshared'] ?? '',
509                         'delivery'        => [
510                                 'queue_count'       => $item['delivery_queue_count'],
511                                 'queue_done'        => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
512                                 'notifier_pending'  => DI::l10n()->t('Notifier task is pending'),
513                                 'delivery_pending'  => DI::l10n()->t('Delivery to remote servers is pending'),
514                                 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
515                                 'delivery_almost'   => DI::l10n()->t('Delivery to remote servers is mostly done'),
516                                 'delivery_done'     => DI::l10n()->t('Delivery to remote servers is done'),
517                         ],
518                 ];
519
520                 $arr = ['item' => $item, 'output' => $tmp_item];
521                 Hook::callAll('display_item', $arr);
522
523                 $result = $arr['output'];
524
525                 $result['children'] = [];
526                 $children = $this->getChildren();
527                 $nb_children = count($children);
528                 if ($nb_children > 0) {
529                         foreach ($children as $child) {
530                                 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
531                         }
532
533                         // Collapse
534                         if (($nb_children > 2) || ($thread_level > 1)) {
535                                 $result['children'][0]['comment_firstcollapsed'] = true;
536                                 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
537                                 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
538                                 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
539                                 if ($thread_level > 1) {
540                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
541                                 } else {
542                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
543                                 }
544                         }
545                 }
546
547                 if ($this->isToplevel()) {
548                         $result['total_comments_num'] = "$total_children";
549                         $result['total_comments_text'] = DI::l10n()->tt('comment', 'comments', $total_children);
550                 }
551
552                 $result['private'] = $item['private'];
553                 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
554
555                 if ($this->isThreaded()) {
556                         $result['flatten'] = false;
557                         $result['threaded'] = true;
558                 } else {
559                         $result['flatten'] = true;
560                         $result['threaded'] = false;
561                 }
562
563                 return $result;
564         }
565
566         /**
567          * @return integer
568          */
569         public function getId()
570         {
571                 return $this->getDataValue('id');
572         }
573
574         /**
575          * @return boolean
576          */
577         public function isThreaded()
578         {
579                 return $this->threaded;
580         }
581
582         /**
583          * Add a child item
584          *
585          * @param Post $item The child item to add
586          *
587          * @return mixed
588          * @throws \Exception
589          */
590         public function addChild(Post $item)
591         {
592                 $item_id = $item->getId();
593                 if (!$item_id) {
594                         Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
595                         return false;
596                 } elseif ($this->getChild($item->getId())) {
597                         Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
598                         return false;
599                 }
600
601                 $activity = DI::activity();
602
603                 /*
604                  * Only add what will be displayed
605                  */
606                 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
607                         return false;
608                 } elseif ($activity->match($item->getDataValue('verb'), Activity::LIKE) ||
609                           $activity->match($item->getDataValue('verb'), Activity::DISLIKE)) {
610                         return false;
611                 }
612
613                 $item->setParent($this);
614                 $this->children[] = $item;
615
616                 return end($this->children);
617         }
618
619         /**
620          * Get a child by its ID
621          *
622          * @param integer $id The child id
623          *
624          * @return mixed
625          */
626         public function getChild($id)
627         {
628                 foreach ($this->getChildren() as $child) {
629                         if ($child->getId() == $id) {
630                                 return $child;
631                         }
632                 }
633
634                 return null;
635         }
636
637         /**
638          * Get all our children
639          *
640          * @return Post[]
641          */
642         public function getChildren()
643         {
644                 return $this->children;
645         }
646
647         /**
648          * Set our parent
649          *
650          * @param Post $item The item to set as parent
651          *
652          * @return void
653          */
654         protected function setParent(Post $item)
655         {
656                 $parent = $this->getParent();
657                 if ($parent) {
658                         $parent->removeChild($this);
659                 }
660
661                 $this->parent = $item;
662                 $this->setThread($item->getThread());
663         }
664
665         /**
666          * Remove our parent
667          *
668          * @return void
669          */
670         protected function removeParent()
671         {
672                 $this->parent = null;
673                 $this->thread = null;
674         }
675
676         /**
677          * Remove a child
678          *
679          * @param Post $item The child to be removed
680          *
681          * @return boolean Success or failure
682          * @throws \Exception
683          */
684         public function removeChild(Post $item)
685         {
686                 $id = $item->getId();
687                 foreach ($this->getChildren() as $key => $child) {
688                         if ($child->getId() == $id) {
689                                 $child->removeParent();
690                                 unset($this->children[$key]);
691                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
692                                 $this->children = array_values($this->children);
693                                 return true;
694                         }
695                 }
696                 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
697                 return false;
698         }
699
700         /**
701          * Get parent item
702          *
703          * @return object
704          */
705         protected function getParent()
706         {
707                 return $this->parent;
708         }
709
710         /**
711          * Set conversation thread
712          *
713          * @param Thread $thread
714          *
715          * @return void
716          */
717         public function setThread(Thread $thread = null)
718         {
719                 $this->thread = $thread;
720
721                 // Set it on our children too
722                 foreach ($this->getChildren() as $child) {
723                         $child->setThread($thread);
724                 }
725         }
726
727         /**
728          * Get conversation
729          *
730          * @return Thread
731          */
732         public function getThread()
733         {
734                 return $this->thread;
735         }
736
737         /**
738          * Get raw data
739          *
740          * We shouldn't need this
741          *
742          * @return array
743          */
744         public function getData()
745         {
746                 return $this->data;
747         }
748
749         /**
750          * Get a data value
751          *
752          * @param string $name key
753          *
754          * @return mixed value on success
755          *               false on failure
756          */
757         public function getDataValue($name)
758         {
759                 if (!isset($this->data[$name])) {
760                         // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
761                         return false;
762                 }
763
764                 return $this->data[$name];
765         }
766
767         /**
768          * Set template
769          *
770          * @param string $name template name
771          * @return bool
772          * @throws \Exception
773          */
774         private function setTemplate($name)
775         {
776                 if (empty($this->available_templates[$name])) {
777                         Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
778                         return false;
779                 }
780
781                 $this->template = $this->available_templates[$name];
782
783                 return true;
784         }
785
786         /**
787          * Get template
788          *
789          * @return object
790          */
791         private function getTemplate()
792         {
793                 return $this->template;
794         }
795
796         /**
797          * Check if this is a toplevel post
798          *
799          * @return boolean
800          */
801         private function isToplevel()
802         {
803                 return $this->toplevel;
804         }
805
806         /**
807          * Check if this is writable
808          *
809          * @return boolean
810          */
811         private function isWritable()
812         {
813                 $conv = $this->getThread();
814
815                 if ($conv) {
816                         // This will allow us to comment on wall-to-wall items owned by our friends
817                         // and community forums even if somebody else wrote the post.
818                         // bug #517 - this fixes for conversation owner
819                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
820                                 return true;
821                         }
822
823                         // this fixes for visitors
824                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
825                 }
826                 return $this->writable;
827         }
828
829         /**
830          * Count the total of our descendants
831          *
832          * @return integer
833          */
834         private function countDescendants()
835         {
836                 $children = $this->getChildren();
837                 $total = count($children);
838                 if ($total > 0) {
839                         foreach ($children as $child) {
840                                 $total += $child->countDescendants();
841                         }
842                 }
843
844                 return $total;
845         }
846
847         /**
848          * Get the template for the comment box
849          *
850          * @return string
851          */
852         private function getCommentBoxTemplate()
853         {
854                 return $this->comment_box_template;
855         }
856
857         /**
858          * Get default text for the comment box
859          *
860          * @return string
861          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
862          */
863         private function getDefaultText()
864         {
865                 $a = DI::app();
866
867                 if (!local_user()) {
868                         return '';
869                 }
870
871                 $owner = User::getOwnerDataById($a->user['uid']);
872
873                 if (!Feature::isEnabled(local_user(), 'explicit_mentions')) {
874                         return '';
875                 }
876
877                 $item = Item::selectFirst(['author-addr', 'uri-id'], ['id' => $this->getId()]);
878                 if (!DBA::isResult($item) || empty($item['author-addr'])) {
879                         // Should not happen
880                         return '';
881                 }
882
883                 if ($item['author-addr'] != $owner['addr']) {
884                         $text = '@' . $item['author-addr'] . ' ';
885                 } else {
886                         $text = '';
887                 }
888
889                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
890                 foreach ($terms as $term) {
891                         $profile = Contact::getByURL($term['url'], false, ['addr', 'contact-type']);
892                         if (!empty($profile['addr']) && ((($profile['contact-type'] ?? '') ?: Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
893                                 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])) {
894                                 $text .= '@' . $profile['addr'] . ' ';
895                         }
896                 }
897
898                 return $text;
899         }
900
901         /**
902          * Get the comment box
903          *
904          * @param string $indent Indent value
905          *
906          * @return mixed The comment box string (empty if no comment box)
907          *               false on failure
908          * @throws \Exception
909          */
910         private function getCommentBox($indent)
911         {
912                 $a = DI::app();
913
914                 $comment_box = '';
915                 $conv = $this->getThread();
916
917                 if ($conv->isWritable() && $this->isWritable()) {
918                         /*
919                          * Hmmm, code depending on the presence of a particular addon?
920                          * This should be better if done by a hook
921                          */
922                         $qcomment = null;
923                         if (Addon::isEnabled('qcomment')) {
924                                 $words = DI::pConfig()->get(local_user(), 'qcomment', 'words');
925                                 $qcomment = $words ? explode("\n", $words) : [];
926                         }
927
928                         // Fetch the user id from the parent when the owner user is empty
929                         $uid = $conv->getProfileOwner();
930                         $parent_uid = $this->getDataValue('uid');
931
932                         $default_text = $this->getDefaultText();
933
934                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
935                                 $uid = $parent_uid;
936                         }
937
938                         $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
939                         $comment_box = Renderer::replaceMacros($template, [
940                                 '$return_path' => DI::args()->getQueryString(),
941                                 '$threaded'    => $this->isThreaded(),
942                                 '$jsreload'    => '',
943                                 '$wall'        => ($conv->getMode() === 'profile'),
944                                 '$id'          => $this->getId(),
945                                 '$parent'      => $this->getId(),
946                                 '$qcomment'    => $qcomment,
947                                 '$default'     => $default_text,
948                                 '$profile_uid' => $uid,
949                                 '$mylink'      => DI::baseUrl()->remove($a->contact['url']),
950                                 '$mytitle'     => DI::l10n()->t('This is you'),
951                                 '$myphoto'     => DI::baseUrl()->remove($a->contact['thumb']),
952                                 '$comment'     => DI::l10n()->t('Comment'),
953                                 '$submit'      => DI::l10n()->t('Submit'),
954                                 '$loading'     => DI::l10n()->t('Loading...'),
955                                 '$edbold'      => DI::l10n()->t('Bold'),
956                                 '$editalic'    => DI::l10n()->t('Italic'),
957                                 '$eduline'     => DI::l10n()->t('Underline'),
958                                 '$edquote'     => DI::l10n()->t('Quote'),
959                                 '$edcode'      => DI::l10n()->t('Code'),
960                                 '$edimg'       => DI::l10n()->t('Image'),
961                                 '$edurl'       => DI::l10n()->t('Link'),
962                                 '$edattach'    => DI::l10n()->t('Link or Media'),
963                                 '$prompttext'  => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
964                                 '$preview'     => DI::l10n()->t('Preview'),
965                                 '$indent'      => $indent,
966                                 '$sourceapp'   => DI::l10n()->t($a->sourcename),
967                                 '$rand_num'    => Crypto::randomDigits(12)
968                         ]);
969                 }
970
971                 return $comment_box;
972         }
973
974         /**
975          * @return string
976          */
977         private function getRedirectUrl()
978         {
979                 return $this->redirect_url;
980         }
981
982         /**
983          * Check if we are a wall to wall item and set the relevant properties
984          *
985          * @return void
986          * @throws \Exception
987          */
988         protected function checkWallToWall()
989         {
990                 $a = DI::app();
991                 $conv = $this->getThread();
992                 $this->wall_to_wall = false;
993
994                 if ($this->isToplevel()) {
995                         if ($conv->getMode() !== 'profile') {
996                                 if ($this->getDataValue('wall') && !$this->getDataValue('self') && !empty($a->page_contact)) {
997                                         // On the network page, I am the owner. On the display page it will be the profile owner.
998                                         // This will have been stored in $a->page_contact by our calling page.
999                                         // Put this person as the wall owner of the wall-to-wall notice.
1000
1001                                         $this->owner_url = Contact::magicLink($a->page_contact['url']);
1002                                         $this->owner_photo = $a->page_contact['thumb'];
1003                                         $this->owner_name = $a->page_contact['name'];
1004                                         $this->wall_to_wall = true;
1005                                 } elseif ($this->getDataValue('owner-link')) {
1006                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1007                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1008                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1009
1010                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1011                                                 // The author url doesn't match the owner (typically the contact)
1012                                                 // and also doesn't match the contact alias.
1013                                                 // The name match is a hack to catch several weird cases where URLs are
1014                                                 // all over the park. It can be tricked, but this prevents you from
1015                                                 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1016                                                 // well that it's the same Bob Smith.
1017                                                 // But it could be somebody else with the same name. It just isn't highly likely.
1018
1019
1020                                                 $this->owner_photo = $this->getDataValue('owner-avatar');
1021                                                 $this->owner_name = $this->getDataValue('owner-name');
1022                                                 $this->wall_to_wall = true;
1023
1024                                                 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
1025                                                         'network' => $this->getDataValue('owner-network'),
1026                                                         'url' => $this->getDataValue('owner-link')];
1027                                                 $this->owner_url = Contact::magicLinkByContact($owner);
1028                                         }
1029                                 }
1030                         }
1031                 }
1032
1033                 if (!$this->wall_to_wall) {
1034                         $this->setTemplate('wall');
1035                         $this->owner_url = '';
1036                         $this->owner_photo = '';
1037                         $this->owner_name = '';
1038                 }
1039         }
1040
1041         /**
1042          * @return boolean
1043          */
1044         private function isWallToWall()
1045         {
1046                 return $this->wall_to_wall;
1047         }
1048
1049         /**
1050          * @return string
1051          */
1052         private function getOwnerUrl()
1053         {
1054                 return $this->owner_url;
1055         }
1056
1057         /**
1058          * @return string
1059          */
1060         private function getOwnerName()
1061         {
1062                 return $this->owner_name;
1063         }
1064
1065         /**
1066          * @return boolean
1067          */
1068         private function isVisiting()
1069         {
1070                 return $this->visiting;
1071         }
1072 }