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