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