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