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