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