3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
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.
27 * All of these become an "item" which is our basic unit of
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;
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;
58 require_once __DIR__ . '/../include/items.php';
60 function item_post(App $a) {
61 if (!Session::isAuthenticated()) {
62 throw new HTTPException\ForbiddenException();
67 if (!empty($_REQUEST['dropitems'])) {
68 $arr_drop = explode(',', $_REQUEST['dropitems']);
69 drop_items($arr_drop);
70 $json = ['success' => 1];
71 System::jsonExit($json);
74 Hook::callAll('post_local_start', $_REQUEST);
76 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
78 $api_source = $_REQUEST['api_source'] ?? false;
80 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
82 $return_path = $_REQUEST['return'] ?? '';
83 $preview = intval($_REQUEST['preview'] ?? 0);
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
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);
95 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
99 // Is this a reply to something?
100 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
101 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
103 $thread_parent_uriid = 0;
104 $thread_parent_contact = null;
106 $toplevel_item = null;
109 $parent_contact = null;
112 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
113 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
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]);
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"]);
129 if ($toplevel_item['id'] != $toplevel_item['parent']) {
130 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item['parent']]);
134 if (!DBA::isResult($toplevel_item)) {
135 notice(DI::l10n()->t('Unable to locate original post.'));
137 DI::baseUrl()->redirect($return_path);
139 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
142 $toplevel_item_id = $toplevel_item['id'];
143 $parent_user = $toplevel_item['uid'];
145 $objecttype = Activity\ObjectType::COMMENT;
148 if ($toplevel_item_id) {
149 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
152 $post_id = intval($_REQUEST['post_id'] ?? 0);
153 $app = strip_tags($_REQUEST['source'] ?? '');
154 $extid = strip_tags($_REQUEST['extid'] ?? '');
155 $object = $_REQUEST['object'] ?? '';
157 // Don't use "defaults" here. It would turn 0 to 1
158 if (!isset($_REQUEST['wall'])) {
161 $wall = $_REQUEST['wall'];
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;
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]);
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);
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.'));
184 DI::baseUrl()->redirect($return_path);
187 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
190 // Init post instance
193 // is this an edited post?
195 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
198 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
200 if (!DBA::isResult($user) && !$toplevel_item_id) {
207 $body = $_REQUEST['body'] ?? '';
208 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
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'] ?? '';
216 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
217 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
219 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
220 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
222 'type' => $attachment_type,
223 'title' => $attachment_title,
224 'text' => $attachment_text,
225 'url' => $attachment_url,
228 if (!empty($attachment_img_src)) {
229 $attachment['images'] = [
231 'src' => $attachment_img_src,
232 'width' => $attachment_img_width,
233 'height' => $attachment_img_height
238 $att_bbcode = add_page_info_data($attachment);
239 $body .= $att_bbcode;
242 // Convert links with empty descriptions to links without an explicit description
243 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
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']));
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'];
264 $str_contact_allow = '';
265 $str_group_allow = '';
266 $str_contact_deny = '';
267 $str_group_deny = '';
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'] ?? '';
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'] ?? ''));
283 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
284 $guid = System::createUUID();
286 $postopts = $_REQUEST['postopts'] ?? '';
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;
293 $private = Item::PUBLIC;
296 // If this is a comment, set the permissions from the parent.
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'];
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'];
312 $wall = $toplevel_item['wall'];
315 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
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(), '']);
324 if (!strlen($body)) {
326 System::jsonExit(['preview' => '']);
329 info(DI::l10n()->t('Empty post discarded.'));
331 DI::baseUrl()->redirect($return_path);
334 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
338 if (!empty($categories)) {
339 // get the "fileas" tags for this post
340 $filedas = FileTag::fileToArray($categories);
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;
348 if (!empty($filedas) && is_array($filedas)) {
349 // append the fileas stuff to the new categories list
350 $categories .= FileTag::arrayToFile($filedas);
353 // get contact info for poster
359 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
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)]);
366 if (DBA::isResult($author)) {
367 $contact_id = $author['id'];
370 // get contact info for owner
371 if ($profile_uid == local_user() || $allow_comment) {
372 $contact_record = $author;
374 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
377 // Look for any tags and linkify them
380 $tags = BBCode::getTags($body);
382 if ($thread_parent_uriid && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
383 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_uriid);
388 $private_forum = false;
389 $only_to_forum = false;
393 foreach ($tags as $tag) {
394 $tag_type = substr($tag, 0, 1);
396 if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
401 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
402 * Robert Johnson should be first in the $tags array
404 $fullnametagged = false;
405 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
406 foreach ($tagged as $nextTag) {
407 if (stristr($nextTag, $tag . ' ')) {
408 $fullnametagged = true;
412 if ($fullnametagged) {
416 $success = handle_tag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
417 if ($success['replaced']) {
420 // When the forum is private or the forum is addressed with a "!" make the post private
421 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]))) {
422 $private_forum = $success['contact']['prv'];
423 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
424 $private_id = $success['contact']['id'];
425 $forum_contact = $success['contact'];
426 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
427 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
428 $private_forum = false;
429 $only_to_forum = true;
430 $private_id = $success['contact']['id'];
431 $forum_contact = $success['contact'];
436 $original_contact_id = $contact_id;
438 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
439 // we tagged a forum in a top level post. Now we change the post
440 $private = $private_forum;
442 $str_group_allow = '';
443 $str_contact_deny = '';
444 $str_group_deny = '';
445 if ($private_forum) {
446 $str_contact_allow = '<' . $private_id . '>';
448 $str_contact_allow = '';
450 $contact_id = $private_id;
451 $contact_record = $forum_contact;
452 $_REQUEST['origin'] = false;
457 * When a photo was uploaded into the message using the (profile wall) ajax
458 * uploader, The permissions are initially set to disallow anybody but the
459 * owner from seeing it. This is because the permissions may not yet have been
460 * set for the post. If it's private, the photo permissions should be set
461 * appropriately. But we didn't know the final permissions on the post until
462 * now. So now we'll look for links of uploaded messages that are in the
463 * post and set them to the same permissions as the post itself.
468 if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
469 $objecttype = Activity\ObjectType::IMAGE;
473 * Next link in any attachment references we find in the post.
477 /// @todo these lines should be moved to Model/Attach (Once it exists)
478 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
479 $attaches = $match[1];
480 if (count($attaches)) {
481 foreach ($attaches as $attach) {
482 // Ensure to only modify attachments that you own
483 $srch = '<' . intval($original_contact_id) . '>';
485 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
487 if (!Attach::exists($condition)) {
491 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
492 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
493 $condition = ['id' => $attach];
494 Attach::update($fields, $condition);
499 // embedded bookmark or attachment in post? set bookmark flag
501 $data = BBCode::getAttachmentData($body);
502 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
503 && ($posttype != Item::PT_PERSONAL_NOTE)) {
504 $posttype = Item::PT_PAGE;
505 $objecttype = Activity\ObjectType::BOOKMARK;
508 $body = DI::bbCodeVideo()->transform($body);
510 $body = BBCode::scaleExternalImages($body);
512 // Setting the object type if not defined before
514 $objecttype = Activity\ObjectType::NOTE; // Default value
515 $objectdata = BBCode::getAttachedData($body);
517 if ($objectdata["type"] == "link") {
518 $objecttype = Activity\ObjectType::BOOKMARK;
519 } elseif ($objectdata["type"] == "video") {
520 $objecttype = Activity\ObjectType::VIDEO;
521 } elseif ($objectdata["type"] == "photo") {
522 $objecttype = Activity\ObjectType::IMAGE;
530 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
531 foreach ($match[2] as $mtch) {
532 $fields = ['id', 'filename', 'filesize', 'filetype'];
533 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
534 if ($attachment !== false) {
535 if (strlen($attachments)) {
538 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
539 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
540 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
542 $body = str_replace($match[1],'',$body);
546 if (!strlen($verb)) {
547 $verb = Activity::POST;
550 if ($network == "") {
551 $network = Protocol::DFRN;
554 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
556 // even if the post arrived via API we are considering that it
557 // originated on this site by default for determining relayability.
559 // Don't use "defaults" here. It would turn 0 to 1
560 if (!isset($_REQUEST['origin'])) {
563 $origin = $_REQUEST['origin'];
566 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
568 // Fallback so that we alway have a parent uri
569 if (!$thr_parent_uri || !$toplevel_item_id) {
570 $thr_parent_uri = $uri;
574 $datarray['uid'] = $profile_uid;
575 $datarray['wall'] = $wall;
576 $datarray['gravity'] = $gravity;
577 $datarray['network'] = $network;
578 $datarray['contact-id'] = $contact_id;
579 $datarray['owner-name'] = $contact_record['name'];
580 $datarray['owner-link'] = $contact_record['url'];
581 $datarray['owner-avatar'] = $contact_record['thumb'];
582 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
583 $datarray['author-name'] = $author['name'];
584 $datarray['author-link'] = $author['url'];
585 $datarray['author-avatar'] = $author['thumb'];
586 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
587 $datarray['created'] = DateTimeFormat::utcNow();
588 $datarray['edited'] = DateTimeFormat::utcNow();
589 $datarray['commented'] = DateTimeFormat::utcNow();
590 $datarray['received'] = DateTimeFormat::utcNow();
591 $datarray['changed'] = DateTimeFormat::utcNow();
592 $datarray['extid'] = $extid;
593 $datarray['guid'] = $guid;
594 $datarray['uri'] = $uri;
595 $datarray['title'] = $title;
596 $datarray['body'] = $body;
597 $datarray['app'] = $app;
598 $datarray['location'] = $location;
599 $datarray['coord'] = $coord;
600 $datarray['file'] = $categories;
601 $datarray['inform'] = $inform;
602 $datarray['verb'] = $verb;
603 $datarray['post-type'] = $posttype;
604 $datarray['object-type'] = $objecttype;
605 $datarray['allow_cid'] = $str_contact_allow;
606 $datarray['allow_gid'] = $str_group_allow;
607 $datarray['deny_cid'] = $str_contact_deny;
608 $datarray['deny_gid'] = $str_group_deny;
609 $datarray['private'] = $private;
610 $datarray['pubmail'] = $pubmail_enabled;
611 $datarray['attach'] = $attachments;
613 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
614 $datarray['parent-uri'] = $thr_parent_uri;
616 $datarray['postopts'] = $postopts;
617 $datarray['origin'] = $origin;
618 $datarray['moderated'] = false;
619 $datarray['object'] = $object;
622 * These fields are for the convenience of addons...
623 * 'self' if true indicates the owner is posting on their own wall
624 * If parent is 0 it is a top-level post.
626 $datarray['parent'] = $toplevel_item_id;
627 $datarray['self'] = $self;
629 // This triggers posts via API and the mirror functions
630 $datarray['api_source'] = $api_source;
632 // This field is for storing the raw conversation data
633 $datarray['protocol'] = Conversation::PARCEL_DFRN;
635 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
636 if (DBA::isResult($conversation)) {
637 if ($conversation['conversation-uri'] != '') {
638 $datarray['conversation-uri'] = $conversation['conversation-uri'];
640 if ($conversation['conversation-href'] != '') {
641 $datarray['conversation-href'] = $conversation['conversation-href'];
646 $datarray['edit'] = true;
648 // If this was a share, add missing data here
649 $datarray = Item::addShareDataFromOriginal($datarray);
651 $datarray['edit'] = false;
654 // Check for hashtags in the body and repair or add hashtag links
655 if ($preview || $orig_post) {
656 Item::setHashtags($datarray);
659 // preview mode - prepare the body for display and send it via json
661 // We set the datarray ID to -1 because in preview mode the dataray
662 // doesn't have an ID.
663 $datarray["id"] = -1;
664 $datarray["item_id"] = -1;
665 $datarray["author-network"] = Protocol::DFRN;
667 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
669 System::jsonExit(['preview' => $o]);
672 Hook::callAll('post_local',$datarray);
674 if (!empty($datarray['cancel'])) {
675 Logger::info('mod_item: post cancelled by addon.');
677 DI::baseUrl()->redirect($return_path);
680 $json = ['cancel' => 1];
681 if (!empty($_REQUEST['jsreload'])) {
682 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
685 System::jsonExit($json);
689 // Fill the cache field
690 // This could be done in Item::update as well - but we have to check for the existance of some fields.
691 Item::putInCache($datarray);
694 'title' => $datarray['title'],
695 'body' => $datarray['body'],
696 'attach' => $datarray['attach'],
697 'file' => $datarray['file'],
698 'rendered-html' => $datarray['rendered-html'],
699 'rendered-hash' => $datarray['rendered-hash'],
700 'edited' => DateTimeFormat::utcNow(),
701 'changed' => DateTimeFormat::utcNow()];
703 Item::update($fields, ['id' => $post_id]);
705 // update filetags in pconfig
706 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
708 info(DI::l10n()->t('Post updated.'));
710 DI::baseUrl()->redirect($return_path);
713 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
716 unset($datarray['edit']);
717 unset($datarray['self']);
718 unset($datarray['api_source']);
721 $signed = Diaspora::createCommentSignature($uid, $datarray);
722 if (!empty($signed)) {
723 $datarray['diaspora_signed_text'] = json_encode($signed);
727 $post_id = Item::insert($datarray);
730 info(DI::l10n()->t('Item wasn\'t stored.'));
732 DI::baseUrl()->redirect($return_path);
735 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
738 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
740 if (!DBA::isResult($datarray)) {
741 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
743 DI::baseUrl()->redirect($return_path);
746 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
749 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
751 // update filetags in pconfig
752 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
754 // These notifications are sent if someone else is commenting other your wall
755 if ($toplevel_item_id) {
756 if ($contact_record != $author) {
758 'type' => Type::COMMENT,
759 'notify_flags' => $user['notify-flags'],
760 'language' => $user['language'],
761 'to_name' => $user['username'],
762 'to_email' => $user['email'],
763 'uid' => $user['uid'],
765 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
766 'source_name' => $datarray['author-name'],
767 'source_link' => $datarray['author-link'],
768 'source_photo' => $datarray['author-avatar'],
769 'verb' => Activity::POST,
771 'parent' => $toplevel_item_id,
772 'parent_uri' => $toplevel_item['uri']
776 if (($contact_record != $author) && !count($forum_contact)) {
778 'type' => Type::WALL,
779 'notify_flags' => $user['notify-flags'],
780 'language' => $user['language'],
781 'to_name' => $user['username'],
782 'to_email' => $user['email'],
783 'uid' => $user['uid'],
785 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
786 'source_name' => $datarray['author-name'],
787 'source_link' => $datarray['author-link'],
788 'source_photo' => $datarray['author-avatar'],
789 'verb' => Activity::POST,
795 Hook::callAll('post_local_end', $datarray);
797 if (strlen($emailcc) && $profile_uid == local_user()) {
798 $recipients = explode(',', $emailcc);
799 if (count($recipients)) {
800 foreach ($recipients as $recipient) {
801 $address = trim($recipient);
802 if (!strlen($address)) {
805 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
806 $datarray, $address, $author['thumb'] ?? ''));
811 // Insert an item entry for UID=0 for global entries.
812 // We now do it in the background to save some time.
813 // This is important in interactive environments like the frontend or the API.
814 // We don't fork a new process since this is done anyway with the following command
815 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
817 // When we are doing some forum posting via ! we have to start the notifier manually.
818 // These kind of posts don't initiate the notifier call in the item class.
819 if ($only_to_forum) {
820 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
823 Logger::info('post_complete');
829 info(DI::l10n()->t('Post published.'));
830 item_post_return(DI::baseUrl(), $api_source, $return_path);
834 function item_post_return($baseurl, $api_source, $return_path)
841 DI::baseUrl()->redirect($return_path);
844 $json = ['success' => 1];
845 if (!empty($_REQUEST['jsreload'])) {
846 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
849 Logger::info('post_json', ['json' => $json]);
851 System::jsonExit($json);
854 function item_content(App $a)
856 if (!Session::isAuthenticated()) {
862 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
863 if (DI::mode()->isAjax()) {
864 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
866 if (!empty($a->argv[3])) {
867 $o = drop_item($a->argv[2], $a->argv[3]);
870 $o = drop_item($a->argv[2]);
874 if (DI::mode()->isAjax()) {
875 // ajax return: [<item id>, 0 (no perm) | <owner id>]
876 System::jsonExit([intval($a->argv[2]), intval($o)]);
884 * This function removes the tag $tag from the text $body and replaces it with
885 * the appropriate link.
888 * @param string $body the text to replace the tag in
889 * @param string $inform a comma-seperated string containing everybody to inform
890 * @param integer $profile_uid
891 * @param string $tag the tag to replace
892 * @param string $network The network of the post
894 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
895 * @throws ImagickException
896 * @throws HTTPException\InternalServerErrorException
898 function handle_tag(&$body, &$inform, $profile_uid, $tag, $network = "")
902 //is it a person tag?
903 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
904 $tag_type = substr($tag, 0, 1);
905 //is it already replaced?
906 if (strpos($tag, '[url=')) {
907 // Checking for the alias that is used for OStatus
908 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
909 if (preg_match($pattern, $tag, $matches)) {
910 $data = Contact::getDetailsByURL($matches[1]);
912 if ($data["alias"] != "") {
913 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
920 //get the person's name
921 $name = substr($tag, 1);
923 // Sometimes the tag detection doesn't seem to work right
924 // This is some workaround
925 $nameparts = explode(" ", $name);
926 $name = $nameparts[0];
928 // Try to detect the contact in various ways
929 if (strpos($name, 'http://')) {
930 // At first we have to ensure that the contact exists
931 Contact::getIdForURL($name);
933 // Now we should have something
934 $contact = Contact::getDetailsByURL($name);
935 } elseif (strpos($name, '@')) {
936 // This function automatically probes when no entry was found
937 $contact = Contact::getDetailsByAddr($name);
940 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
942 if (strrpos($name, '+')) {
943 // Is it in format @nick+number?
944 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
945 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
948 // select someone by nick or attag in the current network
949 if (!DBA::isResult($contact) && ($network != "")) {
950 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
951 $name, $name, $network, $profile_uid];
952 $contact = DBA::selectFirst('contact', $fields, $condition);
955 //select someone by name in the current network
956 if (!DBA::isResult($contact) && ($network != "")) {
957 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
958 $contact = DBA::selectFirst('contact', $fields, $condition);
961 // select someone by nick or attag in any network
962 if (!DBA::isResult($contact)) {
963 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
964 $contact = DBA::selectFirst('contact', $fields, $condition);
967 // select someone by name in any network
968 if (!DBA::isResult($contact)) {
969 $condition = ['name' => $name, 'uid' => $profile_uid];
970 $contact = DBA::selectFirst('contact', $fields, $condition);
974 // Check if $contact has been successfully loaded
975 if (DBA::isResult($contact)) {
976 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
980 if (isset($contact["id"])) {
981 $inform .= 'cid:' . $contact["id"];
982 } elseif (isset($contact["notify"])) {
983 $inform .= $contact["notify"];
986 $profile = $contact["url"];
987 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
990 //if there is an url for this persons profile
991 if (isset($profile) && ($newname != "")) {
993 // create profile link
994 $profile = str_replace(',', '%2c', $profile);
995 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
996 $body = str_replace($tag_type . $name, $newtag, $body);
1000 return ['replaced' => $replaced, 'contact' => $contact];
1003 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_uriid)
1005 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1006 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1007 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1008 $contact = Tag::TAG_CHARACTER[Tag::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1009 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1014 $implicit_mentions = [
1015 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1018 $parent_terms = Tag::getByURIId($thread_parent_uriid, [Tag::MENTION, Tag::IMPLICIT_MENTION]);
1020 foreach ($parent_terms as $parent_term) {
1021 $implicit_mentions[$parent_term['url']] = $parent_term['name'];
1024 foreach ($implicit_mentions as $url => $label) {
1025 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1026 $tags[] = Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';