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\Tag;
50 use Friendica\Model\Term;
51 use Friendica\Network\HTTPException;
52 use Friendica\Object\EMail\ItemCCEMail;
53 use Friendica\Protocol\Activity;
54 use Friendica\Protocol\Diaspora;
55 use Friendica\Util\DateTimeFormat;
56 use Friendica\Util\Security;
57 use Friendica\Util\Strings;
58 use Friendica\Worker\Delivery;
60 require_once __DIR__ . '/../include/items.php';
62 function item_post(App $a) {
63 if (!Session::isAuthenticated()) {
64 throw new HTTPException\ForbiddenException();
69 if (!empty($_REQUEST['dropitems'])) {
70 $arr_drop = explode(',', $_REQUEST['dropitems']);
71 drop_items($arr_drop);
72 $json = ['success' => 1];
73 System::jsonExit($json);
76 Hook::callAll('post_local_start', $_REQUEST);
78 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
80 $api_source = $_REQUEST['api_source'] ?? false;
82 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
84 $return_path = $_REQUEST['return'] ?? '';
85 $preview = intval($_REQUEST['preview'] ?? 0);
88 * Check for doubly-submitted posts, and reject duplicates
89 * Note that we have to ignore previews, otherwise nothing will post
90 * after it's been previewed
92 if (!$preview && !empty($_REQUEST['post_id_random'])) {
93 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
94 Logger::info('item post: duplicate post');
95 item_post_return(DI::baseUrl(), $api_source, $return_path);
97 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
101 // Is this a reply to something?
102 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
103 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
105 $thread_parent_id = 0;
106 $thread_parent_contact = null;
108 $toplevel_item = null;
111 $parent_contact = null;
114 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
115 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
117 if ($toplevel_item_id || $thr_parent_uri) {
118 if ($toplevel_item_id) {
119 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
120 } elseif ($thr_parent_uri) {
121 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
124 // if this isn't the top-level parent of the conversation, find it
125 if (DBA::isResult($toplevel_item)) {
126 // The URI and the contact is taken from the direct parent which needn't to be the top parent
127 $thread_parent_id = $toplevel_item['id'];
128 $thr_parent_uri = $toplevel_item['uri'];
129 $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
131 if ($toplevel_item['id'] != $toplevel_item['parent']) {
132 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item['parent']]);
136 if (!DBA::isResult($toplevel_item)) {
137 notice(DI::l10n()->t('Unable to locate original post.'));
139 DI::baseUrl()->redirect($return_path);
141 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
144 $toplevel_item_id = $toplevel_item['id'];
145 $parent_user = $toplevel_item['uid'];
147 $objecttype = Activity\ObjectType::COMMENT;
150 if ($toplevel_item_id) {
151 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
154 $post_id = intval($_REQUEST['post_id'] ?? 0);
155 $app = strip_tags($_REQUEST['source'] ?? '');
156 $extid = strip_tags($_REQUEST['extid'] ?? '');
157 $object = $_REQUEST['object'] ?? '';
159 // Don't use "defaults" here. It would turn 0 to 1
160 if (!isset($_REQUEST['wall'])) {
163 $wall = $_REQUEST['wall'];
166 // Ensure that the user id in a thread always stay the same
167 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
168 $profile_uid = $parent_user;
171 // Check for multiple posts with the same message id (when the post was created via API)
172 if (($message_id != '') && ($profile_uid != 0)) {
173 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
174 Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
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 = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
200 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
202 if (!DBA::isResult($user) && !$toplevel_item_id) {
209 $body = $_REQUEST['body'] ?? '';
210 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
212 // If we have a speparate attachment, we need to add it to the body.
213 if (!empty($has_attachment)) {
214 $attachment_type = $_REQUEST['attachment_type'] ?? '';
215 $attachment_title = $_REQUEST['attachment_title'] ?? '';
216 $attachment_text = $_REQUEST['attachment_text'] ?? '';
218 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
219 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
221 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
222 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
224 'type' => $attachment_type,
225 'title' => $attachment_title,
226 'text' => $attachment_text,
227 'url' => $attachment_url,
230 if (!empty($attachment_img_src)) {
231 $attachment['images'] = [
233 'src' => $attachment_img_src,
234 'width' => $attachment_img_width,
235 'height' => $attachment_img_height
240 $att_bbcode = add_page_info_data($attachment);
241 $body .= $att_bbcode;
244 // Convert links with empty descriptions to links without an explicit description
245 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
247 if (!empty($orig_post)) {
248 $str_group_allow = $orig_post['allow_gid'];
249 $str_contact_allow = $orig_post['allow_cid'];
250 $str_group_deny = $orig_post['deny_gid'];
251 $str_contact_deny = $orig_post['deny_cid'];
252 $location = $orig_post['location'];
253 $coord = $orig_post['coord'];
254 $verb = $orig_post['verb'];
255 $objecttype = $orig_post['object-type'];
256 $app = $orig_post['app'];
257 $categories = $orig_post['file'];
258 $title = Strings::escapeTags(trim($_REQUEST['title']));
260 $private = $orig_post['private'];
261 $pubmail_enabled = $orig_post['pubmail'];
262 $network = $orig_post['network'];
263 $guid = $orig_post['guid'];
264 $extid = $orig_post['extid'];
266 $str_contact_allow = '';
267 $str_group_allow = '';
268 $str_contact_deny = '';
269 $str_group_deny = '';
271 if (($_REQUEST['visibility'] ?? '') !== 'public') {
272 $aclFormatter = DI::aclFormatter();
273 $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
274 $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? '';
275 $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? '';
276 $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? '';
279 $title = Strings::escapeTags(trim($_REQUEST['title'] ?? ''));
280 $location = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
281 $coord = Strings::escapeTags(trim($_REQUEST['coord'] ?? ''));
282 $verb = Strings::escapeTags(trim($_REQUEST['verb'] ?? ''));
283 $emailcc = Strings::escapeTags(trim($_REQUEST['emailcc'] ?? ''));
285 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
286 $guid = System::createUUID();
288 $postopts = $_REQUEST['postopts'] ?? '';
290 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
291 $private = Item::PRIVATE;
292 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
293 $private = Item::UNLISTED;
295 $private = Item::PUBLIC;
298 // If this is a comment, set the permissions from the parent.
300 if ($toplevel_item) {
301 // for non native networks use the network of the original post as network of the item
302 if (($toplevel_item['network'] != Protocol::DIASPORA)
303 && ($toplevel_item['network'] != Protocol::OSTATUS)
304 && ($network == "")) {
305 $network = $toplevel_item['network'];
308 $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
309 $str_group_allow = $toplevel_item['allow_gid'] ?? '';
310 $str_contact_deny = $toplevel_item['deny_cid'] ?? '';
311 $str_group_deny = $toplevel_item['deny_gid'] ?? '';
312 $private = $toplevel_item['private'];
314 $wall = $toplevel_item['wall'];
317 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
319 // if using the API, we won't see pubmail_enable - figure out if it should be set
320 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
321 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
322 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
326 if (!strlen($body)) {
328 System::jsonExit(['preview' => '']);
331 info(DI::l10n()->t('Empty post discarded.'));
333 DI::baseUrl()->redirect($return_path);
336 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
340 if (!empty($categories)) {
341 // get the "fileas" tags for this post
342 $filedas = FileTag::fileToArray($categories);
345 // save old and new categories, so we can determine what needs to be deleted from pconfig
346 $categories_old = $categories;
347 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
348 $categories_new = $categories;
350 if (!empty($filedas) && is_array($filedas)) {
351 // append the fileas stuff to the new categories list
352 $categories .= FileTag::arrayToFile($filedas);
355 // get contact info for poster
361 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
363 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
364 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
365 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
368 if (DBA::isResult($author)) {
369 $contact_id = $author['id'];
372 // get contact info for owner
373 if ($profile_uid == local_user() || $allow_comment) {
374 $contact_record = $author;
376 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
379 // Look for any tags and linkify them
383 $tags = BBCode::getTags($body);
385 if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
386 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
391 $private_forum = false;
392 $only_to_forum = false;
396 foreach ($tags as $tag) {
397 $tag_type = substr($tag, 0, 1);
399 if ($tag_type == Term::TAG_CHARACTER[Term::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 $fullnametagged = false;
408 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
409 foreach ($tagged as $nextTag) {
410 if (stristr($nextTag, $tag . ' ')) {
411 $fullnametagged = true;
415 if ($fullnametagged) {
419 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
420 if ($success['replaced']) {
423 // When the forum is private or the forum is addressed with a "!" make the post private
424 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
425 $private_forum = $success['contact']['prv'];
426 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
427 $private_id = $success['contact']['id'];
428 $forum_contact = $success['contact'];
429 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
430 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
431 $private_forum = false;
432 $only_to_forum = true;
433 $private_id = $success['contact']['id'];
434 $forum_contact = $success['contact'];
439 $original_contact_id = $contact_id;
441 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
442 // we tagged a forum in a top level post. Now we change the post
443 $private = $private_forum;
445 $str_group_allow = '';
446 $str_contact_deny = '';
447 $str_group_deny = '';
448 if ($private_forum) {
449 $str_contact_allow = '<' . $private_id . '>';
451 $str_contact_allow = '';
453 $contact_id = $private_id;
454 $contact_record = $forum_contact;
455 $_REQUEST['origin'] = false;
460 * When a photo was uploaded into the message using the (profile wall) ajax
461 * uploader, The permissions are initially set to disallow anybody but the
462 * owner from seeing it. This is because the permissions may not yet have been
463 * set for the post. If it's private, the photo permissions should be set
464 * appropriately. But we didn't know the final permissions on the post until
465 * now. So now we'll look for links of uploaded messages that are in the
466 * post and set them to the same permissions as the post itself.
471 if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
472 $objecttype = Activity\ObjectType::IMAGE;
476 * Next link in any attachment references we find in the post.
480 /// @todo these lines should be moved to Model/Attach (Once it exists)
481 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
482 $attaches = $match[1];
483 if (count($attaches)) {
484 foreach ($attaches as $attach) {
485 // Ensure to only modify attachments that you own
486 $srch = '<' . intval($original_contact_id) . '>';
488 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
490 if (!Attach::exists($condition)) {
494 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
495 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
496 $condition = ['id' => $attach];
497 Attach::update($fields, $condition);
502 // embedded bookmark or attachment in post? set bookmark flag
504 $data = BBCode::getAttachmentData($body);
505 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
506 && ($posttype != Item::PT_PERSONAL_NOTE)) {
507 $posttype = Item::PT_PAGE;
508 $objecttype = Activity\ObjectType::BOOKMARK;
511 $body = DI::bbCodeVideo()->transform($body);
513 $body = BBCode::scaleExternalImages($body);
515 // Setting the object type if not defined before
517 $objecttype = Activity\ObjectType::NOTE; // Default value
518 $objectdata = BBCode::getAttachedData($body);
520 if ($objectdata["type"] == "link") {
521 $objecttype = Activity\ObjectType::BOOKMARK;
522 } elseif ($objectdata["type"] == "video") {
523 $objecttype = Activity\ObjectType::VIDEO;
524 } elseif ($objectdata["type"] == "photo") {
525 $objecttype = Activity\ObjectType::IMAGE;
533 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
534 foreach ($match[2] as $mtch) {
535 $fields = ['id', 'filename', 'filesize', 'filetype'];
536 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
537 if ($attachment !== false) {
538 if (strlen($attachments)) {
541 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
542 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
543 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
545 $body = str_replace($match[1],'',$body);
549 if (!strlen($verb)) {
550 $verb = Activity::POST;
553 if ($network == "") {
554 $network = Protocol::DFRN;
557 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
559 // even if the post arrived via API we are considering that it
560 // originated on this site by default for determining relayability.
562 // Don't use "defaults" here. It would turn 0 to 1
563 if (!isset($_REQUEST['origin'])) {
566 $origin = $_REQUEST['origin'];
569 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
571 // Fallback so that we alway have a parent uri
572 if (!$thr_parent_uri || !$toplevel_item_id) {
573 $thr_parent_uri = $uri;
577 $datarray['uid'] = $profile_uid;
578 $datarray['wall'] = $wall;
579 $datarray['gravity'] = $gravity;
580 $datarray['network'] = $network;
581 $datarray['contact-id'] = $contact_id;
582 $datarray['owner-name'] = $contact_record['name'];
583 $datarray['owner-link'] = $contact_record['url'];
584 $datarray['owner-avatar'] = $contact_record['thumb'];
585 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
586 $datarray['author-name'] = $author['name'];
587 $datarray['author-link'] = $author['url'];
588 $datarray['author-avatar'] = $author['thumb'];
589 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
590 $datarray['created'] = DateTimeFormat::utcNow();
591 $datarray['edited'] = DateTimeFormat::utcNow();
592 $datarray['commented'] = DateTimeFormat::utcNow();
593 $datarray['received'] = DateTimeFormat::utcNow();
594 $datarray['changed'] = DateTimeFormat::utcNow();
595 $datarray['extid'] = $extid;
596 $datarray['guid'] = $guid;
597 $datarray['uri'] = $uri;
598 $datarray['title'] = $title;
599 $datarray['body'] = $body;
600 $datarray['app'] = $app;
601 $datarray['location'] = $location;
602 $datarray['coord'] = $coord;
603 $datarray['tag'] = $str_tags;
604 $datarray['file'] = $categories;
605 $datarray['inform'] = $inform;
606 $datarray['verb'] = $verb;
607 $datarray['post-type'] = $posttype;
608 $datarray['object-type'] = $objecttype;
609 $datarray['allow_cid'] = $str_contact_allow;
610 $datarray['allow_gid'] = $str_group_allow;
611 $datarray['deny_cid'] = $str_contact_deny;
612 $datarray['deny_gid'] = $str_group_deny;
613 $datarray['private'] = $private;
614 $datarray['pubmail'] = $pubmail_enabled;
615 $datarray['attach'] = $attachments;
617 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
618 $datarray['parent-uri'] = $thr_parent_uri;
620 $datarray['postopts'] = $postopts;
621 $datarray['origin'] = $origin;
622 $datarray['moderated'] = false;
623 $datarray['object'] = $object;
626 * These fields are for the convenience of addons...
627 * 'self' if true indicates the owner is posting on their own wall
628 * If parent is 0 it is a top-level post.
630 $datarray['parent'] = $toplevel_item_id;
631 $datarray['self'] = $self;
633 // This triggers posts via API and the mirror functions
634 $datarray['api_source'] = $api_source;
636 // This field is for storing the raw conversation data
637 $datarray['protocol'] = Conversation::PARCEL_DFRN;
639 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
640 if (DBA::isResult($conversation)) {
641 if ($conversation['conversation-uri'] != '') {
642 $datarray['conversation-uri'] = $conversation['conversation-uri'];
644 if ($conversation['conversation-href'] != '') {
645 $datarray['conversation-href'] = $conversation['conversation-href'];
650 $datarray['edit'] = true;
652 // If this was a share, add missing data here
653 $datarray = Item::addShareDataFromOriginal($datarray);
655 $datarray['edit'] = false;
658 // Check for hashtags in the body and repair or add hashtag links
659 if ($preview || $orig_post) {
660 Item::setHashtags($datarray);
663 // preview mode - prepare the body for display and send it via json
665 // We set the datarray ID to -1 because in preview mode the dataray
666 // doesn't have an ID.
667 $datarray["id"] = -1;
668 $datarray["item_id"] = -1;
669 $datarray["author-network"] = Protocol::DFRN;
671 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
673 System::jsonExit(['preview' => $o]);
676 Hook::callAll('post_local',$datarray);
678 if (!empty($datarray['cancel'])) {
679 Logger::info('mod_item: post cancelled by addon.');
681 DI::baseUrl()->redirect($return_path);
684 $json = ['cancel' => 1];
685 if (!empty($_REQUEST['jsreload'])) {
686 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
689 System::jsonExit($json);
693 // Fill the cache field
694 // This could be done in Item::update as well - but we have to check for the existance of some fields.
695 Item::putInCache($datarray);
698 'title' => $datarray['title'],
699 'body' => $datarray['body'],
700 'tag' => $datarray['tag'],
701 'attach' => $datarray['attach'],
702 'file' => $datarray['file'],
703 'rendered-html' => $datarray['rendered-html'],
704 'rendered-hash' => $datarray['rendered-hash'],
705 'edited' => DateTimeFormat::utcNow(),
706 'changed' => DateTimeFormat::utcNow()];
708 Item::update($fields, ['id' => $post_id]);
710 // update filetags in pconfig
711 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
713 info(DI::l10n()->t('Post updated.'));
715 DI::baseUrl()->redirect($return_path);
718 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
721 unset($datarray['edit']);
722 unset($datarray['self']);
723 unset($datarray['api_source']);
726 $signed = Diaspora::createCommentSignature($uid, $datarray);
727 if (!empty($signed)) {
728 $datarray['diaspora_signed_text'] = json_encode($signed);
732 $post_id = Item::insert($datarray);
735 info(DI::l10n()->t('Item wasn\'t stored.'));
737 DI::baseUrl()->redirect($return_path);
740 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
743 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
745 if (!DBA::isResult($datarray)) {
746 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
748 DI::baseUrl()->redirect($return_path);
751 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
754 Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
756 // update filetags in pconfig
757 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
759 // These notifications are sent if someone else is commenting other your wall
760 if ($toplevel_item_id) {
761 if ($contact_record != $author) {
763 'type' => Type::COMMENT,
764 'notify_flags' => $user['notify-flags'],
765 'language' => $user['language'],
766 'to_name' => $user['username'],
767 'to_email' => $user['email'],
768 'uid' => $user['uid'],
770 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
771 'source_name' => $datarray['author-name'],
772 'source_link' => $datarray['author-link'],
773 'source_photo' => $datarray['author-avatar'],
774 'verb' => Activity::POST,
776 'parent' => $toplevel_item_id,
777 'parent_uri' => $toplevel_item['uri']
781 if (($contact_record != $author) && !count($forum_contact)) {
783 'type' => Type::WALL,
784 'notify_flags' => $user['notify-flags'],
785 'language' => $user['language'],
786 'to_name' => $user['username'],
787 'to_email' => $user['email'],
788 'uid' => $user['uid'],
790 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
791 'source_name' => $datarray['author-name'],
792 'source_link' => $datarray['author-link'],
793 'source_photo' => $datarray['author-avatar'],
794 'verb' => Activity::POST,
800 Hook::callAll('post_local_end', $datarray);
802 if (strlen($emailcc) && $profile_uid == local_user()) {
803 $recipients = explode(',', $emailcc);
804 if (count($recipients)) {
805 foreach ($recipients as $recipient) {
806 $address = trim($recipient);
807 if (!strlen($address)) {
810 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
811 $datarray, $address, $author['thumb'] ?? ''));
816 // Insert an item entry for UID=0 for global entries.
817 // We now do it in the background to save some time.
818 // This is important in interactive environments like the frontend or the API.
819 // We don't fork a new process since this is done anyway with the following command
820 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
822 // When we are doing some forum posting via ! we have to start the notifier manually.
823 // These kind of posts don't initiate the notifier call in the item class.
824 if ($only_to_forum) {
825 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
828 Logger::info('post_complete');
834 info(DI::l10n()->t('Post published.'));
835 item_post_return(DI::baseUrl(), $api_source, $return_path);
839 function item_post_return($baseurl, $api_source, $return_path)
846 DI::baseUrl()->redirect($return_path);
849 $json = ['success' => 1];
850 if (!empty($_REQUEST['jsreload'])) {
851 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
854 Logger::info('post_json', ['json' => $json]);
856 System::jsonExit($json);
859 function item_content(App $a)
861 if (!Session::isAuthenticated()) {
867 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
868 if (DI::mode()->isAjax()) {
869 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
871 if (!empty($a->argv[3])) {
872 $o = drop_item($a->argv[2], $a->argv[3]);
875 $o = drop_item($a->argv[2]);
879 if (DI::mode()->isAjax()) {
880 // ajax return: [<item id>, 0 (no perm) | <owner id>]
881 System::jsonExit([intval($a->argv[2]), intval($o)]);
889 * This function removes the tag $tag from the text $body and replaces it with
890 * the appropriate link.
893 * @param string $body the text to replace the tag in
894 * @param string $inform a comma-seperated string containing everybody to inform
895 * @param string $str_tags string to add the tag to
896 * @param integer $profile_uid
897 * @param string $tag the tag to replace
898 * @param string $network The network of the post
900 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
901 * @throws ImagickException
902 * @throws HTTPException\InternalServerErrorException
904 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
909 //is it a person tag?
910 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
911 $tag_type = substr($tag, 0, 1);
912 //is it already replaced?
913 if (strpos($tag, '[url=')) {
914 //append tag to str_tags
915 if (!stristr($str_tags, $tag)) {
916 if (strlen($str_tags)) {
922 // Checking for the alias that is used for OStatus
923 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
924 if (preg_match($pattern, $tag, $matches)) {
925 $data = Contact::getDetailsByURL($matches[1]);
927 if ($data["alias"] != "") {
928 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
930 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
931 if (strlen($str_tags)) {
935 $str_tags .= $newtag;
943 //get the person's name
944 $name = substr($tag, 1);
946 // Sometimes the tag detection doesn't seem to work right
947 // This is some workaround
948 $nameparts = explode(" ", $name);
949 $name = $nameparts[0];
951 // Try to detect the contact in various ways
952 if (strpos($name, 'http://')) {
953 // At first we have to ensure that the contact exists
954 Contact::getIdForURL($name);
956 // Now we should have something
957 $contact = Contact::getDetailsByURL($name);
958 } elseif (strpos($name, '@')) {
959 // This function automatically probes when no entry was found
960 $contact = Contact::getDetailsByAddr($name);
963 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
965 if (strrpos($name, '+')) {
966 // Is it in format @nick+number?
967 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
968 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
971 // select someone by nick or attag in the current network
972 if (!DBA::isResult($contact) && ($network != "")) {
973 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
974 $name, $name, $network, $profile_uid];
975 $contact = DBA::selectFirst('contact', $fields, $condition);
978 //select someone by name in the current network
979 if (!DBA::isResult($contact) && ($network != "")) {
980 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
981 $contact = DBA::selectFirst('contact', $fields, $condition);
984 // select someone by nick or attag in any network
985 if (!DBA::isResult($contact)) {
986 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
987 $contact = DBA::selectFirst('contact', $fields, $condition);
990 // select someone by name in any network
991 if (!DBA::isResult($contact)) {
992 $condition = ['name' => $name, 'uid' => $profile_uid];
993 $contact = DBA::selectFirst('contact', $fields, $condition);
997 // Check if $contact has been successfully loaded
998 if (DBA::isResult($contact)) {
999 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1003 if (isset($contact["id"])) {
1004 $inform .= 'cid:' . $contact["id"];
1005 } elseif (isset($contact["notify"])) {
1006 $inform .= $contact["notify"];
1009 $profile = $contact["url"];
1010 $alias = $contact["alias"];
1011 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1014 //if there is an url for this persons profile
1015 if (isset($profile) && ($newname != "")) {
1017 // create profile link
1018 $profile = str_replace(',', '%2c', $profile);
1019 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1020 $body = str_replace($tag_type . $name, $newtag, $body);
1021 // append tag to str_tags
1022 if (!stristr($str_tags, $newtag)) {
1023 if (strlen($str_tags)) {
1026 $str_tags .= $newtag;
1030 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1031 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1033 if (!empty($alias)) {
1034 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1035 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1036 if (strlen($str_tags)) {
1039 $str_tags .= $newtag;
1045 return ['replaced' => $replaced, 'contact' => $contact];
1048 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1050 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1051 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1052 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1053 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1054 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1059 $implicit_mentions = [
1060 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1063 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1065 foreach ($parent_terms as $parent_term) {
1066 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1069 foreach ($implicit_mentions as $url => $label) {
1070 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1071 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';