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