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
18 use Friendica\Core\Config;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Item;
25 use Friendica\Network\Probe;
26 use Friendica\Protocol\Diaspora;
27 use Friendica\Protocol\Email;
28 use Friendica\Util\Emailer;
30 require_once 'include/enotify.php';
31 require_once 'include/tags.php';
32 require_once 'include/threads.php';
33 require_once 'include/text.php';
34 require_once 'include/items.php';
36 function item_post(App $a) {
37 if (!local_user() && !remote_user()) {
41 require_once 'include/security.php';
45 if (x($_REQUEST, 'dropitems')) {
46 $arr_drop = explode(',', $_REQUEST['dropitems']);
47 drop_items($arr_drop);
48 $json = ['success' => 1];
49 echo json_encode($json);
53 call_hooks('post_local_start', $_REQUEST);
54 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
56 $api_source = defaults($_REQUEST, 'api_source', false);
58 $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
60 $return_path = defaults($_REQUEST, 'return', '');
61 $preview = intval(defaults($_REQUEST, 'preview', 0));
64 * Check for doubly-submitted posts, and reject duplicates
65 * Note that we have to ignore previews, otherwise nothing will post
66 * after it's been previewed
68 if (!$preview && x($_REQUEST, 'post_id_random')) {
69 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
70 logger("item post: duplicate post", LOGGER_DEBUG);
71 item_post_return(System::baseUrl(), $api_source, $return_path);
73 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
77 // Is this a reply to something?
78 $thr_parent = intval(defaults($_REQUEST, 'parent', 0));
79 $thr_parent_uri = trim(defaults($_REQUEST, 'parent_uri', ''));
81 $thr_parent_contact = null;
87 $parent_contact = null;
90 $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
92 if ($thr_parent || $thr_parent_uri) {
94 $parent_item = dba::selectFirst('item', [], ['id' => $thr_parent]);
95 } elseif ($thr_parent_uri) {
96 $parent_item = dba::selectFirst('item', [], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
99 // if this isn't the real parent of the conversation, find it
100 if (DBM::is_result($parent_item)) {
102 // The URI and the contact is taken from the direct parent which needn't to be the top parent
103 $thr_parent_uri = $parent_item['uri'];
104 $thr_parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
106 if ($parent_item['id'] != $parent_item['parent']) {
107 $parent_item = dba::selectFirst('item', [], ['id' => $parent_item['parent']]);
111 if (!DBM::is_result($parent_item)) {
112 notice(t('Unable to locate original post.') . EOL);
113 if (x($_REQUEST, 'return')) {
114 goaway($return_path);
119 $parent = $parent_item['id'];
120 $parent_user = $parent_item['uid'];
122 $parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
124 $objecttype = ACTIVITY_OBJ_COMMENT;
126 if (!x($_REQUEST, 'type')) {
127 $_REQUEST['type'] = 'net-comment';
132 logger('mod_item: item_post parent=' . $parent);
135 $post_id = intval(defaults($_REQUEST, 'post_id', 0));
136 $app = strip_tags(defaults($_REQUEST, 'source', ''));
137 $extid = strip_tags(defaults($_REQUEST, 'extid', ''));
138 $object = defaults($_REQUEST, 'object', '');
140 // Ensure that the user id in a thread always stay the same
141 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
142 $profile_uid = $parent_user;
145 // Check for multiple posts with the same message id (when the post was created via API)
146 if (($message_id != '') && ($profile_uid != 0)) {
147 if (dba::exists('item', ['uri' => $message_id, 'uid' => $profile_uid])) {
148 logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
153 // Allow commenting if it is an answer to a public post
154 $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
156 // Now check that valid personal details have been provided
157 if (!can_write_wall($profile_uid) && !$allow_comment) {
158 notice(t('Permission denied.') . EOL) ;
159 if (x($_REQUEST, 'return')) {
160 goaway($return_path);
166 // is this an edited post?
171 $orig_post = dba::selectFirst('item', [], ['id' => $post_id]);
174 $user = dba::selectFirst('user', [], ['uid' => $profile_uid]);
175 if (!DBM::is_result($user) && !$orig_post) {
180 $str_group_allow = $orig_post['allow_gid'];
181 $str_contact_allow = $orig_post['allow_cid'];
182 $str_group_deny = $orig_post['deny_gid'];
183 $str_contact_deny = $orig_post['deny_cid'];
184 $location = $orig_post['location'];
185 $coord = $orig_post['coord'];
186 $verb = $orig_post['verb'];
187 $objecttype = $orig_post['object-type'];
188 $emailcc = $orig_post['emailcc'];
189 $app = $orig_post['app'];
190 $categories = $orig_post['file'];
191 $title = notags(trim($_REQUEST['title']));
192 $body = escape_tags(trim($_REQUEST['body']));
193 $private = $orig_post['private'];
194 $pubmail_enabled = $orig_post['pubmail'];
195 $network = $orig_post['network'];
196 $guid = $orig_post['guid'];
197 $extid = $orig_post['extid'];
202 * if coming from the API and no privacy settings are set,
203 * use the user default permissions - as they won't have
204 * been supplied via a form.
206 /// @TODO use x($_REQUEST, 'foo') here
208 && !array_key_exists('contact_allow', $_REQUEST)
209 && !array_key_exists('group_allow', $_REQUEST)
210 && !array_key_exists('contact_deny', $_REQUEST)
211 && !array_key_exists('group_deny', $_REQUEST)) {
212 $str_group_allow = $user['allow_gid'];
213 $str_contact_allow = $user['allow_cid'];
214 $str_group_deny = $user['deny_gid'];
215 $str_contact_deny = $user['deny_cid'];
217 // use the posted permissions
218 $str_group_allow = perms2str($_REQUEST['group_allow']);
219 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
220 $str_group_deny = perms2str($_REQUEST['group_deny']);
221 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
224 $title = notags(trim($_REQUEST['title']));
225 $location = notags(trim($_REQUEST['location']));
226 $coord = notags(trim($_REQUEST['coord']));
227 $verb = notags(trim($_REQUEST['verb']));
228 $emailcc = notags(trim($_REQUEST['emailcc']));
229 $body = escape_tags(trim($_REQUEST['body']));
230 $network = notags(trim($_REQUEST['network']));
231 $guid = get_guid(32);
233 item_add_language_opt($_REQUEST);
234 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
236 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
238 if ($user['hidewall']) {
242 // If this is a comment, set the permissions from the parent.
246 // for non native networks use the network of the original post as network of the item
247 if (($parent_item['network'] != NETWORK_DIASPORA)
248 && ($parent_item['network'] != NETWORK_OSTATUS)
249 && ($network == "")) {
250 $network = $parent_item['network'];
253 $str_contact_allow = $parent_item['allow_cid'];
254 $str_group_allow = $parent_item['allow_gid'];
255 $str_contact_deny = $parent_item['deny_cid'];
256 $str_group_deny = $parent_item['deny_gid'];
257 $private = $parent_item['private'];
260 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
262 // if using the API, we won't see pubmail_enable - figure out if it should be set
263 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
264 if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
265 $pubmail_enabled = dba::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
269 if (!strlen($body)) {
273 info(t('Empty post discarded.') . EOL);
274 if (x($_REQUEST, 'return')) {
275 goaway($return_path);
281 if (strlen($categories)) {
282 // get the "fileas" tags for this post
283 $filedas = file_tag_file_to_list($categories, 'file');
285 // save old and new categories, so we can determine what needs to be deleted from pconfig
286 $categories_old = $categories;
287 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
288 $categories_new = $categories;
289 if (strlen($filedas)) {
290 // append the fileas stuff to the new categories list
291 $categories .= file_tag_list_to_file($filedas, 'file');
294 // get contact info for poster
300 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
302 $author = dba::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
303 } elseif (remote_user()) {
304 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
305 foreach ($_SESSION['remote'] as $v) {
306 if ($v['uid'] == $profile_uid) {
307 $contact_id = $v['cid'];
313 $author = dba::selectFirst('contact', [], ['id' => $contact_id]);
317 if (DBM::is_result($author)) {
318 $contact_id = $author['id'];
321 // get contact info for owner
322 if ($profile_uid == local_user() || $allow_comment) {
323 $contact_record = $author;
325 $contact_record = dba::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
328 $post_type = notags(trim($_REQUEST['type']));
330 if ($post_type === 'net-comment' && $parent_item !== null) {
331 if ($parent_item['wall'] == 1) {
332 $post_type = 'wall-comment';
334 $post_type = 'remote-comment';
338 // Look for any tags and linkify them
342 $tags = get_tags($body);
344 // Add a tag if the parent contact is from OStatus (This will notify them during delivery)
346 if ($thr_parent_contact['network'] == NETWORK_OSTATUS) {
347 $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
348 if (!in_array($contact, $tags)) {
353 if ($parent_contact['network'] == NETWORK_OSTATUS) {
354 $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
355 if (!in_array($contact, $tags)) {
363 $private_forum = false;
364 $only_to_forum = false;
368 foreach ($tags as $tag) {
370 $tag_type = substr($tag, 0, 1);
372 if ($tag_type == '#') {
377 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
378 * Robert Johnson should be first in the $tags array
380 $fullnametagged = false;
381 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
382 foreach ($tagged as $nextTag) {
383 if (stristr($nextTag, $tag . ' ')) {
384 $fullnametagged = true;
388 if ($fullnametagged) {
392 $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
393 if ($success['replaced']) {
396 // When the forum is private or the forum is addressed with a "!" make the post private
397 if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
398 $private_forum = $success['contact']['prv'];
399 $only_to_forum = ($tag_type == '!');
400 $private_id = $success['contact']['id'];
401 $forum_contact = $success['contact'];
402 } elseif (is_array($success['contact']) && $success['contact']['forum'] &&
403 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
404 $private_forum = false;
405 $only_to_forum = true;
406 $private_id = $success['contact']['id'];
407 $forum_contact = $success['contact'];
412 $original_contact_id = $contact_id;
414 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
415 // we tagged a forum in a top level post. Now we change the post
416 $private = $private_forum;
418 $str_group_allow = '';
419 $str_contact_deny = '';
420 $str_group_deny = '';
421 if ($private_forum) {
422 $str_contact_allow = '<' . $private_id . '>';
424 $str_contact_allow = '';
426 $contact_id = $private_id;
427 $contact_record = $forum_contact;
428 $_REQUEST['origin'] = false;
432 * When a photo was uploaded into the message using the (profile wall) ajax
433 * uploader, The permissions are initially set to disallow anybody but the
434 * owner from seeing it. This is because the permissions may not yet have been
435 * set for the post. If it's private, the photo permissions should be set
436 * appropriately. But we didn't know the final permissions on the post until
437 * now. So now we'll look for links of uploaded messages that are in the
438 * post and set them to the same permissions as the post itself.
443 /// @todo these lines should be moved to Model/Photo
444 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
446 if (count($images)) {
448 $objecttype = ACTIVITY_OBJ_IMAGE;
450 foreach ($images as $image) {
451 if (!stristr($image, System::baseUrl() . '/photo/')) {
454 $image_uri = substr($image,strrpos($image,'/') + 1);
455 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
456 if (!strlen($image_uri)) {
460 // Ensure to only modify photos that you own
461 $srch = '<' . intval($original_contact_id) . '>';
463 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
464 'resource-id' => $image_uri, 'uid' => $profile_uid];
465 if (!dba::exists('photo', $condition)) {
469 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
470 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
471 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid, 'album' => t('Wall Photos')];
472 dba::update('photo', $fields, $condition);
479 * Next link in any attachment references we find in the post.
483 /// @todo these lines should be moved to Model/Attach (Once it exists)
484 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
485 $attaches = $match[1];
486 if (count($attaches)) {
487 foreach ($attaches as $attach) {
488 // Ensure to only modify attachments that you own
489 $srch = '<' . intval($original_contact_id) . '>';
491 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
493 if (!dba::exists('attach', $condition)) {
497 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
498 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
499 $condition = ['id' => $attach];
500 dba::update('attach', $fields, $condition);
505 // embedded bookmark or attachment in post? set bookmark flag
508 $data = get_attachment_data($body);
509 if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
510 $objecttype = ACTIVITY_OBJ_BOOKMARK;
514 $body = bb_translate_video($body);
517 // Fold multi-line [code] sequences
518 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
520 $body = scale_external_images($body, false);
522 // Setting the object type if not defined before
524 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
525 require_once 'include/plaintext.php';
526 $objectdata = get_attached_data($body);
528 if ($objectdata["type"] == "link") {
529 $objecttype = ACTIVITY_OBJ_BOOKMARK;
530 } elseif ($objectdata["type"] == "video") {
531 $objecttype = ACTIVITY_OBJ_VIDEO;
532 } elseif ($objectdata["type"] == "photo") {
533 $objecttype = ACTIVITY_OBJ_IMAGE;
541 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
542 foreach ($match[2] as $mtch) {
543 $fields = ['id', 'filename', 'filesize', 'filetype'];
544 $attachment = dba::selectFirst('attach', $fields, ['id' => $mtch]);
545 if (DBM::is_result($attachment)) {
546 if (strlen($attachments)) {
549 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
550 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
551 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
553 $body = str_replace($match[1],'',$body);
559 if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
563 if (!strlen($verb)) {
564 $verb = ACTIVITY_POST;
567 if ($network == "") {
568 $network = NETWORK_DFRN;
571 $gravity = ($parent ? 6 : 0);
573 // even if the post arrived via API we are considering that it
574 // originated on this site by default for determining relayability.
576 $origin = intval(defaults($_REQUEST, 'origin', 1));
578 $notify_type = ($parent ? 'comment-new' : 'wall-new');
580 $uri = ($message_id ? $message_id : item_new_uri($a->get_hostname(), $profile_uid, $guid));
582 // Fallback so that we alway have a parent uri
583 if (!$thr_parent_uri || !$parent) {
584 $thr_parent_uri = $uri;
588 $datarray['uid'] = $profile_uid;
589 $datarray['type'] = $post_type;
590 $datarray['wall'] = $wall;
591 $datarray['gravity'] = $gravity;
592 $datarray['network'] = $network;
593 $datarray['contact-id'] = $contact_id;
594 $datarray['owner-name'] = $contact_record['name'];
595 $datarray['owner-link'] = $contact_record['url'];
596 $datarray['owner-avatar'] = $contact_record['thumb'];
597 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link'], 0);
598 $datarray['author-name'] = $author['name'];
599 $datarray['author-link'] = $author['url'];
600 $datarray['author-avatar'] = $author['thumb'];
601 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link'], 0);
602 $datarray['created'] = datetime_convert();
603 $datarray['edited'] = datetime_convert();
604 $datarray['commented'] = datetime_convert();
605 $datarray['received'] = datetime_convert();
606 $datarray['changed'] = datetime_convert();
607 $datarray['extid'] = $extid;
608 $datarray['guid'] = $guid;
609 $datarray['uri'] = $uri;
610 $datarray['title'] = $title;
611 $datarray['body'] = $body;
612 $datarray['app'] = $app;
613 $datarray['location'] = $location;
614 $datarray['coord'] = $coord;
615 $datarray['tag'] = $str_tags;
616 $datarray['file'] = $categories;
617 $datarray['inform'] = $inform;
618 $datarray['verb'] = $verb;
619 $datarray['object-type'] = $objecttype;
620 $datarray['allow_cid'] = $str_contact_allow;
621 $datarray['allow_gid'] = $str_group_allow;
622 $datarray['deny_cid'] = $str_contact_deny;
623 $datarray['deny_gid'] = $str_group_deny;
624 $datarray['private'] = $private;
625 $datarray['pubmail'] = $pubmail_enabled;
626 $datarray['attach'] = $attachments;
627 $datarray['bookmark'] = intval($bookmark);
629 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
630 $datarray['parent-uri'] = $thr_parent_uri;
632 $datarray['postopts'] = $postopts;
633 $datarray['origin'] = $origin;
634 $datarray['moderated'] = false;
635 $datarray['gcontact-id'] = GContact::getId(["url" => $datarray['author-link'], "network" => $datarray['network'],
636 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']]);
637 $datarray['object'] = $object;
640 * These fields are for the convenience of plugins...
641 * 'self' if true indicates the owner is posting on their own wall
642 * If parent is 0 it is a top-level post.
644 $datarray['parent'] = $parent;
645 $datarray['self'] = $self;
647 // This triggers posts via API and the mirror functions
648 $datarray['api_source'] = $api_source;
650 // This field is for storing the raw conversation data
651 $datarray['protocol'] = PROTOCOL_DFRN;
653 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
654 if (DBM::is_result($r)) {
655 if ($r['conversation-uri'] != '') {
656 $datarray['conversation-uri'] = $r['conversation-uri'];
658 if ($r['conversation-href'] != '') {
659 $datarray['conversation-href'] = $r['conversation-href'];
664 $datarray['edit'] = true;
667 // Search for hashtags
668 item_body_set_hashtags($datarray);
670 // preview mode - prepare the body for display and send it via json
672 require_once 'include/conversation.php';
673 // We set the datarray ID to -1 because in preview mode the dataray
674 // doesn't have an ID.
675 $datarray["id"] = -1;
676 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
677 logger('preview: ' . $o);
678 echo json_encode(['preview' => $o]);
682 call_hooks('post_local',$datarray);
684 if (x($datarray, 'cancel')) {
685 logger('mod_item: post cancelled by plugin.');
687 goaway($return_path);
690 $json = ['cancel' => 1];
691 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
692 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
695 echo json_encode($json);
701 // Fill the cache field
702 // This could be done in Item::update as well - but we have to check for the existance of some fields.
703 put_item_in_cache($datarray);
706 'title' => $datarray['title'],
707 'body' => $datarray['body'],
708 'tag' => $datarray['tag'],
709 'attach' => $datarray['attach'],
710 'file' => $datarray['file'],
711 'rendered-html' => $datarray['rendered-html'],
712 'rendered-hash' => $datarray['rendered-hash'],
713 'edited' => datetime_convert(),
714 'changed' => datetime_convert()];
716 Item::update($fields, ['id' => $post_id]);
718 // update filetags in pconfig
719 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
721 if (x($_REQUEST, 'return') && strlen($return_path)) {
722 logger('return: ' . $return_path);
723 goaway($return_path);
730 unset($datarray['edit']);
731 unset($datarray['self']);
732 unset($datarray['api_source']);
734 $post_id = item_store($datarray);
737 logger("Item wasn't stored.");
738 goaway($return_path);
741 $datarray = dba::selectFirst('item', [], ['id' => $post_id]);
743 if (!DBM::is_result($datarray)) {
744 logger("Item with id ".$post_id." couldn't be fetched.");
745 goaway($return_path);
748 // update filetags in pconfig
749 file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
751 // These notifications are sent if someone else is commenting other your wall
753 if ($contact_record != $author) {
755 'type' => NOTIFY_COMMENT,
756 'notify_flags' => $user['notify-flags'],
757 'language' => $user['language'],
758 'to_name' => $user['username'],
759 'to_email' => $user['email'],
760 'uid' => $user['uid'],
762 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
763 'source_name' => $datarray['author-name'],
764 'source_link' => $datarray['author-link'],
765 'source_photo' => $datarray['author-avatar'],
766 'verb' => ACTIVITY_POST,
769 'parent_uri' => $parent_item['uri']
773 // Store the comment signature information in case we need to relay to Diaspora
774 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
776 if (($contact_record != $author) && !count($forum_contact)) {
778 'type' => NOTIFY_WALL,
779 'notify_flags' => $user['notify-flags'],
780 'language' => $user['language'],
781 'to_name' => $user['username'],
782 'to_email' => $user['email'],
783 'uid' => $user['uid'],
785 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
786 'source_name' => $datarray['author-name'],
787 'source_link' => $datarray['author-link'],
788 'source_photo' => $datarray['author-avatar'],
789 'verb' => ACTIVITY_POST,
795 call_hooks('post_local_end', $datarray);
797 if (strlen($emailcc) && $profile_uid == local_user()) {
798 $erecips = explode(',', $emailcc);
799 if (count($erecips)) {
800 foreach ($erecips as $recip) {
801 $addr = trim($recip);
802 if (!strlen($addr)) {
805 $disclaimer = '<hr />' . sprintf(t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
807 $disclaimer .= sprintf(t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
808 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
809 if (!$datarray['title']=='') {
810 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
812 $subject = Email::encodeHeader('[Friendica]' . ' ' . sprintf(t('%s posted an update.'), $a->user['username']), 'UTF-8');
814 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
815 $html = prepare_body($datarray);
816 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
817 include_once 'include/html2plain.php';
819 'fromName' => $a->user['username'],
820 'fromEmail' => $a->user['email'],
822 'replyTo' => $a->user['email'],
823 'messageSubject' => $subject,
824 'htmlVersion' => $message,
825 'textVersion' => html2plain($html.$disclaimer)
827 Emailer::send($params);
832 // Insert an item entry for UID=0 for global entries.
833 // We now do it in the background to save some time.
834 // This is important in interactive environments like the frontend or the API.
835 // We don't fork a new process since this is done anyway with the following command
836 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
838 // Call the background process that is delivering the item to the receivers
839 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
841 logger('post_complete');
843 item_post_return(System::baseUrl(), $api_source, $return_path);
847 function item_post_return($baseurl, $api_source, $return_path) {
848 // figure out how to return, depending on from whence we came
855 goaway($return_path);
858 $json = ['success' => 1];
859 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
860 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
863 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
865 echo json_encode($json);
871 function item_content(App $a) {
873 if (!local_user() && !remote_user()) {
877 require_once 'include/security.php';
880 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
882 $o = Item::delete($a->argv[2]);
884 $o = drop_item($a->argv[2]);
887 // ajax return: [<item id>, 0 (no perm) | <owner id>]
888 echo json_encode([intval($a->argv[2]), intval($o)]);
896 * This function removes the tag $tag from the text $body and replaces it with
897 * the appropiate link.
899 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
900 * @param unknown_type $body the text to replace the tag in
901 * @param string $inform a comma-seperated string containing everybody to inform
902 * @param string $str_tags string to add the tag to
903 * @param integer $profile_uid
904 * @param string $tag the tag to replace
905 * @param string $network The network of the post
907 * @return boolean true if replaced, false if not replaced
909 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
915 //is it a person tag?
916 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
917 $tag_type = substr($tag, 0, 1);
918 //is it already replaced?
919 if (strpos($tag, '[url=')) {
920 //append tag to str_tags
921 if (!stristr($str_tags, $tag)) {
922 if (strlen($str_tags)) {
928 // Checking for the alias that is used for OStatus
929 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
930 if (preg_match($pattern, $tag, $matches)) {
932 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
933 normalise_link($matches[1]));
934 if (!DBM::is_result($r)) {
935 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
936 normalise_link($matches[1]));
938 if (DBM::is_result($r)) {
941 $data = Probe::uri($matches[1]);
944 if ($data["alias"] != "") {
945 $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
946 if (!stristr($str_tags, $newtag)) {
947 if (strlen($str_tags)) {
950 $str_tags .= $newtag;
958 //get the person's name
959 $name = substr($tag, 1);
961 // Sometimes the tag detection doesn't seem to work right
962 // This is some workaround
963 $nameparts = explode(" ", $name);
964 $name = $nameparts[0];
966 // Try to detect the contact in various ways
967 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
968 // Is it in format @user@domain.tld or @http://domain.tld/...?
970 // First check the contact table for the address
971 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
972 WHERE `addr` = '%s' AND `uid` = %d AND
973 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
976 intval($profile_uid),
977 dbesc(NETWORK_OSTATUS)
980 // Then check in the contact table for the url
981 if (!DBM::is_result($r)) {
982 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
983 WHERE `nurl` = '%s' AND `uid` = %d AND
984 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
986 dbesc(normalise_link($name)),
987 intval($profile_uid),
988 dbesc(NETWORK_OSTATUS)
992 // Then check in the global contacts for the address
993 if (!DBM::is_result($r)) {
994 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
995 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
998 dbesc(NETWORK_OSTATUS)
1002 // Then check in the global contacts for the url
1003 if (!DBM::is_result($r)) {
1004 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1005 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1007 dbesc(normalise_link($name)),
1008 dbesc(NETWORK_OSTATUS)
1012 if (!DBM::is_result($r)) {
1013 $probed = Probe::uri($name);
1014 if ($result['network'] != NETWORK_PHANTOM) {
1015 GContact::update($probed);
1016 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1017 dbesc(normalise_link($probed["url"])));
1022 if (strrpos($name, '+')) {
1023 // Is it in format @nick+number?
1024 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1026 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1028 intval($profile_uid)
1032 // select someone by attag or nick and the name passed in the current network
1033 if (!DBM::is_result($r) && ($network != ""))
1034 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `network` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1038 intval($profile_uid)
1041 //select someone from this user's contacts by name in the current network
1042 if (!DBM::is_result($r) && ($network != "")) {
1043 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1046 intval($profile_uid)
1050 // select someone by attag or nick and the name passed in
1051 if (!DBM::is_result($r)) {
1052 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1055 intval($profile_uid)
1059 // select someone from this user's contacts by name
1060 if (!DBM::is_result($r)) {
1061 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1063 intval($profile_uid)
1068 if (DBM::is_result($r)) {
1069 if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1073 if (isset($r[0]["id"])) {
1074 $inform .= 'cid:' . $r[0]["id"];
1075 } elseif (isset($r[0]["notify"])) {
1076 $inform .= $r[0]["notify"];
1079 $profile = $r[0]["url"];
1080 $alias = $r[0]["alias"];
1081 $newname = $r[0]["nick"];
1082 if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1083 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1084 $newname = $r[0]["name"];
1088 //if there is an url for this persons profile
1089 if (isset($profile) && ($newname != "")) {
1091 // create profile link
1092 $profile = str_replace(',', '%2c', $profile);
1093 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1094 $body = str_replace($tag_type . $name, $newtag, $body);
1095 // append tag to str_tags
1096 if (!stristr($str_tags, $newtag)) {
1097 if (strlen($str_tags)) {
1100 $str_tags .= $newtag;
1104 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1105 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1107 if (strlen($alias)) {
1108 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1109 if (!stristr($str_tags, $newtag)) {
1110 if (strlen($str_tags)) {
1113 $str_tags .= $newtag;
1119 return ['replaced' => $replaced, 'contact' => $r[0]];