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