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