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