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