]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Check the existence of the `uid` field before accessing it in Module\Photo
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  * This is the POST destination for most all locally posted
21  * text stuff. This function handles status, wall-to-wall status,
22  * local comments, and remote coments that are posted on this site
23  * (as opposed to being delivered in a feed).
24  * Also processed here are posts and comments coming through the
25  * statusnet/twitter API.
26  *
27  * All of these become an "item" which is our basic unit of
28  * information.
29  */
30
31 use Friendica\App;
32 use Friendica\Content\PageInfo;
33 use Friendica\Content\Text\BBCode;
34 use Friendica\Core\Hook;
35 use Friendica\Core\Logger;
36 use Friendica\Core\Protocol;
37 use Friendica\Core\Session;
38 use Friendica\Core\System;
39 use Friendica\Core\Worker;
40 use Friendica\Database\DBA;
41 use Friendica\DI;
42 use Friendica\Model\Attach;
43 use Friendica\Model\Contact;
44 use Friendica\Model\Conversation;
45 use Friendica\Model\FileTag;
46 use Friendica\Model\Group;
47 use Friendica\Model\Item;
48 use Friendica\Model\ItemURI;
49 use Friendica\Model\Notification;
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\Security\Security;
58 use Friendica\Util\DateTimeFormat;
59 use Friendica\Util\ParseUrl;
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 = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item_id]);
118                 } elseif ($thr_parent_uri) {
119                         $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['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 = Post::selectFirst(Item::ITEM_FIELDLIST, ['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 = Post::selectFirst(Item::ITEM_FIELDLIST, ['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() && $toplevel_item_id && in_array($toplevel_item['private'], [Item::PUBLIC, Item::UNLISTED]) && 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                 Logger::notice('Permission denied.', ['local' => local_user(), 'profile_uid' => $profile_uid, 'toplevel_item_id' => $toplevel_item_id, 'network' => $toplevel_item['network']]);
184                 notice(DI::l10n()->t('Permission denied.'));
185                 if ($return_path) {
186                         DI::baseUrl()->redirect($return_path);
187                 }
188
189                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
190         }
191
192         // Init post instance
193         $orig_post = null;
194
195         // is this an edited post?
196         if ($post_id > 0) {
197                 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
198         }
199
200         $user = User::getById($profile_uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
201         if (!DBA::isResult($user) && !$toplevel_item_id) {
202                 return 0;
203         }
204
205         $categories = '';
206         $postopts = '';
207         $emailcc = '';
208         $body = $_REQUEST['body'] ?? '';
209         $has_attachment = $_REQUEST['has_attachment'] ?? 0;
210
211         // If we have a speparate attachment, we need to add it to the body.
212         if (!empty($has_attachment)) {
213                 $attachment_type  = $_REQUEST['attachment_type'] ??  '';
214                 $attachment_title = $_REQUEST['attachment_title'] ?? '';
215                 $attachment_text  = $_REQUEST['attachment_text'] ??  '';
216
217                 $attachment_url     = hex2bin($_REQUEST['attachment_url'] ??     '');
218                 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
219
220                 $attachment_img_width  = $_REQUEST['attachment_img_width'] ??  0;
221                 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
222
223                 // Fetch the basic attachment data
224                 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
225                 unset($attachment['keywords']);
226
227                 // Overwrite the basic data with possible changes from the frontend
228                 $attachment['type'] = $attachment_type;
229                 $attachment['title'] = $attachment_title;
230                 $attachment['text'] = $attachment_text;
231                 $attachment['url'] = $attachment_url;
232
233                 if (!empty($attachment_img_src)) {
234                         $attachment['images'] = [
235                                 0 => [
236                                         'src'    => $attachment_img_src,
237                                         'width'  => $attachment_img_width,
238                                         'height' => $attachment_img_height
239                                 ]
240                         ];
241                 } else {
242                         unset($attachment['images']);
243                 }
244
245                 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
246                 $body .= $att_bbcode;
247         }
248
249         // Convert links with empty descriptions to links without an explicit description
250         $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
251
252         if (!empty($orig_post)) {
253                 $str_group_allow   = $orig_post['allow_gid'];
254                 $str_contact_allow = $orig_post['allow_cid'];
255                 $str_group_deny    = $orig_post['deny_gid'];
256                 $str_contact_deny  = $orig_post['deny_cid'];
257                 $location          = $orig_post['location'];
258                 $coord             = $orig_post['coord'];
259                 $verb              = $orig_post['verb'];
260                 $objecttype        = $orig_post['object-type'];
261                 $app               = $orig_post['app'];
262                 $categories        = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']);
263                 $title             = trim($_REQUEST['title'] ?? '');
264                 $body              = trim($body);
265                 $private           = $orig_post['private'];
266                 $pubmail_enabled   = $orig_post['pubmail'];
267                 $network           = $orig_post['network'];
268                 $guid              = $orig_post['guid'];
269                 $extid             = $orig_post['extid'];
270         } else {
271                 $aclFormatter = DI::aclFormatter();
272                 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
273                 $str_group_allow   = isset($_REQUEST['group_allow'])   ? $aclFormatter->toString($_REQUEST['group_allow'])   : $user['allow_gid'] ?? '';
274                 $str_contact_deny  = isset($_REQUEST['contact_deny'])  ? $aclFormatter->toString($_REQUEST['contact_deny'])  : $user['deny_cid']  ?? '';
275                 $str_group_deny    = isset($_REQUEST['group_deny'])    ? $aclFormatter->toString($_REQUEST['group_deny'])    : $user['deny_gid']  ?? '';
276
277                 $visibility = $_REQUEST['visibility'] ?? '';
278                 if ($visibility === 'public') {
279                         // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
280                         $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
281                 } else if ($visibility === 'custom') {
282                         // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
283                         // case that would make it public. So we always append the author's contact id to the allowed contacts.
284                         // See https://github.com/friendica/friendica/issues/9672
285                         $str_contact_allow .= $aclFormatter->toString(Contact::getPublicIdByUserId($uid));
286                 }
287
288                 $title             = trim($_REQUEST['title']    ?? '');
289                 $location          = trim($_REQUEST['location'] ?? '');
290                 $coord             = trim($_REQUEST['coord']    ?? '');
291                 $verb              = trim($_REQUEST['verb']     ?? '');
292                 $emailcc           = trim($_REQUEST['emailcc']  ?? '');
293                 $body              = trim($body);
294                 $network           = trim(($_REQUEST['network']  ?? '') ?: Protocol::DFRN);
295                 $guid              = System::createUUID();
296
297                 $postopts = $_REQUEST['postopts'] ?? '';
298
299                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
300                         $private = Item::PRIVATE;
301                 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
302                         $private = Item::UNLISTED;
303                 } else {
304                         $private = Item::PUBLIC;
305                 }
306
307                 // If this is a comment, set the permissions from the parent.
308
309                 if ($toplevel_item) {
310                         // for non native networks use the network of the original post as network of the item
311                         if (($toplevel_item['network'] != Protocol::DIASPORA)
312                                 && ($toplevel_item['network'] != Protocol::OSTATUS)
313                                 && ($network == "")) {
314                                 $network = $toplevel_item['network'];
315                         }
316
317                         $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
318                         $str_group_allow   = $toplevel_item['allow_gid'] ?? '';
319                         $str_contact_deny  = $toplevel_item['deny_cid'] ?? '';
320                         $str_group_deny    = $toplevel_item['deny_gid'] ?? '';
321                         $private           = $toplevel_item['private'];
322
323                         $wall              = $toplevel_item['wall'];
324                 }
325
326                 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
327
328                 // if using the API, we won't see pubmail_enable - figure out if it should be set
329                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
330                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
331                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
332                         }
333                 }
334
335                 if (!strlen($body)) {
336                         if ($preview) {
337                                 System::jsonExit(['preview' => '']);
338                         }
339
340                         notice(DI::l10n()->t('Empty post discarded.'));
341                         if ($return_path) {
342                                 DI::baseUrl()->redirect($return_path);
343                         }
344
345                         throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
346                 }
347         }
348
349         if (!empty($categories)) {
350                 // get the "fileas" tags for this post
351                 $filedas = FileTag::fileToArray($categories);
352         }
353
354         $list_array = explode(',', trim($_REQUEST['category'] ?? ''));
355         $categories = FileTag::arrayToFile($list_array, 'category');
356
357         if (!empty($filedas) && is_array($filedas)) {
358                 // append the fileas stuff to the new categories list
359                 $categories .= FileTag::arrayToFile($filedas);
360         }
361
362         // get contact info for poster
363
364         $author = null;
365         $self   = false;
366         $contact_id = 0;
367
368         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
369                 $self = true;
370                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
371         } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
372                 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
373         }
374
375         if (DBA::isResult($author)) {
376                 $contact_id = $author['id'];
377         }
378
379         // get contact info for owner
380         if ($profile_uid == local_user() || $allow_comment) {
381                 $contact_record = $author ?: [];
382         } else {
383                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
384         }
385
386         // Look for any tags and linkify them
387         $inform   = '';
388         $private_forum = false;
389         $private_id = null;
390         $only_to_forum = false;
391         $forum_contact = [];
392
393         // Personal notes must never be altered to a forum post.
394         if ($posttype != Item::PT_PERSONAL_NOTE) {
395                 // Convert mentions in the body to a unified format
396                 $body = BBCode::setMentions($body, local_user() ? local_user() : $profile_uid, $network);
397
398                 // Search for forum mentions
399                 foreach (Tag::getFromBody($body, Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
400                         $contact = Contact::getByURLForUser($tag[2], $profile_uid);
401                         if (!empty($inform)) {
402                                 $inform .= ',';
403                         }
404                         $inform .= 'cid:' . $contact['id'];
405
406                         if ($toplevel_item_id || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
407                                 continue;
408                         }
409
410                         if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
411                                 $private_forum = $contact['prv'];
412                                 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
413                                 $private_id = $contact['id'];
414                                 $forum_contact = $contact;
415                                 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
416                         } elseif ($str_contact_allow == '<' . $contact['id'] . '>') {
417                                 $private_forum = false;
418                                 $only_to_forum = true;
419                                 $private_id = $contact['id'];
420                                 $forum_contact = $contact;
421                                 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
422                         } else {
423                                 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
424                         }
425                 }
426                 Logger::info('Got inform', ['inform' => $inform]);
427         }
428
429         $original_contact_id = $contact_id;
430
431         if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
432                 // we tagged a forum in a top level post. Now we change the post
433                 $private = $private_forum ? Item::PRIVATE : Item::UNLISTED;
434
435                 if ($only_to_forum) {
436                         $postopts = '';
437                 }
438
439                 $str_contact_deny  = '';
440                 $str_group_deny    = '';
441
442                 if ($private_forum) {
443                         $str_contact_allow = '<' . $private_id . '>';
444                         $str_group_allow   = '<' . Group::getIdForForum($forum_contact['id']) . '>';
445                 } else {
446                         $str_contact_allow = '';
447                         $str_group_allow   = '';
448                 }
449         }
450
451         /*
452          * When a photo was uploaded into the message using the (profile wall) ajax
453          * uploader, The permissions are initially set to disallow anybody but the
454          * owner from seeing it. This is because the permissions may not yet have been
455          * set for the post. If it's private, the photo permissions should be set
456          * appropriately. But we didn't know the final permissions on the post until
457          * now. So now we'll look for links of uploaded messages that are in the
458          * post and set them to the same permissions as the post itself.
459          */
460
461         $match = null;
462
463         if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
464                 $objecttype = Activity\ObjectType::IMAGE;
465         }
466
467         /*
468          * Next link in any attachment references we find in the post.
469          */
470         $match = [];
471
472         /// @todo these lines should be moved to Model/Attach (Once it exists)
473         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
474                 $attaches = $match[1];
475                 if (count($attaches)) {
476                         foreach ($attaches as $attach) {
477                                 // Ensure to only modify attachments that you own
478                                 $srch = '<' . intval($original_contact_id) . '>';
479
480                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
481                                                 'id' => $attach];
482                                 if (!Attach::exists($condition)) {
483                                         continue;
484                                 }
485
486                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
487                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
488                                 $condition = ['id' => $attach];
489                                 Attach::update($fields, $condition);
490                         }
491                 }
492         }
493
494         // embedded bookmark or attachment in post? set bookmark flag
495
496         $data = BBCode::getAttachmentData($body);
497         $match = [];
498         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
499                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
500                 $posttype = Item::PT_PAGE;
501                 $objecttype =  Activity\ObjectType::BOOKMARK;
502         }
503
504         $body = DI::bbCodeVideo()->transform($body);
505
506         $body = BBCode::scaleExternalImages($body);
507
508         // Setting the object type if not defined before
509         if (!$objecttype) {
510                 $objecttype = Activity\ObjectType::NOTE; // Default value
511                 $objectdata = BBCode::getAttachedData($body);
512
513                 if ($objectdata["type"] == "link") {
514                         $objecttype = Activity\ObjectType::BOOKMARK;
515                 } elseif ($objectdata["type"] == "video") {
516                         $objecttype = Activity\ObjectType::VIDEO;
517                 } elseif ($objectdata["type"] == "photo") {
518                         $objecttype = Activity\ObjectType::IMAGE;
519                 }
520
521         }
522
523         $attachments = '';
524         $match = [];
525
526         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
527                 foreach ($match[2] as $mtch) {
528                         $fields = ['id', 'filename', 'filesize', 'filetype'];
529                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
530                         if ($attachment !== false) {
531                                 if (strlen($attachments)) {
532                                         $attachments .= ',';
533                                 }
534                                 $attachments .= Post\Media::getAttachElement(DI::baseUrl() . '/attach/' . $attachment['id'],
535                                         $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? '');
536                         }
537                         $body = str_replace($match[1],'',$body);
538                 }
539         }
540
541         if (!strlen($verb)) {
542                 $verb = Activity::POST;
543         }
544
545         if ($network == "") {
546                 $network = Protocol::DFRN;
547         }
548
549         $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
550
551         // even if the post arrived via API we are considering that it
552         // originated on this site by default for determining relayability.
553
554         // Don't use "defaults" here. It would turn 0 to 1
555         if (!isset($_REQUEST['origin'])) {
556                 $origin = 1;
557         } else {
558                 $origin = $_REQUEST['origin'];
559         }
560
561         $uri = Item::newURI($api_source ? $profile_uid : $uid, $guid);
562
563         // Fallback so that we alway have a parent uri
564         if (!$thr_parent_uri || !$toplevel_item_id) {
565                 $thr_parent_uri = $uri;
566         }
567
568         $datarray = [];
569         $datarray['uid']           = $profile_uid;
570         $datarray['wall']          = $wall;
571         $datarray['gravity']       = $gravity;
572         $datarray['network']       = $network;
573         $datarray['contact-id']    = $contact_id;
574         $datarray['owner-name']    = $contact_record['name'] ?? '';
575         $datarray['owner-link']    = $contact_record['url'] ?? '';
576         $datarray['owner-avatar']  = $contact_record['thumb'] ?? '';
577         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
578         $datarray['author-name']   = $author['name'];
579         $datarray['author-link']   = $author['url'];
580         $datarray['author-avatar'] = $author['thumb'];
581         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
582         $datarray['created']       = DateTimeFormat::utcNow();
583         $datarray['edited']        = DateTimeFormat::utcNow();
584         $datarray['commented']     = DateTimeFormat::utcNow();
585         $datarray['received']      = DateTimeFormat::utcNow();
586         $datarray['changed']       = DateTimeFormat::utcNow();
587         $datarray['extid']         = $extid;
588         $datarray['guid']          = $guid;
589         $datarray['uri']           = $uri;
590         $datarray['title']         = $title;
591         $datarray['body']          = $body;
592         $datarray['app']           = $app;
593         $datarray['location']      = $location;
594         $datarray['coord']         = $coord;
595         $datarray['file']          = $categories;
596         $datarray['inform']        = $inform;
597         $datarray['verb']          = $verb;
598         $datarray['post-type']     = $posttype;
599         $datarray['object-type']   = $objecttype;
600         $datarray['allow_cid']     = $str_contact_allow;
601         $datarray['allow_gid']     = $str_group_allow;
602         $datarray['deny_cid']      = $str_contact_deny;
603         $datarray['deny_gid']      = $str_group_deny;
604         $datarray['private']       = $private;
605         $datarray['pubmail']       = $pubmail_enabled;
606         $datarray['attach']        = $attachments;
607
608         $datarray['thr-parent']    = $thr_parent_uri;
609
610         $datarray['postopts']      = $postopts;
611         $datarray['origin']        = $origin;
612         $datarray['object']        = $object;
613
614         $datarray['attachments']   = $_REQUEST['attachments'] ?? [];
615
616         /*
617          * These fields are for the convenience of addons...
618          * 'self' if true indicates the owner is posting on their own wall
619          * If parent is 0 it is a top-level post.
620          */
621         $datarray['parent']        = $toplevel_item_id;
622         $datarray['self']          = $self;
623
624         // This triggers posts via API and the mirror functions
625         $datarray['api_source'] = $api_source;
626
627         // This field is for storing the raw conversation data
628         $datarray['protocol'] = Conversation::PARCEL_DIRECT;
629         $datarray['direction'] = Conversation::PUSH;
630
631         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['thr-parent']]);
632         if (DBA::isResult($conversation)) {
633                 if ($conversation['conversation-uri'] != '') {
634                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
635                 }
636                 if ($conversation['conversation-href'] != '') {
637                         $datarray['conversation-href'] = $conversation['conversation-href'];
638                 }
639         }
640
641         if ($orig_post) {
642                 $datarray['edit'] = true;
643         } else {
644                 // If this was a share, add missing data here
645                 $datarray = Item::addShareDataFromOriginal($datarray);
646
647                 $datarray['edit'] = false;
648         }
649
650         // Check for hashtags in the body and repair or add hashtag links
651         if ($preview || $orig_post) {
652                 $datarray['body'] = Item::setHashtags($datarray['body']);
653         }
654
655         // preview mode - prepare the body for display and send it via json
656         if ($preview) {
657                 // We set the datarray ID to -1 because in preview mode the dataray
658                 // doesn't have an ID.
659                 $datarray["id"] = -1;
660                 $datarray["uri-id"] = -1;
661                 $datarray["author-network"] = Protocol::DFRN;
662
663                 $o = DI::conversation()->create([array_merge($contact_record, $datarray)], 'search', false, true);
664
665                 System::jsonExit(['preview' => $o]);
666         }
667
668         Hook::callAll('post_local',$datarray);
669
670         if (!empty($_REQUEST['scheduled_at'])) {
671                 $scheduled_at = DateTimeFormat::convert($_REQUEST['scheduled_at'], 'UTC', $a->getTimeZone());
672                 if ($scheduled_at > DateTimeFormat::utcNow()) {
673                         unset($datarray['created']);
674                         unset($datarray['edited']);
675                         unset($datarray['commented']);
676                         unset($datarray['received']);
677                         unset($datarray['changed']);
678                         unset($datarray['edit']);
679                         unset($datarray['self']);
680                         unset($datarray['api_source']);
681
682                         Post\Delayed::add($datarray['uri'], $datarray, PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at);
683                         item_post_return(DI::baseUrl(), $api_source, $return_path);
684                 }
685         }
686
687         if (!empty($datarray['cancel'])) {
688                 Logger::info('mod_item: post cancelled by addon.');
689                 if ($return_path) {
690                         DI::baseUrl()->redirect($return_path);
691                 }
692
693                 $json = ['cancel' => 1];
694                 if (!empty($_REQUEST['jsreload'])) {
695                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
696                 }
697
698                 System::jsonExit($json);
699         }
700
701         $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
702
703         if ($orig_post) {
704                 // Fill the cache field
705                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
706                 Item::putInCache($datarray);
707
708                 $fields = [
709                         'title' => $datarray['title'],
710                         'body' => $datarray['body'],
711                         'attach' => $datarray['attach'],
712                         'file' => $datarray['file'],
713                         'rendered-html' => $datarray['rendered-html'],
714                         'rendered-hash' => $datarray['rendered-hash'],
715                         'edited' => DateTimeFormat::utcNow(),
716                         'changed' => DateTimeFormat::utcNow()];
717
718                 Item::update($fields, ['id' => $post_id]);
719
720                 if ($return_path) {
721                         DI::baseUrl()->redirect($return_path);
722                 }
723
724                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
725         }
726
727         unset($datarray['edit']);
728         unset($datarray['self']);
729         unset($datarray['api_source']);
730
731         $post_id = Item::insert($datarray);
732
733         if (!$post_id) {
734                 notice(DI::l10n()->t('Item wasn\'t stored.'));
735                 if ($return_path) {
736                         DI::baseUrl()->redirect($return_path);
737                 }
738
739                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
740         }
741
742         $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
743
744         if (!DBA::isResult($datarray)) {
745                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
746                 if ($return_path) {
747                         DI::baseUrl()->redirect($return_path);
748                 }
749
750                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
751         }
752
753         Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
754
755         if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
756                 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
757         }
758
759         // These notifications are sent if someone else is commenting other your wall
760         if ($contact_record != $author) {
761                 if ($toplevel_item_id) {
762                         DI::notify()->createFromArray([
763                                 'type'  => Notification\Type::COMMENT,
764                                 'otype' => Notification\ObjectType::ITEM,
765                                 'verb'  => Activity::POST,
766                                 'uid'   => $profile_uid,
767                                 'cid'   => $datarray['author-id'],
768                                 'item'  => $datarray,
769                                 'link'  => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
770                         ]);
771                 } elseif (empty($forum_contact)) {
772                         DI::notify()->createFromArray([
773                                 'type'  => Notification\Type::WALL,
774                                 'otype' => Notification\ObjectType::ITEM,
775                                 'verb'  => Activity::POST,
776                                 'uid'   => $profile_uid,
777                                 'cid'   => $datarray['author-id'],
778                                 'item'  => $datarray,
779                                 'link'  => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
780                         ]);
781                 }
782         }
783
784         Hook::callAll('post_local_end', $datarray);
785
786         if (strlen($emailcc) && $profile_uid == local_user()) {
787                 $recipients = explode(',', $emailcc);
788                 if (count($recipients)) {
789                         foreach ($recipients as $recipient) {
790                                 $address = trim($recipient);
791                                 if (!strlen($address)) {
792                                         continue;
793                                 }
794                                 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
795                                         $datarray, $address, $author['thumb'] ?? ''));
796                         }
797                 }
798         }
799
800         // When we are doing some forum posting via ! we have to start the notifier manually.
801         // These kind of posts don't initiate the notifier call in the item class.
802         if ($only_to_forum) {
803                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, (int)$datarray['uri-id'], (int)$datarray['uid']);
804         }
805
806         Logger::info('post_complete');
807
808         if ($api_source) {
809                 return $post_id;
810         }
811
812         item_post_return(DI::baseUrl(), $api_source, $return_path);
813         // NOTREACHED
814 }
815
816 function item_post_return($baseurl, $api_source, $return_path)
817 {
818         if ($api_source) {
819                 return;
820         }
821
822         if ($return_path) {
823                 DI::baseUrl()->redirect($return_path);
824         }
825
826         $json = ['success' => 1];
827         if (!empty($_REQUEST['jsreload'])) {
828                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
829         }
830
831         Logger::info('post_json', ['json' => $json]);
832
833         System::jsonExit($json);
834 }
835
836 function item_content(App $a)
837 {
838         if (!Session::isAuthenticated()) {
839                 throw new HTTPException\UnauthorizedException();
840         }
841
842         $args = DI::args();
843
844         if (!$args->has(3)) {
845                 throw new HTTPException\BadRequestException();
846         }
847
848         $o = '';
849         switch ($args->get(1)) {
850                 case 'drop':
851                         if (DI::mode()->isAjax()) {
852                                 Item::deleteForUser(['id' => $args->get(2)], local_user());
853                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
854                                 System::jsonExit([intval($args->get(2)), local_user()]);
855                         } else {
856                                 if (!empty($args->get(3))) {
857                                         $o = drop_item($args->get(2), $args->get(3));
858                                 } else {
859                                         $o = drop_item($args->get(2));
860                                 }
861                         }
862                         break;
863                 case 'block':
864                         $item = Post::selectFirstForUser(local_user(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
865                         if (empty($item['author-id'])) {
866                                 throw new HTTPException\NotFoundException('Item not found');
867                         }
868
869                         Contact\User::setBlocked($item['author-id'], local_user(), true);
870
871                         if (DI::mode()->isAjax()) {
872                                 // ajax return: [<item id>, 0 (no perm) | <owner id>]
873                                 System::jsonExit([intval($args->get(2)), local_user()]);
874                         } else {
875                                 item_redirect_after_action($item, $args->get(3));
876                         }
877                         break;
878         }
879
880         return $o;
881 }
882
883 /**
884  * @param int    $id
885  * @param string $return
886  * @return string
887  * @throws HTTPException\InternalServerErrorException
888  */
889 function drop_item(int $id, string $return = '')
890 {
891         // locate item to be deleted
892         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
893         $item = Post::selectFirstForUser(local_user(), $fields, ['id' => $id]);
894
895         if (!DBA::isResult($item)) {
896                 notice(DI::l10n()->t('Item not found.'));
897                 DI::baseUrl()->redirect('network');
898         }
899
900         if ($item['deleted']) {
901                 return '';
902         }
903
904         $contact_id = 0;
905
906         // check if logged in user is either the author or owner of this item
907         if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
908                 $contact_id = $item['contact-id'];
909         }
910
911         if ((local_user() == $item['uid']) || $contact_id) {
912                 // delete the item
913                 Item::deleteForUser(['id' => $item['id']], local_user());
914
915                 item_redirect_after_action($item, $return);
916         } else {
917                 Logger::notice('Permission denied.', ['local' => local_user(), 'uid' => $item['uid'], 'cid' => $contact_id]);
918                 notice(DI::l10n()->t('Permission denied.'));
919                 DI::baseUrl()->redirect('display/' . $item['guid']);
920                 //NOTREACHED
921         }
922
923         return '';
924 }
925
926 function item_redirect_after_action($item, $returnUrlHex)
927 {
928         $return_url = hex2bin($returnUrlHex);
929
930         // removes update_* from return_url to ignore Ajax refresh
931         $return_url = str_replace("update_", "", $return_url);
932
933         // Check if delete a comment
934         if ($item['gravity'] == GRAVITY_COMMENT) {
935                 if (!empty($item['parent'])) {
936                         $parentitem = Post::selectFirstForUser(local_user(), ['guid'], ['id' => $item['parent']]);
937                 }
938
939                 // Return to parent guid
940                 if (!empty($parentitem)) {
941                         DI::baseUrl()->redirect('display/' . $parentitem['guid']);
942                         //NOTREACHED
943                 } // In case something goes wrong
944                 else {
945                         DI::baseUrl()->redirect('network');
946                         //NOTREACHED
947                 }
948         } else {
949                 // if unknown location or deleting top level post called from display
950                 if (empty($return_url) || strpos($return_url, 'display') !== false) {
951                         DI::baseUrl()->redirect('network');
952                         //NOTREACHED
953                 } else {
954                         DI::baseUrl()->redirect($return_url);
955                         //NOTREACHED
956                 }
957         }
958 }