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