3 * @copyright Copyright (C) 2010-2021, the Friendica project
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\Session;
39 use Friendica\Core\System;
40 use Friendica\Core\Worker;
41 use Friendica\Database\DBA;
43 use Friendica\Model\Attach;
44 use Friendica\Model\Contact;
45 use Friendica\Model\Conversation;
46 use Friendica\Model\FileTag;
47 use Friendica\Model\Item;
48 use Friendica\Model\ItemURI;
49 use Friendica\Model\Notification;
50 use Friendica\Model\Photo;
51 use Friendica\Model\Post;
52 use Friendica\Model\Tag;
53 use Friendica\Model\User;
54 use Friendica\Network\HTTPException;
55 use Friendica\Object\EMail\ItemCCEMail;
56 use Friendica\Protocol\Activity;
57 use Friendica\Protocol\Diaspora;
58 use Friendica\Security\Security;
59 use Friendica\Util\DateTimeFormat;
60 use Friendica\Util\ParseUrl;
61 use Friendica\Worker\Delivery;
63 function item_post(App $a) {
64 if (!Session::isAuthenticated()) {
65 throw new HTTPException\ForbiddenException();
70 if (!empty($_REQUEST['dropitems'])) {
71 $arr_drop = explode(',', $_REQUEST['dropitems']);
72 foreach ($arr_drop as $item) {
73 Item::deleteForUser(['id' => $item], $uid);
76 $json = ['success' => 1];
77 System::jsonExit($json);
80 Hook::callAll('post_local_start', $_REQUEST);
82 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
84 $api_source = $_REQUEST['api_source'] ?? false;
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 $parent_item_id = intval($_REQUEST['parent'] ?? 0);
105 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
108 $toplevel_item = null;
109 $toplevel_item_id = 0;
110 $toplevel_user_id = null;
113 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
114 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
116 if ($parent_item_id || $thr_parent_uri) {
117 if ($parent_item_id) {
118 $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item_id]);
119 } elseif ($thr_parent_uri) {
120 $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
123 // if this isn't the top-level parent of the conversation, find it
124 if (DBA::isResult($parent_item)) {
125 // The URI and the contact is taken from the direct parent which needn't to be the top parent
126 $thr_parent_uri = $parent_item['uri'];
127 $toplevel_item = $parent_item;
129 if ($parent_item['gravity'] != GRAVITY_PARENT) {
130 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['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 // When commenting on a public post then store the post for the current user
143 // This enables interaction like starring and saving into folders
144 if ($toplevel_item['uid'] == 0) {
145 $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], local_user());
146 Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
148 $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $stored]);
152 $toplevel_item_id = $toplevel_item['id'];
153 $toplevel_user_id = $toplevel_item['uid'];
155 $objecttype = Activity\ObjectType::COMMENT;
158 if ($toplevel_item_id) {
159 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
162 $post_id = intval($_REQUEST['post_id'] ?? 0);
163 $app = strip_tags($_REQUEST['source'] ?? '');
164 $extid = strip_tags($_REQUEST['extid'] ?? '');
165 $object = $_REQUEST['object'] ?? '';
167 // Don't use "defaults" here. It would turn 0 to 1
168 if (!isset($_REQUEST['wall'])) {
171 $wall = $_REQUEST['wall'];
174 // Ensure that the user id in a thread always stay the same
175 if (!is_null($toplevel_user_id) && in_array($toplevel_user_id, [local_user(), 0])) {
176 $profile_uid = $toplevel_user_id;
179 // Allow commenting if it is an answer to a public post
180 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
182 // Now check that valid personal details have been provided
183 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
184 notice(DI::l10n()->t('Permission denied.'));
186 DI::baseUrl()->redirect($return_path);
189 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
192 // Init post instance
195 // is this an edited post?
197 $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
200 $user = User::getById($profile_uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
201 if (!DBA::isResult($user) && !$toplevel_item_id) {
208 $body = $_REQUEST['body'] ?? '';
209 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
211 // If we have a speparate attachment, we need to add it to the body.
212 if (!empty($has_attachment)) {
213 $attachment_type = $_REQUEST['attachment_type'] ?? '';
214 $attachment_title = $_REQUEST['attachment_title'] ?? '';
215 $attachment_text = $_REQUEST['attachment_text'] ?? '';
217 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
218 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
220 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
221 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
223 // Fetch the basic attachment data
224 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
225 unset($attachment['keywords']);
227 // Overwrite the basic data with possible changes from the frontend
228 $attachment['type'] = $attachment_type;
229 $attachment['title'] = $attachment_title;
230 $attachment['text'] = $attachment_text;
231 $attachment['url'] = $attachment_url;
233 if (!empty($attachment_img_src)) {
234 $attachment['images'] = [
236 'src' => $attachment_img_src,
237 'width' => $attachment_img_width,
238 'height' => $attachment_img_height
242 unset($attachment['images']);
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 = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']);
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 $aclFormatter = DI::aclFormatter();
272 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
273 $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? '';
274 $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? '';
275 $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? '';
277 $visibility = $_REQUEST['visibility'] ?? '';
278 if ($visibility === 'public') {
279 // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
280 $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
281 } else if ($visibility === 'custom') {
282 // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
283 // case that would make it public. So we always append the author's contact id to the allowed contacts.
284 // See https://github.com/friendica/friendica/issues/9672
285 $str_contact_allow .= $aclFormatter->toString(Contact::getPublicIdByUserId($uid));
288 $title = trim($_REQUEST['title'] ?? '');
289 $location = trim($_REQUEST['location'] ?? '');
290 $coord = trim($_REQUEST['coord'] ?? '');
291 $verb = trim($_REQUEST['verb'] ?? '');
292 $emailcc = trim($_REQUEST['emailcc'] ?? '');
294 $network = trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN);
295 $guid = System::createUUID();
297 $postopts = $_REQUEST['postopts'] ?? '';
299 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
300 $private = Item::PRIVATE;
301 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
302 $private = Item::UNLISTED;
304 $private = Item::PUBLIC;
307 // If this is a comment, set the permissions from the parent.
309 if ($toplevel_item) {
310 // for non native networks use the network of the original post as network of the item
311 if (($toplevel_item['network'] != Protocol::DIASPORA)
312 && ($toplevel_item['network'] != Protocol::OSTATUS)
313 && ($network == "")) {
314 $network = $toplevel_item['network'];
317 $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
318 $str_group_allow = $toplevel_item['allow_gid'] ?? '';
319 $str_contact_deny = $toplevel_item['deny_cid'] ?? '';
320 $str_group_deny = $toplevel_item['deny_gid'] ?? '';
321 $private = $toplevel_item['private'];
323 $wall = $toplevel_item['wall'];
326 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
328 // if using the API, we won't see pubmail_enable - figure out if it should be set
329 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
330 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
331 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
335 if (!strlen($body)) {
337 System::jsonExit(['preview' => '']);
340 notice(DI::l10n()->t('Empty post discarded.'));
342 DI::baseUrl()->redirect($return_path);
345 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
349 if (!empty($categories)) {
350 // get the "fileas" tags for this post
351 $filedas = FileTag::fileToArray($categories);
354 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
356 if (!empty($filedas) && is_array($filedas)) {
357 // append the fileas stuff to the new categories list
358 $categories .= FileTag::arrayToFile($filedas);
361 // get contact info for poster
367 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
369 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
370 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
371 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
374 if (DBA::isResult($author)) {
375 $contact_id = $author['id'];
378 // get contact info for owner
379 if ($profile_uid == local_user() || $allow_comment) {
380 $contact_record = $author ?: [];
382 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
385 // Look for any tags and linkify them
387 $private_forum = false;
389 $only_to_forum = false;
392 $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) {
393 $tags = BBCode::getTags($body);
397 foreach ($tags as $tag) {
398 $tag_type = substr($tag, 0, 1);
400 if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
404 /* If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
405 * Robert Johnson should be first in the $tags array
407 foreach ($tagged as $nextTag) {
408 if (stristr($nextTag, $tag . ' ')) {
413 $success = ItemHelper::replaceTag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
414 if ($success['replaced']) {
417 // When the forum is private or the forum is addressed with a "!" make the post private
418 if (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
419 $private_forum = $success['contact']['prv'];
420 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
421 $private_id = $success['contact']['id'];
422 $forum_contact = $success['contact'];
423 } elseif (!empty($success['contact']['forum']) && ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
424 $private_forum = false;
425 $only_to_forum = true;
426 $private_id = $success['contact']['id'];
427 $forum_contact = $success['contact'];
434 $original_contact_id = $contact_id;
436 if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
437 // we tagged a forum in a top level post. Now we change the post
438 $private = $private_forum;
440 $str_group_allow = '';
441 $str_contact_deny = '';
442 $str_group_deny = '';
443 if ($private_forum) {
444 $str_contact_allow = '<' . $private_id . '>';
446 $str_contact_allow = '';
448 $contact_id = $private_id;
449 $contact_record = $forum_contact;
450 $_REQUEST['origin'] = false;
455 * When a photo was uploaded into the message using the (profile wall) ajax
456 * uploader, The permissions are initially set to disallow anybody but the
457 * owner from seeing it. This is because the permissions may not yet have been
458 * set for the post. If it's private, the photo permissions should be set
459 * appropriately. But we didn't know the final permissions on the post until
460 * now. So now we'll look for links of uploaded messages that are in the
461 * post and set them to the same permissions as the post itself.
466 if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
467 $objecttype = Activity\ObjectType::IMAGE;
471 * Next link in any attachment references we find in the post.
475 /// @todo these lines should be moved to Model/Attach (Once it exists)
476 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
477 $attaches = $match[1];
478 if (count($attaches)) {
479 foreach ($attaches as $attach) {
480 // Ensure to only modify attachments that you own
481 $srch = '<' . intval($original_contact_id) . '>';
483 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
485 if (!Attach::exists($condition)) {
489 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
490 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
491 $condition = ['id' => $attach];
492 Attach::update($fields, $condition);
497 // embedded bookmark or attachment in post? set bookmark flag
499 $data = BBCode::getAttachmentData($body);
501 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
502 && ($posttype != Item::PT_PERSONAL_NOTE)) {
503 $posttype = Item::PT_PAGE;
504 $objecttype = Activity\ObjectType::BOOKMARK;
507 $body = DI::bbCodeVideo()->transform($body);
509 $body = BBCode::scaleExternalImages($body);
511 // Setting the object type if not defined before
513 $objecttype = Activity\ObjectType::NOTE; // Default value
514 $objectdata = BBCode::getAttachedData($body);
516 if ($objectdata["type"] == "link") {
517 $objecttype = Activity\ObjectType::BOOKMARK;
518 } elseif ($objectdata["type"] == "video") {
519 $objecttype = Activity\ObjectType::VIDEO;
520 } elseif ($objectdata["type"] == "photo") {
521 $objecttype = Activity\ObjectType::IMAGE;
529 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
530 foreach ($match[2] as $mtch) {
531 $fields = ['id', 'filename', 'filesize', 'filetype'];
532 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
533 if ($attachment !== false) {
534 if (strlen($attachments)) {
537 $attachments .= Post\Media::getAttachElement(DI::baseUrl() . '/attach/' . $attachment['id'],
538 $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? '');
540 $body = str_replace($match[1],'',$body);
544 if (!strlen($verb)) {
545 $verb = Activity::POST;
548 if ($network == "") {
549 $network = Protocol::DFRN;
552 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
554 // even if the post arrived via API we are considering that it
555 // originated on this site by default for determining relayability.
557 // Don't use "defaults" here. It would turn 0 to 1
558 if (!isset($_REQUEST['origin'])) {
561 $origin = $_REQUEST['origin'];
564 $uri = Item::newURI($api_source ? $profile_uid : $uid, $guid);
566 // Fallback so that we alway have a parent uri
567 if (!$thr_parent_uri || !$toplevel_item_id) {
568 $thr_parent_uri = $uri;
572 $datarray['uid'] = $profile_uid;
573 $datarray['wall'] = $wall;
574 $datarray['gravity'] = $gravity;
575 $datarray['network'] = $network;
576 $datarray['contact-id'] = $contact_id;
577 $datarray['owner-name'] = $contact_record['name'] ?? '';
578 $datarray['owner-link'] = $contact_record['url'] ?? '';
579 $datarray['owner-avatar'] = $contact_record['thumb'] ?? '';
580 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
581 $datarray['author-name'] = $author['name'];
582 $datarray['author-link'] = $author['url'];
583 $datarray['author-avatar'] = $author['thumb'];
584 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
585 $datarray['created'] = DateTimeFormat::utcNow();
586 $datarray['edited'] = DateTimeFormat::utcNow();
587 $datarray['commented'] = DateTimeFormat::utcNow();
588 $datarray['received'] = DateTimeFormat::utcNow();
589 $datarray['changed'] = DateTimeFormat::utcNow();
590 $datarray['extid'] = $extid;
591 $datarray['guid'] = $guid;
592 $datarray['uri'] = $uri;
593 $datarray['title'] = $title;
594 $datarray['body'] = $body;
595 $datarray['app'] = $app;
596 $datarray['location'] = $location;
597 $datarray['coord'] = $coord;
598 $datarray['file'] = $categories;
599 $datarray['inform'] = $inform;
600 $datarray['verb'] = $verb;
601 $datarray['post-type'] = $posttype;
602 $datarray['object-type'] = $objecttype;
603 $datarray['allow_cid'] = $str_contact_allow;
604 $datarray['allow_gid'] = $str_group_allow;
605 $datarray['deny_cid'] = $str_contact_deny;
606 $datarray['deny_gid'] = $str_group_deny;
607 $datarray['private'] = $private;
608 $datarray['pubmail'] = $pubmail_enabled;
609 $datarray['attach'] = $attachments;
611 $datarray['thr-parent'] = $thr_parent_uri;
613 $datarray['postopts'] = $postopts;
614 $datarray['origin'] = $origin;
615 $datarray['object'] = $object;
617 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
618 $datarray['attachments'] = $_REQUEST['attachments'] ?? [];
621 * These fields are for the convenience of addons...
622 * 'self' if true indicates the owner is posting on their own wall
623 * If parent is 0 it is a top-level post.
625 $datarray['parent'] = $toplevel_item_id;
626 $datarray['self'] = $self;
628 // This triggers posts via API and the mirror functions
629 $datarray['api_source'] = $api_source;
631 // This field is for storing the raw conversation data
632 $datarray['protocol'] = Conversation::PARCEL_DIRECT;
633 $datarray['direction'] = Conversation::PUSH;
635 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['thr-parent']]);
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 $datarray['body'] = Item::setHashtags($datarray['body']);
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["uri-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]);
706 DI::baseUrl()->redirect($return_path);
709 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
712 unset($datarray['edit']);
713 unset($datarray['self']);
714 unset($datarray['api_source']);
717 $signed = Diaspora::createCommentSignature($uid, $datarray);
718 if (!empty($signed)) {
719 $datarray['diaspora_signed_text'] = json_encode($signed);
723 $post_id = Item::insert($datarray);
726 notice(DI::l10n()->t('Item wasn\'t stored.'));
728 DI::baseUrl()->redirect($return_path);
731 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
734 $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
736 if (!DBA::isResult($datarray)) {
737 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
739 DI::baseUrl()->redirect($return_path);
742 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
745 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
747 if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
748 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
751 // These notifications are sent if someone else is commenting other your wall
752 if ($contact_record != $author) {
753 if ($toplevel_item_id) {
755 'type' => Notification\Type::COMMENT,
756 'otype' => Notification\ObjectType::ITEM,
757 'verb' => Activity::POST,
758 'uid' => $profile_uid,
759 'cid' => $datarray['author-id'],
761 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
763 } elseif (empty($forum_contact)) {
765 'type' => Notification\Type::WALL,
766 'otype' => Notification\ObjectType::ITEM,
767 'verb' => Activity::POST,
768 'uid' => $profile_uid,
769 'cid' => $datarray['author-id'],
771 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']),
776 Hook::callAll('post_local_end', $datarray);
778 if (strlen($emailcc) && $profile_uid == local_user()) {
779 $recipients = explode(',', $emailcc);
780 if (count($recipients)) {
781 foreach ($recipients as $recipient) {
782 $address = trim($recipient);
783 if (!strlen($address)) {
786 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
787 $datarray, $address, $author['thumb'] ?? ''));
792 // When we are doing some forum posting via ! we have to start the notifier manually.
793 // These kind of posts don't initiate the notifier call in the item class.
794 if ($only_to_forum) {
795 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, (int)$datarray['uri-id'], (int)$datarray['uid']);
798 Logger::info('post_complete');
804 item_post_return(DI::baseUrl(), $api_source, $return_path);
808 function item_post_return($baseurl, $api_source, $return_path)
815 DI::baseUrl()->redirect($return_path);
818 $json = ['success' => 1];
819 if (!empty($_REQUEST['jsreload'])) {
820 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
823 Logger::info('post_json', ['json' => $json]);
825 System::jsonExit($json);
828 function item_content(App $a)
830 if (!Session::isAuthenticated()) {
831 throw new HTTPException\UnauthorizedException();
836 if (!$args->has(3)) {
837 throw new HTTPException\BadRequestException();
841 switch ($args->get(1)) {
843 if (DI::mode()->isAjax()) {
844 Item::deleteForUser(['id' => $args->get(2)], local_user());
845 // ajax return: [<item id>, 0 (no perm) | <owner id>]
846 System::jsonExit([intval($args->get(2)), local_user()]);
848 if (!empty($args->get(3))) {
849 $o = drop_item($args->get(2), $args->get(3));
851 $o = drop_item($args->get(2));
856 $item = Post::selectFirstForUser(local_user(), ['guid', 'author-id', 'parent', 'gravity'], ['id' => $args->get(2)]);
857 if (empty($item['author-id'])) {
858 throw new HTTPException\NotFoundException('Item not found');
861 Contact\User::setBlocked($item['author-id'], local_user(), true);
863 if (DI::mode()->isAjax()) {
864 // ajax return: [<item id>, 0 (no perm) | <owner id>]
865 System::jsonExit([intval($args->get(2)), local_user()]);
867 item_redirect_after_action($item, $args->get(3));
877 * @param string $return
879 * @throws HTTPException\InternalServerErrorException
881 function drop_item(int $id, string $return = '')
883 // locate item to be deleted
884 $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
885 $item = Post::selectFirstForUser(local_user(), $fields, ['id' => $id]);
887 if (!DBA::isResult($item)) {
888 notice(DI::l10n()->t('Item not found.'));
889 DI::baseUrl()->redirect('network');
892 if ($item['deleted']) {
898 // check if logged in user is either the author or owner of this item
899 if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
900 $contact_id = $item['contact-id'];
903 if ((local_user() == $item['uid']) || $contact_id) {
905 Item::deleteForUser(['id' => $item['id']], local_user());
907 item_redirect_after_action($item, $return);
909 notice(DI::l10n()->t('Permission denied.'));
910 DI::baseUrl()->redirect('display/' . $item['guid']);
917 function item_redirect_after_action($item, $returnUrlHex)
919 $return_url = hex2bin($returnUrlHex);
921 // removes update_* from return_url to ignore Ajax refresh
922 $return_url = str_replace("update_", "", $return_url);
924 // Check if delete a comment
925 if ($item['gravity'] == GRAVITY_COMMENT) {
926 if (!empty($item['parent'])) {
927 $parentitem = Post::selectFirstForUser(local_user(), ['guid'], ['id' => $item['parent']]);
930 // Return to parent guid
931 if (!empty($parentitem)) {
932 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
934 } // In case something goes wrong
936 DI::baseUrl()->redirect('network');
940 // if unknown location or deleting top level post called from display
941 if (empty($return_url) || strpos($return_url, 'display') !== false) {
942 DI::baseUrl()->redirect('network');
945 DI::baseUrl()->redirect($return_url);