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\Notify\Type;
35 use Friendica\Model\Photo;
36 use Friendica\Model\Term;
37 use Friendica\Network\HTTPException;
38 use Friendica\Object\EMail\ItemCCEMail;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Security;
43 use Friendica\Util\Strings;
44 use Friendica\Worker\Delivery;
46 require_once __DIR__ . '/../include/items.php';
48 function item_post(App $a) {
49 if (!Session::isAuthenticated()) {
50 throw new HTTPException\ForbiddenException();
55 if (!empty($_REQUEST['dropitems'])) {
56 $arr_drop = explode(',', $_REQUEST['dropitems']);
57 drop_items($arr_drop);
58 $json = ['success' => 1];
59 System::jsonExit($json);
62 Hook::callAll('post_local_start', $_REQUEST);
64 Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
66 $api_source = $_REQUEST['api_source'] ?? false;
68 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
70 $return_path = $_REQUEST['return'] ?? '';
71 $preview = intval($_REQUEST['preview'] ?? 0);
74 * Check for doubly-submitted posts, and reject duplicates
75 * Note that we have to ignore previews, otherwise nothing will post
76 * after it's been previewed
78 if (!$preview && !empty($_REQUEST['post_id_random'])) {
79 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
80 Logger::info('item post: duplicate post');
81 item_post_return(DI::baseUrl(), $api_source, $return_path);
83 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
87 // Is this a reply to something?
88 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
89 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
91 $thread_parent_id = 0;
92 $thread_parent_contact = null;
94 $toplevel_item = null;
97 $parent_contact = null;
100 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
101 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
103 if ($toplevel_item_id || $thr_parent_uri) {
104 if ($toplevel_item_id) {
105 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
106 } elseif ($thr_parent_uri) {
107 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
110 // if this isn't the top-level parent of the conversation, find it
111 if (DBA::isResult($toplevel_item)) {
112 // The URI and the contact is taken from the direct parent which needn't to be the top parent
113 $thread_parent_id = $toplevel_item['id'];
114 $thr_parent_uri = $toplevel_item['uri'];
115 $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
117 if ($toplevel_item['id'] != $toplevel_item['parent']) {
118 $toplevel_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
122 if (!DBA::isResult($toplevel_item)) {
123 notice(DI::l10n()->t('Unable to locate original post.'));
125 DI::baseUrl()->redirect($return_path);
127 throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
130 $toplevel_item_id = $toplevel_item['id'];
131 $parent_user = $toplevel_item['uid'];
133 $objecttype = Activity\ObjectType::COMMENT;
136 if ($toplevel_item_id) {
137 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
140 $post_id = intval($_REQUEST['post_id'] ?? 0);
141 $app = strip_tags($_REQUEST['source'] ?? '');
142 $extid = strip_tags($_REQUEST['extid'] ?? '');
143 $object = $_REQUEST['object'] ?? '';
145 // Don't use "defaults" here. It would turn 0 to 1
146 if (!isset($_REQUEST['wall'])) {
149 $wall = $_REQUEST['wall'];
152 // Ensure that the user id in a thread always stay the same
153 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
154 $profile_uid = $parent_user;
157 // Check for multiple posts with the same message id (when the post was created via API)
158 if (($message_id != '') && ($profile_uid != 0)) {
159 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
160 Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
165 // Allow commenting if it is an answer to a public post
166 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
168 // Now check that valid personal details have been provided
169 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
170 notice(DI::l10n()->t('Permission denied.'));
172 DI::baseUrl()->redirect($return_path);
175 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
178 // Init post instance
181 // is this an edited post?
183 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
186 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
188 if (!DBA::isResult($user) && !$toplevel_item_id) {
195 $body = $_REQUEST['body'] ?? '';
196 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
198 // If we have a speparate attachment, we need to add it to the body.
199 if (!empty($has_attachment)) {
200 $attachment_type = $_REQUEST['attachment_type'] ?? '';
201 $attachment_title = $_REQUEST['attachment_title'] ?? '';
202 $attachment_text = $_REQUEST['attachment_text'] ?? '';
204 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
205 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
207 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
208 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
210 'type' => $attachment_type,
211 'title' => $attachment_title,
212 'text' => $attachment_text,
213 'url' => $attachment_url,
216 if (!empty($attachment_img_src)) {
217 $attachment['images'] = [
219 'src' => $attachment_img_src,
220 'width' => $attachment_img_width,
221 'height' => $attachment_img_height
226 $att_bbcode = add_page_info_data($attachment);
227 $body .= $att_bbcode;
230 // Convert links with empty descriptions to links without an explicit description
231 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
233 if (!empty($orig_post)) {
234 $str_group_allow = $orig_post['allow_gid'];
235 $str_contact_allow = $orig_post['allow_cid'];
236 $str_group_deny = $orig_post['deny_gid'];
237 $str_contact_deny = $orig_post['deny_cid'];
238 $location = $orig_post['location'];
239 $coord = $orig_post['coord'];
240 $verb = $orig_post['verb'];
241 $objecttype = $orig_post['object-type'];
242 $app = $orig_post['app'];
243 $categories = $orig_post['file'];
244 $title = Strings::escapeTags(trim($_REQUEST['title']));
246 $private = $orig_post['private'];
247 $pubmail_enabled = $orig_post['pubmail'];
248 $network = $orig_post['network'];
249 $guid = $orig_post['guid'];
250 $extid = $orig_post['extid'];
255 * if coming from the API and no privacy settings are set,
256 * use the user default permissions - as they won't have
257 * been supplied via a form.
260 && !array_key_exists('contact_allow', $_REQUEST)
261 && !array_key_exists('group_allow', $_REQUEST)
262 && !array_key_exists('contact_deny', $_REQUEST)
263 && !array_key_exists('group_deny', $_REQUEST)) {
264 $str_group_allow = $user['allow_gid'];
265 $str_contact_allow = $user['allow_cid'];
266 $str_group_deny = $user['deny_gid'];
267 $str_contact_deny = $user['deny_cid'];
269 // use the posted permissions
271 $aclFormatter = DI::aclFormatter();
273 $str_group_allow = $aclFormatter->toString($_REQUEST['group_allow'] ?? '');
274 $str_contact_allow = $aclFormatter->toString($_REQUEST['contact_allow'] ?? '');
275 $str_group_deny = $aclFormatter->toString($_REQUEST['group_deny'] ?? '');
276 $str_contact_deny = $aclFormatter->toString($_REQUEST['contact_deny'] ?? '');
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 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
292 // If this is a comment, set the permissions from the parent.
294 if ($toplevel_item) {
295 // for non native networks use the network of the original post as network of the item
296 if (($toplevel_item['network'] != Protocol::DIASPORA)
297 && ($toplevel_item['network'] != Protocol::OSTATUS)
298 && ($network == "")) {
299 $network = $toplevel_item['network'];
302 $str_contact_allow = $toplevel_item['allow_cid'];
303 $str_group_allow = $toplevel_item['allow_gid'];
304 $str_contact_deny = $toplevel_item['deny_cid'];
305 $str_group_deny = $toplevel_item['deny_gid'];
306 $private = $toplevel_item['private'];
308 $wall = $toplevel_item['wall'];
311 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
313 // if using the API, we won't see pubmail_enable - figure out if it should be set
314 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
315 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
316 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
320 if (!strlen($body)) {
322 System::jsonExit(['preview' => '']);
325 info(DI::l10n()->t('Empty post discarded.'));
327 DI::baseUrl()->redirect($return_path);
330 throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
334 if (!empty($categories)) {
335 // get the "fileas" tags for this post
336 $filedas = FileTag::fileToArray($categories);
339 // save old and new categories, so we can determine what needs to be deleted from pconfig
340 $categories_old = $categories;
341 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
342 $categories_new = $categories;
344 if (!empty($filedas) && is_array($filedas)) {
345 // append the fileas stuff to the new categories list
346 $categories .= FileTag::arrayToFile($filedas);
349 // get contact info for poster
355 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
357 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
358 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
359 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
362 if (DBA::isResult($author)) {
363 $contact_id = $author['id'];
366 // get contact info for owner
367 if ($profile_uid == local_user() || $allow_comment) {
368 $contact_record = $author;
370 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
373 // Look for any tags and linkify them
377 $tags = BBCode::getTags($body);
379 if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
380 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
385 $private_forum = false;
386 $only_to_forum = false;
390 foreach ($tags as $tag) {
391 $tag_type = substr($tag, 0, 1);
393 if ($tag_type == Term::TAG_CHARACTER[Term::HASHTAG]) {
398 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
399 * Robert Johnson should be first in the $tags array
401 $fullnametagged = false;
402 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
403 foreach ($tagged as $nextTag) {
404 if (stristr($nextTag, $tag . ' ')) {
405 $fullnametagged = true;
409 if ($fullnametagged) {
413 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
414 if ($success['replaced']) {
417 // When the forum is private or the forum is addressed with a "!" make the post private
418 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
419 $private_forum = $success['contact']['prv'];
420 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
421 $private_id = $success['contact']['id'];
422 $forum_contact = $success['contact'];
423 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
424 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
425 $private_forum = false;
426 $only_to_forum = true;
427 $private_id = $success['contact']['id'];
428 $forum_contact = $success['contact'];
433 $original_contact_id = $contact_id;
435 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
436 // we tagged a forum in a top level post. Now we change the post
437 $private = $private_forum;
439 $str_group_allow = '';
440 $str_contact_deny = '';
441 $str_group_deny = '';
442 if ($private_forum) {
443 $str_contact_allow = '<' . $private_id . '>';
445 $str_contact_allow = '';
447 $contact_id = $private_id;
448 $contact_record = $forum_contact;
449 $_REQUEST['origin'] = false;
454 * When a photo was uploaded into the message using the (profile wall) ajax
455 * uploader, The permissions are initially set to disallow anybody but the
456 * owner from seeing it. This is because the permissions may not yet have been
457 * set for the post. If it's private, the photo permissions should be set
458 * appropriately. But we didn't know the final permissions on the post until
459 * now. So now we'll look for links of uploaded messages that are in the
460 * post and set them to the same permissions as the post itself.
465 if (!$preview && Photo::setPermissionFromBody($body, $profile_uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
466 $objecttype = Activity\ObjectType::IMAGE;
470 * Next link in any attachment references we find in the post.
474 /// @todo these lines should be moved to Model/Attach (Once it exists)
475 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
476 $attaches = $match[1];
477 if (count($attaches)) {
478 foreach ($attaches as $attach) {
479 // Ensure to only modify attachments that you own
480 $srch = '<' . intval($original_contact_id) . '>';
482 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
484 if (!Attach::exists($condition)) {
488 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
489 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
490 $condition = ['id' => $attach];
491 Attach::update($fields, $condition);
496 // embedded bookmark or attachment in post? set bookmark flag
498 $data = BBCode::getAttachmentData($body);
499 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
500 && ($posttype != Item::PT_PERSONAL_NOTE)) {
501 $posttype = Item::PT_PAGE;
502 $objecttype = Activity\ObjectType::BOOKMARK;
505 $body = DI::bbCodeVideo()->transform($body);
507 $body = BBCode::scaleExternalImages($body);
509 // Setting the object type if not defined before
511 $objecttype = Activity\ObjectType::NOTE; // Default value
512 $objectdata = BBCode::getAttachedData($body);
514 if ($objectdata["type"] == "link") {
515 $objecttype = Activity\ObjectType::BOOKMARK;
516 } elseif ($objectdata["type"] == "video") {
517 $objecttype = Activity\ObjectType::VIDEO;
518 } elseif ($objectdata["type"] == "photo") {
519 $objecttype = Activity\ObjectType::IMAGE;
527 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
528 foreach ($match[2] as $mtch) {
529 $fields = ['id', 'filename', 'filesize', 'filetype'];
530 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
531 if ($attachment !== false) {
532 if (strlen($attachments)) {
535 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
536 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
537 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
539 $body = str_replace($match[1],'',$body);
543 if (!strlen($verb)) {
544 $verb = Activity::POST;
547 if ($network == "") {
548 $network = Protocol::DFRN;
551 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
553 // even if the post arrived via API we are considering that it
554 // originated on this site by default for determining relayability.
556 // Don't use "defaults" here. It would turn 0 to 1
557 if (!isset($_REQUEST['origin'])) {
560 $origin = $_REQUEST['origin'];
563 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
565 // Fallback so that we alway have a parent uri
566 if (!$thr_parent_uri || !$toplevel_item_id) {
567 $thr_parent_uri = $uri;
571 $datarray['uid'] = $profile_uid;
572 $datarray['wall'] = $wall;
573 $datarray['gravity'] = $gravity;
574 $datarray['network'] = $network;
575 $datarray['contact-id'] = $contact_id;
576 $datarray['owner-name'] = $contact_record['name'];
577 $datarray['owner-link'] = $contact_record['url'];
578 $datarray['owner-avatar'] = $contact_record['thumb'];
579 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
580 $datarray['author-name'] = $author['name'];
581 $datarray['author-link'] = $author['url'];
582 $datarray['author-avatar'] = $author['thumb'];
583 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
584 $datarray['created'] = DateTimeFormat::utcNow();
585 $datarray['edited'] = DateTimeFormat::utcNow();
586 $datarray['commented'] = DateTimeFormat::utcNow();
587 $datarray['received'] = DateTimeFormat::utcNow();
588 $datarray['changed'] = DateTimeFormat::utcNow();
589 $datarray['extid'] = $extid;
590 $datarray['guid'] = $guid;
591 $datarray['uri'] = $uri;
592 $datarray['title'] = $title;
593 $datarray['body'] = $body;
594 $datarray['app'] = $app;
595 $datarray['location'] = $location;
596 $datarray['coord'] = $coord;
597 $datarray['tag'] = $str_tags;
598 $datarray['file'] = $categories;
599 $datarray['inform'] = $inform;
600 $datarray['verb'] = $verb;
601 $datarray['post-type'] = $posttype;
602 $datarray['object-type'] = $objecttype;
603 $datarray['allow_cid'] = $str_contact_allow;
604 $datarray['allow_gid'] = $str_group_allow;
605 $datarray['deny_cid'] = $str_contact_deny;
606 $datarray['deny_gid'] = $str_group_deny;
607 $datarray['private'] = $private;
608 $datarray['pubmail'] = $pubmail_enabled;
609 $datarray['attach'] = $attachments;
611 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
612 $datarray['parent-uri'] = $thr_parent_uri;
614 $datarray['postopts'] = $postopts;
615 $datarray['origin'] = $origin;
616 $datarray['moderated'] = false;
617 $datarray['object'] = $object;
620 * These fields are for the convenience of addons...
621 * 'self' if true indicates the owner is posting on their own wall
622 * If parent is 0 it is a top-level post.
624 $datarray['parent'] = $toplevel_item_id;
625 $datarray['self'] = $self;
627 // This triggers posts via API and the mirror functions
628 $datarray['api_source'] = $api_source;
630 // This field is for storing the raw conversation data
631 $datarray['protocol'] = Conversation::PARCEL_DFRN;
633 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
634 if (DBA::isResult($conversation)) {
635 if ($conversation['conversation-uri'] != '') {
636 $datarray['conversation-uri'] = $conversation['conversation-uri'];
638 if ($conversation['conversation-href'] != '') {
639 $datarray['conversation-href'] = $conversation['conversation-href'];
644 $datarray['edit'] = true;
646 // If this was a share, add missing data here
647 $datarray = Item::addShareDataFromOriginal($datarray);
649 $datarray['edit'] = false;
652 // Check for hashtags in the body and repair or add hashtag links
653 if ($preview || $orig_post) {
654 Item::setHashtags($datarray);
657 // preview mode - prepare the body for display and send it via json
659 // We set the datarray ID to -1 because in preview mode the dataray
660 // doesn't have an ID.
661 $datarray["id"] = -1;
662 $datarray["item_id"] = -1;
663 $datarray["author-network"] = Protocol::DFRN;
665 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager(DI::args()->getQueryString()), 'search', false, true);
667 System::jsonExit(['preview' => $o]);
670 Hook::callAll('post_local',$datarray);
672 if (!empty($datarray['cancel'])) {
673 Logger::info('mod_item: post cancelled by addon.');
675 DI::baseUrl()->redirect($return_path);
678 $json = ['cancel' => 1];
679 if (!empty($_REQUEST['jsreload'])) {
680 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
683 System::jsonExit($json);
687 // Fill the cache field
688 // This could be done in Item::update as well - but we have to check for the existance of some fields.
689 Item::putInCache($datarray);
692 'title' => $datarray['title'],
693 'body' => $datarray['body'],
694 'tag' => $datarray['tag'],
695 'attach' => $datarray['attach'],
696 'file' => $datarray['file'],
697 'rendered-html' => $datarray['rendered-html'],
698 'rendered-hash' => $datarray['rendered-hash'],
699 'edited' => DateTimeFormat::utcNow(),
700 'changed' => DateTimeFormat::utcNow()];
702 Item::update($fields, ['id' => $post_id]);
704 // update filetags in pconfig
705 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
707 info(DI::l10n()->t('Post updated.'));
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' => Type::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' => Type::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 info(DI::l10n()->t('Post published.'));
827 item_post_return(DI::baseUrl(), $api_source, $return_path);
831 function item_post_return($baseurl, $api_source, $return_path)
838 DI::baseUrl()->redirect($return_path);
841 $json = ['success' => 1];
842 if (!empty($_REQUEST['jsreload'])) {
843 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
846 Logger::info('post_json', ['json' => $json]);
848 System::jsonExit($json);
851 function item_content(App $a)
853 if (!Session::isAuthenticated()) {
859 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
860 if (DI::mode()->isAjax()) {
861 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
863 if (!empty($a->argv[3])) {
864 $o = drop_item($a->argv[2], $a->argv[3]);
867 $o = drop_item($a->argv[2]);
871 if (DI::mode()->isAjax()) {
872 // ajax return: [<item id>, 0 (no perm) | <owner id>]
873 System::jsonExit([intval($a->argv[2]), intval($o)]);
881 * This function removes the tag $tag from the text $body and replaces it with
882 * the appropriate link.
885 * @param string $body the text to replace the tag in
886 * @param string $inform a comma-seperated string containing everybody to inform
887 * @param string $str_tags string to add the tag to
888 * @param integer $profile_uid
889 * @param string $tag the tag to replace
890 * @param string $network The network of the post
892 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
893 * @throws ImagickException
894 * @throws HTTPException\InternalServerErrorException
896 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
901 //is it a person tag?
902 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
903 $tag_type = substr($tag, 0, 1);
904 //is it already replaced?
905 if (strpos($tag, '[url=')) {
906 //append tag to str_tags
907 if (!stristr($str_tags, $tag)) {
908 if (strlen($str_tags)) {
914 // Checking for the alias that is used for OStatus
915 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
916 if (preg_match($pattern, $tag, $matches)) {
917 $data = Contact::getDetailsByURL($matches[1]);
919 if ($data["alias"] != "") {
920 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
922 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
923 if (strlen($str_tags)) {
927 $str_tags .= $newtag;
935 //get the person's name
936 $name = substr($tag, 1);
938 // Sometimes the tag detection doesn't seem to work right
939 // This is some workaround
940 $nameparts = explode(" ", $name);
941 $name = $nameparts[0];
943 // Try to detect the contact in various ways
944 if (strpos($name, 'http://')) {
945 // At first we have to ensure that the contact exists
946 Contact::getIdForURL($name);
948 // Now we should have something
949 $contact = Contact::getDetailsByURL($name);
950 } elseif (strpos($name, '@')) {
951 // This function automatically probes when no entry was found
952 $contact = Contact::getDetailsByAddr($name);
955 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
957 if (strrpos($name, '+')) {
958 // Is it in format @nick+number?
959 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
960 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
963 // select someone by nick or attag in the current network
964 if (!DBA::isResult($contact) && ($network != "")) {
965 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
966 $name, $name, $network, $profile_uid];
967 $contact = DBA::selectFirst('contact', $fields, $condition);
970 //select someone by name in the current network
971 if (!DBA::isResult($contact) && ($network != "")) {
972 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
973 $contact = DBA::selectFirst('contact', $fields, $condition);
976 // select someone by nick or attag in any network
977 if (!DBA::isResult($contact)) {
978 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
979 $contact = DBA::selectFirst('contact', $fields, $condition);
982 // select someone by name in any network
983 if (!DBA::isResult($contact)) {
984 $condition = ['name' => $name, 'uid' => $profile_uid];
985 $contact = DBA::selectFirst('contact', $fields, $condition);
989 // Check if $contact has been successfully loaded
990 if (DBA::isResult($contact)) {
991 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
995 if (isset($contact["id"])) {
996 $inform .= 'cid:' . $contact["id"];
997 } elseif (isset($contact["notify"])) {
998 $inform .= $contact["notify"];
1001 $profile = $contact["url"];
1002 $alias = $contact["alias"];
1003 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1006 //if there is an url for this persons profile
1007 if (isset($profile) && ($newname != "")) {
1009 // create profile link
1010 $profile = str_replace(',', '%2c', $profile);
1011 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1012 $body = str_replace($tag_type . $name, $newtag, $body);
1013 // append tag to str_tags
1014 if (!stristr($str_tags, $newtag)) {
1015 if (strlen($str_tags)) {
1018 $str_tags .= $newtag;
1022 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1023 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1025 if (!empty($alias)) {
1026 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1027 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1028 if (strlen($str_tags)) {
1031 $str_tags .= $newtag;
1037 return ['replaced' => $replaced, 'contact' => $contact];
1040 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1042 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1043 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1044 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1045 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1046 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1051 $implicit_mentions = [
1052 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1055 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1057 foreach ($parent_terms as $parent_term) {
1058 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1061 foreach ($implicit_mentions as $url => $label) {
1062 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1063 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';