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