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