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