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\Content\Text\HTML;
22 use Friendica\Core\Config;
23 use Friendica\Core\Hook;
24 use Friendica\Core\L10n;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\Session;
28 use Friendica\Core\System;
29 use Friendica\Core\Worker;
30 use Friendica\Database\DBA;
32 use Friendica\Model\Attach;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\FileTag;
36 use Friendica\Model\Item;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Term;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Protocol\Email;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Emailer;
44 use Friendica\Util\Security;
45 use Friendica\Util\Strings;
46 use Friendica\Worker\Delivery;
48 require_once __DIR__ . '/../include/items.php';
50 function item_post(App $a) {
51 if (!Session::isAuthenticated()) {
57 if (!empty($_REQUEST['dropitems'])) {
58 $arr_drop = explode(',', $_REQUEST['dropitems']);
59 drop_items($arr_drop);
60 $json = ['success' => 1];
61 echo json_encode($json);
65 Hook::callAll('post_local_start', $_REQUEST);
67 Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
69 $api_source = $_REQUEST['api_source'] ?? false;
71 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
73 $return_path = $_REQUEST['return'] ?? '';
74 $preview = intval($_REQUEST['preview'] ?? 0);
77 * Check for doubly-submitted posts, and reject duplicates
78 * Note that we have to ignore previews, otherwise nothing will post
79 * after it's been previewed
81 if (!$preview && !empty($_REQUEST['post_id_random'])) {
82 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
83 Logger::log("item post: duplicate post", Logger::DEBUG);
84 item_post_return(DI::baseUrl(), $api_source, $return_path);
86 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
90 // Is this a reply to something?
91 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
92 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
94 $thread_parent_id = 0;
95 $thread_parent_contact = null;
97 $toplevel_item = null;
100 $parent_contact = null;
103 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
104 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
106 if ($toplevel_item_id || $thr_parent_uri) {
107 if ($toplevel_item_id) {
108 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
109 } elseif ($thr_parent_uri) {
110 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
113 // if this isn't the top-level parent of the conversation, find it
114 if (DBA::isResult($toplevel_item)) {
115 // The URI and the contact is taken from the direct parent which needn't to be the top parent
116 $thread_parent_id = $toplevel_item['id'];
117 $thr_parent_uri = $toplevel_item['uri'];
118 $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
120 if ($toplevel_item['id'] != $toplevel_item['parent']) {
121 $toplevel_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
125 if (!DBA::isResult($toplevel_item)) {
126 notice(L10n::t('Unable to locate original post.') . EOL);
127 if (!empty($_REQUEST['return'])) {
128 DI::baseUrl()->redirect($return_path);
133 $toplevel_item_id = $toplevel_item['id'];
134 $parent_user = $toplevel_item['uid'];
136 $objecttype = Activity\ObjectType::COMMENT;
139 if ($toplevel_item_id) {
140 Logger::info('mod_item: item_post parent=' . $toplevel_item_id);
143 $post_id = intval($_REQUEST['post_id'] ?? 0);
144 $app = strip_tags($_REQUEST['source'] ?? '');
145 $extid = strip_tags($_REQUEST['extid'] ?? '');
146 $object = $_REQUEST['object'] ?? '';
148 // Don't use "defaults" here. It would turn 0 to 1
149 if (!isset($_REQUEST['wall'])) {
152 $wall = $_REQUEST['wall'];
155 // Ensure that the user id in a thread always stay the same
156 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
157 $profile_uid = $parent_user;
160 // Check for multiple posts with the same message id (when the post was created via API)
161 if (($message_id != '') && ($profile_uid != 0)) {
162 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
163 Logger::log("Message with URI ".$message_id." already exists for user ".$profile_uid, Logger::DEBUG);
168 // Allow commenting if it is an answer to a public post
169 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
171 // Now check that valid personal details have been provided
172 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
173 notice(L10n::t('Permission denied.') . EOL);
175 if (!empty($_REQUEST['return'])) {
176 DI::baseUrl()->redirect($return_path);
182 // Init post instance
185 // is this an edited post?
187 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
190 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
192 if (!DBA::isResult($user) && !$toplevel_item_id) {
199 $body = $_REQUEST['body'] ?? '';
200 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
202 // If we have a speparate attachment, we need to add it to the body.
203 if (!empty($has_attachment)) {
204 $attachment_type = $_REQUEST['attachment_type'] ?? '';
205 $attachment_title = $_REQUEST['attachment_title'] ?? '';
206 $attachment_text = $_REQUEST['attachment_text'] ?? '';
208 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
209 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
211 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
212 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
214 'type' => $attachment_type,
215 'title' => $attachment_title,
216 'text' => $attachment_text,
217 'url' => $attachment_url,
220 if (!empty($attachment_img_src)) {
221 $attachment['images'] = [
223 'src' => $attachment_img_src,
224 'width' => $attachment_img_width,
225 'height' => $attachment_img_height
230 $att_bbcode = add_page_info_data($attachment);
231 $body .= $att_bbcode;
234 // Convert links with empty descriptions to links without an explicit description
235 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
237 if (!empty($orig_post)) {
238 $str_group_allow = $orig_post['allow_gid'];
239 $str_contact_allow = $orig_post['allow_cid'];
240 $str_group_deny = $orig_post['deny_gid'];
241 $str_contact_deny = $orig_post['deny_cid'];
242 $location = $orig_post['location'];
243 $coord = $orig_post['coord'];
244 $verb = $orig_post['verb'];
245 $objecttype = $orig_post['object-type'];
246 $app = $orig_post['app'];
247 $categories = $orig_post['file'];
248 $title = Strings::escapeTags(trim($_REQUEST['title']));
249 $body = Strings::escapeHtml(trim($body));
250 $private = $orig_post['private'];
251 $pubmail_enabled = $orig_post['pubmail'];
252 $network = $orig_post['network'];
253 $guid = $orig_post['guid'];
254 $extid = $orig_post['extid'];
259 * if coming from the API and no privacy settings are set,
260 * use the user default permissions - as they won't have
261 * been supplied via a form.
264 && !array_key_exists('contact_allow', $_REQUEST)
265 && !array_key_exists('group_allow', $_REQUEST)
266 && !array_key_exists('contact_deny', $_REQUEST)
267 && !array_key_exists('group_deny', $_REQUEST)) {
268 $str_group_allow = $user['allow_gid'];
269 $str_contact_allow = $user['allow_cid'];
270 $str_group_deny = $user['deny_gid'];
271 $str_contact_deny = $user['deny_cid'];
273 // use the posted permissions
275 $aclFormatter = DI::aclFormatter();
277 $str_group_allow = $aclFormatter->toString($_REQUEST['group_allow'] ?? '');
278 $str_contact_allow = $aclFormatter->toString($_REQUEST['contact_allow'] ?? '');
279 $str_group_deny = $aclFormatter->toString($_REQUEST['group_deny'] ?? '');
280 $str_contact_deny = $aclFormatter->toString($_REQUEST['contact_deny'] ?? '');
283 $title = Strings::escapeTags(trim($_REQUEST['title'] ?? ''));
284 $location = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
285 $coord = Strings::escapeTags(trim($_REQUEST['coord'] ?? ''));
286 $verb = Strings::escapeTags(trim($_REQUEST['verb'] ?? ''));
287 $emailcc = Strings::escapeTags(trim($_REQUEST['emailcc'] ?? ''));
288 $body = Strings::escapeHtml(trim($body));
289 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
290 $guid = System::createUUID();
292 $postopts = $_REQUEST['postopts'] ?? '';
294 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
296 // If this is a comment, set the permissions from the parent.
298 if ($toplevel_item) {
299 // for non native networks use the network of the original post as network of the item
300 if (($toplevel_item['network'] != Protocol::DIASPORA)
301 && ($toplevel_item['network'] != Protocol::OSTATUS)
302 && ($network == "")) {
303 $network = $toplevel_item['network'];
306 $str_contact_allow = $toplevel_item['allow_cid'];
307 $str_group_allow = $toplevel_item['allow_gid'];
308 $str_contact_deny = $toplevel_item['deny_cid'];
309 $str_group_deny = $toplevel_item['deny_gid'];
310 $private = $toplevel_item['private'];
312 $wall = $toplevel_item['wall'];
315 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
317 // if using the API, we won't see pubmail_enable - figure out if it should be set
318 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
319 if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
320 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
324 if (!strlen($body)) {
328 info(L10n::t('Empty post discarded.') . EOL);
329 if (!empty($_REQUEST['return'])) {
330 DI::baseUrl()->redirect($return_path);
336 if (!empty($categories)) {
337 // get the "fileas" tags for this post
338 $filedas = FileTag::fileToArray($categories);
341 // save old and new categories, so we can determine what needs to be deleted from pconfig
342 $categories_old = $categories;
343 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
344 $categories_new = $categories;
346 if (!empty($filedas) && is_array($filedas)) {
347 // append the fileas stuff to the new categories list
348 $categories .= FileTag::arrayToFile($filedas);
351 // get contact info for poster
357 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
359 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
360 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
361 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
364 if (DBA::isResult($author)) {
365 $contact_id = $author['id'];
368 // get contact info for owner
369 if ($profile_uid == local_user() || $allow_comment) {
370 $contact_record = $author;
372 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
375 // Look for any tags and linkify them
379 $tags = BBCode::getTags($body);
381 if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
382 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
387 $private_forum = false;
388 $only_to_forum = false;
392 foreach ($tags as $tag) {
393 $tag_type = substr($tag, 0, 1);
395 if ($tag_type == Term::TAG_CHARACTER[Term::HASHTAG]) {
400 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
401 * Robert Johnson should be first in the $tags array
403 $fullnametagged = false;
404 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
405 foreach ($tagged as $nextTag) {
406 if (stristr($nextTag, $tag . ' ')) {
407 $fullnametagged = true;
411 if ($fullnametagged) {
415 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
416 if ($success['replaced']) {
419 // When the forum is private or the forum is addressed with a "!" make the post private
420 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
421 $private_forum = $success['contact']['prv'];
422 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
423 $private_id = $success['contact']['id'];
424 $forum_contact = $success['contact'];
425 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
426 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
427 $private_forum = false;
428 $only_to_forum = true;
429 $private_id = $success['contact']['id'];
430 $forum_contact = $success['contact'];
435 $original_contact_id = $contact_id;
437 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
438 // we tagged a forum in a top level post. Now we change the post
439 $private = $private_forum;
441 $str_group_allow = '';
442 $str_contact_deny = '';
443 $str_group_deny = '';
444 if ($private_forum) {
445 $str_contact_allow = '<' . $private_id . '>';
447 $str_contact_allow = '';
449 $contact_id = $private_id;
450 $contact_record = $forum_contact;
451 $_REQUEST['origin'] = false;
456 * When a photo was uploaded into the message using the (profile wall) ajax
457 * uploader, The permissions are initially set to disallow anybody but the
458 * owner from seeing it. This is because the permissions may not yet have been
459 * set for the post. If it's private, the photo permissions should be set
460 * appropriately. But we didn't know the final permissions on the post until
461 * now. So now we'll look for links of uploaded messages that are in the
462 * post and set them to the same permissions as the post itself.
467 if (!$preview && Photo::setPermissionFromBody($body, $profile_uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
468 $objecttype = Activity\ObjectType::IMAGE;
472 * Next link in any attachment references we find in the post.
476 /// @todo these lines should be moved to Model/Attach (Once it exists)
477 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
478 $attaches = $match[1];
479 if (count($attaches)) {
480 foreach ($attaches as $attach) {
481 // Ensure to only modify attachments that you own
482 $srch = '<' . intval($original_contact_id) . '>';
484 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
486 if (!Attach::exists($condition)) {
490 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
491 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
492 $condition = ['id' => $attach];
493 Attach::update($fields, $condition);
498 // embedded bookmark or attachment in post? set bookmark flag
500 $data = BBCode::getAttachmentData($body);
501 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
502 && ($posttype != Item::PT_PERSONAL_NOTE)) {
503 $posttype = Item::PT_PAGE;
504 $objecttype = Activity\ObjectType::BOOKMARK;
507 $body = DI::bbCodeVideo()->transform($body);
509 // Fold multi-line [code] sequences
510 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
512 $body = BBCode::scaleExternalImages($body, false);
514 // Setting the object type if not defined before
516 $objecttype = Activity\ObjectType::NOTE; // Default value
517 $objectdata = BBCode::getAttachedData($body);
519 if ($objectdata["type"] == "link") {
520 $objecttype = Activity\ObjectType::BOOKMARK;
521 } elseif ($objectdata["type"] == "video") {
522 $objecttype = Activity\ObjectType::VIDEO;
523 } elseif ($objectdata["type"] == "photo") {
524 $objecttype = Activity\ObjectType::IMAGE;
532 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
533 foreach ($match[2] as $mtch) {
534 $fields = ['id', 'filename', 'filesize', 'filetype'];
535 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
536 if ($attachment !== false) {
537 if (strlen($attachments)) {
540 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
541 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
542 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
544 $body = str_replace($match[1],'',$body);
548 if (!strlen($verb)) {
549 $verb = Activity::POST;
552 if ($network == "") {
553 $network = Protocol::DFRN;
556 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
558 // even if the post arrived via API we are considering that it
559 // originated on this site by default for determining relayability.
561 // Don't use "defaults" here. It would turn 0 to 1
562 if (!isset($_REQUEST['origin'])) {
565 $origin = $_REQUEST['origin'];
568 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
570 // Fallback so that we alway have a parent uri
571 if (!$thr_parent_uri || !$toplevel_item_id) {
572 $thr_parent_uri = $uri;
576 $datarray['uid'] = $profile_uid;
577 $datarray['wall'] = $wall;
578 $datarray['gravity'] = $gravity;
579 $datarray['network'] = $network;
580 $datarray['contact-id'] = $contact_id;
581 $datarray['owner-name'] = $contact_record['name'];
582 $datarray['owner-link'] = $contact_record['url'];
583 $datarray['owner-avatar'] = $contact_record['thumb'];
584 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
585 $datarray['author-name'] = $author['name'];
586 $datarray['author-link'] = $author['url'];
587 $datarray['author-avatar'] = $author['thumb'];
588 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
589 $datarray['created'] = DateTimeFormat::utcNow();
590 $datarray['edited'] = DateTimeFormat::utcNow();
591 $datarray['commented'] = DateTimeFormat::utcNow();
592 $datarray['received'] = DateTimeFormat::utcNow();
593 $datarray['changed'] = DateTimeFormat::utcNow();
594 $datarray['extid'] = $extid;
595 $datarray['guid'] = $guid;
596 $datarray['uri'] = $uri;
597 $datarray['title'] = $title;
598 $datarray['body'] = $body;
599 $datarray['app'] = $app;
600 $datarray['location'] = $location;
601 $datarray['coord'] = $coord;
602 $datarray['tag'] = $str_tags;
603 $datarray['file'] = $categories;
604 $datarray['inform'] = $inform;
605 $datarray['verb'] = $verb;
606 $datarray['post-type'] = $posttype;
607 $datarray['object-type'] = $objecttype;
608 $datarray['allow_cid'] = $str_contact_allow;
609 $datarray['allow_gid'] = $str_group_allow;
610 $datarray['deny_cid'] = $str_contact_deny;
611 $datarray['deny_gid'] = $str_group_deny;
612 $datarray['private'] = $private;
613 $datarray['pubmail'] = $pubmail_enabled;
614 $datarray['attach'] = $attachments;
616 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
617 $datarray['parent-uri'] = $thr_parent_uri;
619 $datarray['postopts'] = $postopts;
620 $datarray['origin'] = $origin;
621 $datarray['moderated'] = false;
622 $datarray['object'] = $object;
625 * These fields are for the convenience of addons...
626 * 'self' if true indicates the owner is posting on their own wall
627 * If parent is 0 it is a top-level post.
629 $datarray['parent'] = $toplevel_item_id;
630 $datarray['self'] = $self;
632 // This triggers posts via API and the mirror functions
633 $datarray['api_source'] = $api_source;
635 // This field is for storing the raw conversation data
636 $datarray['protocol'] = Conversation::PARCEL_DFRN;
638 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
639 if (DBA::isResult($conversation)) {
640 if ($conversation['conversation-uri'] != '') {
641 $datarray['conversation-uri'] = $conversation['conversation-uri'];
643 if ($conversation['conversation-href'] != '') {
644 $datarray['conversation-href'] = $conversation['conversation-href'];
649 $datarray['edit'] = true;
651 // If this was a share, add missing data here
652 $datarray = Item::addShareDataFromOriginal($datarray);
654 $datarray['edit'] = false;
657 // Check for hashtags in the body and repair or add hashtag links
658 if ($preview || $orig_post) {
659 Item::setHashtags($datarray);
662 // preview mode - prepare the body for display and send it via json
664 // We set the datarray ID to -1 because in preview mode the dataray
665 // doesn't have an ID.
666 $datarray["id"] = -1;
667 $datarray["item_id"] = -1;
668 $datarray["author-network"] = Protocol::DFRN;
670 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager(DI::args()->getQueryString()), 'search', false, true);
671 Logger::log('preview: ' . $o);
672 echo json_encode(['preview' => $o]);
676 Hook::callAll('post_local',$datarray);
678 if (!empty($datarray['cancel'])) {
679 Logger::log('mod_item: post cancelled by addon.');
681 DI::baseUrl()->redirect($return_path);
684 $json = ['cancel' => 1];
685 if (!empty($_REQUEST['jsreload'])) {
686 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
689 echo json_encode($json);
694 // Fill the cache field
695 // This could be done in Item::update as well - but we have to check for the existance of some fields.
696 Item::putInCache($datarray);
699 'title' => $datarray['title'],
700 'body' => $datarray['body'],
701 'tag' => $datarray['tag'],
702 'attach' => $datarray['attach'],
703 'file' => $datarray['file'],
704 'rendered-html' => $datarray['rendered-html'],
705 'rendered-hash' => $datarray['rendered-hash'],
706 'edited' => DateTimeFormat::utcNow(),
707 'changed' => DateTimeFormat::utcNow()];
709 Item::update($fields, ['id' => $post_id]);
711 // update filetags in pconfig
712 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
714 if (!empty($_REQUEST['return']) && strlen($return_path)) {
715 Logger::log('return: ' . $return_path);
716 DI::baseUrl()->redirect($return_path);
721 unset($datarray['edit']);
722 unset($datarray['self']);
723 unset($datarray['api_source']);
726 $signed = Diaspora::createCommentSignature($uid, $datarray);
727 if (!empty($signed)) {
728 $datarray['diaspora_signed_text'] = json_encode($signed);
732 $post_id = Item::insert($datarray);
735 Logger::log("Item wasn't stored.");
736 DI::baseUrl()->redirect($return_path);
739 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
741 if (!DBA::isResult($datarray)) {
742 Logger::log("Item with id ".$post_id." couldn't be fetched.");
743 DI::baseUrl()->redirect($return_path);
746 // update filetags in pconfig
747 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
749 // These notifications are sent if someone else is commenting other your wall
750 if ($toplevel_item_id) {
751 if ($contact_record != $author) {
753 'type' => NOTIFY_COMMENT,
754 'notify_flags' => $user['notify-flags'],
755 'language' => $user['language'],
756 'to_name' => $user['username'],
757 'to_email' => $user['email'],
758 'uid' => $user['uid'],
760 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
761 'source_name' => $datarray['author-name'],
762 'source_link' => $datarray['author-link'],
763 'source_photo' => $datarray['author-avatar'],
764 'verb' => Activity::POST,
766 'parent' => $toplevel_item_id,
767 'parent_uri' => $toplevel_item['uri']
771 if (($contact_record != $author) && !count($forum_contact)) {
773 'type' => NOTIFY_WALL,
774 'notify_flags' => $user['notify-flags'],
775 'language' => $user['language'],
776 'to_name' => $user['username'],
777 'to_email' => $user['email'],
778 'uid' => $user['uid'],
780 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
781 'source_name' => $datarray['author-name'],
782 'source_link' => $datarray['author-link'],
783 'source_photo' => $datarray['author-avatar'],
784 'verb' => Activity::POST,
790 Hook::callAll('post_local_end', $datarray);
792 if (strlen($emailcc) && $profile_uid == local_user()) {
793 $erecips = explode(',', $emailcc);
794 if (count($erecips)) {
795 foreach ($erecips as $recip) {
796 $addr = trim($recip);
797 if (!strlen($addr)) {
800 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
802 $disclaimer .= L10n::t('You may visit them online at %s', DI::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
803 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
804 if (!$datarray['title']=='') {
805 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
807 $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
809 $link = '<a href="' . DI::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
810 $html = Item::prepareBody($datarray);
811 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
813 'fromName' => $a->user['username'],
814 'fromEmail' => $a->user['email'],
816 'replyTo' => $a->user['email'],
817 'messageSubject' => $subject,
818 'htmlVersion' => $message,
819 'textVersion' => HTML::toPlaintext($html.$disclaimer)
821 Emailer::send($params);
826 // Insert an item entry for UID=0 for global entries.
827 // We now do it in the background to save some time.
828 // This is important in interactive environments like the frontend or the API.
829 // We don't fork a new process since this is done anyway with the following command
830 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
832 // When we are doing some forum posting via ! we have to start the notifier manually.
833 // These kind of posts don't initiate the notifier call in the item class.
834 if ($only_to_forum) {
835 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
838 Logger::log('post_complete');
844 item_post_return(DI::baseUrl(), $api_source, $return_path);
848 function item_post_return($baseurl, $api_source, $return_path)
850 // figure out how to return, depending on from whence we came
858 DI::baseUrl()->redirect($return_path);
861 $json = ['success' => 1];
862 if (!empty($_REQUEST['jsreload'])) {
863 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
866 Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
868 echo json_encode($json);
872 function item_content(App $a)
874 if (!Session::isAuthenticated()) {
880 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
881 if (DI::mode()->isAjax()) {
882 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
884 if (!empty($a->argv[3])) {
885 $o = drop_item($a->argv[2], $a->argv[3]);
888 $o = drop_item($a->argv[2]);
892 if (DI::mode()->isAjax()) {
893 // ajax return: [<item id>, 0 (no perm) | <owner id>]
894 echo json_encode([intval($a->argv[2]), intval($o)]);
903 * This function removes the tag $tag from the text $body and replaces it with
904 * the appropriate link.
907 * @param string $body the text to replace the tag in
908 * @param string $inform a comma-seperated string containing everybody to inform
909 * @param string $str_tags string to add the tag to
910 * @param integer $profile_uid
911 * @param string $tag the tag to replace
912 * @param string $network The network of the post
914 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
915 * @throws ImagickException
916 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
918 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
923 //is it a person tag?
924 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
925 $tag_type = substr($tag, 0, 1);
926 //is it already replaced?
927 if (strpos($tag, '[url=')) {
928 //append tag to str_tags
929 if (!stristr($str_tags, $tag)) {
930 if (strlen($str_tags)) {
936 // Checking for the alias that is used for OStatus
937 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
938 if (preg_match($pattern, $tag, $matches)) {
939 $data = Contact::getDetailsByURL($matches[1]);
941 if ($data["alias"] != "") {
942 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
944 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
945 if (strlen($str_tags)) {
949 $str_tags .= $newtag;
957 //get the person's name
958 $name = substr($tag, 1);
960 // Sometimes the tag detection doesn't seem to work right
961 // This is some workaround
962 $nameparts = explode(" ", $name);
963 $name = $nameparts[0];
965 // Try to detect the contact in various ways
966 if (strpos($name, 'http://')) {
967 // At first we have to ensure that the contact exists
968 Contact::getIdForURL($name);
970 // Now we should have something
971 $contact = Contact::getDetailsByURL($name);
972 } elseif (strpos($name, '@')) {
973 // This function automatically probes when no entry was found
974 $contact = Contact::getDetailsByAddr($name);
977 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
979 if (strrpos($name, '+')) {
980 // Is it in format @nick+number?
981 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
982 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
985 // select someone by nick or attag in the current network
986 if (!DBA::isResult($contact) && ($network != "")) {
987 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
988 $name, $name, $network, $profile_uid];
989 $contact = DBA::selectFirst('contact', $fields, $condition);
992 //select someone by name in the current network
993 if (!DBA::isResult($contact) && ($network != "")) {
994 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
995 $contact = DBA::selectFirst('contact', $fields, $condition);
998 // select someone by nick or attag in any network
999 if (!DBA::isResult($contact)) {
1000 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
1001 $contact = DBA::selectFirst('contact', $fields, $condition);
1004 // select someone by name in any network
1005 if (!DBA::isResult($contact)) {
1006 $condition = ['name' => $name, 'uid' => $profile_uid];
1007 $contact = DBA::selectFirst('contact', $fields, $condition);
1011 // Check if $contact has been successfully loaded
1012 if (DBA::isResult($contact)) {
1013 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1017 if (isset($contact["id"])) {
1018 $inform .= 'cid:' . $contact["id"];
1019 } elseif (isset($contact["notify"])) {
1020 $inform .= $contact["notify"];
1023 $profile = $contact["url"];
1024 $alias = $contact["alias"];
1025 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1028 //if there is an url for this persons profile
1029 if (isset($profile) && ($newname != "")) {
1031 // create profile link
1032 $profile = str_replace(',', '%2c', $profile);
1033 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1034 $body = str_replace($tag_type . $name, $newtag, $body);
1035 // append tag to str_tags
1036 if (!stristr($str_tags, $newtag)) {
1037 if (strlen($str_tags)) {
1040 $str_tags .= $newtag;
1044 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1045 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1047 if (!empty($alias)) {
1048 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1049 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1050 if (strlen($str_tags)) {
1053 $str_tags .= $newtag;
1059 return ['replaced' => $replaced, 'contact' => $contact];
1062 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1064 if (Config::get('system', 'disable_implicit_mentions')) {
1065 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1066 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1067 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1068 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1073 $implicit_mentions = [
1074 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1077 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1079 foreach ($parent_terms as $parent_term) {
1080 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1083 foreach ($implicit_mentions as $url => $label) {
1084 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1085 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';