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