]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Merge pull request #8879 from MrPetovan/task/8847-httpsig-quotes
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  * 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\Item as ItemHelper;
33 use Friendica\Content\PageInfo;
34 use Friendica\Content\Text\BBCode;
35 use Friendica\Core\Hook;
36 use Friendica\Core\Logger;
37 use Friendica\Core\Protocol;
38 use Friendica\Core\Renderer;
39 use Friendica\Core\Session;
40 use Friendica\Core\System;
41 use Friendica\Core\Worker;
42 use Friendica\Database\DBA;
43 use Friendica\DI;
44 use Friendica\Model\Attach;
45 use Friendica\Model\Contact;
46 use Friendica\Model\Conversation;
47 use Friendica\Model\FileTag;
48 use Friendica\Model\Item;
49 use Friendica\Model\Notify\Type;
50 use Friendica\Model\Photo;
51 use Friendica\Model\Tag;
52 use Friendica\Network\HTTPException;
53 use Friendica\Object\EMail\ItemCCEMail;
54 use Friendica\Protocol\Activity;
55 use Friendica\Protocol\Diaspora;
56 use Friendica\Util\DateTimeFormat;
57 use Friendica\Util\Security;
58 use Friendica\Util\Strings;
59 use Friendica\Worker\Delivery;
60
61 function item_post(App $a) {
62         if (!Session::isAuthenticated()) {
63                 throw new HTTPException\ForbiddenException();
64         }
65
66         $uid = local_user();
67
68         if (!empty($_REQUEST['dropitems'])) {
69                 $arr_drop = explode(',', $_REQUEST['dropitems']);
70                 foreach ($arr_drop as $item) {
71                         Item::deleteForUser(['id' => $item], $uid);
72                 }
73
74                 $json = ['success' => 1];
75                 System::jsonExit($json);
76         }
77
78         Hook::callAll('post_local_start', $_REQUEST);
79
80         Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
81
82         $api_source = $_REQUEST['api_source'] ?? false;
83
84         $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
85
86         $return_path = $_REQUEST['return'] ?? '';
87         $preview = intval($_REQUEST['preview'] ?? 0);
88
89         /*
90          * Check for doubly-submitted posts, and reject duplicates
91          * Note that we have to ignore previews, otherwise nothing will post
92          * after it's been previewed
93          */
94         if (!$preview && !empty($_REQUEST['post_id_random'])) {
95                 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
96                         Logger::info('item post: duplicate post');
97                         item_post_return(DI::baseUrl(), $api_source, $return_path);
98                 } else {
99                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
100                 }
101         }
102
103         // Is this a reply to something?
104         $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
105         $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
106
107         $toplevel_item = null;
108         $parent_user = null;
109
110         $objecttype = null;
111         $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
112         $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
113
114         if ($toplevel_item_id || $thr_parent_uri) {
115                 if ($toplevel_item_id) {
116                         $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
117                 } elseif ($thr_parent_uri) {
118                         $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
119                 }
120
121                 // if this isn't the top-level parent of the conversation, find it
122                 if (DBA::isResult($toplevel_item)) {
123                         // The URI and the contact is taken from the direct parent which needn't to be the top parent
124                         $thr_parent_uri = $toplevel_item['uri'];
125
126                         if ($toplevel_item['gravity'] != GRAVITY_PARENT) {
127                                 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item['parent']]);
128                         }
129                 }
130
131                 if (!DBA::isResult($toplevel_item)) {
132                         notice(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                 $toplevel_item_id = $toplevel_item['id'];
140                 $parent_user = $toplevel_item['uid'];
141
142                 $objecttype = Activity\ObjectType::COMMENT;
143         }
144
145         if ($toplevel_item_id) {
146                 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
147         }
148
149         $post_id     = intval($_REQUEST['post_id'] ?? 0);
150         $app         = strip_tags($_REQUEST['source'] ?? '');
151         $extid       = strip_tags($_REQUEST['extid'] ?? '');
152         $object      = $_REQUEST['object'] ?? '';
153
154         // Don't use "defaults" here. It would turn 0 to 1
155         if (!isset($_REQUEST['wall'])) {
156                 $wall = 1;
157         } else {
158                 $wall = $_REQUEST['wall'];
159         }
160
161         // Ensure that the user id in a thread always stay the same
162         if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
163                 $profile_uid = $parent_user;
164         }
165
166         // Check for multiple posts with the same message id (when the post was created via API)
167         if (($message_id != '') && ($profile_uid != 0)) {
168                 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
169                         Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
170                         return 0;
171                 }
172         }
173
174         // Allow commenting if it is an answer to a public post
175         $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
176
177         // Now check that valid personal details have been provided
178         if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
179                 notice(DI::l10n()->t('Permission denied.'));
180                 if ($return_path) {
181                         DI::baseUrl()->redirect($return_path);
182                 }
183
184                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
185         }
186
187         // Init post instance
188         $orig_post = null;
189
190         // is this an edited post?
191         if ($post_id > 0) {
192                 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
193         }
194
195         $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
196
197         if (!DBA::isResult($user) && !$toplevel_item_id) {
198                 return 0;
199         }
200
201         $categories = '';
202         $postopts = '';
203         $emailcc = '';
204         $body = $_REQUEST['body'] ?? '';
205         $has_attachment = $_REQUEST['has_attachment'] ?? 0;
206
207         // If we have a speparate attachment, we need to add it to the body.
208         if (!empty($has_attachment)) {
209                 $attachment_type  = $_REQUEST['attachment_type'] ??  '';
210                 $attachment_title = $_REQUEST['attachment_title'] ?? '';
211                 $attachment_text  = $_REQUEST['attachment_text'] ??  '';
212
213                 $attachment_url     = hex2bin($_REQUEST['attachment_url'] ??     '');
214                 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
215
216                 $attachment_img_width  = $_REQUEST['attachment_img_width'] ??  0;
217                 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
218                 $attachment = [
219                         'type'   => $attachment_type,
220                         'title'  => $attachment_title,
221                         'text'   => $attachment_text,
222                         'url'    => $attachment_url,
223                 ];
224
225                 if (!empty($attachment_img_src)) {
226                         $attachment['images'] = [
227                                 0 => [
228                                         'src'    => $attachment_img_src,
229                                         'width'  => $attachment_img_width,
230                                         'height' => $attachment_img_height
231                                 ]
232                         ];
233                 }
234
235                 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
236                 $body .= $att_bbcode;
237         }
238
239         // Convert links with empty descriptions to links without an explicit description
240         $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
241
242         if (!empty($orig_post)) {
243                 $str_group_allow   = $orig_post['allow_gid'];
244                 $str_contact_allow = $orig_post['allow_cid'];
245                 $str_group_deny    = $orig_post['deny_gid'];
246                 $str_contact_deny  = $orig_post['deny_cid'];
247                 $location          = $orig_post['location'];
248                 $coord             = $orig_post['coord'];
249                 $verb              = $orig_post['verb'];
250                 $objecttype        = $orig_post['object-type'];
251                 $app               = $orig_post['app'];
252                 $categories        = $orig_post['file'] ?? '';
253                 $title             = Strings::escapeTags(trim($_REQUEST['title']));
254                 $body              = trim($body);
255                 $private           = $orig_post['private'];
256                 $pubmail_enabled   = $orig_post['pubmail'];
257                 $network           = $orig_post['network'];
258                 $guid              = $orig_post['guid'];
259                 $extid             = $orig_post['extid'];
260         } else {
261                 $str_contact_allow = '';
262                 $str_group_allow   = '';
263                 $str_contact_deny  = '';
264                 $str_group_deny    = '';
265
266                 if (($_REQUEST['visibility'] ?? '') !== 'public') {
267                         $aclFormatter = DI::aclFormatter();
268                         $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
269                         $str_group_allow   = isset($_REQUEST['group_allow'])   ? $aclFormatter->toString($_REQUEST['group_allow'])   : $user['allow_gid'] ?? '';
270                         $str_contact_deny  = isset($_REQUEST['contact_deny'])  ? $aclFormatter->toString($_REQUEST['contact_deny'])  : $user['deny_cid']  ?? '';
271                         $str_group_deny    = isset($_REQUEST['group_deny'])    ? $aclFormatter->toString($_REQUEST['group_deny'])    : $user['deny_gid']  ?? '';
272                 }
273
274                 $title             = Strings::escapeTags(trim($_REQUEST['title']    ?? ''));
275                 $location          = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
276                 $coord             = Strings::escapeTags(trim($_REQUEST['coord']    ?? ''));
277                 $verb              = Strings::escapeTags(trim($_REQUEST['verb']     ?? ''));
278                 $emailcc           = Strings::escapeTags(trim($_REQUEST['emailcc']  ?? ''));
279                 $body              = trim($body);
280                 $network           = Strings::escapeTags(trim(($_REQUEST['network']  ?? '') ?: Protocol::DFRN));
281                 $guid              = System::createUUID();
282
283                 $postopts = $_REQUEST['postopts'] ?? '';
284
285                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
286                         $private = Item::PRIVATE;
287                 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
288                         $private = Item::UNLISTED;
289                 } else {
290                         $private = Item::PUBLIC;
291                 }
292
293                 // If this is a comment, set the permissions from the parent.
294
295                 if ($toplevel_item) {
296                         // for non native networks use the network of the original post as network of the item
297                         if (($toplevel_item['network'] != Protocol::DIASPORA)
298                                 && ($toplevel_item['network'] != Protocol::OSTATUS)
299                                 && ($network == "")) {
300                                 $network = $toplevel_item['network'];
301                         }
302
303                         $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
304                         $str_group_allow   = $toplevel_item['allow_gid'] ?? '';
305                         $str_contact_deny  = $toplevel_item['deny_cid'] ?? '';
306                         $str_group_deny    = $toplevel_item['deny_gid'] ?? '';
307                         $private           = $toplevel_item['private'];
308
309                         $wall              = $toplevel_item['wall'];
310                 }
311
312                 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
313
314                 // if using the API, we won't see pubmail_enable - figure out if it should be set
315                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
316                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
317                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
318                         }
319                 }
320
321                 if (!strlen($body)) {
322                         if ($preview) {
323                                 System::jsonExit(['preview' => '']);
324                         }
325
326                         info(DI::l10n()->t('Empty post discarded.'));
327                         if ($return_path) {
328                                 DI::baseUrl()->redirect($return_path);
329                         }
330
331                         throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
332                 }
333         }
334
335         if (!empty($categories)) {
336                 // get the "fileas" tags for this post
337                 $filedas = FileTag::fileToArray($categories);
338         }
339
340         // save old and new categories, so we can determine what needs to be deleted from pconfig
341         $categories_old = $categories;
342         $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
343         $categories_new = $categories;
344
345         if (!empty($filedas) && is_array($filedas)) {
346                 // append the fileas stuff to the new categories list
347                 $categories .= FileTag::arrayToFile($filedas);
348         }
349
350         // get contact info for poster
351
352         $author = null;
353         $self   = false;
354         $contact_id = 0;
355
356         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
357                 $self = true;
358                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
359         } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
360                 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
361         }
362
363         if (DBA::isResult($author)) {
364                 $contact_id = $author['id'];
365         }
366
367         // get contact info for owner
368         if ($profile_uid == local_user() || $allow_comment) {
369                 $contact_record = $author ?: [];
370         } else {
371                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
372         }
373
374         // Look for any tags and linkify them
375         $inform   = '';
376         $private_forum = false;
377         $private_id = null;
378         $only_to_forum = false;
379         $forum_contact = [];
380
381         $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) use ($profile_uid, $network, $str_contact_allow, &$inform, &$private_forum, &$private_id, &$only_to_forum, &$forum_contact) {
382                 $tags = BBCode::getTags($body);
383
384                 $tagged = [];
385
386                 foreach ($tags as $tag) {
387                         $tag_type = substr($tag, 0, 1);
388
389                         if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
390                                 continue;
391                         }
392
393                         /* If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
394                          * Robert Johnson should be first in the $tags array
395                          */
396                         foreach ($tagged as $nextTag) {
397                                 if (stristr($nextTag, $tag . ' ')) {
398                                         continue 2;
399                                 }
400                         }
401
402                         $success = ItemHelper::replaceTag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
403                         if ($success['replaced']) {
404                                 $tagged[] = $tag;
405                         }
406                         // When the forum is private or the forum is addressed with a "!" make the post private
407                         if (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
408                                 $private_forum = $success['contact']['prv'];
409                                 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
410                                 $private_id = $success['contact']['id'];
411                                 $forum_contact = $success['contact'];
412                         } elseif (!empty($success['contact']['forum']) && ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
413                                 $private_forum = false;
414                                 $only_to_forum = true;
415                                 $private_id = $success['contact']['id'];
416                                 $forum_contact = $success['contact'];
417                         }
418                 }
419
420                 return $body;
421         });
422
423         $original_contact_id = $contact_id;
424
425         if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
426                 // we tagged a forum in a top level post. Now we change the post
427                 $private = $private_forum;
428
429                 $str_group_allow = '';
430                 $str_contact_deny = '';
431                 $str_group_deny = '';
432                 if ($private_forum) {
433                         $str_contact_allow = '<' . $private_id . '>';
434                 } else {
435                         $str_contact_allow = '';
436                 }
437                 $contact_id = $private_id;
438                 $contact_record = $forum_contact;
439                 $_REQUEST['origin'] = false;
440                 $wall = 0;
441         }
442
443         /*
444          * When a photo was uploaded into the message using the (profile wall) ajax
445          * uploader, The permissions are initially set to disallow anybody but the
446          * owner from seeing it. This is because the permissions may not yet have been
447          * set for the post. If it's private, the photo permissions should be set
448          * appropriately. But we didn't know the final permissions on the post until
449          * now. So now we'll look for links of uploaded messages that are in the
450          * post and set them to the same permissions as the post itself.
451          */
452
453         $match = null;
454
455         if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
456                 $objecttype = Activity\ObjectType::IMAGE;
457         }
458
459         /*
460          * Next link in any attachment references we find in the post.
461          */
462         $match = false;
463
464         /// @todo these lines should be moved to Model/Attach (Once it exists)
465         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
466                 $attaches = $match[1];
467                 if (count($attaches)) {
468                         foreach ($attaches as $attach) {
469                                 // Ensure to only modify attachments that you own
470                                 $srch = '<' . intval($original_contact_id) . '>';
471
472                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
473                                                 'id' => $attach];
474                                 if (!Attach::exists($condition)) {
475                                         continue;
476                                 }
477
478                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
479                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
480                                 $condition = ['id' => $attach];
481                                 Attach::update($fields, $condition);
482                         }
483                 }
484         }
485
486         // embedded bookmark or attachment in post? set bookmark flag
487
488         $data = BBCode::getAttachmentData($body);
489         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
490                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
491                 $posttype = Item::PT_PAGE;
492                 $objecttype =  Activity\ObjectType::BOOKMARK;
493         }
494
495         $body = DI::bbCodeVideo()->transform($body);
496
497         $body = BBCode::scaleExternalImages($body);
498
499         // Setting the object type if not defined before
500         if (!$objecttype) {
501                 $objecttype = Activity\ObjectType::NOTE; // Default value
502                 $objectdata = BBCode::getAttachedData($body);
503
504                 if ($objectdata["type"] == "link") {
505                         $objecttype = Activity\ObjectType::BOOKMARK;
506                 } elseif ($objectdata["type"] == "video") {
507                         $objecttype = Activity\ObjectType::VIDEO;
508                 } elseif ($objectdata["type"] == "photo") {
509                         $objecttype = Activity\ObjectType::IMAGE;
510                 }
511
512         }
513
514         $attachments = '';
515         $match = false;
516
517         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
518                 foreach ($match[2] as $mtch) {
519                         $fields = ['id', 'filename', 'filesize', 'filetype'];
520                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
521                         if ($attachment !== false) {
522                                 if (strlen($attachments)) {
523                                         $attachments .= ',';
524                                 }
525                                 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
526                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
527                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
528                         }
529                         $body = str_replace($match[1],'',$body);
530                 }
531         }
532
533         if (!strlen($verb)) {
534                 $verb = Activity::POST;
535         }
536
537         if ($network == "") {
538                 $network = Protocol::DFRN;
539         }
540
541         $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
542
543         // even if the post arrived via API we are considering that it
544         // originated on this site by default for determining relayability.
545
546         // Don't use "defaults" here. It would turn 0 to 1
547         if (!isset($_REQUEST['origin'])) {
548                 $origin = 1;
549         } else {
550                 $origin = $_REQUEST['origin'];
551         }
552
553         $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
554
555         // Fallback so that we alway have a parent uri
556         if (!$thr_parent_uri || !$toplevel_item_id) {
557                 $thr_parent_uri = $uri;
558         }
559
560         $datarray = [];
561         $datarray['uid']           = $profile_uid;
562         $datarray['wall']          = $wall;
563         $datarray['gravity']       = $gravity;
564         $datarray['network']       = $network;
565         $datarray['contact-id']    = $contact_id;
566         $datarray['owner-name']    = $contact_record['name'] ?? '';
567         $datarray['owner-link']    = $contact_record['url'] ?? '';
568         $datarray['owner-avatar']  = $contact_record['thumb'] ?? '';
569         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
570         $datarray['author-name']   = $author['name'];
571         $datarray['author-link']   = $author['url'];
572         $datarray['author-avatar'] = $author['thumb'];
573         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
574         $datarray['created']       = DateTimeFormat::utcNow();
575         $datarray['edited']        = DateTimeFormat::utcNow();
576         $datarray['commented']     = DateTimeFormat::utcNow();
577         $datarray['received']      = DateTimeFormat::utcNow();
578         $datarray['changed']       = DateTimeFormat::utcNow();
579         $datarray['extid']         = $extid;
580         $datarray['guid']          = $guid;
581         $datarray['uri']           = $uri;
582         $datarray['title']         = $title;
583         $datarray['body']          = $body;
584         $datarray['app']           = $app;
585         $datarray['location']      = $location;
586         $datarray['coord']         = $coord;
587         $datarray['file']          = $categories;
588         $datarray['inform']        = $inform;
589         $datarray['verb']          = $verb;
590         $datarray['post-type']     = $posttype;
591         $datarray['object-type']   = $objecttype;
592         $datarray['allow_cid']     = $str_contact_allow;
593         $datarray['allow_gid']     = $str_group_allow;
594         $datarray['deny_cid']      = $str_contact_deny;
595         $datarray['deny_gid']      = $str_group_deny;
596         $datarray['private']       = $private;
597         $datarray['pubmail']       = $pubmail_enabled;
598         $datarray['attach']        = $attachments;
599
600         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
601         $datarray['parent-uri']    = $thr_parent_uri;
602
603         $datarray['postopts']      = $postopts;
604         $datarray['origin']        = $origin;
605         $datarray['moderated']     = false;
606         $datarray['object']        = $object;
607
608         /*
609          * These fields are for the convenience of addons...
610          * 'self' if true indicates the owner is posting on their own wall
611          * If parent is 0 it is a top-level post.
612          */
613         $datarray['parent']        = $toplevel_item_id;
614         $datarray['self']          = $self;
615
616         // This triggers posts via API and the mirror functions
617         $datarray['api_source'] = $api_source;
618
619         // This field is for storing the raw conversation data
620         $datarray['protocol'] = Conversation::PARCEL_DFRN;
621
622         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
623         if (DBA::isResult($conversation)) {
624                 if ($conversation['conversation-uri'] != '') {
625                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
626                 }
627                 if ($conversation['conversation-href'] != '') {
628                         $datarray['conversation-href'] = $conversation['conversation-href'];
629                 }
630         }
631
632         if ($orig_post) {
633                 $datarray['edit'] = true;
634         } else {
635                 // If this was a share, add missing data here
636                 $datarray = Item::addShareDataFromOriginal($datarray);
637
638                 $datarray['edit'] = false;
639         }
640
641         // Check for hashtags in the body and repair or add hashtag links
642         if ($preview || $orig_post) {
643                 $datarray['body'] = Item::setHashtags($datarray['body']);
644         }
645
646         // preview mode - prepare the body for display and send it via json
647         if ($preview) {
648                 // We set the datarray ID to -1 because in preview mode the dataray
649                 // doesn't have an ID.
650                 $datarray["id"] = -1;
651                 $datarray["uri-id"] = -1;
652                 $datarray["item_id"] = -1;
653                 $datarray["author-network"] = Protocol::DFRN;
654
655                 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
656
657                 System::jsonExit(['preview' => $o]);
658         }
659
660         Hook::callAll('post_local',$datarray);
661
662         if (!empty($datarray['cancel'])) {
663                 Logger::info('mod_item: post cancelled by addon.');
664                 if ($return_path) {
665                         DI::baseUrl()->redirect($return_path);
666                 }
667
668                 $json = ['cancel' => 1];
669                 if (!empty($_REQUEST['jsreload'])) {
670                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
671                 }
672
673                 System::jsonExit($json);
674         }
675
676         if ($orig_post) {
677                 // Fill the cache field
678                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
679                 Item::putInCache($datarray);
680
681                 $fields = [
682                         'title' => $datarray['title'],
683                         'body' => $datarray['body'],
684                         'attach' => $datarray['attach'],
685                         'file' => $datarray['file'],
686                         'rendered-html' => $datarray['rendered-html'],
687                         'rendered-hash' => $datarray['rendered-hash'],
688                         'edited' => DateTimeFormat::utcNow(),
689                         'changed' => DateTimeFormat::utcNow()];
690
691                 Item::update($fields, ['id' => $post_id]);
692
693                 // update filetags in pconfig
694                 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
695
696                 info(DI::l10n()->t('Post updated.'));
697                 if ($return_path) {
698                         DI::baseUrl()->redirect($return_path);
699                 }
700
701                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
702         }
703
704         unset($datarray['edit']);
705         unset($datarray['self']);
706         unset($datarray['api_source']);
707
708         if ($origin) {
709                 $signed = Diaspora::createCommentSignature($uid, $datarray);
710                 if (!empty($signed)) {
711                         $datarray['diaspora_signed_text'] = json_encode($signed);
712                 }
713         }
714
715         $post_id = Item::insert($datarray);
716
717         if (!$post_id) {
718                 info(DI::l10n()->t('Item wasn\'t stored.'));
719                 if ($return_path) {
720                         DI::baseUrl()->redirect($return_path);
721                 }
722
723                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
724         }
725
726         $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
727
728         if (!DBA::isResult($datarray)) {
729                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
730                 if ($return_path) {
731                         DI::baseUrl()->redirect($return_path);
732                 }
733
734                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
735         }
736
737         Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
738
739         if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
740                 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
741         }
742
743         // update filetags in pconfig
744         FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
745
746         // These notifications are sent if someone else is commenting other your wall
747         if ($contact_record != $author) {
748                 if ($toplevel_item_id) {
749                         notification([
750                                 'type'         => Type::COMMENT,
751                                 'notify_flags' => $user['notify-flags'],
752                                 'language'     => $user['language'],
753                                 'to_name'      => $user['username'],
754                                 'to_email'     => $user['email'],
755                                 'uid'          => $user['uid'],
756                                 'item'         => $datarray,
757                                 'link'         => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
758                                 'source_name'  => $datarray['author-name'],
759                                 'source_link'  => $datarray['author-link'],
760                                 'source_photo' => $datarray['author-avatar'],
761                                 'verb'         => Activity::POST,
762                                 'otype'        => 'item',
763                                 'parent'       => $toplevel_item_id,
764                                 'parent_uri'   => $toplevel_item['uri']
765                         ]);
766                 } elseif (empty($forum_contact)) {
767                         notification([
768                                 'type'         => Type::WALL,
769                                 'notify_flags' => $user['notify-flags'],
770                                 'language'     => $user['language'],
771                                 'to_name'      => $user['username'],
772                                 'to_email'     => $user['email'],
773                                 'uid'          => $user['uid'],
774                                 'item'         => $datarray,
775                                 'link'         => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
776                                 'source_name'  => $datarray['author-name'],
777                                 'source_link'  => $datarray['author-link'],
778                                 'source_photo' => $datarray['author-avatar'],
779                                 'verb'         => Activity::POST,
780                                 'otype'        => 'item'
781                         ]);
782                 }
783         }
784
785         Hook::callAll('post_local_end', $datarray);
786
787         if (strlen($emailcc) && $profile_uid == local_user()) {
788                 $recipients = explode(',', $emailcc);
789                 if (count($recipients)) {
790                         foreach ($recipients as $recipient) {
791                                 $address = trim($recipient);
792                                 if (!strlen($address)) {
793                                         continue;
794                                 }
795                                 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
796                                         $datarray, $address, $author['thumb'] ?? ''));
797                         }
798                 }
799         }
800
801         // Insert an item entry for UID=0 for global entries.
802         // We now do it in the background to save some time.
803         // This is important in interactive environments like the frontend or the API.
804         // We don't fork a new process since this is done anyway with the following command
805         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
806
807         // When we are doing some forum posting via ! we have to start the notifier manually.
808         // These kind of posts don't initiate the notifier call in the item class.
809         if ($only_to_forum) {
810                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
811         }
812
813         Logger::info('post_complete');
814
815         if ($api_source) {
816                 return $post_id;
817         }
818
819         info(DI::l10n()->t('Post published.'));
820         item_post_return(DI::baseUrl(), $api_source, $return_path);
821         // NOTREACHED
822 }
823
824 function item_post_return($baseurl, $api_source, $return_path)
825 {
826         if ($api_source) {
827                 return;
828         }
829
830         if ($return_path) {
831                 DI::baseUrl()->redirect($return_path);
832         }
833
834         $json = ['success' => 1];
835         if (!empty($_REQUEST['jsreload'])) {
836                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
837         }
838
839         Logger::info('post_json', ['json' => $json]);
840
841         System::jsonExit($json);
842 }
843
844 function item_content(App $a)
845 {
846         if (!Session::isAuthenticated()) {
847                 return;
848         }
849
850         $o = '';
851
852         if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
853                 if (DI::mode()->isAjax()) {
854                         Item::deleteForUser(['id' => $a->argv[2]], local_user());
855                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
856                         System::jsonExit([intval($a->argv[2]), local_user()]);
857                 } else {
858                         if (!empty($a->argv[3])) {
859                                 $o = drop_item($a->argv[2], $a->argv[3]);
860                         }
861                         else {
862                                 $o = drop_item($a->argv[2]);
863                         }
864                 }
865         }
866
867         return $o;
868 }
869
870 /**
871  * @param int    $id
872  * @param string $return
873  * @return string
874  * @throws HTTPException\InternalServerErrorException
875  */
876 function drop_item(int $id, string $return = '')
877 {
878         // locate item to be deleted
879         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
880         $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
881
882         if (!DBA::isResult($item)) {
883                 notice(DI::l10n()->t('Item not found.') . EOL);
884                 DI::baseUrl()->redirect('network');
885         }
886
887         if ($item['deleted']) {
888                 return '';
889         }
890
891         $contact_id = 0;
892
893         // check if logged in user is either the author or owner of this item
894         if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
895                 $contact_id = $item['contact-id'];
896         }
897
898         if ((local_user() == $item['uid']) || $contact_id) {
899                 // Check if we should do HTML-based delete confirmation
900                 if (!empty($_REQUEST['confirm'])) {
901                         // <form> can't take arguments in its "action" parameter
902                         // so add any arguments as hidden inputs
903                         $query = explode_querystring(DI::args()->getQueryString());
904                         $inputs = [];
905
906                         foreach ($query['args'] as $arg) {
907                                 if (strpos($arg, 'confirm=') === false) {
908                                         $arg_parts = explode('=', $arg);
909                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
910                                 }
911                         }
912
913                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
914                                 '$method' => 'get',
915                                 '$message' => DI::l10n()->t('Do you really want to delete this item?'),
916                                 '$extra_inputs' => $inputs,
917                                 '$confirm' => DI::l10n()->t('Yes'),
918                                 '$confirm_url' => $query['base'],
919                                 '$confirm_name' => 'confirmed',
920                                 '$cancel' => DI::l10n()->t('Cancel'),
921                         ]);
922                 }
923                 // Now check how the user responded to the confirmation query
924                 if (!empty($_REQUEST['canceled'])) {
925                         DI::baseUrl()->redirect('display/' . $item['guid']);
926                 }
927
928                 $is_comment = $item['gravity'] == GRAVITY_COMMENT;
929                 $parentitem = null;
930                 if (!empty($item['parent'])) {
931                         $fields = ['guid'];
932                         $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
933                 }
934
935                 // delete the item
936                 Item::deleteForUser(['id' => $item['id']], local_user());
937
938                 $return_url = hex2bin($return);
939
940                 // removes update_* from return_url to ignore Ajax refresh
941                 $return_url = str_replace("update_", "", $return_url);
942
943                 // Check if delete a comment
944                 if ($is_comment) {
945                         // Return to parent guid
946                         if (!empty($parentitem)) {
947                                 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
948                                 //NOTREACHED
949                         } // In case something goes wrong
950                         else {
951                                 DI::baseUrl()->redirect('network');
952                                 //NOTREACHED
953                         }
954                 } else {
955                         // if unknown location or deleting top level post called from display
956                         if (empty($return_url) || strpos($return_url, 'display') !== false) {
957                                 DI::baseUrl()->redirect('network');
958                                 //NOTREACHED
959                         } else {
960                                 DI::baseUrl()->redirect($return_url);
961                                 //NOTREACHED
962                         }
963                 }
964         } else {
965                 notice(DI::l10n()->t('Permission denied.'));
966                 DI::baseUrl()->redirect('display/' . $item['guid']);
967                 //NOTREACHED
968         }
969
970         return '';
971 }