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