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\System;
28 use Friendica\Core\Worker;
29 use Friendica\Database\DBA;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Conversation;
32 use Friendica\Model\FileTag;
33 use Friendica\Model\Item;
34 use Friendica\Model\Photo;
35 use Friendica\Model\Attach;
36 use Friendica\Protocol\Diaspora;
37 use Friendica\Protocol\Email;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Emailer;
40 use Friendica\Util\Security;
41 use Friendica\Util\Strings;
43 require_once 'include/items.php';
45 function item_post(App $a) {
46 if (!local_user() && !remote_user()) {
52 if (!empty($_REQUEST['dropitems'])) {
53 $arr_drop = explode(',', $_REQUEST['dropitems']);
54 drop_items($arr_drop);
55 $json = ['success' => 1];
56 echo json_encode($json);
60 Hook::callAll('post_local_start', $_REQUEST);
62 Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
64 $api_source = defaults($_REQUEST, 'api_source', false);
66 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
68 $return_path = defaults($_REQUEST, 'return', '');
69 $preview = intval(defaults($_REQUEST, 'preview', 0));
72 * Check for doubly-submitted posts, and reject duplicates
73 * Note that we have to ignore previews, otherwise nothing will post
74 * after it's been previewed
76 if (!$preview && !empty($_REQUEST['post_id_random'])) {
77 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
78 Logger::log("item post: duplicate post", Logger::DEBUG);
79 item_post_return(System::baseUrl(), $api_source, $return_path);
81 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
85 // Is this a reply to something?
86 $thr_parent = intval(defaults($_REQUEST, 'parent', 0));
87 $thr_parent_uri = trim(defaults($_REQUEST, 'parent_uri', ''));
89 $thr_parent_contact = null;
95 $parent_contact = null;
98 $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
99 $posttype = defaults($_REQUEST, 'post_type', Item::PT_ARTICLE);
101 if ($thr_parent || $thr_parent_uri) {
103 $parent_item = Item::selectFirst([], ['id' => $thr_parent]);
104 } elseif ($thr_parent_uri) {
105 $parent_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
108 // if this isn't the real parent of the conversation, find it
109 if (DBA::isResult($parent_item)) {
110 // The URI and the contact is taken from the direct parent which needn't to be the top parent
111 $thr_parent_uri = $parent_item['uri'];
112 $thr_parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
114 if ($parent_item['id'] != $parent_item['parent']) {
115 $parent_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item['parent']]);
119 if (!DBA::isResult($parent_item)) {
120 notice(L10n::t('Unable to locate original post.') . EOL);
121 if (!empty($_REQUEST['return'])) {
122 $a->internalRedirect($return_path);
127 $parent = $parent_item['id'];
128 $parent_user = $parent_item['uid'];
130 $objecttype = ACTIVITY_OBJ_COMMENT;
134 Logger::log('mod_item: item_post parent=' . $parent);
137 $post_id = intval(defaults($_REQUEST, 'post_id', 0));
138 $app = strip_tags(defaults($_REQUEST, 'source', ''));
139 $extid = strip_tags(defaults($_REQUEST, 'extid', ''));
140 $object = defaults($_REQUEST, 'object', '');
142 // Don't use "defaults" here. It would turn 0 to 1
143 if (!isset($_REQUEST['wall'])) {
146 $wall = $_REQUEST['wall'];
149 // Ensure that the user id in a thread always stay the same
150 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
151 $profile_uid = $parent_user;
154 // Check for multiple posts with the same message id (when the post was created via API)
155 if (($message_id != '') && ($profile_uid != 0)) {
156 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
157 Logger::log("Message with URI ".$message_id." already exists for user ".$profile_uid, Logger::DEBUG);
162 // Allow commenting if it is an answer to a public post
163 $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
165 // Now check that valid personal details have been provided
166 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
167 notice(L10n::t('Permission denied.') . EOL);
169 if (!empty($_REQUEST['return'])) {
170 $a->internalRedirect($return_path);
176 // Init post instance
179 // is this an edited post?
181 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
184 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
186 if (!DBA::isResult($user) && !$parent) {
193 $body = defaults($_REQUEST, 'body', '');
194 $has_attachment = defaults($_REQUEST, 'has_attachment', 0);
196 // If we have a speparate attachment, we need to add it to the body.
197 if (!empty($has_attachment)) {
198 $attachment_type = defaults($_REQUEST, 'attachment_type', '');
199 $attachment_title = defaults($_REQUEST, 'attachment_title', '');
200 $attachment_text = defaults($_REQUEST, 'attachment_text', '');
202 $attachment_url = hex2bin(defaults($_REQUEST, 'attachment_url', ''));
203 $attachment_img_src = hex2bin(defaults($_REQUEST, 'attachment_img_src', ''));
205 $attachment_img_width = defaults($_REQUEST, 'attachment_img_width', 0);
206 $attachment_img_height = defaults($_REQUEST, 'attachment_img_height', 0);
208 'type' => $attachment_type,
209 'title' => $attachment_title,
210 'text' => $attachment_text,
211 'url' => $attachment_url,
214 if (!empty($attachment_img_src)) {
215 $attachment['images'] = [
217 'src' => $attachment_img_src,
218 'width' => $attachment_img_width,
219 'height' => $attachment_img_height
224 $att_bbcode = add_page_info_data($attachment);
225 $body .= $att_bbcode;
228 if (!empty($orig_post)) {
229 $str_group_allow = $orig_post['allow_gid'];
230 $str_contact_allow = $orig_post['allow_cid'];
231 $str_group_deny = $orig_post['deny_gid'];
232 $str_contact_deny = $orig_post['deny_cid'];
233 $location = $orig_post['location'];
234 $coord = $orig_post['coord'];
235 $verb = $orig_post['verb'];
236 $objecttype = $orig_post['object-type'];
237 $app = $orig_post['app'];
238 $categories = $orig_post['file'];
239 $title = Strings::escapeTags(trim($_REQUEST['title']));
240 $body = Strings::escapeHtml(trim($body));
241 $private = $orig_post['private'];
242 $pubmail_enabled = $orig_post['pubmail'];
243 $network = $orig_post['network'];
244 $guid = $orig_post['guid'];
245 $extid = $orig_post['extid'];
250 * if coming from the API and no privacy settings are set,
251 * use the user default permissions - as they won't have
252 * been supplied via a form.
255 && !array_key_exists('contact_allow', $_REQUEST)
256 && !array_key_exists('group_allow', $_REQUEST)
257 && !array_key_exists('contact_deny', $_REQUEST)
258 && !array_key_exists('group_deny', $_REQUEST)) {
259 $str_group_allow = $user['allow_gid'];
260 $str_contact_allow = $user['allow_cid'];
261 $str_group_deny = $user['deny_gid'];
262 $str_contact_deny = $user['deny_cid'];
264 // use the posted permissions
265 $str_group_allow = perms2str(defaults($_REQUEST, 'group_allow', ''));
266 $str_contact_allow = perms2str(defaults($_REQUEST, 'contact_allow', ''));
267 $str_group_deny = perms2str(defaults($_REQUEST, 'group_deny', ''));
268 $str_contact_deny = perms2str(defaults($_REQUEST, 'contact_deny', ''));
271 $title = Strings::escapeTags(trim(defaults($_REQUEST, 'title' , '')));
272 $location = Strings::escapeTags(trim(defaults($_REQUEST, 'location', '')));
273 $coord = Strings::escapeTags(trim(defaults($_REQUEST, 'coord' , '')));
274 $verb = Strings::escapeTags(trim(defaults($_REQUEST, 'verb' , '')));
275 $emailcc = Strings::escapeTags(trim(defaults($_REQUEST, 'emailcc' , '')));
276 $body = Strings::escapeHtml(trim($body));
277 $network = Strings::escapeTags(trim(defaults($_REQUEST, 'network' , Protocol::DFRN)));
278 $guid = System::createUUID();
280 $postopts = defaults($_REQUEST, 'postopts', '');
282 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
284 if ($user['hidewall']) {
288 // If this is a comment, set the permissions from the parent.
291 // for non native networks use the network of the original post as network of the item
292 if (($parent_item['network'] != Protocol::DIASPORA)
293 && ($parent_item['network'] != Protocol::OSTATUS)
294 && ($network == "")) {
295 $network = $parent_item['network'];
298 $str_contact_allow = $parent_item['allow_cid'];
299 $str_group_allow = $parent_item['allow_gid'];
300 $str_contact_deny = $parent_item['deny_cid'];
301 $str_group_deny = $parent_item['deny_gid'];
302 $private = $parent_item['private'];
304 $wall = $parent_item['wall'];
307 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
309 // if using the API, we won't see pubmail_enable - figure out if it should be set
310 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
311 if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
312 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
316 if (!strlen($body)) {
320 info(L10n::t('Empty post discarded.') . EOL);
321 if (!empty($_REQUEST['return'])) {
322 $a->internalRedirect($return_path);
328 if (!empty($categories))
330 // get the "fileas" tags for this post
331 $filedas = FileTag::fileToList($categories, 'file');
334 // save old and new categories, so we can determine what needs to be deleted from pconfig
335 $categories_old = $categories;
336 $categories = FileTag::listToFile(trim(defaults($_REQUEST, 'category', '')), 'category');
337 $categories_new = $categories;
339 if (!empty($filedas))
341 // append the fileas stuff to the new categories list
342 $categories .= FileTag::listToFile($filedas, 'file');
345 // get contact info for poster
351 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
353 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
354 } elseif (remote_user()) {
355 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
356 foreach ($_SESSION['remote'] as $v) {
357 if ($v['uid'] == $profile_uid) {
358 $contact_id = $v['cid'];
364 $author = DBA::selectFirst('contact', [], ['id' => $contact_id]);
368 if (DBA::isResult($author)) {
369 $contact_id = $author['id'];
372 // get contact info for owner
373 if ($profile_uid == local_user() || $allow_comment) {
374 $contact_record = $author;
376 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
379 // Look for any tags and linkify them
383 $tags = BBCode::getTags($body);
385 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
386 if ($parent && in_array($thr_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
387 $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
388 if (!stripos(implode($tags), '[url=' . $thr_parent_contact['url'] . ']')) {
395 $private_forum = false;
396 $only_to_forum = false;
400 foreach ($tags as $tag) {
401 $tag_type = substr($tag, 0, 1);
403 if ($tag_type == '#') {
408 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
409 * Robert Johnson should be first in the $tags array
411 $fullnametagged = false;
412 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
413 foreach ($tagged as $nextTag) {
414 if (stristr($nextTag, $tag . ' ')) {
415 $fullnametagged = true;
419 if ($fullnametagged) {
423 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
424 if ($success['replaced']) {
427 // When the forum is private or the forum is addressed with a "!" make the post private
428 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == '!'))) {
429 $private_forum = $success['contact']['prv'];
430 $only_to_forum = ($tag_type == '!');
431 $private_id = $success['contact']['id'];
432 $forum_contact = $success['contact'];
433 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
434 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
435 $private_forum = false;
436 $only_to_forum = true;
437 $private_id = $success['contact']['id'];
438 $forum_contact = $success['contact'];
443 $original_contact_id = $contact_id;
445 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
446 // we tagged a forum in a top level post. Now we change the post
447 $private = $private_forum;
449 $str_group_allow = '';
450 $str_contact_deny = '';
451 $str_group_deny = '';
452 if ($private_forum) {
453 $str_contact_allow = '<' . $private_id . '>';
455 $str_contact_allow = '';
457 $contact_id = $private_id;
458 $contact_record = $forum_contact;
459 $_REQUEST['origin'] = false;
464 * When a photo was uploaded into the message using the (profile wall) ajax
465 * uploader, The permissions are initially set to disallow anybody but the
466 * owner from seeing it. This is because the permissions may not yet have been
467 * set for the post. If it's private, the photo permissions should be set
468 * appropriately. But we didn't know the final permissions on the post until
469 * now. So now we'll look for links of uploaded messages that are in the
470 * post and set them to the same permissions as the post itself.
475 /// @todo these lines should be moved to Model/Photo
476 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
478 if (count($images)) {
480 $objecttype = ACTIVITY_OBJ_IMAGE;
482 foreach ($images as $image) {
483 if (!stristr($image, System::baseUrl() . '/photo/')) {
486 $image_uri = substr($image,strrpos($image,'/') + 1);
487 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
488 if (!strlen($image_uri)) {
492 // Ensure to only modify photos that you own
493 $srch = '<' . intval($original_contact_id) . '>';
496 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
497 'resource-id' => $image_uri, 'uid' => $profile_uid
499 if (!Photo::exists($condition)) {
503 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
504 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
505 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid];
506 Photo::update($fields, $condition);
513 * Next link in any attachment references we find in the post.
517 /// @todo these lines should be moved to Model/Attach (Once it exists)
518 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
519 $attaches = $match[1];
520 if (count($attaches)) {
521 foreach ($attaches as $attach) {
522 // Ensure to only modify attachments that you own
523 $srch = '<' . intval($original_contact_id) . '>';
525 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
527 if (!Attach::exists($condition)) {
531 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
532 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
533 $condition = ['id' => $attach];
534 Attach::update($fields, $condition);
539 // embedded bookmark or attachment in post? set bookmark flag
541 $data = BBCode::getAttachmentData($body);
542 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
543 && ($posttype != Item::PT_PERSONAL_NOTE)) {
544 $posttype = Item::PT_PAGE;
545 $objecttype = ACTIVITY_OBJ_BOOKMARK;
548 $body = bb_translate_video($body);
551 // Fold multi-line [code] sequences
552 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
554 $body = BBCode::scaleExternalImages($body, false);
556 // Setting the object type if not defined before
558 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
559 $objectdata = BBCode::getAttachedData($body);
561 if ($objectdata["type"] == "link") {
562 $objecttype = ACTIVITY_OBJ_BOOKMARK;
563 } elseif ($objectdata["type"] == "video") {
564 $objecttype = ACTIVITY_OBJ_VIDEO;
565 } elseif ($objectdata["type"] == "photo") {
566 $objecttype = ACTIVITY_OBJ_IMAGE;
574 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
575 foreach ($match[2] as $mtch) {
576 $fields = ['id', 'filename', 'filesize', 'filetype'];
577 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
578 if ($attachment !== false) {
579 if (strlen($attachments)) {
582 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
583 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
584 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
586 $body = str_replace($match[1],'',$body);
590 if (!strlen($verb)) {
591 $verb = ACTIVITY_POST;
594 if ($network == "") {
595 $network = Protocol::DFRN;
598 $gravity = ($parent ? GRAVITY_COMMENT : GRAVITY_PARENT);
600 // even if the post arrived via API we are considering that it
601 // originated on this site by default for determining relayability.
603 // Don't use "defaults" here. It would turn 0 to 1
604 if (!isset($_REQUEST['origin'])) {
607 $origin = $_REQUEST['origin'];
610 $notify_type = ($parent ? 'comment-new' : 'wall-new');
612 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
614 // Fallback so that we alway have a parent uri
615 if (!$thr_parent_uri || !$parent) {
616 $thr_parent_uri = $uri;
620 $datarray['uid'] = $profile_uid;
621 $datarray['wall'] = $wall;
622 $datarray['gravity'] = $gravity;
623 $datarray['network'] = $network;
624 $datarray['contact-id'] = $contact_id;
625 $datarray['owner-name'] = $contact_record['name'];
626 $datarray['owner-link'] = $contact_record['url'];
627 $datarray['owner-avatar'] = $contact_record['thumb'];
628 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
629 $datarray['author-name'] = $author['name'];
630 $datarray['author-link'] = $author['url'];
631 $datarray['author-avatar'] = $author['thumb'];
632 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
633 $datarray['created'] = DateTimeFormat::utcNow();
634 $datarray['edited'] = DateTimeFormat::utcNow();
635 $datarray['commented'] = DateTimeFormat::utcNow();
636 $datarray['received'] = DateTimeFormat::utcNow();
637 $datarray['changed'] = DateTimeFormat::utcNow();
638 $datarray['extid'] = $extid;
639 $datarray['guid'] = $guid;
640 $datarray['uri'] = $uri;
641 $datarray['title'] = $title;
642 $datarray['body'] = $body;
643 $datarray['app'] = $app;
644 $datarray['location'] = $location;
645 $datarray['coord'] = $coord;
646 $datarray['tag'] = $str_tags;
647 $datarray['file'] = $categories;
648 $datarray['inform'] = $inform;
649 $datarray['verb'] = $verb;
650 $datarray['post-type'] = $posttype;
651 $datarray['object-type'] = $objecttype;
652 $datarray['allow_cid'] = $str_contact_allow;
653 $datarray['allow_gid'] = $str_group_allow;
654 $datarray['deny_cid'] = $str_contact_deny;
655 $datarray['deny_gid'] = $str_group_deny;
656 $datarray['private'] = $private;
657 $datarray['pubmail'] = $pubmail_enabled;
658 $datarray['attach'] = $attachments;
660 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
661 $datarray['parent-uri'] = $thr_parent_uri;
663 $datarray['postopts'] = $postopts;
664 $datarray['origin'] = $origin;
665 $datarray['moderated'] = false;
666 $datarray['object'] = $object;
669 * These fields are for the convenience of addons...
670 * 'self' if true indicates the owner is posting on their own wall
671 * If parent is 0 it is a top-level post.
673 $datarray['parent'] = $parent;
674 $datarray['self'] = $self;
676 // This triggers posts via API and the mirror functions
677 $datarray['api_source'] = $api_source;
679 // This field is for storing the raw conversation data
680 $datarray['protocol'] = Conversation::PARCEL_DFRN;
682 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
683 if (DBA::isResult($conversation)) {
684 if ($conversation['conversation-uri'] != '') {
685 $datarray['conversation-uri'] = $conversation['conversation-uri'];
687 if ($conversation['conversation-href'] != '') {
688 $datarray['conversation-href'] = $conversation['conversation-href'];
693 $datarray['edit'] = true;
695 $datarray['edit'] = false;
698 // Check for hashtags in the body and repair or add hashtag links
699 if ($preview || $orig_post) {
700 Item::setHashtags($datarray);
703 // preview mode - prepare the body for display and send it via json
705 // We set the datarray ID to -1 because in preview mode the dataray
706 // doesn't have an ID.
707 $datarray["id"] = -1;
708 $datarray["item_id"] = -1;
709 $datarray["author-network"] = Protocol::DFRN;
711 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
712 Logger::log('preview: ' . $o);
713 echo json_encode(['preview' => $o]);
717 Hook::callAll('post_local',$datarray);
719 if (!empty($datarray['cancel'])) {
720 Logger::log('mod_item: post cancelled by addon.');
722 $a->internalRedirect($return_path);
725 $json = ['cancel' => 1];
726 if (!empty($_REQUEST['jsreload'])) {
727 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
730 echo json_encode($json);
735 // Fill the cache field
736 // This could be done in Item::update as well - but we have to check for the existance of some fields.
737 Item::putInCache($datarray);
740 'title' => $datarray['title'],
741 'body' => $datarray['body'],
742 'tag' => $datarray['tag'],
743 'attach' => $datarray['attach'],
744 'file' => $datarray['file'],
745 'rendered-html' => $datarray['rendered-html'],
746 'rendered-hash' => $datarray['rendered-hash'],
747 'edited' => DateTimeFormat::utcNow(),
748 'changed' => DateTimeFormat::utcNow()];
750 Item::update($fields, ['id' => $post_id]);
752 // update filetags in pconfig
753 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
755 if (!empty($_REQUEST['return']) && strlen($return_path)) {
756 Logger::log('return: ' . $return_path);
757 $a->internalRedirect($return_path);
762 unset($datarray['edit']);
763 unset($datarray['self']);
764 unset($datarray['api_source']);
767 $signed = Diaspora::createCommentSignature($uid, $datarray);
768 if (!empty($signed)) {
769 $datarray['diaspora_signed_text'] = json_encode($signed);
773 $post_id = Item::insert($datarray);
776 Logger::log("Item wasn't stored.");
777 $a->internalRedirect($return_path);
780 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
782 if (!DBA::isResult($datarray)) {
783 Logger::log("Item with id ".$post_id." couldn't be fetched.");
784 $a->internalRedirect($return_path);
787 // update filetags in pconfig
788 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
790 // These notifications are sent if someone else is commenting other your wall
792 if ($contact_record != $author) {
794 'type' => NOTIFY_COMMENT,
795 'notify_flags' => $user['notify-flags'],
796 'language' => $user['language'],
797 'to_name' => $user['username'],
798 'to_email' => $user['email'],
799 'uid' => $user['uid'],
801 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
802 'source_name' => $datarray['author-name'],
803 'source_link' => $datarray['author-link'],
804 'source_photo' => $datarray['author-avatar'],
805 'verb' => ACTIVITY_POST,
808 'parent_uri' => $parent_item['uri']
812 if (($contact_record != $author) && !count($forum_contact)) {
814 'type' => NOTIFY_WALL,
815 'notify_flags' => $user['notify-flags'],
816 'language' => $user['language'],
817 'to_name' => $user['username'],
818 'to_email' => $user['email'],
819 'uid' => $user['uid'],
821 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
822 'source_name' => $datarray['author-name'],
823 'source_link' => $datarray['author-link'],
824 'source_photo' => $datarray['author-avatar'],
825 'verb' => ACTIVITY_POST,
831 Hook::callAll('post_local_end', $datarray);
833 if (strlen($emailcc) && $profile_uid == local_user()) {
834 $erecips = explode(',', $emailcc);
835 if (count($erecips)) {
836 foreach ($erecips as $recip) {
837 $addr = trim($recip);
838 if (!strlen($addr)) {
841 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
843 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
844 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
845 if (!$datarray['title']=='') {
846 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
848 $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
850 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
851 $html = Item::prepareBody($datarray);
852 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
854 'fromName' => $a->user['username'],
855 'fromEmail' => $a->user['email'],
857 'replyTo' => $a->user['email'],
858 'messageSubject' => $subject,
859 'htmlVersion' => $message,
860 'textVersion' => HTML::toPlaintext($html.$disclaimer)
862 Emailer::send($params);
867 // Insert an item entry for UID=0 for global entries.
868 // We now do it in the background to save some time.
869 // This is important in interactive environments like the frontend or the API.
870 // We don't fork a new process since this is done anyway with the following command
871 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
873 // When we are doing some forum posting via ! we have to start the notifier manually.
874 // These kind of posts don't initiate the notifier call in the item class.
875 if ($only_to_forum) {
876 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
879 Logger::log('post_complete');
885 item_post_return(System::baseUrl(), $api_source, $return_path);
889 function item_post_return($baseurl, $api_source, $return_path)
891 // figure out how to return, depending on from whence we came
899 $a->internalRedirect($return_path);
902 $json = ['success' => 1];
903 if (!empty($_REQUEST['jsreload'])) {
904 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
907 Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
909 echo json_encode($json);
913 function item_content(App $a)
915 if (!local_user() && !remote_user()) {
921 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
923 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
925 if (!empty($a->argv[3])) {
926 $o = drop_item($a->argv[2], $a->argv[3]);
929 $o = drop_item($a->argv[2]);
934 // ajax return: [<item id>, 0 (no perm) | <owner id>]
935 echo json_encode([intval($a->argv[2]), intval($o)]);
944 * This function removes the tag $tag from the text $body and replaces it with
945 * the appropriate link.
948 * @param string $body the text to replace the tag in
949 * @param string $inform a comma-seperated string containing everybody to inform
950 * @param string $str_tags string to add the tag to
951 * @param integer $profile_uid
952 * @param string $tag the tag to replace
953 * @param string $network The network of the post
955 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
956 * @throws ImagickException
957 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
959 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
964 //is it a person tag?
965 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
966 $tag_type = substr($tag, 0, 1);
967 //is it already replaced?
968 if (strpos($tag, '[url=')) {
969 //append tag to str_tags
970 if (!stristr($str_tags, $tag)) {
971 if (strlen($str_tags)) {
977 // Checking for the alias that is used for OStatus
978 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
979 if (preg_match($pattern, $tag, $matches)) {
980 $data = Contact::getDetailsByURL($matches[1]);
982 if ($data["alias"] != "") {
983 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
985 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
986 if (strlen($str_tags)) {
990 $str_tags .= $newtag;
998 //get the person's name
999 $name = substr($tag, 1);
1001 // Sometimes the tag detection doesn't seem to work right
1002 // This is some workaround
1003 $nameparts = explode(" ", $name);
1004 $name = $nameparts[0];
1006 // Try to detect the contact in various ways
1007 if (strpos($name, 'http://')) {
1008 // At first we have to ensure that the contact exists
1009 Contact::getIdForURL($name);
1011 // Now we should have something
1012 $contact = Contact::getDetailsByURL($name);
1013 } elseif (strpos($name, '@')) {
1014 // This function automatically probes when no entry was found
1015 $contact = Contact::getDetailsByAddr($name);
1018 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
1020 if (strrpos($name, '+')) {
1021 // Is it in format @nick+number?
1022 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1023 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
1026 // select someone by nick or attag in the current network
1027 if (!DBA::isResult($contact) && ($network != "")) {
1028 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
1029 $name, $name, $network, $profile_uid];
1030 $contact = DBA::selectFirst('contact', $fields, $condition);
1033 //select someone by name in the current network
1034 if (!DBA::isResult($contact) && ($network != "")) {
1035 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
1036 $contact = DBA::selectFirst('contact', $fields, $condition);
1039 // select someone by nick or attag in any network
1040 if (!DBA::isResult($contact)) {
1041 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
1042 $contact = DBA::selectFirst('contact', $fields, $condition);
1045 // select someone by name in any network
1046 if (!DBA::isResult($contact)) {
1047 $condition = ['name' => $name, 'uid' => $profile_uid];
1048 $contact = DBA::selectFirst('contact', $fields, $condition);
1052 // Check if $contact has been successfully loaded
1053 if (DBA::isResult($contact)) {
1054 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1058 if (isset($contact["id"])) {
1059 $inform .= 'cid:' . $contact["id"];
1060 } elseif (isset($contact["notify"])) {
1061 $inform .= $contact["notify"];
1064 $profile = $contact["url"];
1065 $alias = $contact["alias"];
1066 $newname = defaults($contact, "name", $contact["nick"]);
1069 //if there is an url for this persons profile
1070 if (isset($profile) && ($newname != "")) {
1072 // create profile link
1073 $profile = str_replace(',', '%2c', $profile);
1074 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1075 $body = str_replace($tag_type . $name, $newtag, $body);
1076 // append tag to str_tags
1077 if (!stristr($str_tags, $newtag)) {
1078 if (strlen($str_tags)) {
1081 $str_tags .= $newtag;
1085 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1086 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1088 if (!empty($alias)) {
1089 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1090 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1091 if (strlen($str_tags)) {
1094 $str_tags .= $newtag;
1100 return ['replaced' => $replaced, 'contact' => $contact];