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