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