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