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