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