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