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