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