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