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