7 * This is the POST destination for most all locally posted
8 * text stuff. This function handles status, wall-to-wall status,
9 * local comments, and remote coments that are posted on this site
10 * (as opposed to being delivered in a feed).
11 * Also processed here are posts and comments coming through the
12 * statusnet/twitter API.
14 * All of these become an "item" which is our basic unit of
19 use Friendica\Content\Pager;
20 use Friendica\Content\Text\BBCode;
21 use Friendica\Core\Hook;
22 use Friendica\Core\Logger;
23 use Friendica\Core\Protocol;
24 use Friendica\Core\Session;
25 use Friendica\Core\System;
26 use Friendica\Core\Worker;
27 use Friendica\Database\DBA;
29 use Friendica\Model\Attach;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Conversation;
32 use Friendica\Model\FileTag;
33 use Friendica\Model\Item;
34 use Friendica\Model\Photo;
35 use Friendica\Model\Term;
36 use Friendica\Network\HTTPException;
37 use Friendica\Object\EMail\ItemCCEMail;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Security;
42 use Friendica\Util\Strings;
43 use Friendica\Worker\Delivery;
45 require_once __DIR__ . '/../include/items.php';
47 function item_post(App $a) {
48 if (!Session::isAuthenticated()) {
49 throw new HTTPException\ForbiddenException();
54 if (!empty($_REQUEST['dropitems'])) {
55 $arr_drop = explode(',', $_REQUEST['dropitems']);
56 drop_items($arr_drop);
57 $json = ['success' => 1];
58 System::jsonExit($json);
61 Hook::callAll('post_local_start', $_REQUEST);
63 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
65 $api_source = $_REQUEST['api_source'] ?? false;
67 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
69 $return_path = $_REQUEST['return'] ?? '';
70 $preview = intval($_REQUEST['preview'] ?? 0);
73 * Check for doubly-submitted posts, and reject duplicates
74 * Note that we have to ignore previews, otherwise nothing will post
75 * after it's been previewed
77 if (!$preview && !empty($_REQUEST['post_id_random'])) {
78 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
79 Logger::info('item post: duplicate post');
80 item_post_return(DI::baseUrl(), $api_source, $return_path);
82 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
86 // Is this a reply to something?
87 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
88 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
90 $thread_parent_id = 0;
91 $thread_parent_contact = null;
93 $toplevel_item = null;
96 $parent_contact = null;
99 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
100 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
102 if ($toplevel_item_id || $thr_parent_uri) {
103 if ($toplevel_item_id) {
104 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
105 } elseif ($thr_parent_uri) {
106 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
109 // if this isn't the top-level parent of the conversation, find it
110 if (DBA::isResult($toplevel_item)) {
111 // The URI and the contact is taken from the direct parent which needn't to be the top parent
112 $thread_parent_id = $toplevel_item['id'];
113 $thr_parent_uri = $toplevel_item['uri'];
114 $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
116 if ($toplevel_item['id'] != $toplevel_item['parent']) {
117 $toplevel_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
121 if (!DBA::isResult($toplevel_item)) {
122 notice(DI::l10n()->t('Unable to locate original post.') . EOL);
124 DI::baseUrl()->redirect($return_path);
126 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
129 $toplevel_item_id = $toplevel_item['id'];
130 $parent_user = $toplevel_item['uid'];
132 $objecttype = Activity\ObjectType::COMMENT;
135 if ($toplevel_item_id) {
136 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
139 $post_id = intval($_REQUEST['post_id'] ?? 0);
140 $app = strip_tags($_REQUEST['source'] ?? '');
141 $extid = strip_tags($_REQUEST['extid'] ?? '');
142 $object = $_REQUEST['object'] ?? '';
144 // Don't use "defaults" here. It would turn 0 to 1
145 if (!isset($_REQUEST['wall'])) {
148 $wall = $_REQUEST['wall'];
151 // Ensure that the user id in a thread always stay the same
152 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
153 $profile_uid = $parent_user;
156 // Check for multiple posts with the same message id (when the post was created via API)
157 if (($message_id != '') && ($profile_uid != 0)) {
158 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
159 Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
164 // Allow commenting if it is an answer to a public post
165 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
167 // Now check that valid personal details have been provided
168 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
169 notice(DI::l10n()->t('Permission denied.') . EOL);
171 DI::baseUrl()->redirect($return_path);
174 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
177 // Init post instance
180 // is this an edited post?
182 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
185 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
187 if (!DBA::isResult($user) && !$toplevel_item_id) {
194 $body = $_REQUEST['body'] ?? '';
195 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
197 // If we have a speparate attachment, we need to add it to the body.
198 if (!empty($has_attachment)) {
199 $attachment_type = $_REQUEST['attachment_type'] ?? '';
200 $attachment_title = $_REQUEST['attachment_title'] ?? '';
201 $attachment_text = $_REQUEST['attachment_text'] ?? '';
203 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
204 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
206 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
207 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
209 'type' => $attachment_type,
210 'title' => $attachment_title,
211 'text' => $attachment_text,
212 'url' => $attachment_url,
215 if (!empty($attachment_img_src)) {
216 $attachment['images'] = [
218 'src' => $attachment_img_src,
219 'width' => $attachment_img_width,
220 'height' => $attachment_img_height
225 $att_bbcode = add_page_info_data($attachment);
226 $body .= $att_bbcode;
229 // Convert links with empty descriptions to links without an explicit description
230 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
232 if (!empty($orig_post)) {
233 $str_group_allow = $orig_post['allow_gid'];
234 $str_contact_allow = $orig_post['allow_cid'];
235 $str_group_deny = $orig_post['deny_gid'];
236 $str_contact_deny = $orig_post['deny_cid'];
237 $location = $orig_post['location'];
238 $coord = $orig_post['coord'];
239 $verb = $orig_post['verb'];
240 $objecttype = $orig_post['object-type'];
241 $app = $orig_post['app'];
242 $categories = $orig_post['file'];
243 $title = Strings::escapeTags(trim($_REQUEST['title']));
245 $private = $orig_post['private'];
246 $pubmail_enabled = $orig_post['pubmail'];
247 $network = $orig_post['network'];
248 $guid = $orig_post['guid'];
249 $extid = $orig_post['extid'];
254 * if coming from the API and no privacy settings are set,
255 * use the user default permissions - as they won't have
256 * been supplied via a form.
259 && !array_key_exists('contact_allow', $_REQUEST)
260 && !array_key_exists('group_allow', $_REQUEST)
261 && !array_key_exists('contact_deny', $_REQUEST)
262 && !array_key_exists('group_deny', $_REQUEST)) {
263 $str_group_allow = $user['allow_gid'];
264 $str_contact_allow = $user['allow_cid'];
265 $str_group_deny = $user['deny_gid'];
266 $str_contact_deny = $user['deny_cid'];
268 // use the posted permissions
270 $aclFormatter = DI::aclFormatter();
272 $str_group_allow = $aclFormatter->toString($_REQUEST['group_allow'] ?? '');
273 $str_contact_allow = $aclFormatter->toString($_REQUEST['contact_allow'] ?? '');
274 $str_group_deny = $aclFormatter->toString($_REQUEST['group_deny'] ?? '');
275 $str_contact_deny = $aclFormatter->toString($_REQUEST['contact_deny'] ?? '');
278 $title = Strings::escapeTags(trim($_REQUEST['title'] ?? ''));
279 $location = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
280 $coord = Strings::escapeTags(trim($_REQUEST['coord'] ?? ''));
281 $verb = Strings::escapeTags(trim($_REQUEST['verb'] ?? ''));
282 $emailcc = Strings::escapeTags(trim($_REQUEST['emailcc'] ?? ''));
284 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
285 $guid = System::createUUID();
287 $postopts = $_REQUEST['postopts'] ?? '';
289 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
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' => '']);
323 info(DI::l10n()->t('Empty post discarded.') . EOL);
325 DI::baseUrl()->redirect($return_path);
328 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
332 if (!empty($categories)) {
333 // get the "fileas" tags for this post
334 $filedas = FileTag::fileToArray($categories);
337 // save old and new categories, so we can determine what needs to be deleted from pconfig
338 $categories_old = $categories;
339 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
340 $categories_new = $categories;
342 if (!empty($filedas) && is_array($filedas)) {
343 // append the fileas stuff to the new categories list
344 $categories .= FileTag::arrayToFile($filedas);
347 // get contact info for poster
353 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
355 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
356 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
357 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
360 if (DBA::isResult($author)) {
361 $contact_id = $author['id'];
364 // get contact info for owner
365 if ($profile_uid == local_user() || $allow_comment) {
366 $contact_record = $author;
368 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
371 // Look for any tags and linkify them
375 $tags = BBCode::getTags($body);
377 if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
378 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
383 $private_forum = false;
384 $only_to_forum = false;
388 foreach ($tags as $tag) {
389 $tag_type = substr($tag, 0, 1);
391 if ($tag_type == Term::TAG_CHARACTER[Term::HASHTAG]) {
396 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
397 * Robert Johnson should be first in the $tags array
399 $fullnametagged = false;
400 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
401 foreach ($tagged as $nextTag) {
402 if (stristr($nextTag, $tag . ' ')) {
403 $fullnametagged = true;
407 if ($fullnametagged) {
411 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
412 if ($success['replaced']) {
415 // When the forum is private or the forum is addressed with a "!" make the post private
416 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
417 $private_forum = $success['contact']['prv'];
418 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
419 $private_id = $success['contact']['id'];
420 $forum_contact = $success['contact'];
421 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
422 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
423 $private_forum = false;
424 $only_to_forum = true;
425 $private_id = $success['contact']['id'];
426 $forum_contact = $success['contact'];
431 $original_contact_id = $contact_id;
433 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
434 // we tagged a forum in a top level post. Now we change the post
435 $private = $private_forum;
437 $str_group_allow = '';
438 $str_contact_deny = '';
439 $str_group_deny = '';
440 if ($private_forum) {
441 $str_contact_allow = '<' . $private_id . '>';
443 $str_contact_allow = '';
445 $contact_id = $private_id;
446 $contact_record = $forum_contact;
447 $_REQUEST['origin'] = false;
452 * When a photo was uploaded into the message using the (profile wall) ajax
453 * uploader, The permissions are initially set to disallow anybody but the
454 * owner from seeing it. This is because the permissions may not yet have been
455 * set for the post. If it's private, the photo permissions should be set
456 * appropriately. But we didn't know the final permissions on the post until
457 * now. So now we'll look for links of uploaded messages that are in the
458 * post and set them to the same permissions as the post itself.
463 if (!$preview && Photo::setPermissionFromBody($body, $profile_uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
464 $objecttype = Activity\ObjectType::IMAGE;
468 * Next link in any attachment references we find in the post.
472 /// @todo these lines should be moved to Model/Attach (Once it exists)
473 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
474 $attaches = $match[1];
475 if (count($attaches)) {
476 foreach ($attaches as $attach) {
477 // Ensure to only modify attachments that you own
478 $srch = '<' . intval($original_contact_id) . '>';
480 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
482 if (!Attach::exists($condition)) {
486 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
487 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
488 $condition = ['id' => $attach];
489 Attach::update($fields, $condition);
494 // embedded bookmark or attachment in post? set bookmark flag
496 $data = BBCode::getAttachmentData($body);
497 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
498 && ($posttype != Item::PT_PERSONAL_NOTE)) {
499 $posttype = Item::PT_PAGE;
500 $objecttype = Activity\ObjectType::BOOKMARK;
503 $body = DI::bbCodeVideo()->transform($body);
505 // Fold multi-line [code] sequences
506 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
508 $body = BBCode::scaleExternalImages($body);
510 // Setting the object type if not defined before
512 $objecttype = Activity\ObjectType::NOTE; // Default value
513 $objectdata = BBCode::getAttachedData($body);
515 if ($objectdata["type"] == "link") {
516 $objecttype = Activity\ObjectType::BOOKMARK;
517 } elseif ($objectdata["type"] == "video") {
518 $objecttype = Activity\ObjectType::VIDEO;
519 } elseif ($objectdata["type"] == "photo") {
520 $objecttype = Activity\ObjectType::IMAGE;
528 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
529 foreach ($match[2] as $mtch) {
530 $fields = ['id', 'filename', 'filesize', 'filetype'];
531 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
532 if ($attachment !== false) {
533 if (strlen($attachments)) {
536 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
537 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
538 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
540 $body = str_replace($match[1],'',$body);
544 if (!strlen($verb)) {
545 $verb = Activity::POST;
548 if ($network == "") {
549 $network = Protocol::DFRN;
552 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
554 // even if the post arrived via API we are considering that it
555 // originated on this site by default for determining relayability.
557 // Don't use "defaults" here. It would turn 0 to 1
558 if (!isset($_REQUEST['origin'])) {
561 $origin = $_REQUEST['origin'];
564 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
566 // Fallback so that we alway have a parent uri
567 if (!$thr_parent_uri || !$toplevel_item_id) {
568 $thr_parent_uri = $uri;
572 $datarray['uid'] = $profile_uid;
573 $datarray['wall'] = $wall;
574 $datarray['gravity'] = $gravity;
575 $datarray['network'] = $network;
576 $datarray['contact-id'] = $contact_id;
577 $datarray['owner-name'] = $contact_record['name'];
578 $datarray['owner-link'] = $contact_record['url'];
579 $datarray['owner-avatar'] = $contact_record['thumb'];
580 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
581 $datarray['author-name'] = $author['name'];
582 $datarray['author-link'] = $author['url'];
583 $datarray['author-avatar'] = $author['thumb'];
584 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
585 $datarray['created'] = DateTimeFormat::utcNow();
586 $datarray['edited'] = DateTimeFormat::utcNow();
587 $datarray['commented'] = DateTimeFormat::utcNow();
588 $datarray['received'] = DateTimeFormat::utcNow();
589 $datarray['changed'] = DateTimeFormat::utcNow();
590 $datarray['extid'] = $extid;
591 $datarray['guid'] = $guid;
592 $datarray['uri'] = $uri;
593 $datarray['title'] = $title;
594 $datarray['body'] = $body;
595 $datarray['app'] = $app;
596 $datarray['location'] = $location;
597 $datarray['coord'] = $coord;
598 $datarray['tag'] = $str_tags;
599 $datarray['file'] = $categories;
600 $datarray['inform'] = $inform;
601 $datarray['verb'] = $verb;
602 $datarray['post-type'] = $posttype;
603 $datarray['object-type'] = $objecttype;
604 $datarray['allow_cid'] = $str_contact_allow;
605 $datarray['allow_gid'] = $str_group_allow;
606 $datarray['deny_cid'] = $str_contact_deny;
607 $datarray['deny_gid'] = $str_group_deny;
608 $datarray['private'] = $private;
609 $datarray['pubmail'] = $pubmail_enabled;
610 $datarray['attach'] = $attachments;
612 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
613 $datarray['parent-uri'] = $thr_parent_uri;
615 $datarray['postopts'] = $postopts;
616 $datarray['origin'] = $origin;
617 $datarray['moderated'] = false;
618 $datarray['object'] = $object;
621 * These fields are for the convenience of addons...
622 * 'self' if true indicates the owner is posting on their own wall
623 * If parent is 0 it is a top-level post.
625 $datarray['parent'] = $toplevel_item_id;
626 $datarray['self'] = $self;
628 // This triggers posts via API and the mirror functions
629 $datarray['api_source'] = $api_source;
631 // This field is for storing the raw conversation data
632 $datarray['protocol'] = Conversation::PARCEL_DFRN;
634 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
635 if (DBA::isResult($conversation)) {
636 if ($conversation['conversation-uri'] != '') {
637 $datarray['conversation-uri'] = $conversation['conversation-uri'];
639 if ($conversation['conversation-href'] != '') {
640 $datarray['conversation-href'] = $conversation['conversation-href'];
645 $datarray['edit'] = true;
647 // If this was a share, add missing data here
648 $datarray = Item::addShareDataFromOriginal($datarray);
650 $datarray['edit'] = false;
653 // Check for hashtags in the body and repair or add hashtag links
654 if ($preview || $orig_post) {
655 Item::setHashtags($datarray);
658 // preview mode - prepare the body for display and send it via json
660 // We set the datarray ID to -1 because in preview mode the dataray
661 // doesn't have an ID.
662 $datarray["id"] = -1;
663 $datarray["item_id"] = -1;
664 $datarray["author-network"] = Protocol::DFRN;
666 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager(DI::args()->getQueryString()), 'search', false, true);
668 System::jsonExit(['preview' => $o]);
671 Hook::callAll('post_local',$datarray);
673 if (!empty($datarray['cancel'])) {
674 Logger::info('mod_item: post cancelled by addon.');
676 DI::baseUrl()->redirect($return_path);
679 $json = ['cancel' => 1];
680 if (!empty($_REQUEST['jsreload'])) {
681 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
684 System::jsonExit($json);
688 // Fill the cache field
689 // This could be done in Item::update as well - but we have to check for the existance of some fields.
690 Item::putInCache($datarray);
693 'title' => $datarray['title'],
694 'body' => $datarray['body'],
695 'tag' => $datarray['tag'],
696 'attach' => $datarray['attach'],
697 'file' => $datarray['file'],
698 'rendered-html' => $datarray['rendered-html'],
699 'rendered-hash' => $datarray['rendered-hash'],
700 'edited' => DateTimeFormat::utcNow(),
701 'changed' => DateTimeFormat::utcNow()];
703 Item::update($fields, ['id' => $post_id]);
705 // update filetags in pconfig
706 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
709 DI::baseUrl()->redirect($return_path);
712 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
715 unset($datarray['edit']);
716 unset($datarray['self']);
717 unset($datarray['api_source']);
720 $signed = Diaspora::createCommentSignature($uid, $datarray);
721 if (!empty($signed)) {
722 $datarray['diaspora_signed_text'] = json_encode($signed);
726 $post_id = Item::insert($datarray);
729 info(DI::l10n()->t('Item wasn\'t stored.'));
731 DI::baseUrl()->redirect($return_path);
734 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
737 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
739 if (!DBA::isResult($datarray)) {
740 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
742 DI::baseUrl()->redirect($return_path);
745 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
748 // update filetags in pconfig
749 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
751 // These notifications are sent if someone else is commenting other your wall
752 if ($toplevel_item_id) {
753 if ($contact_record != $author) {
755 'type' => NOTIFY_COMMENT,
756 'notify_flags' => $user['notify-flags'],
757 'language' => $user['language'],
758 'to_name' => $user['username'],
759 'to_email' => $user['email'],
760 'uid' => $user['uid'],
762 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
763 'source_name' => $datarray['author-name'],
764 'source_link' => $datarray['author-link'],
765 'source_photo' => $datarray['author-avatar'],
766 'verb' => Activity::POST,
768 'parent' => $toplevel_item_id,
769 'parent_uri' => $toplevel_item['uri']
773 if (($contact_record != $author) && !count($forum_contact)) {
775 'type' => NOTIFY_WALL,
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,
792 Hook::callAll('post_local_end', $datarray);
794 if (strlen($emailcc) && $profile_uid == local_user()) {
795 $recipients = explode(',', $emailcc);
796 if (count($recipients)) {
797 foreach ($recipients as $recipient) {
798 $address = trim($recipient);
799 if (!strlen($address)) {
802 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
803 $datarray, $address, $author['thumb'] ?? ''));
808 // Insert an item entry for UID=0 for global entries.
809 // We now do it in the background to save some time.
810 // This is important in interactive environments like the frontend or the API.
811 // We don't fork a new process since this is done anyway with the following command
812 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
814 // When we are doing some forum posting via ! we have to start the notifier manually.
815 // These kind of posts don't initiate the notifier call in the item class.
816 if ($only_to_forum) {
817 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
820 Logger::info('post_complete');
826 item_post_return(DI::baseUrl(), $api_source, $return_path);
830 function item_post_return($baseurl, $api_source, $return_path)
832 // figure out how to return, depending on from whence we came
840 DI::baseUrl()->redirect($return_path);
843 $json = ['success' => 1];
844 if (!empty($_REQUEST['jsreload'])) {
845 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
848 Logger::info('post_json', ['json' => $json]);
850 System::jsonExit($json);
853 function item_content(App $a)
855 if (!Session::isAuthenticated()) {
861 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
862 if (DI::mode()->isAjax()) {
863 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
865 if (!empty($a->argv[3])) {
866 $o = drop_item($a->argv[2], $a->argv[3]);
869 $o = drop_item($a->argv[2]);
873 if (DI::mode()->isAjax()) {
874 // ajax return: [<item id>, 0 (no perm) | <owner id>]
875 System::jsonExit([intval($a->argv[2]), intval($o)]);
883 * This function removes the tag $tag from the text $body and replaces it with
884 * the appropriate link.
887 * @param string $body the text to replace the tag in
888 * @param string $inform a comma-seperated string containing everybody to inform
889 * @param string $str_tags string to add the tag to
890 * @param integer $profile_uid
891 * @param string $tag the tag to replace
892 * @param string $network The network of the post
894 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
895 * @throws ImagickException
896 * @throws HTTPException\InternalServerErrorException
898 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
903 //is it a person tag?
904 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
905 $tag_type = substr($tag, 0, 1);
906 //is it already replaced?
907 if (strpos($tag, '[url=')) {
908 //append tag to str_tags
909 if (!stristr($str_tags, $tag)) {
910 if (strlen($str_tags)) {
916 // Checking for the alias that is used for OStatus
917 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
918 if (preg_match($pattern, $tag, $matches)) {
919 $data = Contact::getDetailsByURL($matches[1]);
921 if ($data["alias"] != "") {
922 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
924 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
925 if (strlen($str_tags)) {
929 $str_tags .= $newtag;
937 //get the person's name
938 $name = substr($tag, 1);
940 // Sometimes the tag detection doesn't seem to work right
941 // This is some workaround
942 $nameparts = explode(" ", $name);
943 $name = $nameparts[0];
945 // Try to detect the contact in various ways
946 if (strpos($name, 'http://')) {
947 // At first we have to ensure that the contact exists
948 Contact::getIdForURL($name);
950 // Now we should have something
951 $contact = Contact::getDetailsByURL($name);
952 } elseif (strpos($name, '@')) {
953 // This function automatically probes when no entry was found
954 $contact = Contact::getDetailsByAddr($name);
957 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
959 if (strrpos($name, '+')) {
960 // Is it in format @nick+number?
961 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
962 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
965 // select someone by nick or attag in the current network
966 if (!DBA::isResult($contact) && ($network != "")) {
967 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
968 $name, $name, $network, $profile_uid];
969 $contact = DBA::selectFirst('contact', $fields, $condition);
972 //select someone by name in the current network
973 if (!DBA::isResult($contact) && ($network != "")) {
974 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
975 $contact = DBA::selectFirst('contact', $fields, $condition);
978 // select someone by nick or attag in any network
979 if (!DBA::isResult($contact)) {
980 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
981 $contact = DBA::selectFirst('contact', $fields, $condition);
984 // select someone by name in any network
985 if (!DBA::isResult($contact)) {
986 $condition = ['name' => $name, 'uid' => $profile_uid];
987 $contact = DBA::selectFirst('contact', $fields, $condition);
991 // Check if $contact has been successfully loaded
992 if (DBA::isResult($contact)) {
993 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
997 if (isset($contact["id"])) {
998 $inform .= 'cid:' . $contact["id"];
999 } elseif (isset($contact["notify"])) {
1000 $inform .= $contact["notify"];
1003 $profile = $contact["url"];
1004 $alias = $contact["alias"];
1005 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1008 //if there is an url for this persons profile
1009 if (isset($profile) && ($newname != "")) {
1011 // create profile link
1012 $profile = str_replace(',', '%2c', $profile);
1013 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1014 $body = str_replace($tag_type . $name, $newtag, $body);
1015 // append tag to str_tags
1016 if (!stristr($str_tags, $newtag)) {
1017 if (strlen($str_tags)) {
1020 $str_tags .= $newtag;
1024 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1025 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1027 if (!empty($alias)) {
1028 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1029 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1030 if (strlen($str_tags)) {
1033 $str_tags .= $newtag;
1039 return ['replaced' => $replaced, 'contact' => $contact];
1042 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1044 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1045 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1046 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1047 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1048 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1053 $implicit_mentions = [
1054 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1057 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1059 foreach ($parent_terms as $parent_term) {
1060 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1063 foreach ($implicit_mentions as $url => $label) {
1064 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1065 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';