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\Item as ItemHelper;
33 use Friendica\Content\PageInfo;
34 use Friendica\Content\Text\BBCode;
35 use Friendica\Core\Hook;
36 use Friendica\Core\Logger;
37 use Friendica\Core\Protocol;
38 use Friendica\Core\Renderer;
39 use Friendica\Core\Session;
40 use Friendica\Core\System;
41 use Friendica\Core\Worker;
42 use Friendica\Database\DBA;
44 use Friendica\Model\Attach;
45 use Friendica\Model\Contact;
46 use Friendica\Model\Conversation;
47 use Friendica\Model\FileTag;
48 use Friendica\Model\Item;
49 use Friendica\Model\Notify\Type;
50 use Friendica\Model\Photo;
51 use Friendica\Model\Tag;
52 use Friendica\Network\HTTPException;
53 use Friendica\Object\EMail\ItemCCEMail;
54 use Friendica\Protocol\Activity;
55 use Friendica\Protocol\Diaspora;
56 use Friendica\Util\DateTimeFormat;
57 use Friendica\Security\Security;
58 use Friendica\Util\Strings;
59 use Friendica\Worker\Delivery;
61 function item_post(App $a) {
62 if (!Session::isAuthenticated()) {
63 throw new HTTPException\ForbiddenException();
68 if (!empty($_REQUEST['dropitems'])) {
69 $arr_drop = explode(',', $_REQUEST['dropitems']);
70 foreach ($arr_drop as $item) {
71 Item::deleteForUser(['id' => $item], $uid);
74 $json = ['success' => 1];
75 System::jsonExit($json);
78 Hook::callAll('post_local_start', $_REQUEST);
80 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
82 $api_source = $_REQUEST['api_source'] ?? false;
84 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
86 $return_path = $_REQUEST['return'] ?? '';
87 $preview = intval($_REQUEST['preview'] ?? 0);
90 * Check for doubly-submitted posts, and reject duplicates
91 * Note that we have to ignore previews, otherwise nothing will post
92 * after it's been previewed
94 if (!$preview && !empty($_REQUEST['post_id_random'])) {
95 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
96 Logger::info('item post: duplicate post');
97 item_post_return(DI::baseUrl(), $api_source, $return_path);
99 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
103 // Is this a reply to something?
104 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
105 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
107 $toplevel_item = null;
111 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
112 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
114 if ($toplevel_item_id || $thr_parent_uri) {
115 if ($toplevel_item_id) {
116 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
117 } elseif ($thr_parent_uri) {
118 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
121 // if this isn't the top-level parent of the conversation, find it
122 if (DBA::isResult($toplevel_item)) {
123 // The URI and the contact is taken from the direct parent which needn't to be the top parent
124 $thr_parent_uri = $toplevel_item['uri'];
126 if ($toplevel_item['gravity'] != GRAVITY_PARENT) {
127 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item['parent']]);
131 if (!DBA::isResult($toplevel_item)) {
132 notice(DI::l10n()->t('Unable to locate original post.'));
134 DI::baseUrl()->redirect($return_path);
136 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
139 // When commenting on a public post then store the post for the current user
140 // This enables interaction like starring and saving into folders
141 if ($toplevel_item['uid'] == 0) {
142 $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], local_user());
143 Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
145 $toplevel_item = Item::selectFirst([], ['id' => $stored]);
149 $toplevel_item_id = $toplevel_item['id'];
150 $parent_user = $toplevel_item['uid'];
152 $objecttype = Activity\ObjectType::COMMENT;
155 if ($toplevel_item_id) {
156 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
159 $post_id = intval($_REQUEST['post_id'] ?? 0);
160 $app = strip_tags($_REQUEST['source'] ?? '');
161 $extid = strip_tags($_REQUEST['extid'] ?? '');
162 $object = $_REQUEST['object'] ?? '';
164 // Don't use "defaults" here. It would turn 0 to 1
165 if (!isset($_REQUEST['wall'])) {
168 $wall = $_REQUEST['wall'];
171 // Ensure that the user id in a thread always stay the same
172 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
173 $profile_uid = $parent_user;
176 // Check for multiple posts with the same message id (when the post was created via API)
177 if (($message_id != '') && ($profile_uid != 0)) {
178 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
179 Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
184 // Allow commenting if it is an answer to a public post
185 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
187 // Now check that valid personal details have been provided
188 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
189 notice(DI::l10n()->t('Permission denied.'));
191 DI::baseUrl()->redirect($return_path);
194 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
197 // Init post instance
200 // is this an edited post?
202 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
205 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
207 if (!DBA::isResult($user) && !$toplevel_item_id) {
214 $body = $_REQUEST['body'] ?? '';
215 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
217 // If we have a speparate attachment, we need to add it to the body.
218 if (!empty($has_attachment)) {
219 $attachment_type = $_REQUEST['attachment_type'] ?? '';
220 $attachment_title = $_REQUEST['attachment_title'] ?? '';
221 $attachment_text = $_REQUEST['attachment_text'] ?? '';
223 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
224 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
226 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
227 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
229 'type' => $attachment_type,
230 'title' => $attachment_title,
231 'text' => $attachment_text,
232 'url' => $attachment_url,
235 if (!empty($attachment_img_src)) {
236 $attachment['images'] = [
238 'src' => $attachment_img_src,
239 'width' => $attachment_img_width,
240 'height' => $attachment_img_height
245 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
246 $body .= $att_bbcode;
249 // Convert links with empty descriptions to links without an explicit description
250 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
252 if (!empty($orig_post)) {
253 $str_group_allow = $orig_post['allow_gid'];
254 $str_contact_allow = $orig_post['allow_cid'];
255 $str_group_deny = $orig_post['deny_gid'];
256 $str_contact_deny = $orig_post['deny_cid'];
257 $location = $orig_post['location'];
258 $coord = $orig_post['coord'];
259 $verb = $orig_post['verb'];
260 $objecttype = $orig_post['object-type'];
261 $app = $orig_post['app'];
262 $categories = $orig_post['file'] ?? '';
263 $title = trim($_REQUEST['title'] ?? '');
265 $private = $orig_post['private'];
266 $pubmail_enabled = $orig_post['pubmail'];
267 $network = $orig_post['network'];
268 $guid = $orig_post['guid'];
269 $extid = $orig_post['extid'];
271 $str_contact_allow = '';
272 $str_group_allow = '';
273 $str_contact_deny = '';
274 $str_group_deny = '';
276 if (($_REQUEST['visibility'] ?? '') !== 'public') {
277 $aclFormatter = DI::aclFormatter();
278 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
279 $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? '';
280 $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? '';
281 $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? '';
284 $title = trim($_REQUEST['title'] ?? '');
285 $location = trim($_REQUEST['location'] ?? '');
286 $coord = trim($_REQUEST['coord'] ?? '');
287 $verb = trim($_REQUEST['verb'] ?? '');
288 $emailcc = trim($_REQUEST['emailcc'] ?? '');
290 $network = trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN);
291 $guid = System::createUUID();
293 $postopts = $_REQUEST['postopts'] ?? '';
295 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
296 $private = Item::PRIVATE;
297 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
298 $private = Item::UNLISTED;
300 $private = Item::PUBLIC;
303 // If this is a comment, set the permissions from the parent.
305 if ($toplevel_item) {
306 // for non native networks use the network of the original post as network of the item
307 if (($toplevel_item['network'] != Protocol::DIASPORA)
308 && ($toplevel_item['network'] != Protocol::OSTATUS)
309 && ($network == "")) {
310 $network = $toplevel_item['network'];
313 $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
314 $str_group_allow = $toplevel_item['allow_gid'] ?? '';
315 $str_contact_deny = $toplevel_item['deny_cid'] ?? '';
316 $str_group_deny = $toplevel_item['deny_gid'] ?? '';
317 $private = $toplevel_item['private'];
319 $wall = $toplevel_item['wall'];
322 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
324 // if using the API, we won't see pubmail_enable - figure out if it should be set
325 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
326 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
327 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
331 if (!strlen($body)) {
333 System::jsonExit(['preview' => '']);
336 notice(DI::l10n()->t('Empty post discarded.'));
338 DI::baseUrl()->redirect($return_path);
341 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
345 if (!empty($categories)) {
346 // get the "fileas" tags for this post
347 $filedas = FileTag::fileToArray($categories);
350 // save old and new categories, so we can determine what needs to be deleted from pconfig
351 $categories_old = $categories;
352 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
353 $categories_new = $categories;
355 if (!empty($filedas) && is_array($filedas)) {
356 // append the fileas stuff to the new categories list
357 $categories .= FileTag::arrayToFile($filedas);
360 // get contact info for poster
366 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
368 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
369 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
370 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
373 if (DBA::isResult($author)) {
374 $contact_id = $author['id'];
377 // get contact info for owner
378 if ($profile_uid == local_user() || $allow_comment) {
379 $contact_record = $author ?: [];
381 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
384 // Look for any tags and linkify them
386 $private_forum = false;
388 $only_to_forum = false;
391 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) use ($profile_uid, $network, $str_contact_allow, &$inform, &$private_forum, &$private_id, &$only_to_forum, &$forum_contact) {
392 $tags = BBCode::getTags($body);
396 foreach ($tags as $tag) {
397 $tag_type = substr($tag, 0, 1);
399 if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
403 /* If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
404 * Robert Johnson should be first in the $tags array
406 foreach ($tagged as $nextTag) {
407 if (stristr($nextTag, $tag . ' ')) {
412 $success = ItemHelper::replaceTag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
413 if ($success['replaced']) {
416 // When the forum is private or the forum is addressed with a "!" make the post private
417 if (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
418 $private_forum = $success['contact']['prv'];
419 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
420 $private_id = $success['contact']['id'];
421 $forum_contact = $success['contact'];
422 } elseif (!empty($success['contact']['forum']) && ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
423 $private_forum = false;
424 $only_to_forum = true;
425 $private_id = $success['contact']['id'];
426 $forum_contact = $success['contact'];
433 $original_contact_id = $contact_id;
435 if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
436 // we tagged a forum in a top level post. Now we change the post
437 $private = $private_forum;
439 $str_group_allow = '';
440 $str_contact_deny = '';
441 $str_group_deny = '';
442 if ($private_forum) {
443 $str_contact_allow = '<' . $private_id . '>';
445 $str_contact_allow = '';
447 $contact_id = $private_id;
448 $contact_record = $forum_contact;
449 $_REQUEST['origin'] = false;
454 * When a photo was uploaded into the message using the (profile wall) ajax
455 * uploader, The permissions are initially set to disallow anybody but the
456 * owner from seeing it. This is because the permissions may not yet have been
457 * set for the post. If it's private, the photo permissions should be set
458 * appropriately. But we didn't know the final permissions on the post until
459 * now. So now we'll look for links of uploaded messages that are in the
460 * post and set them to the same permissions as the post itself.
465 if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
466 $objecttype = Activity\ObjectType::IMAGE;
470 * Next link in any attachment references we find in the post.
474 /// @todo these lines should be moved to Model/Attach (Once it exists)
475 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
476 $attaches = $match[1];
477 if (count($attaches)) {
478 foreach ($attaches as $attach) {
479 // Ensure to only modify attachments that you own
480 $srch = '<' . intval($original_contact_id) . '>';
482 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
484 if (!Attach::exists($condition)) {
488 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
489 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
490 $condition = ['id' => $attach];
491 Attach::update($fields, $condition);
496 // embedded bookmark or attachment in post? set bookmark flag
498 $data = BBCode::getAttachmentData($body);
499 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
500 && ($posttype != Item::PT_PERSONAL_NOTE)) {
501 $posttype = Item::PT_PAGE;
502 $objecttype = Activity\ObjectType::BOOKMARK;
505 $body = DI::bbCodeVideo()->transform($body);
507 $body = BBCode::scaleExternalImages($body);
509 // Setting the object type if not defined before
511 $objecttype = Activity\ObjectType::NOTE; // Default value
512 $objectdata = BBCode::getAttachedData($body);
514 if ($objectdata["type"] == "link") {
515 $objecttype = Activity\ObjectType::BOOKMARK;
516 } elseif ($objectdata["type"] == "video") {
517 $objecttype = Activity\ObjectType::VIDEO;
518 } elseif ($objectdata["type"] == "photo") {
519 $objecttype = Activity\ObjectType::IMAGE;
527 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
528 foreach ($match[2] as $mtch) {
529 $fields = ['id', 'filename', 'filesize', 'filetype'];
530 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
531 if ($attachment !== false) {
532 if (strlen($attachments)) {
535 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
536 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
537 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
539 $body = str_replace($match[1],'',$body);
543 if (!strlen($verb)) {
544 $verb = Activity::POST;
547 if ($network == "") {
548 $network = Protocol::DFRN;
551 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
553 // even if the post arrived via API we are considering that it
554 // originated on this site by default for determining relayability.
556 // Don't use "defaults" here. It would turn 0 to 1
557 if (!isset($_REQUEST['origin'])) {
560 $origin = $_REQUEST['origin'];
563 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
565 // Fallback so that we alway have a parent uri
566 if (!$thr_parent_uri || !$toplevel_item_id) {
567 $thr_parent_uri = $uri;
571 $datarray['uid'] = $profile_uid;
572 $datarray['wall'] = $wall;
573 $datarray['gravity'] = $gravity;
574 $datarray['network'] = $network;
575 $datarray['contact-id'] = $contact_id;
576 $datarray['owner-name'] = $contact_record['name'] ?? '';
577 $datarray['owner-link'] = $contact_record['url'] ?? '';
578 $datarray['owner-avatar'] = $contact_record['thumb'] ?? '';
579 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
580 $datarray['author-name'] = $author['name'];
581 $datarray['author-link'] = $author['url'];
582 $datarray['author-avatar'] = $author['thumb'];
583 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
584 $datarray['created'] = DateTimeFormat::utcNow();
585 $datarray['edited'] = DateTimeFormat::utcNow();
586 $datarray['commented'] = DateTimeFormat::utcNow();
587 $datarray['received'] = DateTimeFormat::utcNow();
588 $datarray['changed'] = DateTimeFormat::utcNow();
589 $datarray['extid'] = $extid;
590 $datarray['guid'] = $guid;
591 $datarray['uri'] = $uri;
592 $datarray['title'] = $title;
593 $datarray['body'] = $body;
594 $datarray['app'] = $app;
595 $datarray['location'] = $location;
596 $datarray['coord'] = $coord;
597 $datarray['file'] = $categories;
598 $datarray['inform'] = $inform;
599 $datarray['verb'] = $verb;
600 $datarray['post-type'] = $posttype;
601 $datarray['object-type'] = $objecttype;
602 $datarray['allow_cid'] = $str_contact_allow;
603 $datarray['allow_gid'] = $str_group_allow;
604 $datarray['deny_cid'] = $str_contact_deny;
605 $datarray['deny_gid'] = $str_group_deny;
606 $datarray['private'] = $private;
607 $datarray['pubmail'] = $pubmail_enabled;
608 $datarray['attach'] = $attachments;
610 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
611 $datarray['parent-uri'] = $thr_parent_uri;
613 $datarray['postopts'] = $postopts;
614 $datarray['origin'] = $origin;
615 $datarray['moderated'] = false;
616 $datarray['object'] = $object;
619 * These fields are for the convenience of addons...
620 * 'self' if true indicates the owner is posting on their own wall
621 * If parent is 0 it is a top-level post.
623 $datarray['parent'] = $toplevel_item_id;
624 $datarray['self'] = $self;
626 // This triggers posts via API and the mirror functions
627 $datarray['api_source'] = $api_source;
629 // This field is for storing the raw conversation data
630 $datarray['protocol'] = Conversation::PARCEL_DFRN;
632 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
633 if (DBA::isResult($conversation)) {
634 if ($conversation['conversation-uri'] != '') {
635 $datarray['conversation-uri'] = $conversation['conversation-uri'];
637 if ($conversation['conversation-href'] != '') {
638 $datarray['conversation-href'] = $conversation['conversation-href'];
643 $datarray['edit'] = true;
645 // If this was a share, add missing data here
646 $datarray = Item::addShareDataFromOriginal($datarray);
648 $datarray['edit'] = false;
651 // Check for hashtags in the body and repair or add hashtag links
652 if ($preview || $orig_post) {
653 $datarray['body'] = Item::setHashtags($datarray['body']);
656 // preview mode - prepare the body for display and send it via json
658 // We set the datarray ID to -1 because in preview mode the dataray
659 // doesn't have an ID.
660 $datarray["id"] = -1;
661 $datarray["uri-id"] = -1;
662 $datarray["item_id"] = -1;
663 $datarray["author-network"] = Protocol::DFRN;
665 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
667 System::jsonExit(['preview' => $o]);
670 Hook::callAll('post_local',$datarray);
672 if (!empty($datarray['cancel'])) {
673 Logger::info('mod_item: post cancelled by addon.');
675 DI::baseUrl()->redirect($return_path);
678 $json = ['cancel' => 1];
679 if (!empty($_REQUEST['jsreload'])) {
680 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
683 System::jsonExit($json);
687 // Fill the cache field
688 // This could be done in Item::update as well - but we have to check for the existance of some fields.
689 Item::putInCache($datarray);
692 'title' => $datarray['title'],
693 'body' => $datarray['body'],
694 'attach' => $datarray['attach'],
695 'file' => $datarray['file'],
696 'rendered-html' => $datarray['rendered-html'],
697 'rendered-hash' => $datarray['rendered-hash'],
698 'edited' => DateTimeFormat::utcNow(),
699 'changed' => DateTimeFormat::utcNow()];
701 Item::update($fields, ['id' => $post_id]);
703 // update filetags in pconfig
704 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
707 DI::baseUrl()->redirect($return_path);
710 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
713 unset($datarray['edit']);
714 unset($datarray['self']);
715 unset($datarray['api_source']);
718 $signed = Diaspora::createCommentSignature($uid, $datarray);
719 if (!empty($signed)) {
720 $datarray['diaspora_signed_text'] = json_encode($signed);
724 $post_id = Item::insert($datarray);
727 notice(DI::l10n()->t('Item wasn\'t stored.'));
729 DI::baseUrl()->redirect($return_path);
732 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
735 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
737 if (!DBA::isResult($datarray)) {
738 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
740 DI::baseUrl()->redirect($return_path);
743 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
746 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
748 if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
749 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
752 // update filetags in pconfig
753 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
755 // These notifications are sent if someone else is commenting other your wall
756 if ($contact_record != $author) {
757 if ($toplevel_item_id) {
759 'type' => Type::COMMENT,
760 'notify_flags' => $user['notify-flags'],
761 'language' => $user['language'],
762 'to_name' => $user['username'],
763 'to_email' => $user['email'],
764 'uid' => $user['uid'],
766 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
767 'source_name' => $datarray['author-name'],
768 'source_link' => $datarray['author-link'],
769 'source_photo' => $datarray['author-avatar'],
770 'verb' => Activity::POST,
772 'parent' => $toplevel_item_id,
773 'parent_uri' => $toplevel_item['uri']
775 } elseif (empty($forum_contact)) {
777 'type' => Type::WALL,
778 'notify_flags' => $user['notify-flags'],
779 'language' => $user['language'],
780 'to_name' => $user['username'],
781 'to_email' => $user['email'],
782 'uid' => $user['uid'],
784 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
785 'source_name' => $datarray['author-name'],
786 'source_link' => $datarray['author-link'],
787 'source_photo' => $datarray['author-avatar'],
788 'verb' => Activity::POST,
794 Hook::callAll('post_local_end', $datarray);
796 if (strlen($emailcc) && $profile_uid == local_user()) {
797 $recipients = explode(',', $emailcc);
798 if (count($recipients)) {
799 foreach ($recipients as $recipient) {
800 $address = trim($recipient);
801 if (!strlen($address)) {
804 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
805 $datarray, $address, $author['thumb'] ?? ''));
810 // Insert an item entry for UID=0 for global entries.
811 // We now do it in the background to save some time.
812 // This is important in interactive environments like the frontend or the API.
813 // We don't fork a new process since this is done anyway with the following command
814 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
816 // When we are doing some forum posting via ! we have to start the notifier manually.
817 // These kind of posts don't initiate the notifier call in the item class.
818 if ($only_to_forum) {
819 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
822 Logger::info('post_complete');
828 item_post_return(DI::baseUrl(), $api_source, $return_path);
832 function item_post_return($baseurl, $api_source, $return_path)
839 DI::baseUrl()->redirect($return_path);
842 $json = ['success' => 1];
843 if (!empty($_REQUEST['jsreload'])) {
844 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
847 Logger::info('post_json', ['json' => $json]);
849 System::jsonExit($json);
852 function item_content(App $a)
854 if (!Session::isAuthenticated()) {
860 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
861 if (DI::mode()->isAjax()) {
862 Item::deleteForUser(['id' => $a->argv[2]], local_user());
863 // ajax return: [<item id>, 0 (no perm) | <owner id>]
864 System::jsonExit([intval($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]);
880 * @param string $return
882 * @throws HTTPException\InternalServerErrorException
884 function drop_item(int $id, string $return = '')
886 // locate item to be deleted
887 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
888 $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
890 if (!DBA::isResult($item)) {
891 notice(DI::l10n()->t('Item not found.'));
892 DI::baseUrl()->redirect('network');
895 if ($item['deleted']) {
901 // check if logged in user is either the author or owner of this item
902 if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
903 $contact_id = $item['contact-id'];
906 if ((local_user() == $item['uid']) || $contact_id) {
907 if (!empty($item['parent'])) {
908 $parentitem = Item::selectFirstForUser(local_user(), ['guid'], ['id' => $item['parent']]);
912 Item::deleteForUser(['id' => $item['id']], local_user());
914 $return_url = hex2bin($return);
916 // removes update_* from return_url to ignore Ajax refresh
917 $return_url = str_replace("update_", "", $return_url);
919 // Check if delete a comment
920 if ($item['gravity'] == GRAVITY_COMMENT) {
921 // Return to parent guid
922 if (!empty($parentitem)) {
923 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
925 } // In case something goes wrong
927 DI::baseUrl()->redirect('network');
931 // if unknown location or deleting top level post called from display
932 if (empty($return_url) || strpos($return_url, 'display') !== false) {
933 DI::baseUrl()->redirect('network');
936 DI::baseUrl()->redirect($return_url);
941 notice(DI::l10n()->t('Permission denied.'));
942 DI::baseUrl()->redirect('display/' . $item['guid']);