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