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