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