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
381 $tags = BBCode::getTags($body);
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);
389 $private_forum = false;
390 $only_to_forum = false;
394 foreach ($tags as $tag) {
395 $tag_type = substr($tag, 0, 1);
397 if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
402 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
403 * Robert Johnson should be first in the $tags array
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;
413 if ($fullnametagged) {
417 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
418 if ($success['replaced']) {
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'];
437 $original_contact_id = $contact_id;
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;
443 $str_group_allow = '';
444 $str_contact_deny = '';
445 $str_group_deny = '';
446 if ($private_forum) {
447 $str_contact_allow = '<' . $private_id . '>';
449 $str_contact_allow = '';
451 $contact_id = $private_id;
452 $contact_record = $forum_contact;
453 $_REQUEST['origin'] = false;
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.
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;
474 * Next link in any attachment references we find in the post.
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) . '>';
486 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
488 if (!Attach::exists($condition)) {
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);
500 // embedded bookmark or attachment in post? set bookmark flag
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;
509 $body = DI::bbCodeVideo()->transform($body);
511 $body = BBCode::scaleExternalImages($body);
513 // Setting the object type if not defined before
515 $objecttype = Activity\ObjectType::NOTE; // Default value
516 $objectdata = BBCode::getAttachedData($body);
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;
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)) {
539 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
540 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
541 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
543 $body = str_replace($match[1],'',$body);
547 if (!strlen($verb)) {
548 $verb = Activity::POST;
551 if ($network == "") {
552 $network = Protocol::DFRN;
555 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
557 // even if the post arrived via API we are considering that it
558 // originated on this site by default for determining relayability.
560 // Don't use "defaults" here. It would turn 0 to 1
561 if (!isset($_REQUEST['origin'])) {
564 $origin = $_REQUEST['origin'];
567 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
569 // Fallback so that we alway have a parent uri
570 if (!$thr_parent_uri || !$toplevel_item_id) {
571 $thr_parent_uri = $uri;
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;
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;
618 $datarray['postopts'] = $postopts;
619 $datarray['origin'] = $origin;
620 $datarray['moderated'] = false;
621 $datarray['object'] = $object;
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.
628 $datarray['parent'] = $toplevel_item_id;
629 $datarray['self'] = $self;
631 // This triggers posts via API and the mirror functions
632 $datarray['api_source'] = $api_source;
634 // This field is for storing the raw conversation data
635 $datarray['protocol'] = Conversation::PARCEL_DFRN;
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'];
642 if ($conversation['conversation-href'] != '') {
643 $datarray['conversation-href'] = $conversation['conversation-href'];
648 $datarray['edit'] = true;
650 // If this was a share, add missing data here
651 $datarray = Item::addShareDataFromOriginal($datarray);
653 $datarray['edit'] = false;
656 // Check for hashtags in the body and repair or add hashtag links
657 if ($preview || $orig_post) {
658 Item::setHashtags($datarray);
661 // preview mode - prepare the body for display and send it via json
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;
669 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
671 System::jsonExit(['preview' => $o]);
674 Hook::callAll('post_local',$datarray);
676 if (!empty($datarray['cancel'])) {
677 Logger::info('mod_item: post cancelled by addon.');
679 DI::baseUrl()->redirect($return_path);
682 $json = ['cancel' => 1];
683 if (!empty($_REQUEST['jsreload'])) {
684 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
687 System::jsonExit($json);
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);
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()];
706 Item::update($fields, ['id' => $post_id]);
708 // update filetags in pconfig
709 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
711 info(DI::l10n()->t('Post updated.'));
713 DI::baseUrl()->redirect($return_path);
716 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
719 unset($datarray['edit']);
720 unset($datarray['self']);
721 unset($datarray['api_source']);
724 $signed = Diaspora::createCommentSignature($uid, $datarray);
725 if (!empty($signed)) {
726 $datarray['diaspora_signed_text'] = json_encode($signed);
730 $post_id = Item::insert($datarray);
733 info(DI::l10n()->t('Item wasn\'t stored.'));
735 DI::baseUrl()->redirect($return_path);
738 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
741 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
743 if (!DBA::isResult($datarray)) {
744 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
746 DI::baseUrl()->redirect($return_path);
749 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
752 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
754 // update filetags in pconfig
755 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
757 // These notifications are sent if someone else is commenting other your wall
758 if ($toplevel_item_id) {
759 if ($contact_record != $author) {
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'],
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,
774 'parent' => $toplevel_item_id,
775 'parent_uri' => $toplevel_item['uri']
779 if (($contact_record != $author) && !count($forum_contact)) {
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'],
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,
798 Hook::callAll('post_local_end', $datarray);
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)) {
808 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
809 $datarray, $address, $author['thumb'] ?? ''));
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);
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);
826 Logger::info('post_complete');
832 info(DI::l10n()->t('Post published.'));
833 item_post_return(DI::baseUrl(), $api_source, $return_path);
837 function item_post_return($baseurl, $api_source, $return_path)
844 DI::baseUrl()->redirect($return_path);
847 $json = ['success' => 1];
848 if (!empty($_REQUEST['jsreload'])) {
849 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
852 Logger::info('post_json', ['json' => $json]);
854 System::jsonExit($json);
857 function item_content(App $a)
859 if (!Session::isAuthenticated()) {
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());
869 if (!empty($a->argv[3])) {
870 $o = drop_item($a->argv[2], $a->argv[3]);
873 $o = drop_item($a->argv[2]);
877 if (DI::mode()->isAjax()) {
878 // ajax return: [<item id>, 0 (no perm) | <owner id>]
879 System::jsonExit([intval($a->argv[2]), intval($o)]);
887 * This function removes the tag $tag from the text $body and replaces it with
888 * the appropriate link.
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
898 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
899 * @throws ImagickException
900 * @throws HTTPException\InternalServerErrorException
902 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
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)) {
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]);
925 if ($data["alias"] != "") {
926 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
928 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
929 if (strlen($str_tags)) {
933 $str_tags .= $newtag;
941 //get the person's name
942 $name = substr($tag, 1);
944 // Sometimes the tag detection doesn't seem to work right
945 // This is some workaround
946 $nameparts = explode(" ", $name);
947 $name = $nameparts[0];
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);
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);
961 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
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]);
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);
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);
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);
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);
995 // Check if $contact has been successfully loaded
996 if (DBA::isResult($contact)) {
997 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1001 if (isset($contact["id"])) {
1002 $inform .= 'cid:' . $contact["id"];
1003 } elseif (isset($contact["notify"])) {
1004 $inform .= $contact["notify"];
1007 $profile = $contact["url"];
1008 $alias = $contact["alias"];
1009 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1012 //if there is an url for this persons profile
1013 if (isset($profile) && ($newname != "")) {
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)) {
1024 $str_tags .= $newtag;
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.
1031 if (!empty($alias)) {
1032 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1033 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1034 if (strlen($str_tags)) {
1037 $str_tags .= $newtag;
1043 return ['replaced' => $replaced, 'contact' => $contact];
1046 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_uriid)
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'] . ']')) {
1057 $implicit_mentions = [
1058 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1061 $parent_terms = Tag::getByURIId($thread_parent_uriid, [Tag::MENTION, Tag::IMPLICIT_MENTION]);
1063 foreach ($parent_terms as $parent_term) {
1064 $implicit_mentions[$parent_term['url']] = $parent_term['name'];
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]';