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