]> git.mxchange.org Git - friendica.git/blob - mod/item.php
old boot.functions replaced in /mod
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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  * This is the POST destination for most all locally posted
21  * text stuff. This function handles status, wall-to-wall status,
22  * local comments, and remote coments that are posted on this site
23  * (as opposed to being delivered in a feed).
24  * Also processed here are posts and comments coming through the
25  * statusnet/twitter API.
26  *
27  * All of these become an "item" which is our basic unit of
28  * information.
29  */
30
31 use Friendica\App;
32 use Friendica\Content\PageInfo;
33 use Friendica\Content\Text\BBCode;
34 use Friendica\Core\Hook;
35 use Friendica\Core\Logger;
36 use Friendica\Core\Protocol;
37 use Friendica\Core\Session;
38 use Friendica\Core\System;
39 use Friendica\Core\Worker;
40 use Friendica\Database\DBA;
41 use Friendica\DI;
42 use Friendica\Model\Attach;
43 use Friendica\Model\Contact;
44 use Friendica\Model\Conversation;
45 use Friendica\Model\FileTag;
46 use Friendica\Model\Item;
47 use Friendica\Model\ItemURI;
48 use Friendica\Model\Notification;
49 use Friendica\Model\Photo;
50 use Friendica\Model\Post;
51 use Friendica\Model\Tag;
52 use Friendica\Model\User;
53 use Friendica\Network\HTTPException;
54 use Friendica\Object\EMail\ItemCCEMail;
55 use Friendica\Protocol\Activity;
56 use Friendica\Security\Security;
57 use Friendica\Util\DateTimeFormat;
58 use Friendica\Util\ParseUrl;
59
60 function item_post(App $a) {
61         if (!Session::isAuthenticated()) {
62                 throw new HTTPException\ForbiddenException();
63         }
64
65         $uid = Session::getLocalUser();
66
67         if (!empty($_REQUEST['dropitems'])) {
68                 $arr_drop = explode(',', $_REQUEST['dropitems']);
69                 foreach ($arr_drop as $item) {
70                         Item::deleteForUser(['id' => $item], $uid);
71                 }
72
73                 $json = ['success' => 1];
74                 System::jsonExit($json);
75         }
76
77         Hook::callAll('post_local_start', $_REQUEST);
78
79         Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
80
81         $api_source = $_REQUEST['api_source'] ?? false;
82
83         $return_path = $_REQUEST['return'] ?? '';
84         $preview = intval($_REQUEST['preview'] ?? 0);
85
86         /*
87          * Check for doubly-submitted posts, and reject duplicates
88          * Note that we have to ignore previews, otherwise nothing will post
89          * after it's been previewed
90          */
91         if (!$preview && !empty($_REQUEST['post_id_random'])) {
92                 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
93                         Logger::warning('duplicate post');
94                         item_post_return(DI::baseUrl(), $api_source, $return_path);
95                 } else {
96                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
97                 }
98         }
99
100         // Is this a reply to something?
101         $parent_item_id = intval($_REQUEST['parent'] ?? 0);
102         $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
103
104         $parent_item = null;
105         $toplevel_item = null;
106         $toplevel_item_id = 0;
107         $toplevel_user_id = null;
108
109         $objecttype = null;
110         $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: Session::getLocalUser();
111         $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
112
113         if ($parent_item_id || $thr_parent_uri) {
114                 if ($parent_item_id) {
115                         $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item_id]);
116                 } elseif ($thr_parent_uri) {
117                         $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
118                 }
119
120                 // if this isn't the top-level parent of the conversation, find it
121                 if (DBA::isResult($parent_item)) {
122                         // The URI and the contact is taken from the direct parent which needn't to be the top parent
123                         $thr_parent_uri = $parent_item['uri'];
124                         $toplevel_item = $parent_item;
125
126                         if ($parent_item['gravity'] != Item::GRAVITY_PARENT) {
127                                 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
128                         }
129                 }
130
131                 if (!DBA::isResult($toplevel_item)) {
132                         DI::sysmsg()->addNotice(DI::l10n()->t('Unable to locate original post.'));
133                         if ($return_path) {
134                                 DI::baseUrl()->redirect($return_path);
135                         }
136                         throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
137                 }
138
139                 // When commenting on a public post then store the post for the current user
140                 // This enables interaction like starring and saving into folders
141                 if ($toplevel_item['uid'] == 0) {
142                         $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], Session::getLocalUser(), ['post-reason' => Item::PR_ACTIVITY]);
143                         Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
144                         if ($stored) {
145                                 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $stored]);
146                         }
147                 }
148
149                 $toplevel_item_id = $toplevel_item['id'];
150                 $toplevel_user_id = $toplevel_item['uid'];
151
152                 $objecttype = Activity\ObjectType::COMMENT;
153         }
154
155         if ($toplevel_item_id) {
156                 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
157         }
158
159         $post_id     = intval($_REQUEST['post_id'] ?? 0);
160         $app         = strip_tags($_REQUEST['source'] ?? '');
161         $extid       = strip_tags($_REQUEST['extid'] ?? '');
162         $object      = $_REQUEST['object'] ?? '';
163
164         // Don't use "defaults" here. It would turn 0 to 1
165         if (!isset($_REQUEST['wall'])) {
166                 $wall = 1;
167         } else {
168                 $wall = $_REQUEST['wall'];
169         }
170
171         // Ensure that the user id in a thread always stay the same
172         if (!is_null($toplevel_user_id) && in_array($toplevel_user_id, [Session::getLocalUser(), 0])) {
173                 $profile_uid = $toplevel_user_id;
174         }
175
176         // Allow commenting if it is an answer to a public post
177         $allow_comment = Session::getLocalUser() && $toplevel_item_id && in_array($toplevel_item['private'], [Item::PUBLIC, Item::UNLISTED]) && in_array($toplevel_item['network'], Protocol::FEDERATED);
178
179         // Now check that valid personal details have been provided
180         if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
181                 Logger::warning('Permission denied.', ['local' => Session::getLocalUser(), 'profile_uid' => $profile_uid, 'toplevel_item_id' => $toplevel_item_id, 'network' => $toplevel_item['network']]);
182                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
183                 if ($return_path) {
184                         DI::baseUrl()->redirect($return_path);
185                 }
186
187                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
188         }
189
190         // Init post instance
191         $orig_post = null;
192
193         // is this an edited post?
194         if ($post_id > 0) {
195                 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
196         }
197
198         $user = User::getById($profile_uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
199         if (!DBA::isResult($user) && !$toplevel_item_id) {
200                 return 0;
201         }
202
203         $categories = '';
204         $postopts = '';
205         $emailcc = '';
206         $body = $_REQUEST['body'] ?? '';
207         $has_attachment = $_REQUEST['has_attachment'] ?? 0;
208
209         // If we have a speparate attachment, we need to add it to the body.
210         if (!empty($has_attachment)) {
211                 $attachment_type  = $_REQUEST['attachment_type'] ??  '';
212                 $attachment_title = $_REQUEST['attachment_title'] ?? '';
213                 $attachment_text  = $_REQUEST['attachment_text'] ??  '';
214
215                 $attachment_url     = hex2bin($_REQUEST['attachment_url'] ??     '');
216                 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
217
218                 $attachment_img_width  = $_REQUEST['attachment_img_width'] ??  0;
219                 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
220
221                 // Fetch the basic attachment data
222                 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
223                 unset($attachment['keywords']);
224
225                 // Overwrite the basic data with possible changes from the frontend
226                 $attachment['type'] = $attachment_type;
227                 $attachment['title'] = $attachment_title;
228                 $attachment['text'] = $attachment_text;
229                 $attachment['url'] = $attachment_url;
230
231                 if (!empty($attachment_img_src)) {
232                         $attachment['images'] = [
233                                 0 => [
234                                         'src'    => $attachment_img_src,
235                                         'width'  => $attachment_img_width,
236                                         'height' => $attachment_img_height
237                                 ]
238                         ];
239                 } else {
240                         unset($attachment['images']);
241                 }
242
243                 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
244                 $body .= $att_bbcode;
245         }
246
247         // Convert links with empty descriptions to links without an explicit description
248         $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
249
250         if (!empty($orig_post)) {
251                 $str_group_allow   = $orig_post['allow_gid'];
252                 $str_contact_allow = $orig_post['allow_cid'];
253                 $str_group_deny    = $orig_post['deny_gid'];
254                 $str_contact_deny  = $orig_post['deny_cid'];
255                 $location          = $orig_post['location'];
256                 $coord             = $orig_post['coord'];
257                 $verb              = $orig_post['verb'];
258                 $objecttype        = $orig_post['object-type'];
259                 $app               = $orig_post['app'];
260                 $categories        = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']);
261                 $title             = trim($_REQUEST['title'] ?? '');
262                 $body              = trim($body);
263                 $private           = $orig_post['private'];
264                 $pubmail_enabled   = $orig_post['pubmail'];
265                 $network           = $orig_post['network'];
266                 $guid              = $orig_post['guid'];
267                 $extid             = $orig_post['extid'];
268         } else {
269                 $aclFormatter = DI::aclFormatter();
270                 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
271                 $str_group_allow   = isset($_REQUEST['group_allow'])   ? $aclFormatter->toString($_REQUEST['group_allow'])   : $user['allow_gid'] ?? '';
272                 $str_contact_deny  = isset($_REQUEST['contact_deny'])  ? $aclFormatter->toString($_REQUEST['contact_deny'])  : $user['deny_cid']  ?? '';
273                 $str_group_deny    = isset($_REQUEST['group_deny'])    ? $aclFormatter->toString($_REQUEST['group_deny'])    : $user['deny_gid']  ?? '';
274
275                 $visibility = $_REQUEST['visibility'] ?? '';
276                 if ($visibility === 'public') {
277                         // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
278                         $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
279                 } else if ($visibility === 'custom') {
280                         // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
281                         // case that would make it public. So we always append the author's contact id to the allowed contacts.
282                         // See https://github.com/friendica/friendica/issues/9672
283                         $str_contact_allow .= $aclFormatter->toString(Contact::getPublicIdByUserId($uid));
284                 }
285
286                 $title             = trim($_REQUEST['title']    ?? '');
287                 $location          = trim($_REQUEST['location'] ?? '');
288                 $coord             = trim($_REQUEST['coord']    ?? '');
289                 $verb              = trim($_REQUEST['verb']     ?? '');
290                 $emailcc           = trim($_REQUEST['emailcc']  ?? '');
291                 $body              = trim($body);
292                 $network           = trim(($_REQUEST['network']  ?? '') ?: Protocol::DFRN);
293                 $guid              = System::createUUID();
294
295                 $postopts = $_REQUEST['postopts'] ?? '';
296
297                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
298                         $private = Item::PRIVATE;
299                 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
300                         $private = Item::UNLISTED;
301                 } else {
302                         $private = Item::PUBLIC;
303                 }
304
305                 // If this is a comment, set the permissions from the parent.
306
307                 if ($toplevel_item) {
308                         // for non native networks use the network of the original post as network of the item
309                         if (($toplevel_item['network'] != Protocol::DIASPORA)
310                                 && ($toplevel_item['network'] != Protocol::OSTATUS)
311                                 && ($network == '')) {
312                                 $network = $toplevel_item['network'];
313                         }
314
315                         $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
316                         $str_group_allow   = $toplevel_item['allow_gid'] ?? '';
317                         $str_contact_deny  = $toplevel_item['deny_cid'] ?? '';
318                         $str_group_deny    = $toplevel_item['deny_gid'] ?? '';
319                         $private           = $toplevel_item['private'];
320
321                         $wall              = $toplevel_item['wall'];
322                 }
323
324                 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
325
326                 // if using the API, we won't see pubmail_enable - figure out if it should be set
327                 if ($api_source && $profile_uid && $profile_uid == Session::getLocalUser() && !$private) {
328                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
329                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", Session::getLocalUser(), '']);
330                         }
331                 }
332
333                 if (!strlen($body)) {
334                         if ($preview) {
335                                 System::jsonExit(['preview' => '']);
336                         }
337
338                         DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.'));
339                         if ($return_path) {
340                                 DI::baseUrl()->redirect($return_path);
341                         }
342
343                         throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
344                 }
345         }
346
347         if (!empty($categories)) {
348                 // get the "fileas" tags for this post
349                 $filedas = FileTag::fileToArray($categories);
350         }
351
352         $list_array = explode(',', trim($_REQUEST['category'] ?? ''));
353         $categories = FileTag::arrayToFile($list_array, 'category');
354
355         if (!empty($filedas) && is_array($filedas)) {
356                 // append the fileas stuff to the new categories list
357                 $categories .= FileTag::arrayToFile($filedas);
358         }
359
360         // get contact info for poster
361
362         $author = null;
363         $self   = false;
364         $contact_id = 0;
365
366         if (Session::getLocalUser() && ((Session::getLocalUser() == $profile_uid) || $allow_comment)) {
367                 $self = true;
368                 $author = DBA::selectFirst('contact', [], ['uid' => Session::getLocalUser(), 'self' => true]);
369         } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
370                 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
371         }
372
373         if (DBA::isResult($author)) {
374                 $contact_id = $author['id'];
375         }
376
377         // get contact info for owner
378         if ($profile_uid == Session::getLocalUser() || $allow_comment) {
379                 $contact_record = $author ?: [];
380         } else {
381                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
382         }
383
384         // Personal notes must never be altered to a forum post.
385         if ($posttype != Item::PT_PERSONAL_NOTE) {
386                 // Look for any tags and linkify them
387                 $item = [
388                         'uid'       => Session::getLocalUser() ? Session::getLocalUser() : $profile_uid,
389                         'gravity'   => $toplevel_item_id ? Item::GRAVITY_COMMENT : Item::GRAVITY_PARENT,
390                         'network'   => $network,
391                         'body'      => $body,
392                         'postopts'  => $postopts,
393                         'private'   => $private,
394                         'allow_cid' => $str_contact_allow,
395                         'allow_gid' => $str_group_allow,
396                         'deny_cid'  => $str_contact_deny,
397                         'deny_gid'  => $str_group_deny,
398                 ];
399
400                 $item = DI::contentItem()->expandTags($item);
401
402                 $body              = $item['body'];
403                 $inform            = $item['inform'];
404                 $postopts          = $item['postopts'];
405                 $private           = $item['private'];
406                 $str_contact_allow = $item['allow_cid'];
407                 $str_group_allow   = $item['allow_gid'];
408                 $str_contact_deny  = $item['deny_cid'];
409                 $str_group_deny    = $item['deny_gid'];
410         } else {
411                 $inform   = '';
412         }
413
414         /*
415          * When a photo was uploaded into the message using the (profile wall) ajax
416          * uploader, The permissions are initially set to disallow anybody but the
417          * owner from seeing it. This is because the permissions may not yet have been
418          * set for the post. If it's private, the photo permissions should be set
419          * appropriately. But we didn't know the final permissions on the post until
420          * now. So now we'll look for links of uploaded messages that are in the
421          * post and set them to the same permissions as the post itself.
422          */
423
424         $match = null;
425
426         if (!$preview && Photo::setPermissionFromBody($body, $uid, $contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
427                 $objecttype = Activity\ObjectType::IMAGE;
428         }
429
430         /*
431          * Next link in any attachment references we find in the post.
432          */
433         $match = [];
434
435         /// @todo these lines should be moved to Model/Attach (Once it exists)
436         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
437                 $attaches = $match[1];
438                 if (count($attaches)) {
439                         foreach ($attaches as $attach) {
440                                 // Ensure to only modify attachments that you own
441                                 $srch = '<' . intval($contact_id) . '>';
442
443                                 $condition = [
444                                         'allow_cid' => $srch,
445                                         'allow_gid' => '',
446                                         'deny_cid' => '',
447                                         'deny_gid' => '',
448                                         'id' => $attach,
449                                 ];
450                                 if (!Attach::exists($condition)) {
451                                         continue;
452                                 }
453
454                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
455                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
456                                 $condition = ['id' => $attach];
457                                 Attach::update($fields, $condition);
458                         }
459                 }
460         }
461
462         // embedded bookmark or attachment in post? set bookmark flag
463
464         $data = BBCode::getAttachmentData($body);
465         $match = [];
466         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data['type']))
467                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
468                 $posttype = Item::PT_PAGE;
469                 $objecttype =  Activity\ObjectType::BOOKMARK;
470         }
471
472         $body = DI::bbCodeVideo()->transform($body);
473
474         $body = BBCode::scaleExternalImages($body);
475
476         // Setting the object type if not defined before
477         if (!$objecttype) {
478                 $objecttype = Activity\ObjectType::NOTE; // Default value
479                 $objectdata = BBCode::getAttachedData($body);
480
481                 if ($objectdata['type'] == 'link') {
482                         $objecttype = Activity\ObjectType::BOOKMARK;
483                 } elseif ($objectdata['type'] == 'video') {
484                         $objecttype = Activity\ObjectType::VIDEO;
485                 } elseif ($objectdata['type'] == 'photo') {
486                         $objecttype = Activity\ObjectType::IMAGE;
487                 }
488
489         }
490
491         $attachments = '';
492         $match = [];
493
494         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
495                 foreach ($match[2] as $mtch) {
496                         $fields = ['id', 'filename', 'filesize', 'filetype'];
497                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
498                         if ($attachment !== false) {
499                                 if (strlen($attachments)) {
500                                         $attachments .= ',';
501                                 }
502                                 $attachments .= Post\Media::getAttachElement(DI::baseUrl() . '/attach/' . $attachment['id'],
503                                         $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? '');
504                         }
505                         $body = str_replace($match[1],'',$body);
506                 }
507         }
508
509         if (!strlen($verb)) {
510                 $verb = Activity::POST;
511         }
512
513         if ($network == '') {
514                 $network = Protocol::DFRN;
515         }
516
517         $gravity = ($toplevel_item_id ? Item::GRAVITY_COMMENT : Item::GRAVITY_PARENT);
518
519         // even if the post arrived via API we are considering that it
520         // originated on this site by default for determining relayability.
521
522         // Don't use "defaults" here. It would turn 0 to 1
523         if (!isset($_REQUEST['origin'])) {
524                 $origin = 1;
525         } else {
526                 $origin = $_REQUEST['origin'];
527         }
528
529         $uri = Item::newURI($guid);
530
531         // Fallback so that we alway have a parent uri
532         if (!$thr_parent_uri || !$toplevel_item_id) {
533                 $thr_parent_uri = $uri;
534         }
535
536         $datarray = [
537                 'uid'           => $profile_uid,
538                 'wall'          => $wall,
539                 'gravity'       => $gravity,
540                 'network'       => $network,
541                 'contact-id'    => $contact_id,
542                 'owner-name'    => $contact_record['name'] ?? '',
543                 'owner-link'    => $contact_record['url'] ?? '',
544                 'owner-avatar'  => $contact_record['thumb'] ?? '',
545                 'author-name'   => $author['name'],
546                 'author-link'   => $author['url'],
547                 'author-avatar' => $author['thumb'],
548                 'created'       => empty($_REQUEST['created_at']) ? DateTimeFormat::utcNow() : $_REQUEST['created_at'],
549                 'received'      => DateTimeFormat::utcNow(),
550                 'extid'         => $extid,
551                 'guid'          => $guid,
552                 'uri'           => $uri,
553                 'title'         => $title,
554                 'body'          => $body,
555                 'app'           => $app,
556                 'location'      => $location,
557                 'coord'         => $coord,
558                 'file'          => $categories,
559                 'inform'        => $inform,
560                 'verb'          => $verb,
561                 'post-type'     => $posttype,
562                 'object-type'   => $objecttype,
563                 'allow_cid'     => $str_contact_allow,
564                 'allow_gid'     => $str_group_allow,
565                 'deny_cid'      => $str_contact_deny,
566                 'deny_gid'      => $str_group_deny,
567                 'private'       => $private,
568                 'pubmail'       => $pubmail_enabled,
569                 'attach'        => $attachments,
570                 'thr-parent'    => $thr_parent_uri,
571                 'postopts'      => $postopts,
572                 'origin'        => $origin,
573                 'object'        => $object,
574                 'attachments'   => $_REQUEST['attachments'] ?? [],
575                 /*
576                  * These fields are for the convenience of addons...
577                  * 'self' if true indicates the owner is posting on their own wall
578                  * If parent is 0 it is a top-level post.
579                  */
580                 'parent'        => $toplevel_item_id,
581                 'self'          => $self,
582                 // This triggers posts via API and the mirror functions
583                 'api_source'    => $api_source,
584                 // This field is for storing the raw conversation data
585                 'protocol'      => Conversation::PARCEL_DIRECT,
586                 'direction'     => Conversation::PUSH,
587         ];
588
589         // These cannot be part of above initialization ...
590         $datarray['edited']    = $datarray['created'];
591         $datarray['commented'] = $datarray['created'];
592         $datarray['changed']   = $datarray['created'];
593         $datarray['owner-id']  = Contact::getIdForURL($datarray['owner-link']);
594         $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
595
596         $datarray['edit'] = $orig_post;
597
598         // Check for hashtags in the body and repair or add hashtag links
599         if ($preview || $orig_post) {
600                 $datarray['body'] = Item::setHashtags($datarray['body']);
601         }
602
603         // preview mode - prepare the body for display and send it via json
604         if ($preview) {
605                 // We set the datarray ID to -1 because in preview mode the dataray
606                 // doesn't have an ID.
607                 $datarray['id'] = -1;
608                 $datarray['uri-id'] = -1;
609                 $datarray['author-network'] = Protocol::DFRN;
610                 $datarray['author-updated'] = '';
611                 $datarray['author-gsid'] = 0;
612                 $datarray['author-uri-id'] = ItemURI::getIdByURI($datarray['author-link']);
613                 $datarray['owner-updated'] = '';
614                 $datarray['has-media'] = false;
615                 $datarray['body'] = Item::improveSharedDataInBody($datarray);
616
617                 $o = DI::conversation()->create([array_merge($contact_record, $datarray)], 'search', false, true);
618
619                 System::jsonExit(['preview' => $o]);
620         }
621
622         Hook::callAll('post_local',$datarray);
623
624         if (!empty($_REQUEST['scheduled_at'])) {
625                 $scheduled_at = DateTimeFormat::convert($_REQUEST['scheduled_at'], 'UTC', $a->getTimeZone());
626                 if ($scheduled_at > DateTimeFormat::utcNow()) {
627                         unset($datarray['created']);
628                         unset($datarray['edited']);
629                         unset($datarray['commented']);
630                         unset($datarray['received']);
631                         unset($datarray['changed']);
632                         unset($datarray['edit']);
633                         unset($datarray['self']);
634                         unset($datarray['api_source']);
635
636                         Post\Delayed::add($datarray['uri'], $datarray, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
637                         item_post_return(DI::baseUrl(), $api_source, $return_path);
638                 }
639         }
640
641         if (!empty($datarray['cancel'])) {
642                 Logger::info('mod_item: post cancelled by addon.');
643                 if ($return_path) {
644                         DI::baseUrl()->redirect($return_path);
645                 }
646
647                 $json = ['cancel' => 1];
648                 if (!empty($_REQUEST['jsreload'])) {
649                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
650                 }
651
652                 System::jsonExit($json);
653         }
654
655         $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
656         $datarray['body']   = Item::improveSharedDataInBody($datarray);
657
658         if ($orig_post) {
659                 $fields = [
660                         'title'   => $datarray['title'],
661                         'body'    => $datarray['body'],
662                         'attach'  => $datarray['attach'],
663                         'file'    => $datarray['file'],
664                         'edited'  => DateTimeFormat::utcNow(),
665                         'changed' => DateTimeFormat::utcNow()
666                 ];
667
668                 Item::update($fields, ['id' => $post_id]);
669                 Item::updateDisplayCache($datarray['uri-id']);
670
671                 if ($return_path) {
672                         DI::baseUrl()->redirect($return_path);
673                 }
674
675                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
676         }
677
678         unset($datarray['edit']);
679         unset($datarray['self']);
680         unset($datarray['api_source']);
681
682         $post_id = Item::insert($datarray);
683
684         if (!$post_id) {
685                 DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
686                 if ($return_path) {
687                         DI::baseUrl()->redirect($return_path);
688                 }
689
690                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
691         }
692
693         $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
694
695         if (!DBA::isResult($datarray)) {
696                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
697                 if ($return_path) {
698                         DI::baseUrl()->redirect($return_path);
699                 }
700
701                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
702         }
703
704         Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
705
706         if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == Item::GRAVITY_COMMENT)) {
707                 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
708         }
709
710         // These notifications are sent if someone else is commenting other your wall
711         if ($contact_record != $author) {
712                 if ($toplevel_item_id) {
713                         DI::notify()->createFromArray([
714                                 'type'  => Notification\Type::COMMENT,
715                                 'otype' => Notification\ObjectType::ITEM,
716                                 'verb'  => Activity::POST,
717                                 'uid'   => $profile_uid,
718                                 'cid'   => $datarray['author-id'],
719                                 'item'  => $datarray,
720                                 'link'  => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
721                         ]);
722                 } elseif (empty($forum_contact)) {
723                         DI::notify()->createFromArray([
724                                 'type'  => Notification\Type::WALL,
725                                 'otype' => Notification\ObjectType::ITEM,
726                                 'verb'  => Activity::POST,
727                                 'uid'   => $profile_uid,
728                                 'cid'   => $datarray['author-id'],
729                                 'item'  => $datarray,
730                                 'link'  => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
731                         ]);
732                 }
733         }
734
735         Hook::callAll('post_local_end', $datarray);
736
737         if (strlen($emailcc) && $profile_uid == Session::getLocalUser()) {
738                 $recipients = explode(',', $emailcc);
739                 if (count($recipients)) {
740                         foreach ($recipients as $recipient) {
741                                 $address = trim($recipient);
742                                 if (!strlen($address)) {
743                                         continue;
744                                 }
745                                 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
746                                         $datarray, $address, $author['thumb'] ?? ''));
747                         }
748                 }
749         }
750
751         Logger::debug('post_complete');
752
753         if ($api_source) {
754                 return $post_id;
755         }
756
757         item_post_return(DI::baseUrl(), $api_source, $return_path);
758         // NOTREACHED
759 }
760
761 function item_post_return($baseurl, $api_source, $return_path)
762 {
763         if ($api_source) {
764                 return;
765         }
766
767         if ($return_path) {
768                 DI::baseUrl()->redirect($return_path);
769         }
770
771         $json = ['success' => 1];
772         if (!empty($_REQUEST['jsreload'])) {
773                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
774         }
775
776         Logger::debug('post_json', ['json' => $json]);
777
778         System::jsonExit($json);
779 }
780
781 function item_content(App $a)
782 {
783         if (!Session::isAuthenticated()) {
784                 throw new HTTPException\UnauthorizedException();
785         }
786
787         $args = DI::args();
788
789         if (!$args->has(3)) {
790                 throw new HTTPException\BadRequestException();
791         }
792
793         $o = '';
794         switch ($args->get(1)) {
795                 case 'drop':
796                         if (DI::mode()->isAjax()) {
797                                 Item::deleteForUser(['id' => $args->get(2)], Session::getLocalUser());
798                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
799                                 System::jsonExit([intval($args->get(2)), Session::getLocalUser()]);
800                         } else {
801                                 if (!empty($args->get(3))) {
802                                         $o = drop_item($args->get(2), $args->get(3));
803                                 } else {
804                                         $o = drop_item($args->get(2));
805                                 }
806                         }
807                         break;
808
809                 case 'block':
810                         $item = Post::selectFirstForUser(Session::getLocalUser(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
811                         if (empty($item['author-id'])) {
812                                 throw new HTTPException\NotFoundException('Item not found');
813                         }
814
815                         Contact\User::setBlocked($item['author-id'], Session::getLocalUser(), true);
816
817                         if (DI::mode()->isAjax()) {
818                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
819                                 System::jsonExit([intval($args->get(2)), Session::getLocalUser()]);
820                         } else {
821                                 item_redirect_after_action($item, $args->get(3));
822                         }
823                         break;
824         }
825
826         return $o;
827 }
828
829 /**
830  * @param int    $id
831  * @param string $return
832  * @return string
833  * @throws HTTPException\InternalServerErrorException
834  */
835 function drop_item(int $id, string $return = ''): string
836 {
837         // Locate item to be deleted
838         $item = Post::selectFirstForUser(Session::getLocalUser(), ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'], ['id' => $id]);
839
840         if (!DBA::isResult($item)) {
841                 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
842                 DI::baseUrl()->redirect('network');
843                 //NOTREACHED
844         }
845
846         if ($item['deleted']) {
847                 return '';
848         }
849
850         $contact_id = 0;
851
852         // check if logged in user is either the author or owner of this item
853         if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
854                 $contact_id = $item['contact-id'];
855         }
856
857         if ((Session::getLocalUser() == $item['uid']) || $contact_id) {
858                 // delete the item
859                 Item::deleteForUser(['id' => $item['id']], Session::getLocalUser());
860
861                 item_redirect_after_action($item, $return);
862                 //NOTREACHED
863         } else {
864                 Logger::warning('Permission denied.', ['local' => Session::getLocalUser(), 'uid' => $item['uid'], 'cid' => $contact_id]);
865                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
866                 DI::baseUrl()->redirect('display/' . $item['guid']);
867                 //NOTREACHED
868         }
869
870         return '';
871 }
872
873 function item_redirect_after_action(array $item, string $returnUrlHex)
874 {
875         $return_url = hex2bin($returnUrlHex);
876
877         // removes update_* from return_url to ignore Ajax refresh
878         $return_url = str_replace('update_', '', $return_url);
879
880         // Check if delete a comment
881         if ($item['gravity'] == Item::GRAVITY_COMMENT) {
882                 if (!empty($item['parent'])) {
883                         $parentitem = Post::selectFirstForUser(Session::getLocalUser(), ['guid'], ['id' => $item['parent']]);
884                 }
885
886                 // Return to parent guid
887                 if (!empty($parentitem)) {
888                         DI::baseUrl()->redirect('display/' . $parentitem['guid']);
889                         //NOTREACHED
890                 } // In case something goes wrong
891                 else {
892                         DI::baseUrl()->redirect('network');
893                         //NOTREACHED
894                 }
895         } else {
896                 // if unknown location or deleting top level post called from display
897                 if (empty($return_url) || strpos($return_url, 'display') !== false) {
898                         DI::baseUrl()->redirect('network');
899                         //NOTREACHED
900                 } else {
901                         DI::baseUrl()->redirect($return_url);
902                         //NOTREACHED
903                 }
904         }
905 }