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