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