]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Replace "notice" calls
[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 = local_user();
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) ?: local_user();
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'] != 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'], local_user(), ['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, [local_user(), 0])) {
173                 $profile_uid = $toplevel_user_id;
174         }
175
176         // Allow commenting if it is an answer to a public post
177         $allow_comment = local_user() && $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' => local_user(), '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 == local_user() && !$private) {
328                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
329                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
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 (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
367                 $self = true;
368                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), '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 == local_user() || $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'       => local_user() ? local_user() : $profile_uid,
389                         'gravity'   => $toplevel_item_id ? GRAVITY_COMMENT : 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 ? GRAVITY_COMMENT : 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         $datarray['uid']           = $profile_uid;
538         $datarray['wall']          = $wall;
539         $datarray['gravity']       = $gravity;
540         $datarray['network']       = $network;
541         $datarray['contact-id']    = $contact_id;
542         $datarray['owner-name']    = $contact_record['name'] ?? '';
543         $datarray['owner-link']    = $contact_record['url'] ?? '';
544         $datarray['owner-avatar']  = $contact_record['thumb'] ?? '';
545         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
546         $datarray['author-name']   = $author['name'];
547         $datarray['author-link']   = $author['url'];
548         $datarray['author-avatar'] = $author['thumb'];
549         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
550         $datarray['created']       = empty($_REQUEST['created_at']) ? DateTimeFormat::utcNow() : $_REQUEST['created_at'];
551         $datarray['edited']        = $datarray['created'];
552         $datarray['commented']     = $datarray['created'];
553         $datarray['changed']       = $datarray['created'];
554         $datarray['received']      = DateTimeFormat::utcNow();
555         $datarray['extid']         = $extid;
556         $datarray['guid']          = $guid;
557         $datarray['uri']           = $uri;
558         $datarray['title']         = $title;
559         $datarray['body']          = $body;
560         $datarray['app']           = $app;
561         $datarray['location']      = $location;
562         $datarray['coord']         = $coord;
563         $datarray['file']          = $categories;
564         $datarray['inform']        = $inform;
565         $datarray['verb']          = $verb;
566         $datarray['post-type']     = $posttype;
567         $datarray['object-type']   = $objecttype;
568         $datarray['allow_cid']     = $str_contact_allow;
569         $datarray['allow_gid']     = $str_group_allow;
570         $datarray['deny_cid']      = $str_contact_deny;
571         $datarray['deny_gid']      = $str_group_deny;
572         $datarray['private']       = $private;
573         $datarray['pubmail']       = $pubmail_enabled;
574         $datarray['attach']        = $attachments;
575
576         $datarray['thr-parent']    = $thr_parent_uri;
577
578         $datarray['postopts']      = $postopts;
579         $datarray['origin']        = $origin;
580         $datarray['object']        = $object;
581
582         $datarray['attachments']   = $_REQUEST['attachments'] ?? [];
583
584         /*
585          * These fields are for the convenience of addons...
586          * 'self' if true indicates the owner is posting on their own wall
587          * If parent is 0 it is a top-level post.
588          */
589         $datarray['parent']        = $toplevel_item_id;
590         $datarray['self']          = $self;
591
592         // This triggers posts via API and the mirror functions
593         $datarray['api_source'] = $api_source;
594
595         // This field is for storing the raw conversation data
596         $datarray['protocol'] = Conversation::PARCEL_DIRECT;
597         $datarray['direction'] = Conversation::PUSH;
598
599         $datarray['edit'] = $orig_post;
600
601         // Check for hashtags in the body and repair or add hashtag links
602         if ($preview || $orig_post) {
603                 $datarray['body'] = Item::setHashtags($datarray['body']);
604         }
605
606         // preview mode - prepare the body for display and send it via json
607         if ($preview) {
608                 // We set the datarray ID to -1 because in preview mode the dataray
609                 // doesn't have an ID.
610                 $datarray["id"] = -1;
611                 $datarray["uri-id"] = -1;
612                 $datarray["author-network"] = Protocol::DFRN;
613                 $datarray["author-updated"] = '';
614                 $datarray["author-gsid"] = 0;
615                 $datarray["author-uri-id"] = ItemURI::getIdByURI($datarray["author-link"]);
616                 $datarray["owner-updated"] = '';
617                 $datarray["has-media"] = false;
618                 $datarray['body'] = Item::improveSharedDataInBody($datarray);
619
620                 $o = DI::conversation()->create([array_merge($contact_record, $datarray)], 'search', false, true);
621
622                 System::jsonExit(['preview' => $o]);
623         }
624
625         Hook::callAll('post_local',$datarray);
626
627         if (!empty($_REQUEST['scheduled_at'])) {
628                 $scheduled_at = DateTimeFormat::convert($_REQUEST['scheduled_at'], 'UTC', $a->getTimeZone());
629                 if ($scheduled_at > DateTimeFormat::utcNow()) {
630                         unset($datarray['created']);
631                         unset($datarray['edited']);
632                         unset($datarray['commented']);
633                         unset($datarray['received']);
634                         unset($datarray['changed']);
635                         unset($datarray['edit']);
636                         unset($datarray['self']);
637                         unset($datarray['api_source']);
638
639                         Post\Delayed::add($datarray['uri'], $datarray, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
640                         item_post_return(DI::baseUrl(), $api_source, $return_path);
641                 }
642         }
643
644         if (!empty($datarray['cancel'])) {
645                 Logger::info('mod_item: post cancelled by addon.');
646                 if ($return_path) {
647                         DI::baseUrl()->redirect($return_path);
648                 }
649
650                 $json = ['cancel' => 1];
651                 if (!empty($_REQUEST['jsreload'])) {
652                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
653                 }
654
655                 System::jsonExit($json);
656         }
657
658         $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
659         $datarray['body']   = Item::improveSharedDataInBody($datarray);
660
661         if ($orig_post) {
662                 $fields = [
663                         'title' => $datarray['title'],
664                         'body' => $datarray['body'],
665                         'attach' => $datarray['attach'],
666                         'file' => $datarray['file'],
667                         'edited' => DateTimeFormat::utcNow(),
668                         'changed' => DateTimeFormat::utcNow()
669                 ];
670
671                 Item::update($fields, ['id' => $post_id]);
672                 Item::updateDisplayCache($datarray['uri-id']);
673
674                 if ($return_path) {
675                         DI::baseUrl()->redirect($return_path);
676                 }
677
678                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
679         }
680
681         unset($datarray['edit']);
682         unset($datarray['self']);
683         unset($datarray['api_source']);
684
685         $post_id = Item::insert($datarray);
686
687         if (!$post_id) {
688                 DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.'));
689                 if ($return_path) {
690                         DI::baseUrl()->redirect($return_path);
691                 }
692
693                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
694         }
695
696         $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
697
698         if (!DBA::isResult($datarray)) {
699                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
700                 if ($return_path) {
701                         DI::baseUrl()->redirect($return_path);
702                 }
703
704                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
705         }
706
707         Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
708
709         if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
710                 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
711         }
712
713         // These notifications are sent if someone else is commenting other your wall
714         if ($contact_record != $author) {
715                 if ($toplevel_item_id) {
716                         DI::notify()->createFromArray([
717                                 'type'  => Notification\Type::COMMENT,
718                                 'otype' => Notification\ObjectType::ITEM,
719                                 'verb'  => Activity::POST,
720                                 'uid'   => $profile_uid,
721                                 'cid'   => $datarray['author-id'],
722                                 'item'  => $datarray,
723                                 'link'  => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
724                         ]);
725                 } elseif (empty($forum_contact)) {
726                         DI::notify()->createFromArray([
727                                 'type'  => Notification\Type::WALL,
728                                 'otype' => Notification\ObjectType::ITEM,
729                                 'verb'  => Activity::POST,
730                                 'uid'   => $profile_uid,
731                                 'cid'   => $datarray['author-id'],
732                                 'item'  => $datarray,
733                                 'link'  => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
734                         ]);
735                 }
736         }
737
738         Hook::callAll('post_local_end', $datarray);
739
740         if (strlen($emailcc) && $profile_uid == local_user()) {
741                 $recipients = explode(',', $emailcc);
742                 if (count($recipients)) {
743                         foreach ($recipients as $recipient) {
744                                 $address = trim($recipient);
745                                 if (!strlen($address)) {
746                                         continue;
747                                 }
748                                 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
749                                         $datarray, $address, $author['thumb'] ?? ''));
750                         }
751                 }
752         }
753
754         Logger::debug('post_complete');
755
756         if ($api_source) {
757                 return $post_id;
758         }
759
760         item_post_return(DI::baseUrl(), $api_source, $return_path);
761         // NOTREACHED
762 }
763
764 function item_post_return($baseurl, $api_source, $return_path)
765 {
766         if ($api_source) {
767                 return;
768         }
769
770         if ($return_path) {
771                 DI::baseUrl()->redirect($return_path);
772         }
773
774         $json = ['success' => 1];
775         if (!empty($_REQUEST['jsreload'])) {
776                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
777         }
778
779         Logger::debug('post_json', ['json' => $json]);
780
781         System::jsonExit($json);
782 }
783
784 function item_content(App $a)
785 {
786         if (!Session::isAuthenticated()) {
787                 throw new HTTPException\UnauthorizedException();
788         }
789
790         $args = DI::args();
791
792         if (!$args->has(3)) {
793                 throw new HTTPException\BadRequestException();
794         }
795
796         $o = '';
797         switch ($args->get(1)) {
798                 case 'drop':
799                         if (DI::mode()->isAjax()) {
800                                 Item::deleteForUser(['id' => $args->get(2)], local_user());
801                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
802                                 System::jsonExit([intval($args->get(2)), local_user()]);
803                         } else {
804                                 if (!empty($args->get(3))) {
805                                         $o = drop_item($args->get(2), $args->get(3));
806                                 } else {
807                                         $o = drop_item($args->get(2));
808                                 }
809                         }
810                         break;
811                 case 'block':
812                         $item = Post::selectFirstForUser(local_user(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
813                         if (empty($item['author-id'])) {
814                                 throw new HTTPException\NotFoundException('Item not found');
815                         }
816
817                         Contact\User::setBlocked($item['author-id'], local_user(), true);
818
819                         if (DI::mode()->isAjax()) {
820                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
821                                 System::jsonExit([intval($args->get(2)), local_user()]);
822                         } else {
823                                 item_redirect_after_action($item, $args->get(3));
824                         }
825                         break;
826         }
827
828         return $o;
829 }
830
831 /**
832  * @param int    $id
833  * @param string $return
834  * @return string
835  * @throws HTTPException\InternalServerErrorException
836  */
837 function drop_item(int $id, string $return = '')
838 {
839         // locate item to be deleted
840         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
841         $item = Post::selectFirstForUser(local_user(), $fields, ['id' => $id]);
842
843         if (!DBA::isResult($item)) {
844                 DI::sysmsg()->addNotice(DI::l10n()->t('Item not found.'));
845                 DI::baseUrl()->redirect('network');
846         }
847
848         if ($item['deleted']) {
849                 return '';
850         }
851
852         $contact_id = 0;
853
854         // check if logged in user is either the author or owner of this item
855         if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
856                 $contact_id = $item['contact-id'];
857         }
858
859         if ((local_user() == $item['uid']) || $contact_id) {
860                 // delete the item
861                 Item::deleteForUser(['id' => $item['id']], local_user());
862
863                 item_redirect_after_action($item, $return);
864         } else {
865                 Logger::warning('Permission denied.', ['local' => local_user(), 'uid' => $item['uid'], 'cid' => $contact_id]);
866                 DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
867                 DI::baseUrl()->redirect('display/' . $item['guid']);
868                 //NOTREACHED
869         }
870
871         return '';
872 }
873
874 function item_redirect_after_action($item, $returnUrlHex)
875 {
876         $return_url = hex2bin($returnUrlHex);
877
878         // removes update_* from return_url to ignore Ajax refresh
879         $return_url = str_replace("update_", "", $return_url);
880
881         // Check if delete a comment
882         if ($item['gravity'] == GRAVITY_COMMENT) {
883                 if (!empty($item['parent'])) {
884                         $parentitem = Post::selectFirstForUser(local_user(), ['guid'], ['id' => $item['parent']]);
885                 }
886
887                 // Return to parent guid
888                 if (!empty($parentitem)) {
889                         DI::baseUrl()->redirect('display/' . $parentitem['guid']);
890                         //NOTREACHED
891                 } // In case something goes wrong
892                 else {
893                         DI::baseUrl()->redirect('network');
894                         //NOTREACHED
895                 }
896         } else {
897                 // if unknown location or deleting top level post called from display
898                 if (empty($return_url) || strpos($return_url, 'display') !== false) {
899                         DI::baseUrl()->redirect('network');
900                         //NOTREACHED
901                 } else {
902                         DI::baseUrl()->redirect($return_url);
903                         //NOTREACHED
904                 }
905         }
906 }