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