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