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