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 $toplevel_item = null;
107 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
108 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
110 if ($toplevel_item_id || $thr_parent_uri) {
111 if ($toplevel_item_id) {
112 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
113 } elseif ($thr_parent_uri) {
114 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
117 // if this isn't the top-level parent of the conversation, find it
118 if (DBA::isResult($toplevel_item)) {
119 // The URI and the contact is taken from the direct parent which needn't to be the top parent
120 $thr_parent_uri = $toplevel_item['uri'];
122 if ($toplevel_item['gravity'] != GRAVITY_PARENT) {
123 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item['parent']]);
127 if (!DBA::isResult($toplevel_item)) {
128 notice(DI::l10n()->t('Unable to locate original post.'));
130 DI::baseUrl()->redirect($return_path);
132 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
135 $toplevel_item_id = $toplevel_item['id'];
136 $parent_user = $toplevel_item['uid'];
138 $objecttype = Activity\ObjectType::COMMENT;
141 if ($toplevel_item_id) {
142 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
145 $post_id = intval($_REQUEST['post_id'] ?? 0);
146 $app = strip_tags($_REQUEST['source'] ?? '');
147 $extid = strip_tags($_REQUEST['extid'] ?? '');
148 $object = $_REQUEST['object'] ?? '';
150 // Don't use "defaults" here. It would turn 0 to 1
151 if (!isset($_REQUEST['wall'])) {
154 $wall = $_REQUEST['wall'];
157 // Ensure that the user id in a thread always stay the same
158 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
159 $profile_uid = $parent_user;
162 // Check for multiple posts with the same message id (when the post was created via API)
163 if (($message_id != '') && ($profile_uid != 0)) {
164 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
165 Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
170 // Allow commenting if it is an answer to a public post
171 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
173 // Now check that valid personal details have been provided
174 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
175 notice(DI::l10n()->t('Permission denied.'));
177 DI::baseUrl()->redirect($return_path);
180 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
183 // Init post instance
186 // is this an edited post?
188 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
191 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
193 if (!DBA::isResult($user) && !$toplevel_item_id) {
200 $body = $_REQUEST['body'] ?? '';
201 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
203 // If we have a speparate attachment, we need to add it to the body.
204 if (!empty($has_attachment)) {
205 $attachment_type = $_REQUEST['attachment_type'] ?? '';
206 $attachment_title = $_REQUEST['attachment_title'] ?? '';
207 $attachment_text = $_REQUEST['attachment_text'] ?? '';
209 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
210 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
212 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
213 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
215 'type' => $attachment_type,
216 'title' => $attachment_title,
217 'text' => $attachment_text,
218 'url' => $attachment_url,
221 if (!empty($attachment_img_src)) {
222 $attachment['images'] = [
224 'src' => $attachment_img_src,
225 'width' => $attachment_img_width,
226 'height' => $attachment_img_height
231 $att_bbcode = add_page_info_data($attachment);
232 $body .= $att_bbcode;
235 // Convert links with empty descriptions to links without an explicit description
236 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
238 if (!empty($orig_post)) {
239 $str_group_allow = $orig_post['allow_gid'];
240 $str_contact_allow = $orig_post['allow_cid'];
241 $str_group_deny = $orig_post['deny_gid'];
242 $str_contact_deny = $orig_post['deny_cid'];
243 $location = $orig_post['location'];
244 $coord = $orig_post['coord'];
245 $verb = $orig_post['verb'];
246 $objecttype = $orig_post['object-type'];
247 $app = $orig_post['app'];
248 $categories = $orig_post['file'];
249 $title = Strings::escapeTags(trim($_REQUEST['title']));
251 $private = $orig_post['private'];
252 $pubmail_enabled = $orig_post['pubmail'];
253 $network = $orig_post['network'];
254 $guid = $orig_post['guid'];
255 $extid = $orig_post['extid'];
257 $str_contact_allow = '';
258 $str_group_allow = '';
259 $str_contact_deny = '';
260 $str_group_deny = '';
262 if (($_REQUEST['visibility'] ?? '') !== 'public') {
263 $aclFormatter = DI::aclFormatter();
264 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
265 $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? '';
266 $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? '';
267 $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? '';
270 $title = Strings::escapeTags(trim($_REQUEST['title'] ?? ''));
271 $location = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
272 $coord = Strings::escapeTags(trim($_REQUEST['coord'] ?? ''));
273 $verb = Strings::escapeTags(trim($_REQUEST['verb'] ?? ''));
274 $emailcc = Strings::escapeTags(trim($_REQUEST['emailcc'] ?? ''));
276 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
277 $guid = System::createUUID();
279 $postopts = $_REQUEST['postopts'] ?? '';
281 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
282 $private = Item::PRIVATE;
283 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
284 $private = Item::UNLISTED;
286 $private = Item::PUBLIC;
289 // If this is a comment, set the permissions from the parent.
291 if ($toplevel_item) {
292 // for non native networks use the network of the original post as network of the item
293 if (($toplevel_item['network'] != Protocol::DIASPORA)
294 && ($toplevel_item['network'] != Protocol::OSTATUS)
295 && ($network == "")) {
296 $network = $toplevel_item['network'];
299 $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
300 $str_group_allow = $toplevel_item['allow_gid'] ?? '';
301 $str_contact_deny = $toplevel_item['deny_cid'] ?? '';
302 $str_group_deny = $toplevel_item['deny_gid'] ?? '';
303 $private = $toplevel_item['private'];
305 $wall = $toplevel_item['wall'];
308 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
310 // if using the API, we won't see pubmail_enable - figure out if it should be set
311 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
312 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
313 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
317 if (!strlen($body)) {
319 System::jsonExit(['preview' => '']);
322 info(DI::l10n()->t('Empty post discarded.'));
324 DI::baseUrl()->redirect($return_path);
327 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
331 if (!empty($categories)) {
332 // get the "fileas" tags for this post
333 $filedas = FileTag::fileToArray($categories);
336 // save old and new categories, so we can determine what needs to be deleted from pconfig
337 $categories_old = $categories;
338 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
339 $categories_new = $categories;
341 if (!empty($filedas) && is_array($filedas)) {
342 // append the fileas stuff to the new categories list
343 $categories .= FileTag::arrayToFile($filedas);
346 // get contact info for poster
352 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
354 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
355 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
356 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
359 if (DBA::isResult($author)) {
360 $contact_id = $author['id'];
363 // get contact info for owner
364 if ($profile_uid == local_user() || $allow_comment) {
365 $contact_record = $author;
367 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
370 // Look for any tags and linkify them
373 $tags = BBCode::getTags($body);
377 $private_forum = false;
378 $only_to_forum = false;
382 foreach ($tags as $tag) {
383 $tag_type = substr($tag, 0, 1);
385 if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
390 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
391 * Robert Johnson should be first in the $tags array
393 $fullnametagged = false;
394 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
395 foreach ($tagged as $nextTag) {
396 if (stristr($nextTag, $tag . ' ')) {
397 $fullnametagged = true;
401 if ($fullnametagged) {
405 $success = handle_tag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
406 if ($success['replaced']) {
409 // When the forum is private or the forum is addressed with a "!" make the post private
410 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]))) {
411 $private_forum = $success['contact']['prv'];
412 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
413 $private_id = $success['contact']['id'];
414 $forum_contact = $success['contact'];
415 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
416 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
417 $private_forum = false;
418 $only_to_forum = true;
419 $private_id = $success['contact']['id'];
420 $forum_contact = $success['contact'];
425 $original_contact_id = $contact_id;
427 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
428 // we tagged a forum in a top level post. Now we change the post
429 $private = $private_forum;
431 $str_group_allow = '';
432 $str_contact_deny = '';
433 $str_group_deny = '';
434 if ($private_forum) {
435 $str_contact_allow = '<' . $private_id . '>';
437 $str_contact_allow = '';
439 $contact_id = $private_id;
440 $contact_record = $forum_contact;
441 $_REQUEST['origin'] = false;
446 * When a photo was uploaded into the message using the (profile wall) ajax
447 * uploader, The permissions are initially set to disallow anybody but the
448 * owner from seeing it. This is because the permissions may not yet have been
449 * set for the post. If it's private, the photo permissions should be set
450 * appropriately. But we didn't know the final permissions on the post until
451 * now. So now we'll look for links of uploaded messages that are in the
452 * post and set them to the same permissions as the post itself.
457 if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
458 $objecttype = Activity\ObjectType::IMAGE;
462 * Next link in any attachment references we find in the post.
466 /// @todo these lines should be moved to Model/Attach (Once it exists)
467 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
468 $attaches = $match[1];
469 if (count($attaches)) {
470 foreach ($attaches as $attach) {
471 // Ensure to only modify attachments that you own
472 $srch = '<' . intval($original_contact_id) . '>';
474 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
476 if (!Attach::exists($condition)) {
480 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
481 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
482 $condition = ['id' => $attach];
483 Attach::update($fields, $condition);
488 // embedded bookmark or attachment in post? set bookmark flag
490 $data = BBCode::getAttachmentData($body);
491 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
492 && ($posttype != Item::PT_PERSONAL_NOTE)) {
493 $posttype = Item::PT_PAGE;
494 $objecttype = Activity\ObjectType::BOOKMARK;
497 $body = DI::bbCodeVideo()->transform($body);
499 $body = BBCode::scaleExternalImages($body);
501 // Setting the object type if not defined before
503 $objecttype = Activity\ObjectType::NOTE; // Default value
504 $objectdata = BBCode::getAttachedData($body);
506 if ($objectdata["type"] == "link") {
507 $objecttype = Activity\ObjectType::BOOKMARK;
508 } elseif ($objectdata["type"] == "video") {
509 $objecttype = Activity\ObjectType::VIDEO;
510 } elseif ($objectdata["type"] == "photo") {
511 $objecttype = Activity\ObjectType::IMAGE;
519 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
520 foreach ($match[2] as $mtch) {
521 $fields = ['id', 'filename', 'filesize', 'filetype'];
522 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
523 if ($attachment !== false) {
524 if (strlen($attachments)) {
527 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
528 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
529 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
531 $body = str_replace($match[1],'',$body);
535 if (!strlen($verb)) {
536 $verb = Activity::POST;
539 if ($network == "") {
540 $network = Protocol::DFRN;
543 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
545 // even if the post arrived via API we are considering that it
546 // originated on this site by default for determining relayability.
548 // Don't use "defaults" here. It would turn 0 to 1
549 if (!isset($_REQUEST['origin'])) {
552 $origin = $_REQUEST['origin'];
555 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
557 // Fallback so that we alway have a parent uri
558 if (!$thr_parent_uri || !$toplevel_item_id) {
559 $thr_parent_uri = $uri;
563 $datarray['uid'] = $profile_uid;
564 $datarray['wall'] = $wall;
565 $datarray['gravity'] = $gravity;
566 $datarray['network'] = $network;
567 $datarray['contact-id'] = $contact_id;
568 $datarray['owner-name'] = $contact_record['name'];
569 $datarray['owner-link'] = $contact_record['url'];
570 $datarray['owner-avatar'] = $contact_record['thumb'];
571 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
572 $datarray['author-name'] = $author['name'];
573 $datarray['author-link'] = $author['url'];
574 $datarray['author-avatar'] = $author['thumb'];
575 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
576 $datarray['created'] = DateTimeFormat::utcNow();
577 $datarray['edited'] = DateTimeFormat::utcNow();
578 $datarray['commented'] = DateTimeFormat::utcNow();
579 $datarray['received'] = DateTimeFormat::utcNow();
580 $datarray['changed'] = DateTimeFormat::utcNow();
581 $datarray['extid'] = $extid;
582 $datarray['guid'] = $guid;
583 $datarray['uri'] = $uri;
584 $datarray['title'] = $title;
585 $datarray['body'] = $body;
586 $datarray['app'] = $app;
587 $datarray['location'] = $location;
588 $datarray['coord'] = $coord;
589 $datarray['file'] = $categories;
590 $datarray['inform'] = $inform;
591 $datarray['verb'] = $verb;
592 $datarray['post-type'] = $posttype;
593 $datarray['object-type'] = $objecttype;
594 $datarray['allow_cid'] = $str_contact_allow;
595 $datarray['allow_gid'] = $str_group_allow;
596 $datarray['deny_cid'] = $str_contact_deny;
597 $datarray['deny_gid'] = $str_group_deny;
598 $datarray['private'] = $private;
599 $datarray['pubmail'] = $pubmail_enabled;
600 $datarray['attach'] = $attachments;
602 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
603 $datarray['parent-uri'] = $thr_parent_uri;
605 $datarray['postopts'] = $postopts;
606 $datarray['origin'] = $origin;
607 $datarray['moderated'] = false;
608 $datarray['object'] = $object;
611 * These fields are for the convenience of addons...
612 * 'self' if true indicates the owner is posting on their own wall
613 * If parent is 0 it is a top-level post.
615 $datarray['parent'] = $toplevel_item_id;
616 $datarray['self'] = $self;
618 // This triggers posts via API and the mirror functions
619 $datarray['api_source'] = $api_source;
621 // This field is for storing the raw conversation data
622 $datarray['protocol'] = Conversation::PARCEL_DFRN;
624 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
625 if (DBA::isResult($conversation)) {
626 if ($conversation['conversation-uri'] != '') {
627 $datarray['conversation-uri'] = $conversation['conversation-uri'];
629 if ($conversation['conversation-href'] != '') {
630 $datarray['conversation-href'] = $conversation['conversation-href'];
635 $datarray['edit'] = true;
637 // If this was a share, add missing data here
638 $datarray = Item::addShareDataFromOriginal($datarray);
640 $datarray['edit'] = false;
643 // Check for hashtags in the body and repair or add hashtag links
644 if ($preview || $orig_post) {
645 Item::setHashtags($datarray);
648 // preview mode - prepare the body for display and send it via json
650 // We set the datarray ID to -1 because in preview mode the dataray
651 // doesn't have an ID.
652 $datarray["id"] = -1;
653 $datarray["uri-id"] = -1;
654 $datarray["item_id"] = -1;
655 $datarray["author-network"] = Protocol::DFRN;
657 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
659 System::jsonExit(['preview' => $o]);
662 Hook::callAll('post_local',$datarray);
664 if (!empty($datarray['cancel'])) {
665 Logger::info('mod_item: post cancelled by addon.');
667 DI::baseUrl()->redirect($return_path);
670 $json = ['cancel' => 1];
671 if (!empty($_REQUEST['jsreload'])) {
672 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
675 System::jsonExit($json);
679 // Fill the cache field
680 // This could be done in Item::update as well - but we have to check for the existance of some fields.
681 Item::putInCache($datarray);
684 'title' => $datarray['title'],
685 'body' => $datarray['body'],
686 'attach' => $datarray['attach'],
687 'file' => $datarray['file'],
688 'rendered-html' => $datarray['rendered-html'],
689 'rendered-hash' => $datarray['rendered-hash'],
690 'edited' => DateTimeFormat::utcNow(),
691 'changed' => DateTimeFormat::utcNow()];
693 Item::update($fields, ['id' => $post_id]);
695 // update filetags in pconfig
696 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
698 info(DI::l10n()->t('Post updated.'));
700 DI::baseUrl()->redirect($return_path);
703 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
706 unset($datarray['edit']);
707 unset($datarray['self']);
708 unset($datarray['api_source']);
711 $signed = Diaspora::createCommentSignature($uid, $datarray);
712 if (!empty($signed)) {
713 $datarray['diaspora_signed_text'] = json_encode($signed);
717 $post_id = Item::insert($datarray);
720 info(DI::l10n()->t('Item wasn\'t stored.'));
722 DI::baseUrl()->redirect($return_path);
725 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
728 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
730 if (!DBA::isResult($datarray)) {
731 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
733 DI::baseUrl()->redirect($return_path);
736 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
739 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
741 if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
742 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
745 // update filetags in pconfig
746 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
748 // These notifications are sent if someone else is commenting other your wall
749 if ($toplevel_item_id) {
750 if ($contact_record != $author) {
752 'type' => Type::COMMENT,
753 'notify_flags' => $user['notify-flags'],
754 'language' => $user['language'],
755 'to_name' => $user['username'],
756 'to_email' => $user['email'],
757 'uid' => $user['uid'],
759 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
760 'source_name' => $datarray['author-name'],
761 'source_link' => $datarray['author-link'],
762 'source_photo' => $datarray['author-avatar'],
763 'verb' => Activity::POST,
765 'parent' => $toplevel_item_id,
766 'parent_uri' => $toplevel_item['uri']
770 if (($contact_record != $author) && !count($forum_contact)) {
772 'type' => Type::WALL,
773 'notify_flags' => $user['notify-flags'],
774 'language' => $user['language'],
775 'to_name' => $user['username'],
776 'to_email' => $user['email'],
777 'uid' => $user['uid'],
779 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
780 'source_name' => $datarray['author-name'],
781 'source_link' => $datarray['author-link'],
782 'source_photo' => $datarray['author-avatar'],
783 'verb' => Activity::POST,
789 Hook::callAll('post_local_end', $datarray);
791 if (strlen($emailcc) && $profile_uid == local_user()) {
792 $recipients = explode(',', $emailcc);
793 if (count($recipients)) {
794 foreach ($recipients as $recipient) {
795 $address = trim($recipient);
796 if (!strlen($address)) {
799 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
800 $datarray, $address, $author['thumb'] ?? ''));
805 // Insert an item entry for UID=0 for global entries.
806 // We now do it in the background to save some time.
807 // This is important in interactive environments like the frontend or the API.
808 // We don't fork a new process since this is done anyway with the following command
809 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
811 // When we are doing some forum posting via ! we have to start the notifier manually.
812 // These kind of posts don't initiate the notifier call in the item class.
813 if ($only_to_forum) {
814 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
817 Logger::info('post_complete');
823 info(DI::l10n()->t('Post published.'));
824 item_post_return(DI::baseUrl(), $api_source, $return_path);
828 function item_post_return($baseurl, $api_source, $return_path)
835 DI::baseUrl()->redirect($return_path);
838 $json = ['success' => 1];
839 if (!empty($_REQUEST['jsreload'])) {
840 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
843 Logger::info('post_json', ['json' => $json]);
845 System::jsonExit($json);
848 function item_content(App $a)
850 if (!Session::isAuthenticated()) {
856 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
857 if (DI::mode()->isAjax()) {
858 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
860 if (!empty($a->argv[3])) {
861 $o = drop_item($a->argv[2], $a->argv[3]);
864 $o = drop_item($a->argv[2]);
868 if (DI::mode()->isAjax()) {
869 // ajax return: [<item id>, 0 (no perm) | <owner id>]
870 System::jsonExit([intval($a->argv[2]), intval($o)]);
878 * This function removes the tag $tag from the text $body and replaces it with
879 * the appropriate link.
882 * @param string $body the text to replace the tag in
883 * @param string $inform a comma-seperated string containing everybody to inform
884 * @param integer $profile_uid
885 * @param string $tag the tag to replace
886 * @param string $network The network of the post
888 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
889 * @throws ImagickException
890 * @throws HTTPException\InternalServerErrorException
892 function handle_tag(&$body, &$inform, $profile_uid, $tag, $network = "")
896 //is it a person tag?
897 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
898 $tag_type = substr($tag, 0, 1);
899 //is it already replaced?
900 if (strpos($tag, '[url=')) {
901 // Checking for the alias that is used for OStatus
902 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
903 if (preg_match($pattern, $tag, $matches)) {
904 $data = Contact::getDetailsByURL($matches[1]);
906 if ($data["alias"] != "") {
907 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
914 //get the person's name
915 $name = substr($tag, 1);
917 // Sometimes the tag detection doesn't seem to work right
918 // This is some workaround
919 $nameparts = explode(" ", $name);
920 $name = $nameparts[0];
922 // Try to detect the contact in various ways
923 if (strpos($name, 'http://')) {
924 // At first we have to ensure that the contact exists
925 Contact::getIdForURL($name);
927 // Now we should have something
928 $contact = Contact::getDetailsByURL($name);
929 } elseif (strpos($name, '@')) {
930 // This function automatically probes when no entry was found
931 $contact = Contact::getDetailsByAddr($name);
934 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
936 if (strrpos($name, '+')) {
937 // Is it in format @nick+number?
938 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
939 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
942 // select someone by nick or attag in the current network
943 if (!DBA::isResult($contact) && ($network != "")) {
944 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
945 $name, $name, $network, $profile_uid];
946 $contact = DBA::selectFirst('contact', $fields, $condition);
949 //select someone by name in the current network
950 if (!DBA::isResult($contact) && ($network != "")) {
951 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
952 $contact = DBA::selectFirst('contact', $fields, $condition);
955 // select someone by nick or attag in any network
956 if (!DBA::isResult($contact)) {
957 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
958 $contact = DBA::selectFirst('contact', $fields, $condition);
961 // select someone by name in any network
962 if (!DBA::isResult($contact)) {
963 $condition = ['name' => $name, 'uid' => $profile_uid];
964 $contact = DBA::selectFirst('contact', $fields, $condition);
968 // Check if $contact has been successfully loaded
969 if (DBA::isResult($contact)) {
970 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
974 if (isset($contact["id"])) {
975 $inform .= 'cid:' . $contact["id"];
976 } elseif (isset($contact["notify"])) {
977 $inform .= $contact["notify"];
980 $profile = $contact["url"];
981 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
984 //if there is an url for this persons profile
985 if (isset($profile) && ($newname != "")) {
987 // create profile link
988 $profile = str_replace(',', '%2c', $profile);
989 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
990 $body = str_replace($tag_type . $name, $newtag, $body);
994 return ['replaced' => $replaced, 'contact' => $contact];