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