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() && !x($_REQUEST, 'commenter')) {
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('postinput ' . file_get_contents('php://input'));
55 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
57 $api_source = x($_REQUEST, 'api_source') && $_REQUEST['api_source'];
59 $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
61 $return_path = (x($_REQUEST, 'return') ? $_REQUEST['return'] : '');
62 $preview = (x($_REQUEST, 'preview') ? intval($_REQUEST['preview']) : 0);
65 * Check for doubly-submitted posts, and reject duplicates
66 * Note that we have to ignore previews, otherwise nothing will post
67 * after it's been previewed
69 if (!$preview && x($_REQUEST, 'post_id_random')) {
70 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
71 logger("item post: duplicate post", LOGGER_DEBUG);
72 item_post_return(System::baseUrl(), $api_source, $return_path);
74 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
78 // Is this a reply to something?
79 $parent = (x($_REQUEST, 'parent') ? intval($_REQUEST['parent']) : 0);
80 $parent_uri = (x($_REQUEST, 'parent_uri') ? trim($_REQUEST['parent_uri']) : '');
83 $parent_contact = null;
88 if ($parent || $parent_uri) {
90 $objecttype = ACTIVITY_OBJ_COMMENT;
92 if (!x($_REQUEST, 'type')) {
93 $_REQUEST['type'] = 'net-comment';
97 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
100 } elseif ($parent_uri && local_user()) {
101 // This is coming from an API source, and we are logged in
102 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
107 // if this isn't the real parent of the conversation, find it
108 if (DBM::is_result($r)) {
109 $parid = $r[0]['parent'];
110 if ($r[0]['id'] != $r[0]['parent']) {
111 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
118 if (!DBM::is_result($r)) {
119 notice(t('Unable to locate original post.') . EOL);
120 if (x($_REQUEST, 'return')) {
121 goaway($return_path);
125 $parent_item = $r[0];
126 $parent = $parent_item['id'];
127 $parent_uri = $parent_item['uri'];
129 if ($parent_item['contact-id']) {
130 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
131 intval($parent_item['contact-id'])
133 if (DBM::is_result($r)) {
134 $parent_contact = $r[0];
137 // If the contact id doesn't fit with the contact, then set the contact to null
138 $thrparent = q("SELECT `author-link`, `network` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($parent_uri));
139 if (DBM::is_result($thrparent) && ($thrparent[0]["network"] === NETWORK_OSTATUS)
140 && (normalise_link($parent_contact["url"]) != normalise_link($thrparent[0]["author-link"]))) {
141 $parent_contact = Contact::getDetailsByURL($thrparent[0]["author-link"]);
143 if (!isset($parent_contact["nick"])) {
144 $probed_contact = Probe::uri($thrparent[0]["author-link"]);
145 if ($probed_contact["network"] != NETWORK_FEED) {
146 $parent_contact = $probed_contact;
147 $parent_contact["nurl"] = normalise_link($probed_contact["url"]);
148 $parent_contact["thumb"] = $probed_contact["photo"];
149 $parent_contact["micro"] = $probed_contact["photo"];
150 $parent_contact["addr"] = $probed_contact["addr"];
153 logger('no contact found: ' . print_r($thrparent, true), LOGGER_DEBUG);
155 logger('parent contact: ' . print_r($parent_contact, true), LOGGER_DEBUG);
158 if ($parent_contact["nick"] == "") {
159 $parent_contact["nick"] = $parent_contact["name"];
165 logger('mod_item: item_post parent=' . $parent);
168 $profile_uid = (x($_REQUEST, 'profile_uid') ? intval($_REQUEST['profile_uid']) : 0);
169 $post_id = (x($_REQUEST, 'post_id') ? intval($_REQUEST['post_id']) : 0);
170 $app = (x($_REQUEST, 'source') ? strip_tags($_REQUEST['source']) : '');
171 $extid = (x($_REQUEST, 'extid') ? strip_tags($_REQUEST['extid']) : '');
172 $object = (x($_REQUEST, 'object') ? $_REQUEST['object'] : '');
174 // Check for multiple posts with the same message id (when the post was created via API)
175 if (($message_id != '') && ($profile_uid != 0)) {
176 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
181 if (DBM::is_result($r)) {
182 logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
187 $allow_moderated = false;
189 // here is where we are going to check for permission to post a moderated comment.
191 // First check that the parent exists and it is a wall item.
193 if (x($_REQUEST, 'commenter') && (!$parent || !$parent_item['wall'])) {
194 notice(t('Permission denied.') . EOL) ;
195 if (x($_REQUEST, 'return')) {
196 goaway($return_path);
201 // Allow commenting if it is an answer to a public post
202 $allow_comment = ($profile_uid == 0) && $parent && in_array($parent_item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
205 * Now check that it is a page_type of PAGE_BLOG, and that valid personal details
206 * have been provided, and run any anti-spam plugins
208 if (!(can_write_wall($profile_uid) || $allow_comment) && !$allow_moderated) {
209 notice(t('Permission denied.') . EOL) ;
210 if (x($_REQUEST, 'return')) {
211 goaway($return_path);
217 // is this an edited post?
222 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
223 intval($profile_uid),
226 if (!DBM::is_result($i)) {
234 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
237 if (DBM::is_result($r)) {
242 $str_group_allow = $orig_post['allow_gid'];
243 $str_contact_allow = $orig_post['allow_cid'];
244 $str_group_deny = $orig_post['deny_gid'];
245 $str_contact_deny = $orig_post['deny_cid'];
246 $location = $orig_post['location'];
247 $coord = $orig_post['coord'];
248 $verb = $orig_post['verb'];
249 $objecttype = $orig_post['object-type'];
250 $emailcc = $orig_post['emailcc'];
251 $app = $orig_post['app'];
252 $categories = $orig_post['file'];
253 $title = notags(trim($_REQUEST['title']));
254 $body = escape_tags(trim($_REQUEST['body']));
255 $private = $orig_post['private'];
256 $pubmail_enable = $orig_post['pubmail'];
257 $network = $orig_post['network'];
258 $guid = $orig_post['guid'];
259 $extid = $orig_post['extid'];
264 * if coming from the API and no privacy settings are set,
265 * use the user default permissions - as they won't have
266 * been supplied via a form.
268 /// @TODO use x($_REQUEST, 'foo') here
270 && !array_key_exists('contact_allow', $_REQUEST)
271 && !array_key_exists('group_allow', $_REQUEST)
272 && !array_key_exists('contact_deny', $_REQUEST)
273 && !array_key_exists('group_deny', $_REQUEST)) {
274 $str_group_allow = $user['allow_gid'];
275 $str_contact_allow = $user['allow_cid'];
276 $str_group_deny = $user['deny_gid'];
277 $str_contact_deny = $user['deny_cid'];
280 // use the posted permissions
282 $str_group_allow = perms2str($_REQUEST['group_allow']);
283 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
284 $str_group_deny = perms2str($_REQUEST['group_deny']);
285 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
288 $title = notags(trim($_REQUEST['title']));
289 $location = notags(trim($_REQUEST['location']));
290 $coord = notags(trim($_REQUEST['coord']));
291 $verb = notags(trim($_REQUEST['verb']));
292 $emailcc = notags(trim($_REQUEST['emailcc']));
293 $body = escape_tags(trim($_REQUEST['body']));
294 $network = notags(trim($_REQUEST['network']));
295 $guid = get_guid(32);
297 item_add_language_opt($_REQUEST);
298 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
300 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
302 if ($user['hidewall']) {
306 // If this is a comment, set the permissions from the parent.
310 // for non native networks use the network of the original post as network of the item
311 if (($parent_item['network'] != NETWORK_DIASPORA)
312 && ($parent_item['network'] != NETWORK_OSTATUS)
313 && ($network == "")) {
314 $network = $parent_item['network'];
317 $str_contact_allow = $parent_item['allow_cid'];
318 $str_group_allow = $parent_item['allow_gid'];
319 $str_contact_deny = $parent_item['deny_cid'];
320 $str_group_deny = $parent_item['deny_gid'];
321 $private = $parent_item['private'];
324 $pubmail_enable = ((x($_REQUEST, 'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && !$private) ? 1 : 0);
326 // if using the API, we won't see pubmail_enable - figure out if it should be set
328 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
329 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
330 if (!$mail_disabled) {
331 /// @TODO Check if only pubmail is loaded, * loads all columns
332 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
335 if (DBM::is_result($r) && intval($r[0]['pubmail'])) {
336 $pubmail_enabled = true;
341 if (!strlen($body)) {
345 info(t('Empty post discarded.') . EOL);
346 if (x($_REQUEST, 'return')) {
347 goaway($return_path);
353 if (strlen($categories)) {
354 // get the "fileas" tags for this post
355 $filedas = file_tag_file_to_list($categories, 'file');
357 // save old and new categories, so we can determine what needs to be deleted from pconfig
358 $categories_old = $categories;
359 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
360 $categories_new = $categories;
361 if (strlen($filedas)) {
362 // append the fileas stuff to the new categories list
363 $categories .= file_tag_list_to_file($filedas, 'file');
366 // get contact info for poster
372 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
374 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
375 intval($_SESSION['uid']));
376 } elseif (remote_user()) {
377 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
378 foreach ($_SESSION['remote'] as $v) {
379 if ($v['uid'] == $profile_uid) {
380 $contact_id = $v['cid'];
386 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
392 if (DBM::is_result($r)) {
394 $contact_id = $author['id'];
397 // get contact info for owner
399 if ($profile_uid == local_user() || $allow_comment) {
400 $contact_record = $author;
402 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
405 if (DBM::is_result($r)) {
406 $contact_record = $r[0];
410 $post_type = notags(trim($_REQUEST['type']));
412 if ($post_type === 'net-comment' && $parent_item !== null) {
413 if ($parent_item['wall'] == 1) {
414 $post_type = 'wall-comment';
416 $post_type = 'remote-comment';
420 // Look for any tags and linkify them
424 $tags = get_tags($body);
427 * add a statusnet style reply tag if the original post was from there
428 * and we are replying, and there isn't one already
430 if ($parent && ($parent_contact['network'] == NETWORK_OSTATUS)) {
431 $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
433 if (!in_array($contact, $tags)) {
434 $body = $contact . ' ' . $body;
438 $toplevel_contact = "";
439 $toplevel_parent = q("SELECT `contact`.* FROM `contact`
440 INNER JOIN `item` ON `item`.`contact-id` = `contact`.`id` AND `contact`.`url` = `item`.`author-link`
441 WHERE `item`.`id` = `item`.`parent` AND `item`.`parent` = %d", intval($parent));
442 if (DBM::is_result($toplevel_parent)) {
443 if (!empty($toplevel_parent[0]['addr'])) {
444 $toplevel_contact = '@' . $toplevel_parent[0]['addr'];
446 $toplevel_contact = '@' . $toplevel_parent[0]['nick'] . '+' . $toplevel_parent[0]['id'];
449 $toplevel_parent = q("SELECT `author-link`, `author-name` FROM `item` WHERE `id` = `parent` AND `parent` = %d", intval($parent));
450 $toplevel_contact = '@[url=' . $toplevel_parent[0]['author-link'] . ']' . $toplevel_parent[0]['author-name'] . '[/url]';
453 if (!in_array($toplevel_contact, $tags)) {
454 $tags[] = $toplevel_contact;
460 $private_forum = false;
461 $only_to_forum = false;
465 foreach ($tags as $tag) {
467 $tag_type = substr($tag, 0, 1);
469 if ($tag_type == '#') {
474 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
475 * Robert Johnson should be first in the $tags array
477 $fullnametagged = false;
478 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
479 foreach ($tagged as $nextTag) {
480 if (stristr($nextTag, $tag . ' ')) {
481 $fullnametagged = true;
485 if ($fullnametagged) {
489 $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
490 if ($success['replaced']) {
493 // When the forum is private or the forum is addressed with a "!" make the post private
494 if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
495 $private_forum = $success['contact']['prv'];
496 $only_to_forum = ($tag_type == '!');
497 $private_id = $success['contact']['id'];
498 $forum_contact = $success['contact'];
499 } elseif (is_array($success['contact']) && $success['contact']['forum'] &&
500 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
501 $private_forum = false;
502 $only_to_forum = true;
503 $private_id = $success['contact']['id'];
504 $forum_contact = $success['contact'];
509 $original_contact_id = $contact_id;
511 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
512 // we tagged a forum in a top level post. Now we change the post
513 $private = $private_forum;
515 $str_group_allow = '';
516 $str_contact_deny = '';
517 $str_group_deny = '';
518 if ($private_forum) {
519 $str_contact_allow = '<' . $private_id . '>';
521 $str_contact_allow = '';
523 $contact_id = $private_id;
524 $contact_record = $forum_contact;
525 $_REQUEST['origin'] = false;
529 * When a photo was uploaded into the message using the (profile wall) ajax
530 * uploader, The permissions are initially set to disallow anybody but the
531 * owner from seeing it. This is because the permissions may not yet have been
532 * set for the post. If it's private, the photo permissions should be set
533 * appropriately. But we didn't know the final permissions on the post until
534 * now. So now we'll look for links of uploaded messages that are in the
535 * post and set them to the same permissions as the post itself.
540 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
542 if (count($images)) {
544 $objecttype = ACTIVITY_OBJ_IMAGE;
546 foreach ($images as $image) {
547 if (!stristr($image, System::baseUrl() . '/photo/')) {
550 $image_uri = substr($image,strrpos($image,'/') + 1);
551 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
552 if (!strlen($image_uri)) {
555 $srch = '<' . intval($original_contact_id) . '>';
557 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
558 AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
564 if (!DBM::is_result($r)) {
568 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
569 WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
570 dbesc($str_contact_allow),
571 dbesc($str_group_allow),
572 dbesc($str_contact_deny),
573 dbesc($str_group_deny),
575 intval($profile_uid),
576 dbesc(t('Wall Photos'))
584 * Next link in any attachment references we find in the post.
588 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
589 $attaches = $match[1];
590 if (count($attaches)) {
591 foreach ($attaches as $attach) {
592 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
593 intval($profile_uid),
596 if (DBM::is_result($r)) {
597 $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
598 WHERE `uid` = %d AND `id` = %d",
599 dbesc($str_contact_allow),
600 dbesc($str_group_allow),
601 dbesc($str_contact_deny),
602 dbesc($str_group_deny),
603 intval($profile_uid),
611 // embedded bookmark or attachment in post? set bookmark flag
614 $data = get_attachment_data($body);
615 if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
616 $objecttype = ACTIVITY_OBJ_BOOKMARK;
620 $body = bb_translate_video($body);
623 // Fold multi-line [code] sequences
624 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
626 $body = scale_external_images($body, false);
628 // Setting the object type if not defined before
630 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
631 require_once 'include/plaintext.php';
632 $objectdata = get_attached_data($body);
634 if ($objectdata["type"] == "link") {
635 $objecttype = ACTIVITY_OBJ_BOOKMARK;
636 } elseif ($objectdata["type"] == "video") {
637 $objecttype = ACTIVITY_OBJ_VIDEO;
638 } elseif ($objectdata["type"] == "photo") {
639 $objecttype = ACTIVITY_OBJ_IMAGE;
647 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
648 foreach ($match[2] as $mtch) {
649 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
650 intval($profile_uid),
653 if (DBM::is_result($r)) {
654 if (strlen($attachments)) {
657 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $r[0]['id'] . '" length="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . (($r[0]['filename']) ? $r[0]['filename'] : '') . '"[/attach]';
659 $body = str_replace($match[1],'',$body);
665 if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
669 if (!strlen($verb)) {
670 $verb = ACTIVITY_POST;
673 if ($network == "") {
674 $network = NETWORK_DFRN;
677 $gravity = ($parent ? 6 : 0);
679 // even if the post arrived via API we are considering that it
680 // originated on this site by default for determining relayability.
682 $origin = (x($_REQUEST, 'origin') ? intval($_REQUEST['origin']) : 1);
684 $notify_type = ($parent ? 'comment-new' : 'wall-new');
686 $uri = ($message_id ? $message_id : item_new_uri($a->get_hostname(), $profile_uid, $guid));
688 // Fallback so that we alway have a parent uri
689 if (!$parent_uri || !$parent) {
694 $datarray['uid'] = $profile_uid;
695 $datarray['type'] = $post_type;
696 $datarray['wall'] = $wall;
697 $datarray['gravity'] = $gravity;
698 $datarray['network'] = $network;
699 $datarray['contact-id'] = $contact_id;
700 $datarray['owner-name'] = $contact_record['name'];
701 $datarray['owner-link'] = $contact_record['url'];
702 $datarray['owner-avatar'] = $contact_record['thumb'];
703 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link'], 0);
704 $datarray['author-name'] = $author['name'];
705 $datarray['author-link'] = $author['url'];
706 $datarray['author-avatar'] = $author['thumb'];
707 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link'], 0);
708 $datarray['created'] = datetime_convert();
709 $datarray['edited'] = datetime_convert();
710 $datarray['commented'] = datetime_convert();
711 $datarray['received'] = datetime_convert();
712 $datarray['changed'] = datetime_convert();
713 $datarray['extid'] = $extid;
714 $datarray['guid'] = $guid;
715 $datarray['uri'] = $uri;
716 $datarray['title'] = $title;
717 $datarray['body'] = $body;
718 $datarray['app'] = $app;
719 $datarray['location'] = $location;
720 $datarray['coord'] = $coord;
721 $datarray['tag'] = $str_tags;
722 $datarray['file'] = $categories;
723 $datarray['inform'] = $inform;
724 $datarray['verb'] = $verb;
725 $datarray['object-type'] = $objecttype;
726 $datarray['allow_cid'] = $str_contact_allow;
727 $datarray['allow_gid'] = $str_group_allow;
728 $datarray['deny_cid'] = $str_contact_deny;
729 $datarray['deny_gid'] = $str_group_deny;
730 $datarray['private'] = $private;
731 $datarray['pubmail'] = $pubmail_enable;
732 $datarray['attach'] = $attachments;
733 $datarray['bookmark'] = intval($bookmark);
734 $datarray['parent-uri'] = $parent_uri;
735 $datarray['postopts'] = $postopts;
736 $datarray['origin'] = $origin;
737 $datarray['moderated'] = $allow_moderated;
738 $datarray['gcontact-id'] = GContact::getId(["url" => $datarray['author-link'], "network" => $datarray['network'],
739 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']]);
740 $datarray['object'] = $object;
741 $datarray['last-child'] = 1;
744 * These fields are for the convenience of plugins...
745 * 'self' if true indicates the owner is posting on their own wall
746 * If parent is 0 it is a top-level post.
748 $datarray['parent'] = $parent;
749 $datarray['self'] = $self;
751 // This triggers posts via API and the mirror functions
752 $datarray['api_source'] = $api_source;
754 // This field is for storing the raw conversation data
755 $datarray['protocol'] = PROTOCOL_DFRN;
757 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
758 if (DBM::is_result($r)) {
759 if ($r['conversation-uri'] != '') {
760 $datarray['conversation-uri'] = $r['conversation-uri'];
762 if ($r['conversation-href'] != '') {
763 $datarray['conversation-href'] = $r['conversation-href'];
768 $datarray['edit'] = true;
771 // Search for hashtags
772 item_body_set_hashtags($datarray);
774 // preview mode - prepare the body for display and send it via json
776 require_once 'include/conversation.php';
777 // We set the datarray ID to -1 because in preview mode the dataray
778 // doesn't have an ID.
779 $datarray["id"] = -1;
780 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
781 logger('preview: ' . $o);
782 echo json_encode(['preview' => $o]);
786 call_hooks('post_local',$datarray);
788 if (x($datarray, 'cancel')) {
789 logger('mod_item: post cancelled by plugin.');
791 goaway($return_path);
794 $json = ['cancel' => 1];
795 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
796 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
799 echo json_encode($json);
805 // Fill the cache field
806 // This could be done in Item::update as well - but we have to check for the existance of some fields.
807 put_item_in_cache($datarray);
810 'title' => $datarray['title'],
811 'body' => $datarray['body'],
812 'tag' => $datarray['tag'],
813 'attach' => $datarray['attach'],
814 'file' => $datarray['file'],
815 'rendered-html' => $datarray['rendered-html'],
816 'rendered-hash' => $datarray['rendered-hash'],
817 'edited' => datetime_convert(),
818 'changed' => datetime_convert()];
820 Item::update($fields, ['id' => $post_id]);
822 // update filetags in pconfig
823 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
825 if (x($_REQUEST, 'return') && strlen($return_path)) {
826 logger('return: ' . $return_path);
827 goaway($return_path);
834 unset($datarray['edit']);
835 unset($datarray['self']);
836 unset($datarray['api_source']);
838 $post_id = item_store($datarray);
840 $datarray["id"] = $post_id;
842 // update filetags in pconfig
843 file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
845 // These notifications are sent if someone else is commenting other your wall
847 if ($contact_record != $author) {
849 'type' => NOTIFY_COMMENT,
850 'notify_flags' => $user['notify-flags'],
851 'language' => $user['language'],
852 'to_name' => $user['username'],
853 'to_email' => $user['email'],
854 'uid' => $user['uid'],
856 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
857 'source_name' => $datarray['author-name'],
858 'source_link' => $datarray['author-link'],
859 'source_photo' => $datarray['author-avatar'],
860 'verb' => ACTIVITY_POST,
863 'parent_uri' => $parent_item['uri']
867 // Store the comment signature information in case we need to relay to Diaspora
868 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
870 if (($contact_record != $author) && !count($forum_contact)) {
872 'type' => NOTIFY_WALL,
873 'notify_flags' => $user['notify-flags'],
874 'language' => $user['language'],
875 'to_name' => $user['username'],
876 'to_email' => $user['email'],
877 'uid' => $user['uid'],
879 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
880 'source_name' => $datarray['author-name'],
881 'source_link' => $datarray['author-link'],
882 'source_photo' => $datarray['author-avatar'],
883 'verb' => ACTIVITY_POST,
889 call_hooks('post_local_end', $datarray);
891 if (strlen($emailcc) && $profile_uid == local_user()) {
892 $erecips = explode(',', $emailcc);
893 if (count($erecips)) {
894 foreach ($erecips as $recip) {
895 $addr = trim($recip);
896 if (!strlen($addr)) {
899 $disclaimer = '<hr />' . sprintf(t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
901 $disclaimer .= sprintf(t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
902 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
903 if (!$datarray['title']=='') {
904 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
906 $subject = Email::encodeHeader('[Friendica]' . ' ' . sprintf(t('%s posted an update.'), $a->user['username']), 'UTF-8');
908 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
909 $html = prepare_body($datarray);
910 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
911 include_once 'include/html2plain.php';
913 'fromName' => $a->user['username'],
914 'fromEmail' => $a->user['email'],
916 'replyTo' => $a->user['email'],
917 'messageSubject' => $subject,
918 'htmlVersion' => $message,
919 'textVersion' => html2plain($html.$disclaimer)
921 Emailer::send($params);
926 // Insert an item entry for UID=0 for global entries.
927 // We now do it in the background to save some time.
928 // This is important in interactive environments like the frontend or the API.
929 // We don't fork a new process since this is done anyway with the following command
930 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
932 // Call the background process that is delivering the item to the receivers
933 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
935 logger('post_complete');
937 item_post_return(System::baseUrl(), $api_source, $return_path);
941 function item_post_return($baseurl, $api_source, $return_path) {
942 // figure out how to return, depending on from whence we came
949 goaway($return_path);
952 $json = ['success' => 1];
953 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
954 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
957 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
959 echo json_encode($json);
965 function item_content(App $a) {
967 if (!local_user() && !remote_user()) {
971 require_once 'include/security.php';
974 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
975 $o = drop_item($a->argv[2], !is_ajax());
977 // ajax return: [<item id>, 0 (no perm) | <owner id>]
978 echo json_encode([intval($a->argv[2]), intval($o)]);
986 * This function removes the tag $tag from the text $body and replaces it with
987 * the appropiate link.
989 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
990 * @param unknown_type $body the text to replace the tag in
991 * @param string $inform a comma-seperated string containing everybody to inform
992 * @param string $str_tags string to add the tag to
993 * @param integer $profile_uid
994 * @param string $tag the tag to replace
995 * @param string $network The network of the post
997 * @return boolean true if replaced, false if not replaced
999 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
1005 //is it a person tag?
1006 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
1007 $tag_type = substr($tag, 0, 1);
1008 //is it already replaced?
1009 if (strpos($tag, '[url=')) {
1010 //append tag to str_tags
1011 if (!stristr($str_tags, $tag)) {
1012 if (strlen($str_tags)) {
1018 // Checking for the alias that is used for OStatus
1019 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
1020 if (preg_match($pattern, $tag, $matches)) {
1022 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1023 normalise_link($matches[1]));
1024 if (!DBM::is_result($r)) {
1025 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1026 normalise_link($matches[1]));
1028 if (DBM::is_result($r)) {
1031 $data = Probe::uri($matches[1]);
1034 if ($data["alias"] != "") {
1035 $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
1036 if (!stristr($str_tags, $newtag)) {
1037 if (strlen($str_tags)) {
1040 $str_tags .= $newtag;
1048 //get the person's name
1049 $name = substr($tag, 1);
1051 // Sometimes the tag detection doesn't seem to work right
1052 // This is some workaround
1053 $nameparts = explode(" ", $name);
1054 $name = $nameparts[0];
1056 // Try to detect the contact in various ways
1057 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
1058 // Is it in format @user@domain.tld or @http://domain.tld/...?
1060 // First check the contact table for the address
1061 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1062 WHERE `addr` = '%s' AND `uid` = %d AND
1063 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1066 intval($profile_uid),
1067 dbesc(NETWORK_OSTATUS)
1070 // Then check in the contact table for the url
1071 if (!DBM::is_result($r)) {
1072 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1073 WHERE `nurl` = '%s' AND `uid` = %d AND
1074 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1076 dbesc(normalise_link($name)),
1077 intval($profile_uid),
1078 dbesc(NETWORK_OSTATUS)
1082 // Then check in the global contacts for the address
1083 if (!DBM::is_result($r)) {
1084 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1085 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1088 dbesc(NETWORK_OSTATUS)
1092 // Then check in the global contacts for the url
1093 if (!DBM::is_result($r)) {
1094 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1095 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1097 dbesc(normalise_link($name)),
1098 dbesc(NETWORK_OSTATUS)
1102 if (!DBM::is_result($r)) {
1103 $probed = Probe::uri($name);
1104 if ($result['network'] != NETWORK_PHANTOM) {
1105 GContact::update($probed);
1106 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1107 dbesc(normalise_link($probed["url"])));
1112 if (strrpos($name, '+')) {
1113 // Is it in format @nick+number?
1114 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1116 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1118 intval($profile_uid)
1122 // select someone by attag or nick and the name passed in the current network
1123 if (!DBM::is_result($r) && ($network != ""))
1124 $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",
1128 intval($profile_uid)
1131 //select someone from this user's contacts by name in the current network
1132 if (!DBM::is_result($r) && ($network != "")) {
1133 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1136 intval($profile_uid)
1140 // select someone by attag or nick and the name passed in
1141 if (!DBM::is_result($r)) {
1142 $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",
1145 intval($profile_uid)
1149 // select someone from this user's contacts by name
1150 if (!DBM::is_result($r)) {
1151 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1153 intval($profile_uid)
1158 if (DBM::is_result($r)) {
1159 if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1163 if (isset($r[0]["id"])) {
1164 $inform .= 'cid:' . $r[0]["id"];
1165 } elseif (isset($r[0]["notify"])) {
1166 $inform .= $r[0]["notify"];
1169 $profile = $r[0]["url"];
1170 $alias = $r[0]["alias"];
1171 $newname = $r[0]["nick"];
1172 if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1173 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1174 $newname = $r[0]["name"];
1178 //if there is an url for this persons profile
1179 if (isset($profile) && ($newname != "")) {
1181 // create profile link
1182 $profile = str_replace(',', '%2c', $profile);
1183 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1184 $body = str_replace($tag_type . $name, $newtag, $body);
1185 // append tag to str_tags
1186 if (!stristr($str_tags, $newtag)) {
1187 if (strlen($str_tags)) {
1190 $str_tags .= $newtag;
1194 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1195 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1197 if (strlen($alias)) {
1198 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1199 if (!stristr($str_tags, $newtag)) {
1200 if (strlen($str_tags)) {
1203 $str_tags .= $newtag;
1209 return ['replaced' => $replaced, 'contact' => $r[0]];