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