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\Pager;
33 use Friendica\Content\Text\BBCode;
34 use Friendica\Core\Hook;
35 use Friendica\Core\Logger;
36 use Friendica\Core\Protocol;
37 use Friendica\Core\Session;
38 use Friendica\Core\System;
39 use Friendica\Core\Worker;
40 use Friendica\Database\DBA;
42 use Friendica\Model\Attach;
43 use Friendica\Model\Contact;
44 use Friendica\Model\Conversation;
45 use Friendica\Model\FileTag;
46 use Friendica\Model\Item;
47 use Friendica\Model\Notify\Type;
48 use Friendica\Model\Photo;
49 use Friendica\Model\Term;
50 use Friendica\Network\HTTPException;
51 use Friendica\Object\EMail\ItemCCEMail;
52 use Friendica\Protocol\Activity;
53 use Friendica\Protocol\Diaspora;
54 use Friendica\Util\DateTimeFormat;
55 use Friendica\Util\Security;
56 use Friendica\Util\Strings;
57 use Friendica\Worker\Delivery;
59 require_once __DIR__ . '/../include/items.php';
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 drop_items($arr_drop);
71 $json = ['success' => 1];
72 System::jsonExit($json);
75 Hook::callAll('post_local_start', $_REQUEST);
77 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
79 $api_source = $_REQUEST['api_source'] ?? false;
81 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
83 $return_path = $_REQUEST['return'] ?? '';
84 $preview = intval($_REQUEST['preview'] ?? 0);
87 * Check for doubly-submitted posts, and reject duplicates
88 * Note that we have to ignore previews, otherwise nothing will post
89 * after it's been previewed
91 if (!$preview && !empty($_REQUEST['post_id_random'])) {
92 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
93 Logger::info('item post: duplicate post');
94 item_post_return(DI::baseUrl(), $api_source, $return_path);
96 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
100 // Is this a reply to something?
101 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
102 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
104 $thread_parent_id = 0;
105 $thread_parent_contact = null;
107 $toplevel_item = null;
110 $parent_contact = null;
113 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
114 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
116 if ($toplevel_item_id || $thr_parent_uri) {
117 if ($toplevel_item_id) {
118 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
119 } elseif ($thr_parent_uri) {
120 $toplevel_item = Item::selectFirst([], ['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($toplevel_item)) {
125 // The URI and the contact is taken from the direct parent which needn't to be the top parent
126 $thread_parent_id = $toplevel_item['id'];
127 $thr_parent_uri = $toplevel_item['uri'];
128 $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
130 if ($toplevel_item['id'] != $toplevel_item['parent']) {
131 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item['parent']]);
135 if (!DBA::isResult($toplevel_item)) {
136 notice(DI::l10n()->t('Unable to locate original post.'));
138 DI::baseUrl()->redirect($return_path);
140 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
143 $toplevel_item_id = $toplevel_item['id'];
144 $parent_user = $toplevel_item['uid'];
146 $objecttype = Activity\ObjectType::COMMENT;
149 if ($toplevel_item_id) {
150 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
153 $post_id = intval($_REQUEST['post_id'] ?? 0);
154 $app = strip_tags($_REQUEST['source'] ?? '');
155 $extid = strip_tags($_REQUEST['extid'] ?? '');
156 $object = $_REQUEST['object'] ?? '';
158 // Don't use "defaults" here. It would turn 0 to 1
159 if (!isset($_REQUEST['wall'])) {
162 $wall = $_REQUEST['wall'];
165 // Ensure that the user id in a thread always stay the same
166 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
167 $profile_uid = $parent_user;
170 // Check for multiple posts with the same message id (when the post was created via API)
171 if (($message_id != '') && ($profile_uid != 0)) {
172 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
173 Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
178 // Allow commenting if it is an answer to a public post
179 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
181 // Now check that valid personal details have been provided
182 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
183 notice(DI::l10n()->t('Permission denied.'));
185 DI::baseUrl()->redirect($return_path);
188 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
191 // Init post instance
194 // is this an edited post?
196 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
199 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
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 'type' => $attachment_type,
224 'title' => $attachment_title,
225 'text' => $attachment_text,
226 'url' => $attachment_url,
229 if (!empty($attachment_img_src)) {
230 $attachment['images'] = [
232 'src' => $attachment_img_src,
233 'width' => $attachment_img_width,
234 'height' => $attachment_img_height
239 $att_bbcode = add_page_info_data($attachment);
240 $body .= $att_bbcode;
243 // Convert links with empty descriptions to links without an explicit description
244 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
246 if (!empty($orig_post)) {
247 $str_group_allow = $orig_post['allow_gid'];
248 $str_contact_allow = $orig_post['allow_cid'];
249 $str_group_deny = $orig_post['deny_gid'];
250 $str_contact_deny = $orig_post['deny_cid'];
251 $location = $orig_post['location'];
252 $coord = $orig_post['coord'];
253 $verb = $orig_post['verb'];
254 $objecttype = $orig_post['object-type'];
255 $app = $orig_post['app'];
256 $categories = $orig_post['file'];
257 $title = Strings::escapeTags(trim($_REQUEST['title']));
259 $private = $orig_post['private'];
260 $pubmail_enabled = $orig_post['pubmail'];
261 $network = $orig_post['network'];
262 $guid = $orig_post['guid'];
263 $extid = $orig_post['extid'];
265 $aclFormatter = DI::aclFormatter();
267 $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? '';
268 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
269 $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? '';
270 $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? '';
272 $title = Strings::escapeTags(trim($_REQUEST['title'] ?? ''));
273 $location = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
274 $coord = Strings::escapeTags(trim($_REQUEST['coord'] ?? ''));
275 $verb = Strings::escapeTags(trim($_REQUEST['verb'] ?? ''));
276 $emailcc = Strings::escapeTags(trim($_REQUEST['emailcc'] ?? ''));
278 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
279 $guid = System::createUUID();
281 $postopts = $_REQUEST['postopts'] ?? '';
283 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
284 $private = Item::PRIVATE;
285 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
286 $private = Item::UNLISTED;
288 $private = Item::PUBLIC;
291 // If this is a comment, set the permissions from the parent.
293 if ($toplevel_item) {
294 // for non native networks use the network of the original post as network of the item
295 if (($toplevel_item['network'] != Protocol::DIASPORA)
296 && ($toplevel_item['network'] != Protocol::OSTATUS)
297 && ($network == "")) {
298 $network = $toplevel_item['network'];
301 $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
302 $str_group_allow = $toplevel_item['allow_gid'] ?? '';
303 $str_contact_deny = $toplevel_item['deny_cid'] ?? '';
304 $str_group_deny = $toplevel_item['deny_gid'] ?? '';
305 $private = $toplevel_item['private'];
307 $wall = $toplevel_item['wall'];
310 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
312 // if using the API, we won't see pubmail_enable - figure out if it should be set
313 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
314 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
315 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
319 if (!strlen($body)) {
321 System::jsonExit(['preview' => '']);
324 info(DI::l10n()->t('Empty post discarded.'));
326 DI::baseUrl()->redirect($return_path);
329 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
333 if (!empty($categories)) {
334 // get the "fileas" tags for this post
335 $filedas = FileTag::fileToArray($categories);
338 // save old and new categories, so we can determine what needs to be deleted from pconfig
339 $categories_old = $categories;
340 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
341 $categories_new = $categories;
343 if (!empty($filedas) && is_array($filedas)) {
344 // append the fileas stuff to the new categories list
345 $categories .= FileTag::arrayToFile($filedas);
348 // get contact info for poster
354 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
356 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
357 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
358 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
361 if (DBA::isResult($author)) {
362 $contact_id = $author['id'];
365 // get contact info for owner
366 if ($profile_uid == local_user() || $allow_comment) {
367 $contact_record = $author;
369 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
372 // Look for any tags and linkify them
376 $tags = BBCode::getTags($body);
378 if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
379 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
384 $private_forum = false;
385 $only_to_forum = false;
389 foreach ($tags as $tag) {
390 $tag_type = substr($tag, 0, 1);
392 if ($tag_type == Term::TAG_CHARACTER[Term::HASHTAG]) {
397 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
398 * Robert Johnson should be first in the $tags array
400 $fullnametagged = false;
401 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
402 foreach ($tagged as $nextTag) {
403 if (stristr($nextTag, $tag . ' ')) {
404 $fullnametagged = true;
408 if ($fullnametagged) {
412 $success = handle_tag($body, $inform, $str_tags, 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 (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
418 $private_forum = $success['contact']['prv'];
419 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
420 $private_id = $success['contact']['id'];
421 $forum_contact = $success['contact'];
422 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
423 ($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'];
432 $original_contact_id = $contact_id;
434 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
435 // we tagged a forum in a top level post. Now we change the post
436 $private = $private_forum;
438 $str_group_allow = '';
439 $str_contact_deny = '';
440 $str_group_deny = '';
441 if ($private_forum) {
442 $str_contact_allow = '<' . $private_id . '>';
444 $str_contact_allow = '';
446 $contact_id = $private_id;
447 $contact_record = $forum_contact;
448 $_REQUEST['origin'] = false;
453 * When a photo was uploaded into the message using the (profile wall) ajax
454 * uploader, The permissions are initially set to disallow anybody but the
455 * owner from seeing it. This is because the permissions may not yet have been
456 * set for the post. If it's private, the photo permissions should be set
457 * appropriately. But we didn't know the final permissions on the post until
458 * now. So now we'll look for links of uploaded messages that are in the
459 * post and set them to the same permissions as the post itself.
464 if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
465 $objecttype = Activity\ObjectType::IMAGE;
469 * Next link in any attachment references we find in the post.
473 /// @todo these lines should be moved to Model/Attach (Once it exists)
474 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
475 $attaches = $match[1];
476 if (count($attaches)) {
477 foreach ($attaches as $attach) {
478 // Ensure to only modify attachments that you own
479 $srch = '<' . intval($original_contact_id) . '>';
481 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
483 if (!Attach::exists($condition)) {
487 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
488 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
489 $condition = ['id' => $attach];
490 Attach::update($fields, $condition);
495 // embedded bookmark or attachment in post? set bookmark flag
497 $data = BBCode::getAttachmentData($body);
498 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
499 && ($posttype != Item::PT_PERSONAL_NOTE)) {
500 $posttype = Item::PT_PAGE;
501 $objecttype = Activity\ObjectType::BOOKMARK;
504 $body = DI::bbCodeVideo()->transform($body);
506 $body = BBCode::scaleExternalImages($body);
508 // Setting the object type if not defined before
510 $objecttype = Activity\ObjectType::NOTE; // Default value
511 $objectdata = BBCode::getAttachedData($body);
513 if ($objectdata["type"] == "link") {
514 $objecttype = Activity\ObjectType::BOOKMARK;
515 } elseif ($objectdata["type"] == "video") {
516 $objecttype = Activity\ObjectType::VIDEO;
517 } elseif ($objectdata["type"] == "photo") {
518 $objecttype = Activity\ObjectType::IMAGE;
526 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
527 foreach ($match[2] as $mtch) {
528 $fields = ['id', 'filename', 'filesize', 'filetype'];
529 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
530 if ($attachment !== false) {
531 if (strlen($attachments)) {
534 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
535 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
536 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
538 $body = str_replace($match[1],'',$body);
542 if (!strlen($verb)) {
543 $verb = Activity::POST;
546 if ($network == "") {
547 $network = Protocol::DFRN;
550 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
552 // even if the post arrived via API we are considering that it
553 // originated on this site by default for determining relayability.
555 // Don't use "defaults" here. It would turn 0 to 1
556 if (!isset($_REQUEST['origin'])) {
559 $origin = $_REQUEST['origin'];
562 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
564 // Fallback so that we alway have a parent uri
565 if (!$thr_parent_uri || !$toplevel_item_id) {
566 $thr_parent_uri = $uri;
570 $datarray['uid'] = $profile_uid;
571 $datarray['wall'] = $wall;
572 $datarray['gravity'] = $gravity;
573 $datarray['network'] = $network;
574 $datarray['contact-id'] = $contact_id;
575 $datarray['owner-name'] = $contact_record['name'];
576 $datarray['owner-link'] = $contact_record['url'];
577 $datarray['owner-avatar'] = $contact_record['thumb'];
578 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
579 $datarray['author-name'] = $author['name'];
580 $datarray['author-link'] = $author['url'];
581 $datarray['author-avatar'] = $author['thumb'];
582 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
583 $datarray['created'] = DateTimeFormat::utcNow();
584 $datarray['edited'] = DateTimeFormat::utcNow();
585 $datarray['commented'] = DateTimeFormat::utcNow();
586 $datarray['received'] = DateTimeFormat::utcNow();
587 $datarray['changed'] = DateTimeFormat::utcNow();
588 $datarray['extid'] = $extid;
589 $datarray['guid'] = $guid;
590 $datarray['uri'] = $uri;
591 $datarray['title'] = $title;
592 $datarray['body'] = $body;
593 $datarray['app'] = $app;
594 $datarray['location'] = $location;
595 $datarray['coord'] = $coord;
596 $datarray['tag'] = $str_tags;
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 Item::setHashtags($datarray);
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["item_id"] = -1;
662 $datarray["author-network"] = Protocol::DFRN;
664 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
666 System::jsonExit(['preview' => $o]);
669 Hook::callAll('post_local',$datarray);
671 if (!empty($datarray['cancel'])) {
672 Logger::info('mod_item: post cancelled by addon.');
674 DI::baseUrl()->redirect($return_path);
677 $json = ['cancel' => 1];
678 if (!empty($_REQUEST['jsreload'])) {
679 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
682 System::jsonExit($json);
686 // Fill the cache field
687 // This could be done in Item::update as well - but we have to check for the existance of some fields.
688 Item::putInCache($datarray);
691 'title' => $datarray['title'],
692 'body' => $datarray['body'],
693 'tag' => $datarray['tag'],
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');
706 info(DI::l10n()->t('Post updated.'));
708 DI::baseUrl()->redirect($return_path);
711 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
714 unset($datarray['edit']);
715 unset($datarray['self']);
716 unset($datarray['api_source']);
719 $signed = Diaspora::createCommentSignature($uid, $datarray);
720 if (!empty($signed)) {
721 $datarray['diaspora_signed_text'] = json_encode($signed);
725 $post_id = Item::insert($datarray);
728 info(DI::l10n()->t('Item wasn\'t stored.'));
730 DI::baseUrl()->redirect($return_path);
733 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
736 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
738 if (!DBA::isResult($datarray)) {
739 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
741 DI::baseUrl()->redirect($return_path);
744 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
747 // update filetags in pconfig
748 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
750 // These notifications are sent if someone else is commenting other your wall
751 if ($toplevel_item_id) {
752 if ($contact_record != $author) {
754 'type' => Type::COMMENT,
755 'notify_flags' => $user['notify-flags'],
756 'language' => $user['language'],
757 'to_name' => $user['username'],
758 'to_email' => $user['email'],
759 'uid' => $user['uid'],
761 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
762 'source_name' => $datarray['author-name'],
763 'source_link' => $datarray['author-link'],
764 'source_photo' => $datarray['author-avatar'],
765 'verb' => Activity::POST,
767 'parent' => $toplevel_item_id,
768 'parent_uri' => $toplevel_item['uri']
772 if (($contact_record != $author) && !count($forum_contact)) {
774 'type' => Type::WALL,
775 'notify_flags' => $user['notify-flags'],
776 'language' => $user['language'],
777 'to_name' => $user['username'],
778 'to_email' => $user['email'],
779 'uid' => $user['uid'],
781 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
782 'source_name' => $datarray['author-name'],
783 'source_link' => $datarray['author-link'],
784 'source_photo' => $datarray['author-avatar'],
785 'verb' => Activity::POST,
791 Hook::callAll('post_local_end', $datarray);
793 if (strlen($emailcc) && $profile_uid == local_user()) {
794 $recipients = explode(',', $emailcc);
795 if (count($recipients)) {
796 foreach ($recipients as $recipient) {
797 $address = trim($recipient);
798 if (!strlen($address)) {
801 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
802 $datarray, $address, $author['thumb'] ?? ''));
807 // Insert an item entry for UID=0 for global entries.
808 // We now do it in the background to save some time.
809 // This is important in interactive environments like the frontend or the API.
810 // We don't fork a new process since this is done anyway with the following command
811 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
813 // When we are doing some forum posting via ! we have to start the notifier manually.
814 // These kind of posts don't initiate the notifier call in the item class.
815 if ($only_to_forum) {
816 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
819 Logger::info('post_complete');
825 info(DI::l10n()->t('Post published.'));
826 item_post_return(DI::baseUrl(), $api_source, $return_path);
830 function item_post_return($baseurl, $api_source, $return_path)
837 DI::baseUrl()->redirect($return_path);
840 $json = ['success' => 1];
841 if (!empty($_REQUEST['jsreload'])) {
842 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
845 Logger::info('post_json', ['json' => $json]);
847 System::jsonExit($json);
850 function item_content(App $a)
852 if (!Session::isAuthenticated()) {
858 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
859 if (DI::mode()->isAjax()) {
860 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
862 if (!empty($a->argv[3])) {
863 $o = drop_item($a->argv[2], $a->argv[3]);
866 $o = drop_item($a->argv[2]);
870 if (DI::mode()->isAjax()) {
871 // ajax return: [<item id>, 0 (no perm) | <owner id>]
872 System::jsonExit([intval($a->argv[2]), intval($o)]);
880 * This function removes the tag $tag from the text $body and replaces it with
881 * the appropriate link.
884 * @param string $body the text to replace the tag in
885 * @param string $inform a comma-seperated string containing everybody to inform
886 * @param string $str_tags string to add the tag to
887 * @param integer $profile_uid
888 * @param string $tag the tag to replace
889 * @param string $network The network of the post
891 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
892 * @throws ImagickException
893 * @throws HTTPException\InternalServerErrorException
895 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
900 //is it a person tag?
901 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
902 $tag_type = substr($tag, 0, 1);
903 //is it already replaced?
904 if (strpos($tag, '[url=')) {
905 //append tag to str_tags
906 if (!stristr($str_tags, $tag)) {
907 if (strlen($str_tags)) {
913 // Checking for the alias that is used for OStatus
914 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
915 if (preg_match($pattern, $tag, $matches)) {
916 $data = Contact::getDetailsByURL($matches[1]);
918 if ($data["alias"] != "") {
919 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
921 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
922 if (strlen($str_tags)) {
926 $str_tags .= $newtag;
934 //get the person's name
935 $name = substr($tag, 1);
937 // Sometimes the tag detection doesn't seem to work right
938 // This is some workaround
939 $nameparts = explode(" ", $name);
940 $name = $nameparts[0];
942 // Try to detect the contact in various ways
943 if (strpos($name, 'http://')) {
944 // At first we have to ensure that the contact exists
945 Contact::getIdForURL($name);
947 // Now we should have something
948 $contact = Contact::getDetailsByURL($name);
949 } elseif (strpos($name, '@')) {
950 // This function automatically probes when no entry was found
951 $contact = Contact::getDetailsByAddr($name);
954 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
956 if (strrpos($name, '+')) {
957 // Is it in format @nick+number?
958 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
959 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
962 // select someone by nick or attag in the current network
963 if (!DBA::isResult($contact) && ($network != "")) {
964 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
965 $name, $name, $network, $profile_uid];
966 $contact = DBA::selectFirst('contact', $fields, $condition);
969 //select someone by name in the current network
970 if (!DBA::isResult($contact) && ($network != "")) {
971 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
972 $contact = DBA::selectFirst('contact', $fields, $condition);
975 // select someone by nick or attag in any network
976 if (!DBA::isResult($contact)) {
977 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
978 $contact = DBA::selectFirst('contact', $fields, $condition);
981 // select someone by name in any network
982 if (!DBA::isResult($contact)) {
983 $condition = ['name' => $name, 'uid' => $profile_uid];
984 $contact = DBA::selectFirst('contact', $fields, $condition);
988 // Check if $contact has been successfully loaded
989 if (DBA::isResult($contact)) {
990 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
994 if (isset($contact["id"])) {
995 $inform .= 'cid:' . $contact["id"];
996 } elseif (isset($contact["notify"])) {
997 $inform .= $contact["notify"];
1000 $profile = $contact["url"];
1001 $alias = $contact["alias"];
1002 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1005 //if there is an url for this persons profile
1006 if (isset($profile) && ($newname != "")) {
1008 // create profile link
1009 $profile = str_replace(',', '%2c', $profile);
1010 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1011 $body = str_replace($tag_type . $name, $newtag, $body);
1012 // append tag to str_tags
1013 if (!stristr($str_tags, $newtag)) {
1014 if (strlen($str_tags)) {
1017 $str_tags .= $newtag;
1021 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1022 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1024 if (!empty($alias)) {
1025 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1026 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1027 if (strlen($str_tags)) {
1030 $str_tags .= $newtag;
1036 return ['replaced' => $replaced, 'contact' => $contact];
1039 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1041 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1042 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1043 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1044 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1045 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1050 $implicit_mentions = [
1051 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1054 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1056 foreach ($parent_terms as $parent_term) {
1057 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1060 foreach ($implicit_mentions as $url => $label) {
1061 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1062 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';