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