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