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