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