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