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