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\Config\PConfig;
44 use Friendica\Model\Contact;
45 use Friendica\Model\Conversation;
46 use Friendica\Model\FileTag;
47 use Friendica\Model\Item;
48 use Friendica\Model\Notify\Type;
49 use Friendica\Model\Photo;
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(Item::ITEM_FIELDLIST, ['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'];
269 * if coming from the API and no privacy settings are set,
270 * use the user default permissions - as they won't have
271 * been supplied via a form.
274 && !array_key_exists('contact_allow', $_REQUEST)
275 && !array_key_exists('group_allow', $_REQUEST)
276 && !array_key_exists('contact_deny', $_REQUEST)
277 && !array_key_exists('group_deny', $_REQUEST)) {
278 $str_group_allow = $user['allow_gid'];
279 $str_contact_allow = $user['allow_cid'];
280 $str_group_deny = $user['deny_gid'];
281 $str_contact_deny = $user['deny_cid'];
283 // use the posted permissions
285 $aclFormatter = DI::aclFormatter();
287 $str_group_allow = $aclFormatter->toString($_REQUEST['group_allow'] ?? '');
288 $str_contact_allow = $aclFormatter->toString($_REQUEST['contact_allow'] ?? '');
289 $str_group_deny = $aclFormatter->toString($_REQUEST['group_deny'] ?? '');
290 $str_contact_deny = $aclFormatter->toString($_REQUEST['contact_deny'] ?? '');
293 $title = Strings::escapeTags(trim($_REQUEST['title'] ?? ''));
294 $location = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
295 $coord = Strings::escapeTags(trim($_REQUEST['coord'] ?? ''));
296 $verb = Strings::escapeTags(trim($_REQUEST['verb'] ?? ''));
297 $emailcc = Strings::escapeTags(trim($_REQUEST['emailcc'] ?? ''));
299 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
300 $guid = System::createUUID();
302 $postopts = $_REQUEST['postopts'] ?? '';
304 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
305 $private = Item::PRIVATE;
306 } elseif (PConfig::get($profile_uid, 'system', 'unlisted')) {
307 $private == Item::UNLISTED;
309 $private == Item::PUBLIC;
312 // If this is a comment, set the permissions from the parent.
314 if ($toplevel_item) {
315 // for non native networks use the network of the original post as network of the item
316 if (($toplevel_item['network'] != Protocol::DIASPORA)
317 && ($toplevel_item['network'] != Protocol::OSTATUS)
318 && ($network == "")) {
319 $network = $toplevel_item['network'];
322 $str_contact_allow = $toplevel_item['allow_cid'];
323 $str_group_allow = $toplevel_item['allow_gid'];
324 $str_contact_deny = $toplevel_item['deny_cid'];
325 $str_group_deny = $toplevel_item['deny_gid'];
326 $private = $toplevel_item['private'];
328 $wall = $toplevel_item['wall'];
331 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
333 // if using the API, we won't see pubmail_enable - figure out if it should be set
334 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
335 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
336 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
340 if (!strlen($body)) {
342 System::jsonExit(['preview' => '']);
345 info(DI::l10n()->t('Empty post discarded.'));
347 DI::baseUrl()->redirect($return_path);
350 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
354 if (!empty($categories)) {
355 // get the "fileas" tags for this post
356 $filedas = FileTag::fileToArray($categories);
359 // save old and new categories, so we can determine what needs to be deleted from pconfig
360 $categories_old = $categories;
361 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
362 $categories_new = $categories;
364 if (!empty($filedas) && is_array($filedas)) {
365 // append the fileas stuff to the new categories list
366 $categories .= FileTag::arrayToFile($filedas);
369 // get contact info for poster
375 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
377 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
378 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
379 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
382 if (DBA::isResult($author)) {
383 $contact_id = $author['id'];
386 // get contact info for owner
387 if ($profile_uid == local_user() || $allow_comment) {
388 $contact_record = $author;
390 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
393 // Look for any tags and linkify them
397 $tags = BBCode::getTags($body);
399 if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
400 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
405 $private_forum = false;
406 $only_to_forum = false;
410 foreach ($tags as $tag) {
411 $tag_type = substr($tag, 0, 1);
413 if ($tag_type == Term::TAG_CHARACTER[Term::HASHTAG]) {
418 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
419 * Robert Johnson should be first in the $tags array
421 $fullnametagged = false;
422 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
423 foreach ($tagged as $nextTag) {
424 if (stristr($nextTag, $tag . ' ')) {
425 $fullnametagged = true;
429 if ($fullnametagged) {
433 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
434 if ($success['replaced']) {
437 // When the forum is private or the forum is addressed with a "!" make the post private
438 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
439 $private_forum = $success['contact']['prv'];
440 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
441 $private_id = $success['contact']['id'];
442 $forum_contact = $success['contact'];
443 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
444 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
445 $private_forum = false;
446 $only_to_forum = true;
447 $private_id = $success['contact']['id'];
448 $forum_contact = $success['contact'];
453 $original_contact_id = $contact_id;
455 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
456 // we tagged a forum in a top level post. Now we change the post
457 $private = $private_forum;
459 $str_group_allow = '';
460 $str_contact_deny = '';
461 $str_group_deny = '';
462 if ($private_forum) {
463 $str_contact_allow = '<' . $private_id . '>';
465 $str_contact_allow = '';
467 $contact_id = $private_id;
468 $contact_record = $forum_contact;
469 $_REQUEST['origin'] = false;
474 * When a photo was uploaded into the message using the (profile wall) ajax
475 * uploader, The permissions are initially set to disallow anybody but the
476 * owner from seeing it. This is because the permissions may not yet have been
477 * set for the post. If it's private, the photo permissions should be set
478 * appropriately. But we didn't know the final permissions on the post until
479 * now. So now we'll look for links of uploaded messages that are in the
480 * post and set them to the same permissions as the post itself.
485 if (!$preview && Photo::setPermissionFromBody($body, $profile_uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
486 $objecttype = Activity\ObjectType::IMAGE;
490 * Next link in any attachment references we find in the post.
494 /// @todo these lines should be moved to Model/Attach (Once it exists)
495 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
496 $attaches = $match[1];
497 if (count($attaches)) {
498 foreach ($attaches as $attach) {
499 // Ensure to only modify attachments that you own
500 $srch = '<' . intval($original_contact_id) . '>';
502 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
504 if (!Attach::exists($condition)) {
508 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
509 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
510 $condition = ['id' => $attach];
511 Attach::update($fields, $condition);
516 // embedded bookmark or attachment in post? set bookmark flag
518 $data = BBCode::getAttachmentData($body);
519 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
520 && ($posttype != Item::PT_PERSONAL_NOTE)) {
521 $posttype = Item::PT_PAGE;
522 $objecttype = Activity\ObjectType::BOOKMARK;
525 $body = DI::bbCodeVideo()->transform($body);
527 $body = BBCode::scaleExternalImages($body);
529 // Setting the object type if not defined before
531 $objecttype = Activity\ObjectType::NOTE; // Default value
532 $objectdata = BBCode::getAttachedData($body);
534 if ($objectdata["type"] == "link") {
535 $objecttype = Activity\ObjectType::BOOKMARK;
536 } elseif ($objectdata["type"] == "video") {
537 $objecttype = Activity\ObjectType::VIDEO;
538 } elseif ($objectdata["type"] == "photo") {
539 $objecttype = Activity\ObjectType::IMAGE;
547 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
548 foreach ($match[2] as $mtch) {
549 $fields = ['id', 'filename', 'filesize', 'filetype'];
550 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
551 if ($attachment !== false) {
552 if (strlen($attachments)) {
555 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
556 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
557 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
559 $body = str_replace($match[1],'',$body);
563 if (!strlen($verb)) {
564 $verb = Activity::POST;
567 if ($network == "") {
568 $network = Protocol::DFRN;
571 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
573 // even if the post arrived via API we are considering that it
574 // originated on this site by default for determining relayability.
576 // Don't use "defaults" here. It would turn 0 to 1
577 if (!isset($_REQUEST['origin'])) {
580 $origin = $_REQUEST['origin'];
583 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
585 // Fallback so that we alway have a parent uri
586 if (!$thr_parent_uri || !$toplevel_item_id) {
587 $thr_parent_uri = $uri;
591 $datarray['uid'] = $profile_uid;
592 $datarray['wall'] = $wall;
593 $datarray['gravity'] = $gravity;
594 $datarray['network'] = $network;
595 $datarray['contact-id'] = $contact_id;
596 $datarray['owner-name'] = $contact_record['name'];
597 $datarray['owner-link'] = $contact_record['url'];
598 $datarray['owner-avatar'] = $contact_record['thumb'];
599 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
600 $datarray['author-name'] = $author['name'];
601 $datarray['author-link'] = $author['url'];
602 $datarray['author-avatar'] = $author['thumb'];
603 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
604 $datarray['created'] = DateTimeFormat::utcNow();
605 $datarray['edited'] = DateTimeFormat::utcNow();
606 $datarray['commented'] = DateTimeFormat::utcNow();
607 $datarray['received'] = DateTimeFormat::utcNow();
608 $datarray['changed'] = DateTimeFormat::utcNow();
609 $datarray['extid'] = $extid;
610 $datarray['guid'] = $guid;
611 $datarray['uri'] = $uri;
612 $datarray['title'] = $title;
613 $datarray['body'] = $body;
614 $datarray['app'] = $app;
615 $datarray['location'] = $location;
616 $datarray['coord'] = $coord;
617 $datarray['tag'] = $str_tags;
618 $datarray['file'] = $categories;
619 $datarray['inform'] = $inform;
620 $datarray['verb'] = $verb;
621 $datarray['post-type'] = $posttype;
622 $datarray['object-type'] = $objecttype;
623 $datarray['allow_cid'] = $str_contact_allow;
624 $datarray['allow_gid'] = $str_group_allow;
625 $datarray['deny_cid'] = $str_contact_deny;
626 $datarray['deny_gid'] = $str_group_deny;
627 $datarray['private'] = $private;
628 $datarray['pubmail'] = $pubmail_enabled;
629 $datarray['attach'] = $attachments;
631 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
632 $datarray['parent-uri'] = $thr_parent_uri;
634 $datarray['postopts'] = $postopts;
635 $datarray['origin'] = $origin;
636 $datarray['moderated'] = false;
637 $datarray['object'] = $object;
640 * These fields are for the convenience of addons...
641 * 'self' if true indicates the owner is posting on their own wall
642 * If parent is 0 it is a top-level post.
644 $datarray['parent'] = $toplevel_item_id;
645 $datarray['self'] = $self;
647 // This triggers posts via API and the mirror functions
648 $datarray['api_source'] = $api_source;
650 // This field is for storing the raw conversation data
651 $datarray['protocol'] = Conversation::PARCEL_DFRN;
653 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
654 if (DBA::isResult($conversation)) {
655 if ($conversation['conversation-uri'] != '') {
656 $datarray['conversation-uri'] = $conversation['conversation-uri'];
658 if ($conversation['conversation-href'] != '') {
659 $datarray['conversation-href'] = $conversation['conversation-href'];
664 $datarray['edit'] = true;
666 // If this was a share, add missing data here
667 $datarray = Item::addShareDataFromOriginal($datarray);
669 $datarray['edit'] = false;
672 // Check for hashtags in the body and repair or add hashtag links
673 if ($preview || $orig_post) {
674 Item::setHashtags($datarray);
677 // preview mode - prepare the body for display and send it via json
679 // We set the datarray ID to -1 because in preview mode the dataray
680 // doesn't have an ID.
681 $datarray["id"] = -1;
682 $datarray["item_id"] = -1;
683 $datarray["author-network"] = Protocol::DFRN;
685 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
687 System::jsonExit(['preview' => $o]);
690 Hook::callAll('post_local',$datarray);
692 if (!empty($datarray['cancel'])) {
693 Logger::info('mod_item: post cancelled by addon.');
695 DI::baseUrl()->redirect($return_path);
698 $json = ['cancel' => 1];
699 if (!empty($_REQUEST['jsreload'])) {
700 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
703 System::jsonExit($json);
707 // Fill the cache field
708 // This could be done in Item::update as well - but we have to check for the existance of some fields.
709 Item::putInCache($datarray);
712 'title' => $datarray['title'],
713 'body' => $datarray['body'],
714 'tag' => $datarray['tag'],
715 'attach' => $datarray['attach'],
716 'file' => $datarray['file'],
717 'rendered-html' => $datarray['rendered-html'],
718 'rendered-hash' => $datarray['rendered-hash'],
719 'edited' => DateTimeFormat::utcNow(),
720 'changed' => DateTimeFormat::utcNow()];
722 Item::update($fields, ['id' => $post_id]);
724 // update filetags in pconfig
725 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
727 info(DI::l10n()->t('Post updated.'));
729 DI::baseUrl()->redirect($return_path);
732 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
735 unset($datarray['edit']);
736 unset($datarray['self']);
737 unset($datarray['api_source']);
740 $signed = Diaspora::createCommentSignature($uid, $datarray);
741 if (!empty($signed)) {
742 $datarray['diaspora_signed_text'] = json_encode($signed);
746 $post_id = Item::insert($datarray);
749 info(DI::l10n()->t('Item wasn\'t stored.'));
751 DI::baseUrl()->redirect($return_path);
754 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
757 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
759 if (!DBA::isResult($datarray)) {
760 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
762 DI::baseUrl()->redirect($return_path);
765 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
768 // update filetags in pconfig
769 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
771 // These notifications are sent if someone else is commenting other your wall
772 if ($toplevel_item_id) {
773 if ($contact_record != $author) {
775 'type' => Type::COMMENT,
776 'notify_flags' => $user['notify-flags'],
777 'language' => $user['language'],
778 'to_name' => $user['username'],
779 'to_email' => $user['email'],
780 'uid' => $user['uid'],
782 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
783 'source_name' => $datarray['author-name'],
784 'source_link' => $datarray['author-link'],
785 'source_photo' => $datarray['author-avatar'],
786 'verb' => Activity::POST,
788 'parent' => $toplevel_item_id,
789 'parent_uri' => $toplevel_item['uri']
793 if (($contact_record != $author) && !count($forum_contact)) {
795 'type' => Type::WALL,
796 'notify_flags' => $user['notify-flags'],
797 'language' => $user['language'],
798 'to_name' => $user['username'],
799 'to_email' => $user['email'],
800 'uid' => $user['uid'],
802 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
803 'source_name' => $datarray['author-name'],
804 'source_link' => $datarray['author-link'],
805 'source_photo' => $datarray['author-avatar'],
806 'verb' => Activity::POST,
812 Hook::callAll('post_local_end', $datarray);
814 if (strlen($emailcc) && $profile_uid == local_user()) {
815 $recipients = explode(',', $emailcc);
816 if (count($recipients)) {
817 foreach ($recipients as $recipient) {
818 $address = trim($recipient);
819 if (!strlen($address)) {
822 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
823 $datarray, $address, $author['thumb'] ?? ''));
828 // Insert an item entry for UID=0 for global entries.
829 // We now do it in the background to save some time.
830 // This is important in interactive environments like the frontend or the API.
831 // We don't fork a new process since this is done anyway with the following command
832 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
834 // When we are doing some forum posting via ! we have to start the notifier manually.
835 // These kind of posts don't initiate the notifier call in the item class.
836 if ($only_to_forum) {
837 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
840 Logger::info('post_complete');
846 info(DI::l10n()->t('Post published.'));
847 item_post_return(DI::baseUrl(), $api_source, $return_path);
851 function item_post_return($baseurl, $api_source, $return_path)
858 DI::baseUrl()->redirect($return_path);
861 $json = ['success' => 1];
862 if (!empty($_REQUEST['jsreload'])) {
863 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
866 Logger::info('post_json', ['json' => $json]);
868 System::jsonExit($json);
871 function item_content(App $a)
873 if (!Session::isAuthenticated()) {
879 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
880 if (DI::mode()->isAjax()) {
881 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
883 if (!empty($a->argv[3])) {
884 $o = drop_item($a->argv[2], $a->argv[3]);
887 $o = drop_item($a->argv[2]);
891 if (DI::mode()->isAjax()) {
892 // ajax return: [<item id>, 0 (no perm) | <owner id>]
893 System::jsonExit([intval($a->argv[2]), intval($o)]);
901 * This function removes the tag $tag from the text $body and replaces it with
902 * the appropriate link.
905 * @param string $body the text to replace the tag in
906 * @param string $inform a comma-seperated string containing everybody to inform
907 * @param string $str_tags string to add the tag to
908 * @param integer $profile_uid
909 * @param string $tag the tag to replace
910 * @param string $network The network of the post
912 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
913 * @throws ImagickException
914 * @throws HTTPException\InternalServerErrorException
916 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
921 //is it a person tag?
922 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
923 $tag_type = substr($tag, 0, 1);
924 //is it already replaced?
925 if (strpos($tag, '[url=')) {
926 //append tag to str_tags
927 if (!stristr($str_tags, $tag)) {
928 if (strlen($str_tags)) {
934 // Checking for the alias that is used for OStatus
935 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
936 if (preg_match($pattern, $tag, $matches)) {
937 $data = Contact::getDetailsByURL($matches[1]);
939 if ($data["alias"] != "") {
940 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
942 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
943 if (strlen($str_tags)) {
947 $str_tags .= $newtag;
955 //get the person's name
956 $name = substr($tag, 1);
958 // Sometimes the tag detection doesn't seem to work right
959 // This is some workaround
960 $nameparts = explode(" ", $name);
961 $name = $nameparts[0];
963 // Try to detect the contact in various ways
964 if (strpos($name, 'http://')) {
965 // At first we have to ensure that the contact exists
966 Contact::getIdForURL($name);
968 // Now we should have something
969 $contact = Contact::getDetailsByURL($name);
970 } elseif (strpos($name, '@')) {
971 // This function automatically probes when no entry was found
972 $contact = Contact::getDetailsByAddr($name);
975 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
977 if (strrpos($name, '+')) {
978 // Is it in format @nick+number?
979 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
980 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
983 // select someone by nick or attag in the current network
984 if (!DBA::isResult($contact) && ($network != "")) {
985 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
986 $name, $name, $network, $profile_uid];
987 $contact = DBA::selectFirst('contact', $fields, $condition);
990 //select someone by name in the current network
991 if (!DBA::isResult($contact) && ($network != "")) {
992 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
993 $contact = DBA::selectFirst('contact', $fields, $condition);
996 // select someone by nick or attag in any network
997 if (!DBA::isResult($contact)) {
998 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
999 $contact = DBA::selectFirst('contact', $fields, $condition);
1002 // select someone by name in any network
1003 if (!DBA::isResult($contact)) {
1004 $condition = ['name' => $name, 'uid' => $profile_uid];
1005 $contact = DBA::selectFirst('contact', $fields, $condition);
1009 // Check if $contact has been successfully loaded
1010 if (DBA::isResult($contact)) {
1011 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1015 if (isset($contact["id"])) {
1016 $inform .= 'cid:' . $contact["id"];
1017 } elseif (isset($contact["notify"])) {
1018 $inform .= $contact["notify"];
1021 $profile = $contact["url"];
1022 $alias = $contact["alias"];
1023 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1026 //if there is an url for this persons profile
1027 if (isset($profile) && ($newname != "")) {
1029 // create profile link
1030 $profile = str_replace(',', '%2c', $profile);
1031 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1032 $body = str_replace($tag_type . $name, $newtag, $body);
1033 // append tag to str_tags
1034 if (!stristr($str_tags, $newtag)) {
1035 if (strlen($str_tags)) {
1038 $str_tags .= $newtag;
1042 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1043 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1045 if (!empty($alias)) {
1046 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1047 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1048 if (strlen($str_tags)) {
1051 $str_tags .= $newtag;
1057 return ['replaced' => $replaced, 'contact' => $contact];
1060 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1062 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1063 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1064 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1065 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1066 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1071 $implicit_mentions = [
1072 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1075 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1077 foreach ($parent_terms as $parent_term) {
1078 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1081 foreach ($implicit_mentions as $url => $label) {
1082 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1083 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';