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\Hook;
23 use Friendica\Core\Logger;
24 use Friendica\Core\Protocol;
25 use Friendica\Core\Session;
26 use Friendica\Core\System;
27 use Friendica\Core\Worker;
28 use Friendica\Database\DBA;
30 use Friendica\Model\Attach;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Conversation;
33 use Friendica\Model\FileTag;
34 use Friendica\Model\Item;
35 use Friendica\Model\Photo;
36 use Friendica\Model\Term;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\Diaspora;
39 use Friendica\Protocol\Email;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Emailer;
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()) {
55 if (!empty($_REQUEST['dropitems'])) {
56 $arr_drop = explode(',', $_REQUEST['dropitems']);
57 drop_items($arr_drop);
58 $json = ['success' => 1];
59 echo json_encode($json);
63 Hook::callAll('post_local_start', $_REQUEST);
65 Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
67 $api_source = $_REQUEST['api_source'] ?? false;
69 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
71 $return_path = $_REQUEST['return'] ?? '';
72 $preview = intval($_REQUEST['preview'] ?? 0);
75 * Check for doubly-submitted posts, and reject duplicates
76 * Note that we have to ignore previews, otherwise nothing will post
77 * after it's been previewed
79 if (!$preview && !empty($_REQUEST['post_id_random'])) {
80 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
81 Logger::log("item post: duplicate post", Logger::DEBUG);
82 item_post_return(DI::baseUrl(), $api_source, $return_path);
84 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
88 // Is this a reply to something?
89 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
90 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
92 $thread_parent_id = 0;
93 $thread_parent_contact = null;
95 $toplevel_item = null;
98 $parent_contact = null;
101 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
102 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
104 if ($toplevel_item_id || $thr_parent_uri) {
105 if ($toplevel_item_id) {
106 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
107 } elseif ($thr_parent_uri) {
108 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
111 // if this isn't the top-level parent of the conversation, find it
112 if (DBA::isResult($toplevel_item)) {
113 // The URI and the contact is taken from the direct parent which needn't to be the top parent
114 $thread_parent_id = $toplevel_item['id'];
115 $thr_parent_uri = $toplevel_item['uri'];
116 $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
118 if ($toplevel_item['id'] != $toplevel_item['parent']) {
119 $toplevel_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
123 if (!DBA::isResult($toplevel_item)) {
124 notice(DI::l10n()->t('Unable to locate original post.') . EOL);
125 if (!empty($_REQUEST['return'])) {
126 DI::baseUrl()->redirect($return_path);
131 $toplevel_item_id = $toplevel_item['id'];
132 $parent_user = $toplevel_item['uid'];
134 $objecttype = Activity\ObjectType::COMMENT;
137 if ($toplevel_item_id) {
138 Logger::info('mod_item: item_post parent=' . $toplevel_item_id);
141 $post_id = intval($_REQUEST['post_id'] ?? 0);
142 $app = strip_tags($_REQUEST['source'] ?? '');
143 $extid = strip_tags($_REQUEST['extid'] ?? '');
144 $object = $_REQUEST['object'] ?? '';
146 // Don't use "defaults" here. It would turn 0 to 1
147 if (!isset($_REQUEST['wall'])) {
150 $wall = $_REQUEST['wall'];
153 // Ensure that the user id in a thread always stay the same
154 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
155 $profile_uid = $parent_user;
158 // Check for multiple posts with the same message id (when the post was created via API)
159 if (($message_id != '') && ($profile_uid != 0)) {
160 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
161 Logger::log("Message with URI ".$message_id." already exists for user ".$profile_uid, Logger::DEBUG);
166 // Allow commenting if it is an answer to a public post
167 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
169 // Now check that valid personal details have been provided
170 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
171 notice(DI::l10n()->t('Permission denied.') . EOL);
173 if (!empty($_REQUEST['return'])) {
174 DI::baseUrl()->redirect($return_path);
180 // Init post instance
183 // is this an edited post?
185 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
188 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
190 if (!DBA::isResult($user) && !$toplevel_item_id) {
197 $body = $_REQUEST['body'] ?? '';
198 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
200 // If we have a speparate attachment, we need to add it to the body.
201 if (!empty($has_attachment)) {
202 $attachment_type = $_REQUEST['attachment_type'] ?? '';
203 $attachment_title = $_REQUEST['attachment_title'] ?? '';
204 $attachment_text = $_REQUEST['attachment_text'] ?? '';
206 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
207 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
209 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
210 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
212 'type' => $attachment_type,
213 'title' => $attachment_title,
214 'text' => $attachment_text,
215 'url' => $attachment_url,
218 if (!empty($attachment_img_src)) {
219 $attachment['images'] = [
221 'src' => $attachment_img_src,
222 'width' => $attachment_img_width,
223 'height' => $attachment_img_height
228 $att_bbcode = add_page_info_data($attachment);
229 $body .= $att_bbcode;
232 // Convert links with empty descriptions to links without an explicit description
233 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
235 if (!empty($orig_post)) {
236 $str_group_allow = $orig_post['allow_gid'];
237 $str_contact_allow = $orig_post['allow_cid'];
238 $str_group_deny = $orig_post['deny_gid'];
239 $str_contact_deny = $orig_post['deny_cid'];
240 $location = $orig_post['location'];
241 $coord = $orig_post['coord'];
242 $verb = $orig_post['verb'];
243 $objecttype = $orig_post['object-type'];
244 $app = $orig_post['app'];
245 $categories = $orig_post['file'];
246 $title = Strings::escapeTags(trim($_REQUEST['title']));
248 $private = $orig_post['private'];
249 $pubmail_enabled = $orig_post['pubmail'];
250 $network = $orig_post['network'];
251 $guid = $orig_post['guid'];
252 $extid = $orig_post['extid'];
257 * if coming from the API and no privacy settings are set,
258 * use the user default permissions - as they won't have
259 * been supplied via a form.
262 && !array_key_exists('contact_allow', $_REQUEST)
263 && !array_key_exists('group_allow', $_REQUEST)
264 && !array_key_exists('contact_deny', $_REQUEST)
265 && !array_key_exists('group_deny', $_REQUEST)) {
266 $str_group_allow = $user['allow_gid'];
267 $str_contact_allow = $user['allow_cid'];
268 $str_group_deny = $user['deny_gid'];
269 $str_contact_deny = $user['deny_cid'];
271 // use the posted permissions
273 $aclFormatter = DI::aclFormatter();
275 $str_group_allow = $aclFormatter->toString($_REQUEST['group_allow'] ?? '');
276 $str_contact_allow = $aclFormatter->toString($_REQUEST['contact_allow'] ?? '');
277 $str_group_deny = $aclFormatter->toString($_REQUEST['group_deny'] ?? '');
278 $str_contact_deny = $aclFormatter->toString($_REQUEST['contact_deny'] ?? '');
281 $title = Strings::escapeTags(trim($_REQUEST['title'] ?? ''));
282 $location = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
283 $coord = Strings::escapeTags(trim($_REQUEST['coord'] ?? ''));
284 $verb = Strings::escapeTags(trim($_REQUEST['verb'] ?? ''));
285 $emailcc = Strings::escapeTags(trim($_REQUEST['emailcc'] ?? ''));
287 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
288 $guid = System::createUUID();
290 $postopts = $_REQUEST['postopts'] ?? '';
292 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
294 // If this is a comment, set the permissions from the parent.
296 if ($toplevel_item) {
297 // for non native networks use the network of the original post as network of the item
298 if (($toplevel_item['network'] != Protocol::DIASPORA)
299 && ($toplevel_item['network'] != Protocol::OSTATUS)
300 && ($network == "")) {
301 $network = $toplevel_item['network'];
304 $str_contact_allow = $toplevel_item['allow_cid'];
305 $str_group_allow = $toplevel_item['allow_gid'];
306 $str_contact_deny = $toplevel_item['deny_cid'];
307 $str_group_deny = $toplevel_item['deny_gid'];
308 $private = $toplevel_item['private'];
310 $wall = $toplevel_item['wall'];
313 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
315 // if using the API, we won't see pubmail_enable - figure out if it should be set
316 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
317 if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
318 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
322 if (!strlen($body)) {
326 info(DI::l10n()->t('Empty post discarded.') . EOL);
327 if (!empty($_REQUEST['return'])) {
328 DI::baseUrl()->redirect($return_path);
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 // Fold multi-line [code] sequences
508 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
510 $body = BBCode::scaleExternalImages($body);
512 // Setting the object type if not defined before
514 $objecttype = Activity\ObjectType::NOTE; // Default value
515 $objectdata = BBCode::getAttachedData($body);
517 if ($objectdata["type"] == "link") {
518 $objecttype = Activity\ObjectType::BOOKMARK;
519 } elseif ($objectdata["type"] == "video") {
520 $objecttype = Activity\ObjectType::VIDEO;
521 } elseif ($objectdata["type"] == "photo") {
522 $objecttype = Activity\ObjectType::IMAGE;
530 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
531 foreach ($match[2] as $mtch) {
532 $fields = ['id', 'filename', 'filesize', 'filetype'];
533 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
534 if ($attachment !== false) {
535 if (strlen($attachments)) {
538 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
539 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
540 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
542 $body = str_replace($match[1],'',$body);
546 if (!strlen($verb)) {
547 $verb = Activity::POST;
550 if ($network == "") {
551 $network = Protocol::DFRN;
554 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
556 // even if the post arrived via API we are considering that it
557 // originated on this site by default for determining relayability.
559 // Don't use "defaults" here. It would turn 0 to 1
560 if (!isset($_REQUEST['origin'])) {
563 $origin = $_REQUEST['origin'];
566 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
568 // Fallback so that we alway have a parent uri
569 if (!$thr_parent_uri || !$toplevel_item_id) {
570 $thr_parent_uri = $uri;
574 $datarray['uid'] = $profile_uid;
575 $datarray['wall'] = $wall;
576 $datarray['gravity'] = $gravity;
577 $datarray['network'] = $network;
578 $datarray['contact-id'] = $contact_id;
579 $datarray['owner-name'] = $contact_record['name'];
580 $datarray['owner-link'] = $contact_record['url'];
581 $datarray['owner-avatar'] = $contact_record['thumb'];
582 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
583 $datarray['author-name'] = $author['name'];
584 $datarray['author-link'] = $author['url'];
585 $datarray['author-avatar'] = $author['thumb'];
586 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
587 $datarray['created'] = DateTimeFormat::utcNow();
588 $datarray['edited'] = DateTimeFormat::utcNow();
589 $datarray['commented'] = DateTimeFormat::utcNow();
590 $datarray['received'] = DateTimeFormat::utcNow();
591 $datarray['changed'] = DateTimeFormat::utcNow();
592 $datarray['extid'] = $extid;
593 $datarray['guid'] = $guid;
594 $datarray['uri'] = $uri;
595 $datarray['title'] = $title;
596 $datarray['body'] = $body;
597 $datarray['app'] = $app;
598 $datarray['location'] = $location;
599 $datarray['coord'] = $coord;
600 $datarray['tag'] = $str_tags;
601 $datarray['file'] = $categories;
602 $datarray['inform'] = $inform;
603 $datarray['verb'] = $verb;
604 $datarray['post-type'] = $posttype;
605 $datarray['object-type'] = $objecttype;
606 $datarray['allow_cid'] = $str_contact_allow;
607 $datarray['allow_gid'] = $str_group_allow;
608 $datarray['deny_cid'] = $str_contact_deny;
609 $datarray['deny_gid'] = $str_group_deny;
610 $datarray['private'] = $private;
611 $datarray['pubmail'] = $pubmail_enabled;
612 $datarray['attach'] = $attachments;
614 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
615 $datarray['parent-uri'] = $thr_parent_uri;
617 $datarray['postopts'] = $postopts;
618 $datarray['origin'] = $origin;
619 $datarray['moderated'] = false;
620 $datarray['object'] = $object;
623 * These fields are for the convenience of addons...
624 * 'self' if true indicates the owner is posting on their own wall
625 * If parent is 0 it is a top-level post.
627 $datarray['parent'] = $toplevel_item_id;
628 $datarray['self'] = $self;
630 // This triggers posts via API and the mirror functions
631 $datarray['api_source'] = $api_source;
633 // This field is for storing the raw conversation data
634 $datarray['protocol'] = Conversation::PARCEL_DFRN;
636 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
637 if (DBA::isResult($conversation)) {
638 if ($conversation['conversation-uri'] != '') {
639 $datarray['conversation-uri'] = $conversation['conversation-uri'];
641 if ($conversation['conversation-href'] != '') {
642 $datarray['conversation-href'] = $conversation['conversation-href'];
647 $datarray['edit'] = true;
649 // If this was a share, add missing data here
650 $datarray = Item::addShareDataFromOriginal($datarray);
652 $datarray['edit'] = false;
655 // Check for hashtags in the body and repair or add hashtag links
656 if ($preview || $orig_post) {
657 Item::setHashtags($datarray);
660 // preview mode - prepare the body for display and send it via json
662 // We set the datarray ID to -1 because in preview mode the dataray
663 // doesn't have an ID.
664 $datarray["id"] = -1;
665 $datarray["item_id"] = -1;
666 $datarray["author-network"] = Protocol::DFRN;
668 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager(DI::args()->getQueryString()), 'search', false, true);
669 Logger::log('preview: ' . $o);
670 echo json_encode(['preview' => $o]);
674 Hook::callAll('post_local',$datarray);
676 if (!empty($datarray['cancel'])) {
677 Logger::log('mod_item: post cancelled by addon.');
679 DI::baseUrl()->redirect($return_path);
682 $json = ['cancel' => 1];
683 if (!empty($_REQUEST['jsreload'])) {
684 $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
687 echo json_encode($json);
692 // Fill the cache field
693 // This could be done in Item::update as well - but we have to check for the existance of some fields.
694 Item::putInCache($datarray);
697 'title' => $datarray['title'],
698 'body' => $datarray['body'],
699 'tag' => $datarray['tag'],
700 'attach' => $datarray['attach'],
701 'file' => $datarray['file'],
702 'rendered-html' => $datarray['rendered-html'],
703 'rendered-hash' => $datarray['rendered-hash'],
704 'edited' => DateTimeFormat::utcNow(),
705 'changed' => DateTimeFormat::utcNow()];
707 Item::update($fields, ['id' => $post_id]);
709 // update filetags in pconfig
710 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
712 if (!empty($_REQUEST['return']) && strlen($return_path)) {
713 Logger::log('return: ' . $return_path);
714 DI::baseUrl()->redirect($return_path);
719 unset($datarray['edit']);
720 unset($datarray['self']);
721 unset($datarray['api_source']);
724 $signed = Diaspora::createCommentSignature($uid, $datarray);
725 if (!empty($signed)) {
726 $datarray['diaspora_signed_text'] = json_encode($signed);
730 $post_id = Item::insert($datarray);
733 Logger::log("Item wasn't stored.");
734 DI::baseUrl()->redirect($return_path);
737 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
739 if (!DBA::isResult($datarray)) {
740 Logger::log("Item with id ".$post_id." couldn't be fetched.");
741 DI::baseUrl()->redirect($return_path);
744 // update filetags in pconfig
745 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
747 // These notifications are sent if someone else is commenting other your wall
748 if ($toplevel_item_id) {
749 if ($contact_record != $author) {
751 'type' => NOTIFY_COMMENT,
752 'notify_flags' => $user['notify-flags'],
753 'language' => $user['language'],
754 'to_name' => $user['username'],
755 'to_email' => $user['email'],
756 'uid' => $user['uid'],
758 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
759 'source_name' => $datarray['author-name'],
760 'source_link' => $datarray['author-link'],
761 'source_photo' => $datarray['author-avatar'],
762 'verb' => Activity::POST,
764 'parent' => $toplevel_item_id,
765 'parent_uri' => $toplevel_item['uri']
769 if (($contact_record != $author) && !count($forum_contact)) {
771 'type' => NOTIFY_WALL,
772 'notify_flags' => $user['notify-flags'],
773 'language' => $user['language'],
774 'to_name' => $user['username'],
775 'to_email' => $user['email'],
776 'uid' => $user['uid'],
778 'link' => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
779 'source_name' => $datarray['author-name'],
780 'source_link' => $datarray['author-link'],
781 'source_photo' => $datarray['author-avatar'],
782 'verb' => Activity::POST,
788 Hook::callAll('post_local_end', $datarray);
790 if (strlen($emailcc) && $profile_uid == local_user()) {
791 $erecips = explode(',', $emailcc);
792 if (count($erecips)) {
793 foreach ($erecips as $recip) {
794 $addr = trim($recip);
795 if (!strlen($addr)) {
798 $disclaimer = '<hr />' . DI::l10n()->t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
800 $disclaimer .= DI::l10n()->t('You may visit them online at %s', DI::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
801 $disclaimer .= DI::l10n()->t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
802 if (!$datarray['title']=='') {
803 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
805 $subject = Email::encodeHeader('[Friendica]' . ' ' . DI::l10n()->t('%s posted an update.', $a->user['username']), 'UTF-8');
807 $link = '<a href="' . DI::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
808 $html = Item::prepareBody($datarray);
809 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
811 'fromName' => $a->user['username'],
812 'fromEmail' => $a->user['email'],
814 'replyTo' => $a->user['email'],
815 'messageSubject' => $subject,
816 'htmlVersion' => $message,
817 'textVersion' => HTML::toPlaintext($html.$disclaimer)
819 Emailer::send($params);
824 // Insert an item entry for UID=0 for global entries.
825 // We now do it in the background to save some time.
826 // This is important in interactive environments like the frontend or the API.
827 // We don't fork a new process since this is done anyway with the following command
828 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
830 // When we are doing some forum posting via ! we have to start the notifier manually.
831 // These kind of posts don't initiate the notifier call in the item class.
832 if ($only_to_forum) {
833 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
836 Logger::log('post_complete');
842 item_post_return(DI::baseUrl(), $api_source, $return_path);
846 function item_post_return($baseurl, $api_source, $return_path)
848 // figure out how to return, depending on from whence we came
856 DI::baseUrl()->redirect($return_path);
859 $json = ['success' => 1];
860 if (!empty($_REQUEST['jsreload'])) {
861 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
864 Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
866 echo json_encode($json);
870 function item_content(App $a)
872 if (!Session::isAuthenticated()) {
878 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
879 if (DI::mode()->isAjax()) {
880 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
882 if (!empty($a->argv[3])) {
883 $o = drop_item($a->argv[2], $a->argv[3]);
886 $o = drop_item($a->argv[2]);
890 if (DI::mode()->isAjax()) {
891 // ajax return: [<item id>, 0 (no perm) | <owner id>]
892 echo json_encode([intval($a->argv[2]), intval($o)]);
901 * This function removes the tag $tag from the text $body and replaces it with
902 * the appropriate link.
905 * @param string $body the text to replace the tag in
906 * @param string $inform a comma-seperated string containing everybody to inform
907 * @param string $str_tags string to add the tag to
908 * @param integer $profile_uid
909 * @param string $tag the tag to replace
910 * @param string $network The network of the post
912 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
913 * @throws ImagickException
914 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
916 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
921 //is it a person tag?
922 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
923 $tag_type = substr($tag, 0, 1);
924 //is it already replaced?
925 if (strpos($tag, '[url=')) {
926 //append tag to str_tags
927 if (!stristr($str_tags, $tag)) {
928 if (strlen($str_tags)) {
934 // Checking for the alias that is used for OStatus
935 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
936 if (preg_match($pattern, $tag, $matches)) {
937 $data = Contact::getDetailsByURL($matches[1]);
939 if ($data["alias"] != "") {
940 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
942 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
943 if (strlen($str_tags)) {
947 $str_tags .= $newtag;
955 //get the person's name
956 $name = substr($tag, 1);
958 // Sometimes the tag detection doesn't seem to work right
959 // This is some workaround
960 $nameparts = explode(" ", $name);
961 $name = $nameparts[0];
963 // Try to detect the contact in various ways
964 if (strpos($name, 'http://')) {
965 // At first we have to ensure that the contact exists
966 Contact::getIdForURL($name);
968 // Now we should have something
969 $contact = Contact::getDetailsByURL($name);
970 } elseif (strpos($name, '@')) {
971 // This function automatically probes when no entry was found
972 $contact = Contact::getDetailsByAddr($name);
975 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
977 if (strrpos($name, '+')) {
978 // Is it in format @nick+number?
979 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
980 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
983 // select someone by nick or attag in the current network
984 if (!DBA::isResult($contact) && ($network != "")) {
985 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
986 $name, $name, $network, $profile_uid];
987 $contact = DBA::selectFirst('contact', $fields, $condition);
990 //select someone by name in the current network
991 if (!DBA::isResult($contact) && ($network != "")) {
992 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
993 $contact = DBA::selectFirst('contact', $fields, $condition);
996 // select someone by nick or attag in any network
997 if (!DBA::isResult($contact)) {
998 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
999 $contact = DBA::selectFirst('contact', $fields, $condition);
1002 // select someone by name in any network
1003 if (!DBA::isResult($contact)) {
1004 $condition = ['name' => $name, 'uid' => $profile_uid];
1005 $contact = DBA::selectFirst('contact', $fields, $condition);
1009 // Check if $contact has been successfully loaded
1010 if (DBA::isResult($contact)) {
1011 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1015 if (isset($contact["id"])) {
1016 $inform .= 'cid:' . $contact["id"];
1017 } elseif (isset($contact["notify"])) {
1018 $inform .= $contact["notify"];
1021 $profile = $contact["url"];
1022 $alias = $contact["alias"];
1023 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1026 //if there is an url for this persons profile
1027 if (isset($profile) && ($newname != "")) {
1029 // create profile link
1030 $profile = str_replace(',', '%2c', $profile);
1031 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1032 $body = str_replace($tag_type . $name, $newtag, $body);
1033 // append tag to str_tags
1034 if (!stristr($str_tags, $newtag)) {
1035 if (strlen($str_tags)) {
1038 $str_tags .= $newtag;
1042 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1043 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1045 if (!empty($alias)) {
1046 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1047 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1048 if (strlen($str_tags)) {
1051 $str_tags .= $newtag;
1057 return ['replaced' => $replaced, 'contact' => $contact];
1060 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1062 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1063 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1064 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1065 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1066 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1071 $implicit_mentions = [
1072 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1075 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1077 foreach ($parent_terms as $parent_term) {
1078 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1081 foreach ($implicit_mentions as $url => $label) {
1082 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1083 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';