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