]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
Issue 7563: Use icons instead of names on posts
[friendica.git] / src / Object / Post.php
1 <?php
2 /**
3  * @file src/Object/Post.php
4  */
5 namespace Friendica\Object;
6
7 use Friendica\BaseObject;
8 use Friendica\Content\ContactSelector;
9 use Friendica\Content\Feature;
10 use Friendica\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\Core\Session;
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['remote']) && is_array($_SESSION['remote'])) {
75                         foreach ($_SESSION['remote'] as $visitor) {
76                                 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
77                                         $this->visiting = true;
78                                         break;
79                                 }
80                         }
81                 }
82
83                 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
84                 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
85                         'network' => $this->getDataValue('author-network'),
86                         'url' => $this->getDataValue('author-link')];
87                 $this->redirect_url = Contact::magicLinkByContact($author);
88                 if (!$this->isToplevel()) {
89                         $this->threaded = true;
90                 }
91
92                 // Prepare the children
93                 if (!empty($data['children'])) {
94                         foreach ($data['children'] as $item) {
95                                 // Only add will be displayed
96                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
97                                         continue;
98                                 } elseif (!visible_activity($item)) {
99                                         continue;
100                                 }
101
102                                 // You can always comment on Diaspora and OStatus items
103                                 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (local_user() == $item['uid'])) {
104                                         $item['writable'] = true;
105                                 }
106
107                                 $item['pagedrop'] = $data['pagedrop'];
108                                 $child = new Post($item);
109                                 $this->addChild($child);
110                         }
111                 }
112         }
113
114         /**
115          * Get data in a form usable by a conversation template
116          *
117          * @param array   $conv_responses conversation responses
118          * @param integer $thread_level   default = 1
119          *
120          * @return mixed The data requested on success
121          *               false on failure
122          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
123          * @throws \ImagickException
124          */
125         public function getTemplateData(array $conv_responses, $thread_level = 1)
126         {
127                 $a = self::getApp();
128
129                 $item = $this->getData();
130                 $edited = false;
131                 // If the time between "created" and "edited" differs we add
132                 // a notice that the post was edited.
133                 // Note: In some networks reshared items seem to have (sometimes) a difference
134                 // between creation time and edit time of a second. Thats why we add the notice
135                 // only if the difference is more than 1 second.
136                 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
137                         $edited = [
138                                 'label'    => L10n::t('This entry was edited'),
139                                 'date'     => DateTimeFormat::local($item['edited'], 'r'),
140                                 'relative' => Temporal::getRelativeDate($item['edited'])
141                         ];
142                 }
143                 $sparkle = '';
144                 $buttons = '';
145                 $dropping = false;
146                 $star = false;
147                 $ignore = false;
148                 $isstarred = "unstarred";
149                 $indent = '';
150                 $shiny = '';
151                 $osparkle = '';
152                 $total_children = $this->countDescendants();
153
154                 $conv = $this->getThread();
155
156                 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
157                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
158                         ? L10n::t('Private Message')
159                         : false);
160
161                 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
162
163                 $edpost = false;
164
165                 if (local_user()) {
166                         if (Strings::compareLink($a->contact['url'], $item['author-link'])) {
167                                 if ($item["event-id"] != 0) {
168                                         $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
169                                 } else {
170                                         $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
171                                 }
172                         }
173                         $dropping = in_array($item['uid'], [0, local_user()]);
174                 }
175
176                 // Editing on items of not subscribed users isn't currently possible
177                 // There are some issues on editing that prevent this.
178                 // But also it is an issue of the supported protocols that doesn't allow editing at all.
179                 if ($item['uid'] == 0) {
180                         $edpost = false;
181                 }
182
183                 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
184                         $dropping = true;
185                 }
186
187                 $origin = $item['origin'];
188
189                 if (!$origin) {
190                         /// @todo This shouldn't be done as query here, but better during the data creation.
191                         // it is now done here, since during the RC phase we shouldn't make to intense changes.
192                         $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
193                         if (DBA::isResult($parent)) {
194                                 $origin = $parent['origin'];
195                         }
196                 }
197
198                 if ($origin && ($item['id'] != $item['parent']) && ($item['network'] == Protocol::ACTIVITYPUB)) {
199                         // ActivityPub doesn't allow removal of remote comments
200                         $delete = L10n::t('Delete locally');
201                 } else {
202                         // Showing the one or the other text, depending upon if we can only hide it or really delete it.
203                         $delete = $origin ? L10n::t('Delete globally') : L10n::t('Remove locally');
204                 }
205
206                 $drop = [
207                         'dropping' => $dropping,
208                         'pagedrop' => $item['pagedrop'],
209                         'select'   => L10n::t('Select'),
210                         'delete'   => $delete,
211                 ];
212
213                 if (!local_user()) {
214                         $drop = false;
215                 }
216
217                 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
218
219                 $profile_name = $item['author-name'];
220                 if (!empty($item['author-link']) && empty($item['author-name'])) {
221                         $profile_name = $item['author-link'];
222                 }
223
224                 $author = ['uid' => 0, 'id' => $item['author-id'],
225                         'network' => $item['author-network'], 'url' => $item['author-link']];
226
227                 if (local_user() || remote_user()) {
228                         $profile_link = Contact::magicLinkByContact($author);
229                 } else {
230                         $profile_link = $item['author-link'];
231                 }
232
233                 if (strpos($profile_link, 'redir/') === 0) {
234                         $sparkle = ' sparkle';
235                 }
236
237                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
238                 Hook::callAll('render_location', $locate);
239                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
240
241                 // process action responses - e.g. like/dislike/attend/agree/whatever
242                 $response_verbs = ['like', 'dislike', 'announce'];
243
244                 $isevent = false;
245                 $attend = [];
246                 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
247                         $response_verbs[] = 'attendyes';
248                         $response_verbs[] = 'attendno';
249                         $response_verbs[] = 'attendmaybe';
250                         if ($conv->isWritable()) {
251                                 $isevent = true;
252                                 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
253                         }
254                 }
255
256                 $responses = get_responses($conv_responses, $response_verbs, $item, $this);
257
258                 foreach ($response_verbs as $value => $verbs) {
259                         $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']) : '';
260                 }
261
262                 /*
263                  * We should avoid doing this all the time, but it depends on the conversation mode
264                  * And the conv mode may change when we change the conv, or it changes its mode
265                  * Maybe we should establish a way to be notified about conversation changes
266                  */
267                 $this->checkWallToWall();
268
269                 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
270                         $osparkle = ' sparkle';
271                 }
272
273                 $tagger = '';
274
275                 if ($this->isToplevel()) {
276                         if(local_user()) {
277                                 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
278                                 if (DBA::isResult($thread)) {
279                                         $ignore = [
280                                                 'do'        => L10n::t("ignore thread"),
281                                                 'undo'      => L10n::t("unignore thread"),
282                                                 'toggle'    => L10n::t("toggle ignore status"),
283                                                 'classdo'   => $thread['ignored'] ? "hidden" : "",
284                                                 'classundo' => $thread['ignored'] ? "" : "hidden",
285                                                 'ignored'   => L10n::t('ignored'),
286                                         ];
287                                 }
288
289                                 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
290                                         $isstarred = (($item['starred']) ? "starred" : "unstarred");
291
292                                         $star = [
293                                                 'do'        => L10n::t("add star"),
294                                                 'undo'      => L10n::t("remove star"),
295                                                 'toggle'    => L10n::t("toggle star status"),
296                                                 'classdo'   => $item['starred'] ? "hidden" : "",
297                                                 'classundo' => $item['starred'] ? "" : "hidden",
298                                                 'starred'   => L10n::t('starred'),
299                                         ];
300
301                                         $tagger = [
302                                                 'add'   => L10n::t("add tag"),
303                                                 'class' => "",
304                                         ];
305                                 }
306                         }
307                 } else {
308                         $indent = 'comment';
309                 }
310
311                 if ($conv->isWritable()) {
312                         $buttons = [
313                                 'like'    => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
314                                 'dislike' => [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")],
315                         ];
316                         if ($shareable) {
317                                 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
318                         }
319                 }
320
321                 $comment = $this->getCommentBox($indent);
322
323                 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
324                         $shiny = 'shiny';
325                 }
326
327                 localize_item($item);
328
329                 $body = Item::prepareBody($item, true);
330
331                 list($categories, $folders) = get_cats_and_terms($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                  * Only add what will be displayed
527                  */
528                 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
529                         return false;
530                 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
531                         return false;
532                 }
533
534                 $item->setParent($this);
535                 $this->children[] = $item;
536
537                 return end($this->children);
538         }
539
540         /**
541          * Get a child by its ID
542          *
543          * @param integer $id The child id
544          *
545          * @return mixed
546          */
547         public function getChild($id)
548         {
549                 foreach ($this->getChildren() as $child) {
550                         if ($child->getId() == $id) {
551                                 return $child;
552                         }
553                 }
554
555                 return null;
556         }
557
558         /**
559          * Get all our children
560          *
561          * @return Post[]
562          */
563         public function getChildren()
564         {
565                 return $this->children;
566         }
567
568         /**
569          * Set our parent
570          *
571          * @param Post $item The item to set as parent
572          *
573          * @return void
574          */
575         protected function setParent(Post $item)
576         {
577                 $parent = $this->getParent();
578                 if ($parent) {
579                         $parent->removeChild($this);
580                 }
581
582                 $this->parent = $item;
583                 $this->setThread($item->getThread());
584         }
585
586         /**
587          * Remove our parent
588          *
589          * @return void
590          */
591         protected function removeParent()
592         {
593                 $this->parent = null;
594                 $this->thread = null;
595         }
596
597         /**
598          * Remove a child
599          *
600          * @param Post $item The child to be removed
601          *
602          * @return boolean Success or failure
603          * @throws \Exception
604          */
605         public function removeChild(Post $item)
606         {
607                 $id = $item->getId();
608                 foreach ($this->getChildren() as $key => $child) {
609                         if ($child->getId() == $id) {
610                                 $child->removeParent();
611                                 unset($this->children[$key]);
612                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
613                                 $this->children = array_values($this->children);
614                                 return true;
615                         }
616                 }
617                 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
618                 return false;
619         }
620
621         /**
622          * Get parent item
623          *
624          * @return object
625          */
626         protected function getParent()
627         {
628                 return $this->parent;
629         }
630
631         /**
632          * Set conversation thread
633          *
634          * @param Thread $thread
635          *
636          * @return void
637          */
638         public function setThread(Thread $thread = null)
639         {
640                 $this->thread = $thread;
641
642                 // Set it on our children too
643                 foreach ($this->getChildren() as $child) {
644                         $child->setThread($thread);
645                 }
646         }
647
648         /**
649          * Get conversation
650          *
651          * @return Thread
652          */
653         public function getThread()
654         {
655                 return $this->thread;
656         }
657
658         /**
659          * Get raw data
660          *
661          * We shouldn't need this
662          *
663          * @return array
664          */
665         public function getData()
666         {
667                 return $this->data;
668         }
669
670         /**
671          * Get a data value
672          *
673          * @param string $name key
674          *
675          * @return mixed value on success
676          *               false on failure
677          */
678         public function getDataValue($name)
679         {
680                 if (!isset($this->data[$name])) {
681                         // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
682                         return false;
683                 }
684
685                 return $this->data[$name];
686         }
687
688         /**
689          * Set template
690          *
691          * @param string $name template name
692          * @return bool
693          * @throws \Exception
694          */
695         private function setTemplate($name)
696         {
697                 if (empty($this->available_templates[$name])) {
698                         Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
699                         return false;
700                 }
701
702                 $this->template = $this->available_templates[$name];
703
704                 return true;
705         }
706
707         /**
708          * Get template
709          *
710          * @return object
711          */
712         private function getTemplate()
713         {
714                 return $this->template;
715         }
716
717         /**
718          * Check if this is a toplevel post
719          *
720          * @return boolean
721          */
722         private function isToplevel()
723         {
724                 return $this->toplevel;
725         }
726
727         /**
728          * Check if this is writable
729          *
730          * @return boolean
731          */
732         private function isWritable()
733         {
734                 $conv = $this->getThread();
735
736                 if ($conv) {
737                         // This will allow us to comment on wall-to-wall items owned by our friends
738                         // and community forums even if somebody else wrote the post.
739                         // bug #517 - this fixes for conversation owner
740                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
741                                 return true;
742                         }
743
744                         // this fixes for visitors
745                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
746                 }
747                 return $this->writable;
748         }
749
750         /**
751          * Count the total of our descendants
752          *
753          * @return integer
754          */
755         private function countDescendants()
756         {
757                 $children = $this->getChildren();
758                 $total = count($children);
759                 if ($total > 0) {
760                         foreach ($children as $child) {
761                                 $total += $child->countDescendants();
762                         }
763                 }
764
765                 return $total;
766         }
767
768         /**
769          * Get the template for the comment box
770          *
771          * @return string
772          */
773         private function getCommentBoxTemplate()
774         {
775                 return $this->comment_box_template;
776         }
777
778         /**
779          * Get default text for the comment box
780          *
781          * @return string
782          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
783          */
784         private function getDefaultText()
785         {
786                 $a = self::getApp();
787
788                 if (!local_user()) {
789                         return '';
790                 }
791
792                 $owner = User::getOwnerDataById($a->user['uid']);
793
794                 if (!Feature::isEnabled(local_user(), 'explicit_mentions')) {
795                         return '';
796                 }
797
798                 $item = Item::selectFirst(['author-addr'], ['id' => $this->getId()]);
799                 if (!DBA::isResult($item) || empty($item['author-addr'])) {
800                         // Should not happen
801                         return '';
802                 }
803
804                 if ($item['author-addr'] != $owner['addr']) {
805                         $text = '@' . $item['author-addr'] . ' ';
806                 } else {
807                         $text = '';
808                 }
809
810                 $terms = Term::tagArrayFromItemId($this->getId(), [Term::MENTION, Term::IMPLICIT_MENTION]);
811                 foreach ($terms as $term) {
812                         $profile = Contact::getDetailsByURL($term['url']);
813                         if (!empty($profile['addr']) && (defaults($profile, 'contact-type', Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
814                                 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])) {
815                                 $text .= '@' . $profile['addr'] . ' ';
816                         }
817                 }
818
819                 return $text;
820         }
821
822         /**
823          * Get the comment box
824          *
825          * @param string $indent Indent value
826          *
827          * @return mixed The comment box string (empty if no comment box)
828          *               false on failure
829          * @throws \Exception
830          */
831         private function getCommentBox($indent)
832         {
833                 $a = self::getApp();
834
835                 $comment_box = '';
836                 $conv = $this->getThread();
837                 $ww = '';
838                 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
839                         $ww = 'ww';
840                 }
841
842                 if ($conv->isWritable() && $this->isWritable()) {
843                         $qcomment = null;
844
845                         /*
846                          * Hmmm, code depending on the presence of a particular addon?
847                          * This should be better if done by a hook
848                          */
849                         if (Addon::isEnabled('qcomment')) {
850                                 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
851                                 $qcomment = (($qc) ? explode("\n", $qc) : null);
852                         }
853
854                         // Fetch the user id from the parent when the owner user is empty
855                         $uid = $conv->getProfileOwner();
856                         $parent_uid = $this->getDataValue('uid');
857
858                         $default_text = $this->getDefaultText();
859
860                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
861                                 $uid = $parent_uid;
862                         }
863
864                         $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
865                         $comment_box = Renderer::replaceMacros($template, [
866                                 '$return_path' => $a->query_string,
867                                 '$threaded'    => $this->isThreaded(),
868                                 '$jsreload'    => '',
869                                 '$wall'        => ($conv->getMode() === 'profile'),
870                                 '$id'          => $this->getId(),
871                                 '$parent'      => $this->getId(),
872                                 '$qcomment'    => $qcomment,
873                                 '$default'     => $default_text,
874                                 '$profile_uid' => $uid,
875                                 '$mylink'      => $a->removeBaseURL($a->contact['url']),
876                                 '$mytitle'     => L10n::t('This is you'),
877                                 '$myphoto'     => $a->removeBaseURL($a->contact['thumb']),
878                                 '$comment'     => L10n::t('Comment'),
879                                 '$submit'      => L10n::t('Submit'),
880                                 '$edbold'      => L10n::t('Bold'),
881                                 '$editalic'    => L10n::t('Italic'),
882                                 '$eduline'     => L10n::t('Underline'),
883                                 '$edquote'     => L10n::t('Quote'),
884                                 '$edcode'      => L10n::t('Code'),
885                                 '$edimg'       => L10n::t('Image'),
886                                 '$edurl'       => L10n::t('Link'),
887                                 '$edattach'    => L10n::t('Link or Media'),
888                                 '$prompttext'  => L10n::t('Please enter a image/video/audio/webpage URL:'),
889                                 '$preview'     => L10n::t('Preview'),
890                                 '$indent'      => $indent,
891                                 '$sourceapp'   => L10n::t($a->sourcename),
892                                 '$ww'          => $conv->getMode() === 'network' ? $ww : '',
893                                 '$rand_num'    => Crypto::randomDigits(12)
894                         ]);
895                 }
896
897                 return $comment_box;
898         }
899
900         /**
901          * @return string
902          */
903         private function getRedirectUrl()
904         {
905                 return $this->redirect_url;
906         }
907
908         /**
909          * Check if we are a wall to wall item and set the relevant properties
910          *
911          * @return void
912          * @throws \Exception
913          */
914         protected function checkWallToWall()
915         {
916                 $a = self::getApp();
917                 $conv = $this->getThread();
918                 $this->wall_to_wall = false;
919
920                 if ($this->isToplevel()) {
921                         if ($conv->getMode() !== 'profile') {
922                                 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
923                                         // On the network page, I am the owner. On the display page it will be the profile owner.
924                                         // This will have been stored in $a->page_contact by our calling page.
925                                         // Put this person as the wall owner of the wall-to-wall notice.
926
927                                         $this->owner_url = Contact::magicLink($a->page_contact['url']);
928                                         $this->owner_photo = $a->page_contact['thumb'];
929                                         $this->owner_name = $a->page_contact['name'];
930                                         $this->wall_to_wall = true;
931                                 } elseif ($this->getDataValue('owner-link')) {
932                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
933                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
934                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
935
936                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
937                                                 // The author url doesn't match the owner (typically the contact)
938                                                 // and also doesn't match the contact alias.
939                                                 // The name match is a hack to catch several weird cases where URLs are
940                                                 // all over the park. It can be tricked, but this prevents you from
941                                                 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
942                                                 // well that it's the same Bob Smith.
943                                                 // But it could be somebody else with the same name. It just isn't highly likely.
944
945
946                                                 $this->owner_photo = $this->getDataValue('owner-avatar');
947                                                 $this->owner_name = $this->getDataValue('owner-name');
948                                                 $this->wall_to_wall = true;
949
950                                                 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
951                                                         'network' => $this->getDataValue('owner-network'),
952                                                         'url' => $this->getDataValue('owner-link')];
953                                                 $this->owner_url = Contact::magicLinkByContact($owner);
954                                         }
955                                 }
956                         }
957                 }
958
959                 if (!$this->wall_to_wall) {
960                         $this->setTemplate('wall');
961                         $this->owner_url = '';
962                         $this->owner_photo = '';
963                         $this->owner_name = '';
964                 }
965         }
966
967         /**
968          * @return boolean
969          */
970         private function isWallToWall()
971         {
972                 return $this->wall_to_wall;
973         }
974
975         /**
976          * @return string
977          */
978         private function getOwnerUrl()
979         {
980                 return $this->owner_url;
981         }
982
983         /**
984          * @return string
985          */
986         private function getOwnerName()
987         {
988                 return $this->owner_name;
989         }
990
991         /**
992          * @return boolean
993          */
994         private function isVisiting()
995         {
996                 return $this->visiting;
997         }
998 }