]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Merge pull request #6209 from MrPetovan/task/move-config-to-php-array
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @file mod/item.php
4  */
5
6 /*
7  * This is the POST destination for most all locally posted
8  * text stuff. This function handles status, wall-to-wall status,
9  * local comments, and remote coments that are posted on this site
10  * (as opposed to being delivered in a feed).
11  * Also processed here are posts and comments coming through the
12  * statusnet/twitter API.
13  *
14  * All of these become an "item" which is our basic unit of
15  * information.
16  */
17
18 use Friendica\App;
19 use Friendica\Content\Pager;
20 use Friendica\Content\Text\BBCode;
21 use Friendica\Content\Text\HTML;
22 use Friendica\Core\Addon;
23 use Friendica\Core\Config;
24 use Friendica\Core\L10n;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\System;
28 use Friendica\Core\Worker;
29 use Friendica\Database\DBA;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Conversation;
32 use Friendica\Model\FileTag;
33 use Friendica\Model\Item;
34 use Friendica\Protocol\Diaspora;
35 use Friendica\Protocol\Email;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Emailer;
38 use Friendica\Util\Security;
39 use Friendica\Util\Strings;
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::log('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::log("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                                 $a->internalRedirect($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::log('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::log("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                         $a->internalRedirect($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             = Strings::escapeTags(trim($_REQUEST['title']));
204                 $body              = Strings::escapeHtml(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             = Strings::escapeTags(trim(defaults($_REQUEST, 'title'   , '')));
236                 $location          = Strings::escapeTags(trim(defaults($_REQUEST, 'location', '')));
237                 $coord             = Strings::escapeTags(trim(defaults($_REQUEST, 'coord'   , '')));
238                 $verb              = Strings::escapeTags(trim(defaults($_REQUEST, 'verb'    , '')));
239                 $emailcc           = Strings::escapeTags(trim(defaults($_REQUEST, 'emailcc' , '')));
240                 $body              = Strings::escapeHtml(trim(defaults($_REQUEST, 'body'    , '')));
241                 $network           = Strings::escapeTags(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                                 $a->internalRedirect($return_path);
287                         }
288                         killme();
289                 }
290         }
291
292         if (!empty($categories))
293         {
294                 // get the "fileas" tags for this post
295                 $filedas = FileTag::fileToList($categories, 'file');
296         }
297
298         // save old and new categories, so we can determine what needs to be deleted from pconfig
299         $categories_old = $categories;
300         $categories = FileTag::listToFile(trim(defaults($_REQUEST, 'category', '')), 'category');
301         $categories_new = $categories;
302
303         if (!empty($filedas))
304         {
305                 // append the fileas stuff to the new categories list
306                 $categories .= FileTag::listToFile($filedas, 'file');
307         }
308
309         // get contact info for poster
310
311         $author = null;
312         $self   = false;
313         $contact_id = 0;
314
315         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
316                 $self = true;
317                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
318         } elseif (remote_user()) {
319                 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
320                         foreach ($_SESSION['remote'] as $v) {
321                                 if ($v['uid'] == $profile_uid) {
322                                         $contact_id = $v['cid'];
323                                         break;
324                                 }
325                         }
326                 }
327                 if ($contact_id) {
328                         $author = DBA::selectFirst('contact', [], ['id' => $contact_id]);
329                 }
330         }
331
332         if (DBA::isResult($author)) {
333                 $contact_id = $author['id'];
334         }
335
336         // get contact info for owner
337         if ($profile_uid == local_user() || $allow_comment) {
338                 $contact_record = $author;
339         } else {
340                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
341         }
342
343         // Look for any tags and linkify them
344         $str_tags = '';
345         $inform   = '';
346
347         $tags = BBCode::getTags($body);
348
349         // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
350         if ($parent && in_array($thr_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
351                 $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
352                 if (!stripos(implode($tags), '[url=' . $thr_parent_contact['url'] . ']')) {
353                         $tags[] = $contact;
354                 }
355         }
356
357         $tagged = [];
358
359         $private_forum = false;
360         $only_to_forum = false;
361         $forum_contact = [];
362
363         if (count($tags)) {
364                 foreach ($tags as $tag) {
365                         $tag_type = substr($tag, 0, 1);
366
367                         if ($tag_type == '#') {
368                                 continue;
369                         }
370
371                         /*
372                          * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
373                          * Robert Johnson should be first in the $tags array
374                          */
375                         $fullnametagged = false;
376                         /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
377                         foreach ($tagged as $nextTag) {
378                                 if (stristr($nextTag, $tag . ' ')) {
379                                         $fullnametagged = true;
380                                         break;
381                                 }
382                         }
383                         if ($fullnametagged) {
384                                 continue;
385                         }
386
387                         $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
388                         if ($success['replaced']) {
389                                 $tagged[] = $tag;
390                         }
391                         // When the forum is private or the forum is addressed with a "!" make the post private
392                         if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == '!'))) {
393                                 $private_forum = $success['contact']['prv'];
394                                 $only_to_forum = ($tag_type == '!');
395                                 $private_id = $success['contact']['id'];
396                                 $forum_contact = $success['contact'];
397                         } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
398                                 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
399                                 $private_forum = false;
400                                 $only_to_forum = true;
401                                 $private_id = $success['contact']['id'];
402                                 $forum_contact = $success['contact'];
403                         }
404                 }
405         }
406
407         $original_contact_id = $contact_id;
408
409         if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
410                 // we tagged a forum in a top level post. Now we change the post
411                 $private = $private_forum;
412
413                 $str_group_allow = '';
414                 $str_contact_deny = '';
415                 $str_group_deny = '';
416                 if ($private_forum) {
417                         $str_contact_allow = '<' . $private_id . '>';
418                 } else {
419                         $str_contact_allow = '';
420                 }
421                 $contact_id = $private_id;
422                 $contact_record = $forum_contact;
423                 $_REQUEST['origin'] = false;
424                 $wall = 0;
425         }
426
427         /*
428          * When a photo was uploaded into the message using the (profile wall) ajax
429          * uploader, The permissions are initially set to disallow anybody but the
430          * owner from seeing it. This is because the permissions may not yet have been
431          * set for the post. If it's private, the photo permissions should be set
432          * appropriately. But we didn't know the final permissions on the post until
433          * now. So now we'll look for links of uploaded messages that are in the
434          * post and set them to the same permissions as the post itself.
435          */
436
437         $match = null;
438
439         /// @todo these lines should be moved to Model/Photo
440         if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
441                 $images = $match[2];
442                 if (count($images)) {
443
444                         $objecttype = ACTIVITY_OBJ_IMAGE;
445
446                         foreach ($images as $image) {
447                                 if (!stristr($image, System::baseUrl() . '/photo/')) {
448                                         continue;
449                                 }
450                                 $image_uri = substr($image,strrpos($image,'/') + 1);
451                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
452                                 if (!strlen($image_uri)) {
453                                         continue;
454                                 }
455
456                                 // Ensure to only modify photos that you own
457                                 $srch = '<' . intval($original_contact_id) . '>';
458
459                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
460                                                 'resource-id' => $image_uri, 'uid' => $profile_uid];
461                                 if (!DBA::exists('photo', $condition)) {
462                                         continue;
463                                 }
464
465                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
466                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
467                                 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid];
468                                 DBA::update('photo', $fields, $condition);
469                         }
470                 }
471         }
472
473
474         /*
475          * Next link in any attachment references we find in the post.
476          */
477         $match = false;
478
479         /// @todo these lines should be moved to Model/Attach (Once it exists)
480         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
481                 $attaches = $match[1];
482                 if (count($attaches)) {
483                         foreach ($attaches as $attach) {
484                                 // Ensure to only modify attachments that you own
485                                 $srch = '<' . intval($original_contact_id) . '>';
486
487                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
488                                                 'id' => $attach];
489                                 if (!DBA::exists('attach', $condition)) {
490                                         continue;
491                                 }
492
493                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
494                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
495                                 $condition = ['id' => $attach];
496                                 DBA::update('attach', $fields, $condition);
497                         }
498                 }
499         }
500
501         // embedded bookmark or attachment in post? set bookmark flag
502
503         $data = BBCode::getAttachmentData($body);
504         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
505                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
506                 $posttype = Item::PT_PAGE;
507                 $objecttype = ACTIVITY_OBJ_BOOKMARK;
508         }
509
510         $body = bb_translate_video($body);
511
512
513         // Fold multi-line [code] sequences
514         $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
515
516         $body = BBCode::scaleExternalImages($body, false);
517
518         // Setting the object type if not defined before
519         if (!$objecttype) {
520                 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
521                 $objectdata = BBCode::getAttachedData($body);
522
523                 if ($objectdata["type"] == "link") {
524                         $objecttype = ACTIVITY_OBJ_BOOKMARK;
525                 } elseif ($objectdata["type"] == "video") {
526                         $objecttype = ACTIVITY_OBJ_VIDEO;
527                 } elseif ($objectdata["type"] == "photo") {
528                         $objecttype = ACTIVITY_OBJ_IMAGE;
529                 }
530
531         }
532
533         $attachments = '';
534         $match = false;
535
536         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
537                 foreach ($match[2] as $mtch) {
538                         $fields = ['id', 'filename', 'filesize', 'filetype'];
539                         $attachment = DBA::selectFirst('attach', $fields, ['id' => $mtch]);
540                         if (DBA::isResult($attachment)) {
541                                 if (strlen($attachments)) {
542                                         $attachments .= ',';
543                                 }
544                                 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
545                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
546                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
547                         }
548                         $body = str_replace($match[1],'',$body);
549                 }
550         }
551
552         if (!strlen($verb)) {
553                 $verb = ACTIVITY_POST;
554         }
555
556         if ($network == "") {
557                 $network = Protocol::DFRN;
558         }
559
560         $gravity = ($parent ? GRAVITY_COMMENT : GRAVITY_PARENT);
561
562         // even if the post arrived via API we are considering that it
563         // originated on this site by default for determining relayability.
564
565         // Don't use "defaults" here. It would turn 0 to 1
566         if (!isset($_REQUEST['origin'])) {
567                 $origin = 1;
568         } else {
569                 $origin = $_REQUEST['origin'];
570         }
571
572         $notify_type = ($parent ? 'comment-new' : 'wall-new');
573
574         $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
575
576         // Fallback so that we alway have a parent uri
577         if (!$thr_parent_uri || !$parent) {
578                 $thr_parent_uri = $uri;
579         }
580
581         $datarray = [];
582         $datarray['uid']           = $profile_uid;
583         $datarray['wall']          = $wall;
584         $datarray['gravity']       = $gravity;
585         $datarray['network']       = $network;
586         $datarray['contact-id']    = $contact_id;
587         $datarray['owner-name']    = $contact_record['name'];
588         $datarray['owner-link']    = $contact_record['url'];
589         $datarray['owner-avatar']  = $contact_record['thumb'];
590         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
591         $datarray['author-name']   = $author['name'];
592         $datarray['author-link']   = $author['url'];
593         $datarray['author-avatar'] = $author['thumb'];
594         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
595         $datarray['created']       = DateTimeFormat::utcNow();
596         $datarray['edited']        = DateTimeFormat::utcNow();
597         $datarray['commented']     = DateTimeFormat::utcNow();
598         $datarray['received']      = DateTimeFormat::utcNow();
599         $datarray['changed']       = DateTimeFormat::utcNow();
600         $datarray['extid']         = $extid;
601         $datarray['guid']          = $guid;
602         $datarray['uri']           = $uri;
603         $datarray['title']         = $title;
604         $datarray['body']          = $body;
605         $datarray['app']           = $app;
606         $datarray['location']      = $location;
607         $datarray['coord']         = $coord;
608         $datarray['tag']           = $str_tags;
609         $datarray['file']          = $categories;
610         $datarray['inform']        = $inform;
611         $datarray['verb']          = $verb;
612         $datarray['post-type']     = $posttype;
613         $datarray['object-type']   = $objecttype;
614         $datarray['allow_cid']     = $str_contact_allow;
615         $datarray['allow_gid']     = $str_group_allow;
616         $datarray['deny_cid']      = $str_contact_deny;
617         $datarray['deny_gid']      = $str_group_deny;
618         $datarray['private']       = $private;
619         $datarray['pubmail']       = $pubmail_enabled;
620         $datarray['attach']        = $attachments;
621
622         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
623         $datarray['parent-uri']    = $thr_parent_uri;
624
625         $datarray['postopts']      = $postopts;
626         $datarray['origin']        = $origin;
627         $datarray['moderated']     = false;
628         $datarray['object']        = $object;
629
630         /*
631          * These fields are for the convenience of addons...
632          * 'self' if true indicates the owner is posting on their own wall
633          * If parent is 0 it is a top-level post.
634          */
635         $datarray['parent']        = $parent;
636         $datarray['self']          = $self;
637
638         // This triggers posts via API and the mirror functions
639         $datarray['api_source'] = $api_source;
640
641         // This field is for storing the raw conversation data
642         $datarray['protocol'] = Conversation::PARCEL_DFRN;
643
644         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
645         if (DBA::isResult($conversation)) {
646                 if ($conversation['conversation-uri'] != '') {
647                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
648                 }
649                 if ($conversation['conversation-href'] != '') {
650                         $datarray['conversation-href'] = $conversation['conversation-href'];
651                 }
652         }
653
654         if ($orig_post) {
655                 $datarray['edit'] = true;
656         } else {
657                 $datarray['edit'] = false;
658         }
659
660         // Check for hashtags in the body and repair or add hashtag links
661         if ($preview || $orig_post) {
662                 Item::setHashtags($datarray);
663         }
664
665         // preview mode - prepare the body for display and send it via json
666         if ($preview) {
667                 // We set the datarray ID to -1 because in preview mode the dataray
668                 // doesn't have an ID.
669                 $datarray["id"] = -1;
670                 $datarray["item_id"] = -1;
671                 $datarray["author-network"] = Protocol::DFRN;
672
673                 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
674                 Logger::log('preview: ' . $o);
675                 echo json_encode(['preview' => $o]);
676                 exit();
677         }
678
679         Addon::callHooks('post_local',$datarray);
680
681         if (!empty($datarray['cancel'])) {
682                 Logger::log('mod_item: post cancelled by addon.');
683                 if ($return_path) {
684                         $a->internalRedirect($return_path);
685                 }
686
687                 $json = ['cancel' => 1];
688                 if (!empty($_REQUEST['jsreload'])) {
689                         $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
690                 }
691
692                 echo json_encode($json);
693                 killme();
694         }
695
696         if ($orig_post) {
697                 // Fill the cache field
698                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
699                 Item::putInCache($datarray);
700
701                 $fields = [
702                         'title' => $datarray['title'],
703                         'body' => $datarray['body'],
704                         'tag' => $datarray['tag'],
705                         'attach' => $datarray['attach'],
706                         'file' => $datarray['file'],
707                         'rendered-html' => $datarray['rendered-html'],
708                         'rendered-hash' => $datarray['rendered-hash'],
709                         'edited' => DateTimeFormat::utcNow(),
710                         'changed' => DateTimeFormat::utcNow()];
711
712                 Item::update($fields, ['id' => $post_id]);
713
714                 // update filetags in pconfig
715                 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
716
717                 if (!empty($_REQUEST['return']) && strlen($return_path)) {
718                         Logger::log('return: ' . $return_path);
719                         $a->internalRedirect($return_path);
720                 }
721                 killme();
722         } else {
723                 $post_id = 0;
724         }
725
726         unset($datarray['edit']);
727         unset($datarray['self']);
728         unset($datarray['api_source']);
729
730         if ($origin) {
731                 $signed = Diaspora::createCommentSignature($uid, $datarray);
732                 if (!empty($signed)) {
733                         $datarray['diaspora_signed_text'] = json_encode($signed);
734                 }
735         }
736
737         $post_id = Item::insert($datarray);
738
739         if (!$post_id) {
740                 Logger::log("Item wasn't stored.");
741                 $a->internalRedirect($return_path);
742         }
743
744         $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
745
746         if (!DBA::isResult($datarray)) {
747                 Logger::log("Item with id ".$post_id." couldn't be fetched.");
748                 $a->internalRedirect($return_path);
749         }
750
751         // update filetags in pconfig
752         FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
753
754         // These notifications are sent if someone else is commenting other your wall
755         if ($parent) {
756                 if ($contact_record != $author) {
757                         notification([
758                                 'type'         => NOTIFY_COMMENT,
759                                 'notify_flags' => $user['notify-flags'],
760                                 'language'     => $user['language'],
761                                 'to_name'      => $user['username'],
762                                 'to_email'     => $user['email'],
763                                 'uid'          => $user['uid'],
764                                 'item'         => $datarray,
765                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
766                                 'source_name'  => $datarray['author-name'],
767                                 'source_link'  => $datarray['author-link'],
768                                 'source_photo' => $datarray['author-avatar'],
769                                 'verb'         => ACTIVITY_POST,
770                                 'otype'        => 'item',
771                                 'parent'       => $parent,
772                                 'parent_uri'   => $parent_item['uri']
773                         ]);
774                 }
775         } else {
776                 if (($contact_record != $author) && !count($forum_contact)) {
777                         notification([
778                                 'type'         => NOTIFY_WALL,
779                                 'notify_flags' => $user['notify-flags'],
780                                 'language'     => $user['language'],
781                                 'to_name'      => $user['username'],
782                                 'to_email'     => $user['email'],
783                                 'uid'          => $user['uid'],
784                                 'item'         => $datarray,
785                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
786                                 'source_name'  => $datarray['author-name'],
787                                 'source_link'  => $datarray['author-link'],
788                                 'source_photo' => $datarray['author-avatar'],
789                                 'verb'         => ACTIVITY_POST,
790                                 'otype'        => 'item'
791                         ]);
792                 }
793         }
794
795         Addon::callHooks('post_local_end', $datarray);
796
797         if (strlen($emailcc) && $profile_uid == local_user()) {
798                 $erecips = explode(',', $emailcc);
799                 if (count($erecips)) {
800                         foreach ($erecips as $recip) {
801                                 $addr = trim($recip);
802                                 if (!strlen($addr)) {
803                                         continue;
804                                 }
805                                 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
806                                         . '<br />';
807                                 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
808                                 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
809                                 if (!$datarray['title']=='') {
810                                         $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
811                                 } else {
812                                         $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
813                                 }
814                                 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
815                                 $html    = Item::prepareBody($datarray);
816                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
817                                 $params =  [
818                                         'fromName' => $a->user['username'],
819                                         'fromEmail' => $a->user['email'],
820                                         'toEmail' => $addr,
821                                         'replyTo' => $a->user['email'],
822                                         'messageSubject' => $subject,
823                                         'htmlVersion' => $message,
824                                         'textVersion' => HTML::toPlaintext($html.$disclaimer)
825                                 ];
826                                 Emailer::send($params);
827                         }
828                 }
829         }
830
831         // Insert an item entry for UID=0 for global entries.
832         // We now do it in the background to save some time.
833         // This is important in interactive environments like the frontend or the API.
834         // We don't fork a new process since this is done anyway with the following command
835         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
836
837         // When we are doing some forum posting via ! we have to start the notifier manually.
838         // These kind of posts don't initiate the notifier call in the item class.
839         if ($only_to_forum) {
840                 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
841         }
842
843         Logger::log('post_complete');
844
845         if ($api_source) {
846                 return $post_id;
847         }
848
849         item_post_return(System::baseUrl(), $api_source, $return_path);
850         // NOTREACHED
851 }
852
853 function item_post_return($baseurl, $api_source, $return_path)
854 {
855         // figure out how to return, depending on from whence we came
856     $a = get_app();
857
858         if ($api_source) {
859                 return;
860         }
861
862         if ($return_path) {
863                 $a->internalRedirect($return_path);
864         }
865
866         $json = ['success' => 1];
867         if (!empty($_REQUEST['jsreload'])) {
868                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
869         }
870
871         Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
872
873         echo json_encode($json);
874         killme();
875 }
876
877 function item_content(App $a)
878 {
879         if (!local_user() && !remote_user()) {
880                 return;
881         }
882
883         $o = '';
884
885         if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
886                 if ($a->isAjax()) {
887                         $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
888                 } else {
889                         if (!empty($a->argv[3])) {
890                                 $o = drop_item($a->argv[2], $a->argv[3]);
891                         }
892                         else {
893                                 $o = drop_item($a->argv[2]);
894                         }
895                 }
896
897                 if ($a->isAjax()) {
898                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
899                         echo json_encode([intval($a->argv[2]), intval($o)]);
900                         killme();
901                 }
902         }
903
904         return $o;
905 }
906
907 /**
908  * This function removes the tag $tag from the text $body and replaces it with
909  * the appropiate link.
910  *
911  * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
912  * @param unknown_type $body the text to replace the tag in
913  * @param string $inform a comma-seperated string containing everybody to inform
914  * @param string $str_tags string to add the tag to
915  * @param integer $profile_uid
916  * @param string $tag the tag to replace
917  * @param string $network The network of the post
918  *
919  * @return boolean true if replaced, false if not replaced
920  */
921 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
922 {
923         $replaced = false;
924         $r = null;
925         $tag_type = '@';
926
927         //is it a person tag?
928         if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
929                 $tag_type = substr($tag, 0, 1);
930                 //is it already replaced?
931                 if (strpos($tag, '[url=')) {
932                         //append tag to str_tags
933                         if (!stristr($str_tags, $tag)) {
934                                 if (strlen($str_tags)) {
935                                         $str_tags .= ',';
936                                 }
937                                 $str_tags .= $tag;
938                         }
939
940                         // Checking for the alias that is used for OStatus
941                         $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
942                         if (preg_match($pattern, $tag, $matches)) {
943                                 $data = Contact::getDetailsByURL($matches[1]);
944
945                                 if ($data["alias"] != "") {
946                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
947
948                                         if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
949                                                 if (strlen($str_tags)) {
950                                                         $str_tags .= ',';
951                                                 }
952
953                                                 $str_tags .= $newtag;
954                                         }
955                                 }
956                         }
957
958                         return $replaced;
959                 }
960
961                 $stat = false;
962                 //get the person's name
963                 $name = substr($tag, 1);
964
965                 // Sometimes the tag detection doesn't seem to work right
966                 // This is some workaround
967                 $nameparts = explode(" ", $name);
968                 $name = $nameparts[0];
969
970                 // Try to detect the contact in various ways
971                 if (strpos($name, 'http://')) {
972                         // At first we have to ensure that the contact exists
973                         Contact::getIdForURL($name);
974
975                         // Now we should have something
976                         $contact = Contact::getDetailsByURL($name);
977                 } elseif (strpos($name, '@')) {
978                         // This function automatically probes when no entry was found
979                         $contact = Contact::getDetailsByAddr($name);
980                 } else {
981                         $contact = false;
982                         $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
983
984                         if (strrpos($name, '+')) {
985                                 // Is it in format @nick+number?
986                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
987                                 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
988                         }
989
990                         // select someone by nick or attag in the current network
991                         if (!DBA::isResult($contact) && ($network != "")) {
992                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
993                                                 $name, $name, $network, $profile_uid];
994                                 $contact = DBA::selectFirst('contact', $fields, $condition);
995                         }
996
997                         //select someone by name in the current network
998                         if (!DBA::isResult($contact) && ($network != "")) {
999                                 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
1000                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1001                         }
1002
1003                         // select someone by nick or attag in any network
1004                         if (!DBA::isResult($contact)) {
1005                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
1006                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1007                         }
1008
1009                         // select someone by name in any network
1010                         if (!DBA::isResult($contact)) {
1011                                 $condition = ['name' => $name, 'uid' => $profile_uid];
1012                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1013                         }
1014                 }
1015
1016                 // Check if $contact has been successfully loaded
1017                 if (DBA::isResult($contact)) {
1018                         if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1019                                 $inform .= ',';
1020                         }
1021
1022                         if (isset($contact["id"])) {
1023                                 $inform .= 'cid:' . $contact["id"];
1024                         } elseif (isset($contact["notify"])) {
1025                                 $inform  .= $contact["notify"];
1026                         }
1027
1028                         $profile = $contact["url"];
1029                         $alias   = $contact["alias"];
1030                         $newname = defaults($contact, "name", $contact["nick"]);
1031                 }
1032
1033                 //if there is an url for this persons profile
1034                 if (isset($profile) && ($newname != "")) {
1035                         $replaced = true;
1036                         // create profile link
1037                         $profile = str_replace(',', '%2c', $profile);
1038                         $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1039                         $body = str_replace($tag_type . $name, $newtag, $body);
1040                         // append tag to str_tags
1041                         if (!stristr($str_tags, $newtag)) {
1042                                 if (strlen($str_tags)) {
1043                                         $str_tags .= ',';
1044                                 }
1045                                 $str_tags .= $newtag;
1046                         }
1047
1048                         /*
1049                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1050                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1051                          */
1052                         if (strlen($alias)) {
1053                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1054                                 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1055                                         if (strlen($str_tags)) {
1056                                                 $str_tags .= ',';
1057                                         }
1058                                         $str_tags .= $newtag;
1059                                 }
1060                         }
1061                 }
1062         }
1063
1064         return ['replaced' => $replaced, 'contact' => $contact];
1065 }