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