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