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