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\BaseObject;
20 use Friendica\Content\Pager;
21 use Friendica\Content\Text\BBCode;
22 use Friendica\Content\Text\HTML;
23 use Friendica\Core\Config;
24 use Friendica\Core\Hook;
25 use Friendica\Core\L10n;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\Session;
29 use Friendica\Core\System;
30 use Friendica\Core\Worker;
31 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\ACLFormatter;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Emailer;
45 use Friendica\Util\Security;
46 use Friendica\Util\Strings;
47 use Friendica\Worker\Delivery;
49 require_once __DIR__ . '/../include/items.php';
51 function item_post(App $a) {
52 if (!Session::isAuthenticated()) {
58 if (!empty($_REQUEST['dropitems'])) {
59 $arr_drop = explode(',', $_REQUEST['dropitems']);
60 drop_items($arr_drop);
61 $json = ['success' => 1];
62 echo json_encode($json);
66 Hook::callAll('post_local_start', $_REQUEST);
68 Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
70 $api_source = $_REQUEST['api_source'] ?? false;
72 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
74 $return_path = $_REQUEST['return'] ?? '';
75 $preview = intval($_REQUEST['preview'] ?? 0);
78 * Check for doubly-submitted posts, and reject duplicates
79 * Note that we have to ignore previews, otherwise nothing will post
80 * after it's been previewed
82 if (!$preview && !empty($_REQUEST['post_id_random'])) {
83 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
84 Logger::log("item post: duplicate post", Logger::DEBUG);
85 item_post_return(System::baseUrl(), $api_source, $return_path);
87 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
91 // Is this a reply to something?
92 $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
93 $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
95 $thread_parent_id = 0;
96 $thread_parent_contact = null;
98 $toplevel_item = null;
101 $parent_contact = null;
104 $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
105 $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
107 if ($toplevel_item_id || $thr_parent_uri) {
108 if ($toplevel_item_id) {
109 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
110 } elseif ($thr_parent_uri) {
111 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
114 // if this isn't the top-level parent of the conversation, find it
115 if (DBA::isResult($toplevel_item)) {
116 // The URI and the contact is taken from the direct parent which needn't to be the top parent
117 $thread_parent_id = $toplevel_item['id'];
118 $thr_parent_uri = $toplevel_item['uri'];
119 $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
121 if ($toplevel_item['id'] != $toplevel_item['parent']) {
122 $toplevel_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
126 if (!DBA::isResult($toplevel_item)) {
127 notice(L10n::t('Unable to locate original post.') . EOL);
128 if (!empty($_REQUEST['return'])) {
129 $a->internalRedirect($return_path);
134 $toplevel_item_id = $toplevel_item['id'];
135 $parent_user = $toplevel_item['uid'];
137 $objecttype = Activity\ObjectType::COMMENT;
140 if ($toplevel_item_id) {
141 Logger::info('mod_item: item_post parent=' . $toplevel_item_id);
144 $post_id = intval($_REQUEST['post_id'] ?? 0);
145 $app = strip_tags($_REQUEST['source'] ?? '');
146 $extid = strip_tags($_REQUEST['extid'] ?? '');
147 $object = $_REQUEST['object'] ?? '';
149 // Don't use "defaults" here. It would turn 0 to 1
150 if (!isset($_REQUEST['wall'])) {
153 $wall = $_REQUEST['wall'];
156 // Ensure that the user id in a thread always stay the same
157 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
158 $profile_uid = $parent_user;
161 // Check for multiple posts with the same message id (when the post was created via API)
162 if (($message_id != '') && ($profile_uid != 0)) {
163 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
164 Logger::log("Message with URI ".$message_id." already exists for user ".$profile_uid, Logger::DEBUG);
169 // Allow commenting if it is an answer to a public post
170 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
172 // Now check that valid personal details have been provided
173 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
174 notice(L10n::t('Permission denied.') . EOL);
176 if (!empty($_REQUEST['return'])) {
177 $a->internalRedirect($return_path);
183 // Init post instance
186 // is this an edited post?
188 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
191 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
193 if (!DBA::isResult($user) && !$toplevel_item_id) {
200 $body = $_REQUEST['body'] ?? '';
201 $has_attachment = $_REQUEST['has_attachment'] ?? 0;
203 // If we have a speparate attachment, we need to add it to the body.
204 if (!empty($has_attachment)) {
205 $attachment_type = $_REQUEST['attachment_type'] ?? '';
206 $attachment_title = $_REQUEST['attachment_title'] ?? '';
207 $attachment_text = $_REQUEST['attachment_text'] ?? '';
209 $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? '');
210 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
212 $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0;
213 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
215 'type' => $attachment_type,
216 'title' => $attachment_title,
217 'text' => $attachment_text,
218 'url' => $attachment_url,
221 if (!empty($attachment_img_src)) {
222 $attachment['images'] = [
224 'src' => $attachment_img_src,
225 'width' => $attachment_img_width,
226 'height' => $attachment_img_height
231 $att_bbcode = add_page_info_data($attachment);
232 $body .= $att_bbcode;
235 // Convert links with empty descriptions to links without an explicit description
236 $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
238 if (!empty($orig_post)) {
239 $str_group_allow = $orig_post['allow_gid'];
240 $str_contact_allow = $orig_post['allow_cid'];
241 $str_group_deny = $orig_post['deny_gid'];
242 $str_contact_deny = $orig_post['deny_cid'];
243 $location = $orig_post['location'];
244 $coord = $orig_post['coord'];
245 $verb = $orig_post['verb'];
246 $objecttype = $orig_post['object-type'];
247 $app = $orig_post['app'];
248 $categories = $orig_post['file'];
249 $title = Strings::escapeTags(trim($_REQUEST['title']));
250 $body = Strings::escapeHtml(trim($body));
251 $private = $orig_post['private'];
252 $pubmail_enabled = $orig_post['pubmail'];
253 $network = $orig_post['network'];
254 $guid = $orig_post['guid'];
255 $extid = $orig_post['extid'];
260 * if coming from the API and no privacy settings are set,
261 * use the user default permissions - as they won't have
262 * been supplied via a form.
265 && !array_key_exists('contact_allow', $_REQUEST)
266 && !array_key_exists('group_allow', $_REQUEST)
267 && !array_key_exists('contact_deny', $_REQUEST)
268 && !array_key_exists('group_deny', $_REQUEST)) {
269 $str_group_allow = $user['allow_gid'];
270 $str_contact_allow = $user['allow_cid'];
271 $str_group_deny = $user['deny_gid'];
272 $str_contact_deny = $user['deny_cid'];
274 // use the posted permissions
276 /** @var ACLFormatter $aclFormatter */
277 $aclFormatter = BaseObject::getClass(ACLFormatter::class);
279 $str_group_allow = $aclFormatter->toString($_REQUEST['group_allow'] ?? '');
280 $str_contact_allow = $aclFormatter->toString($_REQUEST['contact_allow'] ?? '');
281 $str_group_deny = $aclFormatter->toString($_REQUEST['group_deny'] ?? '');
282 $str_contact_deny = $aclFormatter->toString($_REQUEST['contact_deny'] ?? '');
285 $title = Strings::escapeTags(trim($_REQUEST['title'] ?? ''));
286 $location = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
287 $coord = Strings::escapeTags(trim($_REQUEST['coord'] ?? ''));
288 $verb = Strings::escapeTags(trim($_REQUEST['verb'] ?? ''));
289 $emailcc = Strings::escapeTags(trim($_REQUEST['emailcc'] ?? ''));
290 $body = Strings::escapeHtml(trim($body));
291 $network = Strings::escapeTags(trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN));
292 $guid = System::createUUID();
294 $postopts = $_REQUEST['postopts'] ?? '';
296 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
298 // If this is a comment, set the permissions from the parent.
300 if ($toplevel_item) {
301 // for non native networks use the network of the original post as network of the item
302 if (($toplevel_item['network'] != Protocol::DIASPORA)
303 && ($toplevel_item['network'] != Protocol::OSTATUS)
304 && ($network == "")) {
305 $network = $toplevel_item['network'];
308 $str_contact_allow = $toplevel_item['allow_cid'];
309 $str_group_allow = $toplevel_item['allow_gid'];
310 $str_contact_deny = $toplevel_item['deny_cid'];
311 $str_group_deny = $toplevel_item['deny_gid'];
312 $private = $toplevel_item['private'];
314 $wall = $toplevel_item['wall'];
317 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
319 // if using the API, we won't see pubmail_enable - figure out if it should be set
320 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
321 if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
322 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
326 if (!strlen($body)) {
330 info(L10n::t('Empty post discarded.') . EOL);
331 if (!empty($_REQUEST['return'])) {
332 $a->internalRedirect($return_path);
338 if (!empty($categories)) {
339 // get the "fileas" tags for this post
340 $filedas = FileTag::fileToArray($categories);
343 // save old and new categories, so we can determine what needs to be deleted from pconfig
344 $categories_old = $categories;
345 $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
346 $categories_new = $categories;
348 if (!empty($filedas) && is_array($filedas)) {
349 // append the fileas stuff to the new categories list
350 $categories .= FileTag::arrayToFile($filedas);
353 // get contact info for poster
359 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
361 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
362 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
363 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
366 if (DBA::isResult($author)) {
367 $contact_id = $author['id'];
370 // get contact info for owner
371 if ($profile_uid == local_user() || $allow_comment) {
372 $contact_record = $author;
374 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
377 // Look for any tags and linkify them
381 $tags = BBCode::getTags($body);
383 if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
384 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
389 $private_forum = false;
390 $only_to_forum = false;
394 foreach ($tags as $tag) {
395 $tag_type = substr($tag, 0, 1);
397 if ($tag_type == Term::TAG_CHARACTER[Term::HASHTAG]) {
402 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
403 * Robert Johnson should be first in the $tags array
405 $fullnametagged = false;
406 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
407 foreach ($tagged as $nextTag) {
408 if (stristr($nextTag, $tag . ' ')) {
409 $fullnametagged = true;
413 if ($fullnametagged) {
417 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
418 if ($success['replaced']) {
421 // When the forum is private or the forum is addressed with a "!" make the post private
422 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
423 $private_forum = $success['contact']['prv'];
424 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
425 $private_id = $success['contact']['id'];
426 $forum_contact = $success['contact'];
427 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
428 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
429 $private_forum = false;
430 $only_to_forum = true;
431 $private_id = $success['contact']['id'];
432 $forum_contact = $success['contact'];
437 $original_contact_id = $contact_id;
439 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
440 // we tagged a forum in a top level post. Now we change the post
441 $private = $private_forum;
443 $str_group_allow = '';
444 $str_contact_deny = '';
445 $str_group_deny = '';
446 if ($private_forum) {
447 $str_contact_allow = '<' . $private_id . '>';
449 $str_contact_allow = '';
451 $contact_id = $private_id;
452 $contact_record = $forum_contact;
453 $_REQUEST['origin'] = false;
458 * When a photo was uploaded into the message using the (profile wall) ajax
459 * uploader, The permissions are initially set to disallow anybody but the
460 * owner from seeing it. This is because the permissions may not yet have been
461 * set for the post. If it's private, the photo permissions should be set
462 * appropriately. But we didn't know the final permissions on the post until
463 * now. So now we'll look for links of uploaded messages that are in the
464 * post and set them to the same permissions as the post itself.
469 if (!$preview && Photo::setPermissionFromBody($body, $profile_uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
470 $objecttype = Activity\ObjectType::IMAGE;
474 * Next link in any attachment references we find in the post.
478 /// @todo these lines should be moved to Model/Attach (Once it exists)
479 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
480 $attaches = $match[1];
481 if (count($attaches)) {
482 foreach ($attaches as $attach) {
483 // Ensure to only modify attachments that you own
484 $srch = '<' . intval($original_contact_id) . '>';
486 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
488 if (!Attach::exists($condition)) {
492 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
493 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
494 $condition = ['id' => $attach];
495 Attach::update($fields, $condition);
500 // embedded bookmark or attachment in post? set bookmark flag
502 $data = BBCode::getAttachmentData($body);
503 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
504 && ($posttype != Item::PT_PERSONAL_NOTE)) {
505 $posttype = Item::PT_PAGE;
506 $objecttype = Activity\ObjectType::BOOKMARK;
509 /** @var BBCode\Video $bbCodeVideo */
510 $bbCodeVideo = BaseObject::getClass(BBCode\Video::class);
511 $body = $bbCodeVideo->transform($body);
513 // Fold multi-line [code] sequences
514 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
516 $body = BBCode::scaleExternalImages($body, false);
518 // Setting the object type if not defined before
520 $objecttype = Activity\ObjectType::NOTE; // Default value
521 $objectdata = BBCode::getAttachedData($body);
523 if ($objectdata["type"] == "link") {
524 $objecttype = Activity\ObjectType::BOOKMARK;
525 } elseif ($objectdata["type"] == "video") {
526 $objecttype = Activity\ObjectType::VIDEO;
527 } elseif ($objectdata["type"] == "photo") {
528 $objecttype = Activity\ObjectType::IMAGE;
536 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
537 foreach ($match[2] as $mtch) {
538 $fields = ['id', 'filename', 'filesize', 'filetype'];
539 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
540 if ($attachment !== false) {
541 if (strlen($attachments)) {
544 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
545 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
546 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
548 $body = str_replace($match[1],'',$body);
552 if (!strlen($verb)) {
553 $verb = Activity::POST;
556 if ($network == "") {
557 $network = Protocol::DFRN;
560 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
562 // even if the post arrived via API we are considering that it
563 // originated on this site by default for determining relayability.
565 // Don't use "defaults" here. It would turn 0 to 1
566 if (!isset($_REQUEST['origin'])) {
569 $origin = $_REQUEST['origin'];
572 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
574 // Fallback so that we alway have a parent uri
575 if (!$thr_parent_uri || !$toplevel_item_id) {
576 $thr_parent_uri = $uri;
580 $datarray['uid'] = $profile_uid;
581 $datarray['wall'] = $wall;
582 $datarray['gravity'] = $gravity;
583 $datarray['network'] = $network;
584 $datarray['contact-id'] = $contact_id;
585 $datarray['owner-name'] = $contact_record['name'];
586 $datarray['owner-link'] = $contact_record['url'];
587 $datarray['owner-avatar'] = $contact_record['thumb'];
588 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
589 $datarray['author-name'] = $author['name'];
590 $datarray['author-link'] = $author['url'];
591 $datarray['author-avatar'] = $author['thumb'];
592 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
593 $datarray['created'] = DateTimeFormat::utcNow();
594 $datarray['edited'] = DateTimeFormat::utcNow();
595 $datarray['commented'] = DateTimeFormat::utcNow();
596 $datarray['received'] = DateTimeFormat::utcNow();
597 $datarray['changed'] = DateTimeFormat::utcNow();
598 $datarray['extid'] = $extid;
599 $datarray['guid'] = $guid;
600 $datarray['uri'] = $uri;
601 $datarray['title'] = $title;
602 $datarray['body'] = $body;
603 $datarray['app'] = $app;
604 $datarray['location'] = $location;
605 $datarray['coord'] = $coord;
606 $datarray['tag'] = $str_tags;
607 $datarray['file'] = $categories;
608 $datarray['inform'] = $inform;
609 $datarray['verb'] = $verb;
610 $datarray['post-type'] = $posttype;
611 $datarray['object-type'] = $objecttype;
612 $datarray['allow_cid'] = $str_contact_allow;
613 $datarray['allow_gid'] = $str_group_allow;
614 $datarray['deny_cid'] = $str_contact_deny;
615 $datarray['deny_gid'] = $str_group_deny;
616 $datarray['private'] = $private;
617 $datarray['pubmail'] = $pubmail_enabled;
618 $datarray['attach'] = $attachments;
620 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
621 $datarray['parent-uri'] = $thr_parent_uri;
623 $datarray['postopts'] = $postopts;
624 $datarray['origin'] = $origin;
625 $datarray['moderated'] = false;
626 $datarray['object'] = $object;
629 * These fields are for the convenience of addons...
630 * 'self' if true indicates the owner is posting on their own wall
631 * If parent is 0 it is a top-level post.
633 $datarray['parent'] = $toplevel_item_id;
634 $datarray['self'] = $self;
636 // This triggers posts via API and the mirror functions
637 $datarray['api_source'] = $api_source;
639 // This field is for storing the raw conversation data
640 $datarray['protocol'] = Conversation::PARCEL_DFRN;
642 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
643 if (DBA::isResult($conversation)) {
644 if ($conversation['conversation-uri'] != '') {
645 $datarray['conversation-uri'] = $conversation['conversation-uri'];
647 if ($conversation['conversation-href'] != '') {
648 $datarray['conversation-href'] = $conversation['conversation-href'];
653 $datarray['edit'] = true;
655 // If this was a share, add missing data here
656 $datarray = Item::addShareDataFromOriginal($datarray);
658 $datarray['edit'] = false;
661 // Check for hashtags in the body and repair or add hashtag links
662 if ($preview || $orig_post) {
663 Item::setHashtags($datarray);
666 // preview mode - prepare the body for display and send it via json
668 // We set the datarray ID to -1 because in preview mode the dataray
669 // doesn't have an ID.
670 $datarray["id"] = -1;
671 $datarray["item_id"] = -1;
672 $datarray["author-network"] = Protocol::DFRN;
674 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
675 Logger::log('preview: ' . $o);
676 echo json_encode(['preview' => $o]);
680 Hook::callAll('post_local',$datarray);
682 if (!empty($datarray['cancel'])) {
683 Logger::log('mod_item: post cancelled by addon.');
685 $a->internalRedirect($return_path);
688 $json = ['cancel' => 1];
689 if (!empty($_REQUEST['jsreload'])) {
690 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
693 echo json_encode($json);
698 // Fill the cache field
699 // This could be done in Item::update as well - but we have to check for the existance of some fields.
700 Item::putInCache($datarray);
703 'title' => $datarray['title'],
704 'body' => $datarray['body'],
705 'tag' => $datarray['tag'],
706 'attach' => $datarray['attach'],
707 'file' => $datarray['file'],
708 'rendered-html' => $datarray['rendered-html'],
709 'rendered-hash' => $datarray['rendered-hash'],
710 'edited' => DateTimeFormat::utcNow(),
711 'changed' => DateTimeFormat::utcNow()];
713 Item::update($fields, ['id' => $post_id]);
715 // update filetags in pconfig
716 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
718 if (!empty($_REQUEST['return']) && strlen($return_path)) {
719 Logger::log('return: ' . $return_path);
720 $a->internalRedirect($return_path);
725 unset($datarray['edit']);
726 unset($datarray['self']);
727 unset($datarray['api_source']);
730 $signed = Diaspora::createCommentSignature($uid, $datarray);
731 if (!empty($signed)) {
732 $datarray['diaspora_signed_text'] = json_encode($signed);
736 $post_id = Item::insert($datarray);
739 Logger::log("Item wasn't stored.");
740 $a->internalRedirect($return_path);
743 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
745 if (!DBA::isResult($datarray)) {
746 Logger::log("Item with id ".$post_id." couldn't be fetched.");
747 $a->internalRedirect($return_path);
750 // update filetags in pconfig
751 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
753 // These notifications are sent if someone else is commenting other your wall
754 if ($toplevel_item_id) {
755 if ($contact_record != $author) {
757 'type' => NOTIFY_COMMENT,
758 'notify_flags' => $user['notify-flags'],
759 'language' => $user['language'],
760 'to_name' => $user['username'],
761 'to_email' => $user['email'],
762 'uid' => $user['uid'],
764 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
765 'source_name' => $datarray['author-name'],
766 'source_link' => $datarray['author-link'],
767 'source_photo' => $datarray['author-avatar'],
768 'verb' => Activity::POST,
770 'parent' => $toplevel_item_id,
771 'parent_uri' => $toplevel_item['uri']
775 if (($contact_record != $author) && !count($forum_contact)) {
777 'type' => NOTIFY_WALL,
778 'notify_flags' => $user['notify-flags'],
779 'language' => $user['language'],
780 'to_name' => $user['username'],
781 'to_email' => $user['email'],
782 'uid' => $user['uid'],
784 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
785 'source_name' => $datarray['author-name'],
786 'source_link' => $datarray['author-link'],
787 'source_photo' => $datarray['author-avatar'],
788 'verb' => Activity::POST,
794 Hook::callAll('post_local_end', $datarray);
796 if (strlen($emailcc) && $profile_uid == local_user()) {
797 $erecips = explode(',', $emailcc);
798 if (count($erecips)) {
799 foreach ($erecips as $recip) {
800 $addr = trim($recip);
801 if (!strlen($addr)) {
804 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
806 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
807 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
808 if (!$datarray['title']=='') {
809 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
811 $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
813 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
814 $html = Item::prepareBody($datarray);
815 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
817 'fromName' => $a->user['username'],
818 'fromEmail' => $a->user['email'],
820 'replyTo' => $a->user['email'],
821 'messageSubject' => $subject,
822 'htmlVersion' => $message,
823 'textVersion' => HTML::toPlaintext($html.$disclaimer)
825 Emailer::send($params);
830 // Insert an item entry for UID=0 for global entries.
831 // We now do it in the background to save some time.
832 // This is important in interactive environments like the frontend or the API.
833 // We don't fork a new process since this is done anyway with the following command
834 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
836 // When we are doing some forum posting via ! we have to start the notifier manually.
837 // These kind of posts don't initiate the notifier call in the item class.
838 if ($only_to_forum) {
839 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
842 Logger::log('post_complete');
848 item_post_return(System::baseUrl(), $api_source, $return_path);
852 function item_post_return($baseurl, $api_source, $return_path)
854 // figure out how to return, depending on from whence we came
862 $a->internalRedirect($return_path);
865 $json = ['success' => 1];
866 if (!empty($_REQUEST['jsreload'])) {
867 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
870 Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
872 echo json_encode($json);
876 function item_content(App $a)
878 if (!Session::isAuthenticated()) {
884 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
886 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
888 if (!empty($a->argv[3])) {
889 $o = drop_item($a->argv[2], $a->argv[3]);
892 $o = drop_item($a->argv[2]);
897 // ajax return: [<item id>, 0 (no perm) | <owner id>]
898 echo json_encode([intval($a->argv[2]), intval($o)]);
907 * This function removes the tag $tag from the text $body and replaces it with
908 * the appropriate link.
911 * @param string $body the text to replace the tag in
912 * @param string $inform a comma-seperated string containing everybody to inform
913 * @param string $str_tags string to add the tag to
914 * @param integer $profile_uid
915 * @param string $tag the tag to replace
916 * @param string $network The network of the post
918 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
919 * @throws ImagickException
920 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
922 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
927 //is it a person tag?
928 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
929 $tag_type = substr($tag, 0, 1);
930 //is it already replaced?
931 if (strpos($tag, '[url=')) {
932 //append tag to str_tags
933 if (!stristr($str_tags, $tag)) {
934 if (strlen($str_tags)) {
940 // Checking for the alias that is used for OStatus
941 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
942 if (preg_match($pattern, $tag, $matches)) {
943 $data = Contact::getDetailsByURL($matches[1]);
945 if ($data["alias"] != "") {
946 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
948 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
949 if (strlen($str_tags)) {
953 $str_tags .= $newtag;
961 //get the person's name
962 $name = substr($tag, 1);
964 // Sometimes the tag detection doesn't seem to work right
965 // This is some workaround
966 $nameparts = explode(" ", $name);
967 $name = $nameparts[0];
969 // Try to detect the contact in various ways
970 if (strpos($name, 'http://')) {
971 // At first we have to ensure that the contact exists
972 Contact::getIdForURL($name);
974 // Now we should have something
975 $contact = Contact::getDetailsByURL($name);
976 } elseif (strpos($name, '@')) {
977 // This function automatically probes when no entry was found
978 $contact = Contact::getDetailsByAddr($name);
981 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
983 if (strrpos($name, '+')) {
984 // Is it in format @nick+number?
985 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
986 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
989 // select someone by nick or attag in the current network
990 if (!DBA::isResult($contact) && ($network != "")) {
991 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
992 $name, $name, $network, $profile_uid];
993 $contact = DBA::selectFirst('contact', $fields, $condition);
996 //select someone by name in the current network
997 if (!DBA::isResult($contact) && ($network != "")) {
998 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
999 $contact = DBA::selectFirst('contact', $fields, $condition);
1002 // select someone by nick or attag in any network
1003 if (!DBA::isResult($contact)) {
1004 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
1005 $contact = DBA::selectFirst('contact', $fields, $condition);
1008 // select someone by name in any network
1009 if (!DBA::isResult($contact)) {
1010 $condition = ['name' => $name, 'uid' => $profile_uid];
1011 $contact = DBA::selectFirst('contact', $fields, $condition);
1015 // Check if $contact has been successfully loaded
1016 if (DBA::isResult($contact)) {
1017 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1021 if (isset($contact["id"])) {
1022 $inform .= 'cid:' . $contact["id"];
1023 } elseif (isset($contact["notify"])) {
1024 $inform .= $contact["notify"];
1027 $profile = $contact["url"];
1028 $alias = $contact["alias"];
1029 $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1032 //if there is an url for this persons profile
1033 if (isset($profile) && ($newname != "")) {
1035 // create profile link
1036 $profile = str_replace(',', '%2c', $profile);
1037 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1038 $body = str_replace($tag_type . $name, $newtag, $body);
1039 // append tag to str_tags
1040 if (!stristr($str_tags, $newtag)) {
1041 if (strlen($str_tags)) {
1044 $str_tags .= $newtag;
1048 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1049 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1051 if (!empty($alias)) {
1052 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1053 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1054 if (strlen($str_tags)) {
1057 $str_tags .= $newtag;
1063 return ['replaced' => $replaced, 'contact' => $contact];
1066 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1068 if (Config::get('system', 'disable_implicit_mentions')) {
1069 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1070 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1071 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1072 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1077 $implicit_mentions = [
1078 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1081 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1083 foreach ($parent_terms as $parent_term) {
1084 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1087 foreach ($implicit_mentions as $url => $label) {
1088 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1089 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';