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