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