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