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