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