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