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