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