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
17 * Posts that originate externally or do not fall into the above
18 * posting categories go through item_store() instead of this function.
21 use Friendica\Core\Config;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBM;
25 use Friendica\Model\Contact;
26 use Friendica\Model\GContact;
27 use Friendica\Network\Probe;
28 use Friendica\Protocol\Diaspora;
29 use Friendica\Protocol\Email;
30 use Friendica\Util\Emailer;
32 require_once 'include/enotify.php';
33 require_once 'include/tags.php';
34 require_once 'include/files.php';
35 require_once 'include/threads.php';
36 require_once 'include/text.php';
37 require_once 'include/items.php';
39 function item_post(App $a) {
41 if (!local_user() && !remote_user() && !x($_REQUEST, 'commenter')) {
45 require_once 'include/security.php';
49 if (x($_REQUEST, 'dropitems')) {
50 $arr_drop = explode(',', $_REQUEST['dropitems']);
51 drop_items($arr_drop);
52 $json = array('success' => 1);
53 echo json_encode($json);
57 call_hooks('post_local_start', $_REQUEST);
58 // logger('postinput ' . file_get_contents('php://input'));
59 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
61 $api_source = ((x($_REQUEST, 'api_source') && $_REQUEST['api_source']) ? true : false);
63 $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
65 $return_path = ((x($_REQUEST, 'return')) ? $_REQUEST['return'] : '');
66 $preview = ((x($_REQUEST, 'preview')) ? intval($_REQUEST['preview']) : 0);
69 * Check for doubly-submitted posts, and reject duplicates
70 * Note that we have to ignore previews, otherwise nothing will post
71 * after it's been previewed
73 if (!$preview && x($_REQUEST, 'post_id_random')) {
74 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
75 logger("item post: duplicate post", LOGGER_DEBUG);
76 item_post_return(System::baseUrl(), $api_source, $return_path);
78 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
82 // Is this a reply to something?
83 $parent = (x($_REQUEST, 'parent') ? intval($_REQUEST['parent']) : 0);
84 $parent_uri = (x($_REQUEST, 'parent_uri') ? trim($_REQUEST['parent_uri']) : '');
87 $parent_contact = null;
93 if ($parent || $parent_uri) {
95 $objecttype = ACTIVITY_OBJ_COMMENT;
97 if (! x($_REQUEST, 'type')) {
98 $_REQUEST['type'] = 'net-comment';
102 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
105 } elseif ($parent_uri && local_user()) {
106 // This is coming from an API source, and we are logged in
107 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
113 // if this isn't the real parent of the conversation, find it
114 if (DBM::is_result($r)) {
115 $parid = $r[0]['parent'];
116 $parent_uri = $r[0]['uri'];
117 if ($r[0]['id'] != $r[0]['parent']) {
118 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
124 if (!DBM::is_result($r)) {
125 notice( t('Unable to locate original post.') . EOL);
126 if (x($_REQUEST, 'return')) {
127 goaway($return_path);
131 $parent_item = $r[0];
132 $parent = $r[0]['id'];
134 // multi-level threading - preserve the info but re-parent to our single level threading
135 //if(($parid) && ($parid != $parent))
136 $thr_parent = $parent_uri;
138 if ($parent_item['contact-id'] && $uid) {
139 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
140 intval($parent_item['contact-id']),
143 if (DBM::is_result($r)) {
144 $parent_contact = $r[0];
147 // If the contact id doesn't fit with the contact, then set the contact to null
148 $thrparent = q("SELECT `author-link`, `network` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($thr_parent));
149 if (DBM::is_result($thrparent) && ($thrparent[0]["network"] === NETWORK_OSTATUS)
150 && (normalise_link($parent_contact["url"]) != normalise_link($thrparent[0]["author-link"]))) {
151 $parent_contact = Contact::getDetailsByURL($thrparent[0]["author-link"]);
153 if (!isset($parent_contact["nick"])) {
154 $probed_contact = Probe::uri($thrparent[0]["author-link"]);
155 if ($probed_contact["network"] != NETWORK_FEED) {
156 $parent_contact = $probed_contact;
157 $parent_contact["nurl"] = normalise_link($probed_contact["url"]);
158 $parent_contact["thumb"] = $probed_contact["photo"];
159 $parent_contact["micro"] = $probed_contact["photo"];
160 $parent_contact["addr"] = $probed_contact["addr"];
163 logger('no contact found: ' . print_r($thrparent, true), LOGGER_DEBUG);
165 logger('parent contact: ' . print_r($parent_contact, true), LOGGER_DEBUG);
168 if ($parent_contact["nick"] == "") {
169 $parent_contact["nick"] = $parent_contact["name"];
175 logger('mod_item: item_post parent=' . $parent);
178 $profile_uid = ((x($_REQUEST, 'profile_uid')) ? intval($_REQUEST['profile_uid']) : 0);
179 $post_id = ((x($_REQUEST, 'post_id')) ? intval($_REQUEST['post_id']) : 0);
180 $app = ((x($_REQUEST, 'source')) ? strip_tags($_REQUEST['source']) : '');
181 $extid = ((x($_REQUEST, 'extid')) ? strip_tags($_REQUEST['extid']) : '');
182 $object = ((x($_REQUEST, 'object')) ? $_REQUEST['object'] : '');
184 // Check for multiple posts with the same message id (when the post was created via API)
185 if (($message_id != '') && ($profile_uid != 0)) {
186 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
191 if (DBM::is_result($r)) {
192 logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
197 $allow_moderated = false;
199 // here is where we are going to check for permission to post a moderated comment.
201 // First check that the parent exists and it is a wall item.
203 if (x($_REQUEST, 'commenter') && (!$parent || !$parent_item['wall'])) {
204 notice(t('Permission denied.') . EOL) ;
205 if (x($_REQUEST, 'return')) {
206 goaway($return_path);
211 // Allow commenting if it is an answer to a public post
212 $allow_comment = ($profile_uid == 0) && $parent && in_array($parent_item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
215 * Now check that it is a page_type of PAGE_BLOG, and that valid personal details
216 * have been provided, and run any anti-spam plugins
218 if (!(can_write_wall($profile_uid) || $allow_comment) && !$allow_moderated) {
219 notice(t('Permission denied.') . EOL) ;
220 if (x($_REQUEST, 'return')) {
221 goaway($return_path);
227 // is this an edited post?
232 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
233 intval($profile_uid),
236 if (! DBM::is_result($i)) {
244 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
247 if (DBM::is_result($r)) {
252 $str_group_allow = $orig_post['allow_gid'];
253 $str_contact_allow = $orig_post['allow_cid'];
254 $str_group_deny = $orig_post['deny_gid'];
255 $str_contact_deny = $orig_post['deny_cid'];
256 $location = $orig_post['location'];
257 $coord = $orig_post['coord'];
258 $verb = $orig_post['verb'];
259 $objecttype = $orig_post['object-type'];
260 $emailcc = $orig_post['emailcc'];
261 $app = $orig_post['app'];
262 $categories = $orig_post['file'];
263 $title = notags(trim($_REQUEST['title']));
264 $body = escape_tags(trim($_REQUEST['body']));
265 $private = $orig_post['private'];
266 $pubmail_enable = $orig_post['pubmail'];
267 $network = $orig_post['network'];
268 $guid = $orig_post['guid'];
269 $extid = $orig_post['extid'];
274 * if coming from the API and no privacy settings are set,
275 * use the user default permissions - as they won't have
276 * been supplied via a form.
278 /// @TODO use x($_REQUEST, 'foo') here
280 && (! array_key_exists('contact_allow', $_REQUEST))
281 && (! array_key_exists('group_allow', $_REQUEST))
282 && (! array_key_exists('contact_deny', $_REQUEST))
283 && (! array_key_exists('group_deny', $_REQUEST))) {
284 $str_group_allow = $user['allow_gid'];
285 $str_contact_allow = $user['allow_cid'];
286 $str_group_deny = $user['deny_gid'];
287 $str_contact_deny = $user['deny_cid'];
290 // use the posted permissions
292 $str_group_allow = perms2str($_REQUEST['group_allow']);
293 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
294 $str_group_deny = perms2str($_REQUEST['group_deny']);
295 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
298 $title = notags(trim($_REQUEST['title']));
299 $location = notags(trim($_REQUEST['location']));
300 $coord = notags(trim($_REQUEST['coord']));
301 $verb = notags(trim($_REQUEST['verb']));
302 $emailcc = notags(trim($_REQUEST['emailcc']));
303 $body = escape_tags(trim($_REQUEST['body']));
304 $network = notags(trim($_REQUEST['network']));
305 $guid = get_guid(32);
307 item_add_language_opt($_REQUEST);
308 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
310 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
312 if ($user['hidewall']) {
316 // If this is a comment, set the permissions from the parent.
320 // for non native networks use the network of the original post as network of the item
321 if (($parent_item['network'] != NETWORK_DIASPORA)
322 && ($parent_item['network'] != NETWORK_OSTATUS)
323 && ($network == "")) {
324 $network = $parent_item['network'];
327 $str_contact_allow = $parent_item['allow_cid'];
328 $str_group_allow = $parent_item['allow_gid'];
329 $str_contact_deny = $parent_item['deny_cid'];
330 $str_group_deny = $parent_item['deny_gid'];
331 $private = $parent_item['private'];
334 $pubmail_enable = ((x($_REQUEST, 'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && (! $private)) ? 1 : 0);
336 // if using the API, we won't see pubmail_enable - figure out if it should be set
338 if ($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
339 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system', 'imap_disabled'))) ? 0 : 1);
340 if (! $mail_disabled) {
341 /// @TODO Check if only pubmail is loaded, * loads all columns
342 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
345 if (DBM::is_result($r) && intval($r[0]['pubmail'])) {
346 $pubmail_enabled = true;
351 if (! strlen($body)) {
355 info(t('Empty post discarded.') . EOL );
356 if (x($_REQUEST, 'return')) {
357 goaway($return_path);
363 if (strlen($categories)) {
364 // get the "fileas" tags for this post
365 $filedas = file_tag_file_to_list($categories, 'file');
367 // save old and new categories, so we can determine what needs to be deleted from pconfig
368 $categories_old = $categories;
369 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
370 $categories_new = $categories;
371 if (strlen($filedas)) {
372 // append the fileas stuff to the new categories list
373 $categories .= file_tag_list_to_file($filedas, 'file');
376 // get contact info for poster
382 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
384 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
385 intval($_SESSION['uid']));
386 } elseif (remote_user()) {
387 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
388 foreach ($_SESSION['remote'] as $v) {
389 if ($v['uid'] == $profile_uid) {
390 $contact_id = $v['cid'];
396 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
402 if (DBM::is_result($r)) {
404 $contact_id = $author['id'];
407 // get contact info for owner
409 if ($profile_uid == local_user() || $allow_comment) {
410 $contact_record = $author;
412 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
415 if (DBM::is_result($r)) {
416 $contact_record = $r[0];
420 $post_type = notags(trim($_REQUEST['type']));
422 if ($post_type === 'net-comment' && $parent_item !== null) {
423 if ($parent_item['wall'] == 1) {
424 $post_type = 'wall-comment';
426 $post_type = 'remote-comment';
430 // Look for any tags and linkify them
434 $tags = get_tags($body);
437 * add a statusnet style reply tag if the original post was from there
438 * and we are replying, and there isn't one already
440 if ($parent && ($parent_contact['network'] == NETWORK_OSTATUS)) {
441 $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
443 if (!in_array($contact, $tags)) {
444 $body = $contact . ' ' . $body;
448 $toplevel_contact = "";
449 $toplevel_parent = q("SELECT `contact`.* FROM `contact`
450 INNER JOIN `item` ON `item`.`contact-id` = `contact`.`id` AND `contact`.`url` = `item`.`author-link`
451 WHERE `item`.`id` = `item`.`parent` AND `item`.`parent` = %d", intval($parent));
452 if (DBM::is_result($toplevel_parent)) {
453 if (!empty($toplevel_parent[0]['addr'])) {
454 $toplevel_contact = '@' . $toplevel_parent[0]['addr'];
456 $toplevel_contact = '@' . $toplevel_parent[0]['nick'] . '+' . $toplevel_parent[0]['id'];
459 $toplevel_parent = q("SELECT `author-link`, `author-name` FROM `item` WHERE `id` = `parent` AND `parent` = %d", intval($parent));
460 $toplevel_contact = '@[url=' . $toplevel_parent[0]['author-link'] . ']' . $toplevel_parent[0]['author-name'] . '[/url]';
463 if (!in_array($toplevel_contact, $tags)) {
464 $tags[] = $toplevel_contact;
470 $private_forum = false;
471 $only_to_forum = false;
472 $forum_contact = array();
475 foreach ($tags as $tag) {
477 $tag_type = substr($tag, 0, 1);
479 if ($tag_type == '#') {
484 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
485 * Robert Johnson should be first in the $tags array
487 $fullnametagged = false;
488 /// @TODO $tagged is initialized above if() block and is not filled, maybe old-lost code?
489 foreach ($tagged as $nextTag) {
490 if (stristr($nextTag, $tag . ' ')) {
491 $fullnametagged = true;
495 if ($fullnametagged) {
499 $success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag, $network);
500 if ($success['replaced']) {
503 // When the forum is private or the forum is addressed with a "!" make the post private
504 if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
505 $private_forum = $success['contact']['prv'];
506 $only_to_forum = ($tag_type == '!');
507 $private_id = $success['contact']['id'];
508 $forum_contact = $success['contact'];
509 } elseif (is_array($success['contact']) && $success['contact']['forum'] &&
510 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
511 $private_forum = false;
512 $only_to_forum = true;
513 $private_id = $success['contact']['id'];
514 $forum_contact = $success['contact'];
519 $original_contact_id = $contact_id;
521 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
522 // we tagged a forum in a top level post. Now we change the post
523 $private = $private_forum;
525 $str_group_allow = '';
526 $str_contact_deny = '';
527 $str_group_deny = '';
528 if ($private_forum) {
529 $str_contact_allow = '<' . $private_id . '>';
531 $str_contact_allow = '';
533 $contact_id = $private_id;
534 $contact_record = $forum_contact;
535 $_REQUEST['origin'] = false;
539 * When a photo was uploaded into the message using the (profile wall) ajax
540 * uploader, The permissions are initially set to disallow anybody but the
541 * owner from seeing it. This is because the permissions may not yet have been
542 * set for the post. If it's private, the photo permissions should be set
543 * appropriately. But we didn't know the final permissions on the post until
544 * now. So now we'll look for links of uploaded messages that are in the
545 * post and set them to the same permissions as the post itself.
550 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
552 if (count($images)) {
554 $objecttype = ACTIVITY_OBJ_IMAGE;
556 foreach ($images as $image) {
557 if (!stristr($image, System::baseUrl() . '/photo/')) {
560 $image_uri = substr($image,strrpos($image,'/') + 1);
561 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
562 if (!strlen($image_uri)) {
565 $srch = '<' . intval($original_contact_id) . '>';
567 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
568 AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
574 if (! DBM::is_result($r)) {
578 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
579 WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
580 dbesc($str_contact_allow),
581 dbesc($str_group_allow),
582 dbesc($str_contact_deny),
583 dbesc($str_group_deny),
585 intval($profile_uid),
586 dbesc(t('Wall Photos'))
594 * Next link in any attachment references we find in the post.
598 if ((! $preview) && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
599 $attaches = $match[1];
600 if (count($attaches)) {
601 foreach ($attaches as $attach) {
602 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
603 intval($profile_uid),
606 if (DBM::is_result($r)) {
607 $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
608 WHERE `uid` = %d AND `id` = %d",
609 dbesc($str_contact_allow),
610 dbesc($str_group_allow),
611 dbesc($str_contact_deny),
612 dbesc($str_group_deny),
613 intval($profile_uid),
621 // embedded bookmark or attachment in post? set bookmark flag
624 $data = get_attachment_data($body);
625 if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
626 $objecttype = ACTIVITY_OBJ_BOOKMARK;
630 $body = bb_translate_video($body);
633 // Fold multi-line [code] sequences
634 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
636 $body = scale_external_images($body, false);
638 // Setting the object type if not defined before
640 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
641 require_once 'include/plaintext.php';
642 $objectdata = get_attached_data($body);
644 if ($objectdata["type"] == "link") {
645 $objecttype = ACTIVITY_OBJ_BOOKMARK;
646 } elseif ($objectdata["type"] == "video") {
647 $objecttype = ACTIVITY_OBJ_VIDEO;
648 } elseif ($objectdata["type"] == "photo") {
649 $objecttype = ACTIVITY_OBJ_IMAGE;
657 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
658 foreach ($match[2] as $mtch) {
659 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
660 intval($profile_uid),
663 if (DBM::is_result($r)) {
664 if (strlen($attachments)) {
667 $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]';
669 $body = str_replace($match[1],'',$body);
675 if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
679 if (! strlen($verb)) {
680 $verb = ACTIVITY_POST ;
683 if ($network == "") {
684 $network = NETWORK_DFRN;
687 $gravity = (($parent) ? 6 : 0 );
689 // even if the post arrived via API we are considering that it
690 // originated on this site by default for determining relayability.
692 $origin = ((x($_REQUEST, 'origin')) ? intval($_REQUEST['origin']) : 1);
694 $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
696 $uri = (($message_id) ? $message_id : item_new_uri($a->get_hostname(),$profile_uid, $guid));
698 // Fallback so that we alway have a thr-parent
704 $datarray['uid'] = $profile_uid;
705 $datarray['type'] = $post_type;
706 $datarray['wall'] = $wall;
707 $datarray['gravity'] = $gravity;
708 $datarray['network'] = $network;
709 $datarray['contact-id'] = $contact_id;
710 $datarray['owner-name'] = $contact_record['name'];
711 $datarray['owner-link'] = $contact_record['url'];
712 $datarray['owner-avatar'] = $contact_record['thumb'];
713 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link'], 0);
714 $datarray['author-name'] = $author['name'];
715 $datarray['author-link'] = $author['url'];
716 $datarray['author-avatar'] = $author['thumb'];
717 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link'], 0);
718 $datarray['created'] = datetime_convert();
719 $datarray['edited'] = datetime_convert();
720 $datarray['commented'] = datetime_convert();
721 $datarray['received'] = datetime_convert();
722 $datarray['changed'] = datetime_convert();
723 $datarray['extid'] = $extid;
724 $datarray['guid'] = $guid;
725 $datarray['uri'] = $uri;
726 $datarray['title'] = $title;
727 $datarray['body'] = $body;
728 $datarray['app'] = $app;
729 $datarray['location'] = $location;
730 $datarray['coord'] = $coord;
731 $datarray['tag'] = $str_tags;
732 $datarray['file'] = $categories;
733 $datarray['inform'] = $inform;
734 $datarray['verb'] = $verb;
735 $datarray['object-type'] = $objecttype;
736 $datarray['allow_cid'] = $str_contact_allow;
737 $datarray['allow_gid'] = $str_group_allow;
738 $datarray['deny_cid'] = $str_contact_deny;
739 $datarray['deny_gid'] = $str_group_deny;
740 $datarray['private'] = $private;
741 $datarray['pubmail'] = $pubmail_enable;
742 $datarray['attach'] = $attachments;
743 $datarray['bookmark'] = intval($bookmark);
744 $datarray['thr-parent'] = $thr_parent;
745 $datarray['postopts'] = $postopts;
746 $datarray['origin'] = $origin;
747 $datarray['moderated'] = $allow_moderated;
748 $datarray['gcontact-id'] = GContact::getId(array("url" => $datarray['author-link'], "network" => $datarray['network'],
749 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']));
750 $datarray['object'] = $object;
753 * These fields are for the convenience of plugins...
754 * 'self' if true indicates the owner is posting on their own wall
755 * If parent is 0 it is a top-level post.
757 $datarray['parent'] = $parent;
758 $datarray['self'] = $self;
759 // $datarray['prvnets'] = $user['prvnets'];
761 // This triggers posts via API and the mirror functions
762 $datarray['api_source'] = $api_source;
764 $datarray['parent-uri'] = ($parent == 0) ? $uri : $parent_item['uri'];
765 $datarray['plink'] = System::baseUrl() . '/display/' . urlencode($datarray['guid']);
766 $datarray['last-child'] = 1;
767 $datarray['visible'] = 1;
769 $datarray['protocol'] = PROTOCOL_DFRN;
771 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
772 if (DBM::is_result($r)) {
773 if ($r['conversation-uri'] != '') {
774 $datarray['conversation-uri'] = $r['conversation-uri'];
776 if ($r['conversation-href'] != '') {
777 $datarray['conversation-href'] = $r['conversation-href'];
782 $datarray['edit'] = true;
785 // Search for hashtags
786 item_body_set_hashtags($datarray);
788 // preview mode - prepare the body for display and send it via json
790 require_once 'include/conversation.php';
791 // We set the datarray ID to -1 because in preview mode the dataray
792 // doesn't have an ID.
793 $datarray["id"] = -1;
794 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
795 logger('preview: ' . $o);
796 echo json_encode(array('preview' => $o));
800 call_hooks('post_local',$datarray);
802 if (x($datarray, 'cancel')) {
803 logger('mod_item: post cancelled by plugin.');
805 goaway($return_path);
808 $json = array('cancel' => 1);
809 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
810 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
813 echo json_encode($json);
817 // Fill the cache field
818 put_item_in_cache($datarray);
820 $datarray = store_conversation($datarray);
823 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `attach` = '%s', `file` = '%s', `rendered-html` = '%s', `rendered-hash` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d",
824 dbesc($datarray['title']),
825 dbesc($datarray['body']),
826 dbesc($datarray['tag']),
827 dbesc($datarray['attach']),
828 dbesc($datarray['file']),
829 dbesc($datarray['rendered-html']),
830 dbesc($datarray['rendered-hash']),
831 dbesc(datetime_convert()),
832 dbesc(datetime_convert()),
837 create_tags_from_item($post_id);
838 create_files_from_item($post_id);
839 update_thread($post_id);
841 // update filetags in pconfig
842 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
844 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $post_id);
845 if ((x($_REQUEST, 'return')) && strlen($return_path)) {
846 logger('return: ' . $return_path);
847 goaway($return_path);
856 $r = q("INSERT INTO `item` (`guid`, `extid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,
857 `owner-name`,`owner-link`,`owner-avatar`, `owner-id`,
858 `author-name`, `author-link`, `author-avatar`, `author-id`,
859 `created`, `edited`, `commented`, `received`, `changed`,
860 `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`,
861 `tag`, `inform`, `verb`, `object-type`, `postopts`,
862 `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`,
863 `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file`,
864 `rendered-html`, `rendered-hash`, `gcontact-id`, `object`,
865 `parent`, `parent-uri`, `plink`, `last-child`, `visible`)
866 VALUES('%s', '%s', %d, '%s', %d, %d, '%s', %d,
867 '%s', '%s', '%s', %d,
868 '%s', '%s', '%s', %d,
869 '%s', '%s', '%s', '%s', '%s',
870 '%s', '%s', '%s', '%s', '%s', '%s', '%s',
871 '%s', '%s', '%s', '%s', '%s',
872 '%s', '%s', '%s', '%s', %d,
873 %d, '%s', %d, %d, %d, '%s',
874 '%s', '%s', %d, '%s',
875 %d, '%s', '%s', %d, %d)",
876 dbesc($datarray['guid']),
877 dbesc($datarray['extid']),
878 intval($datarray['uid']),
879 dbesc($datarray['type']),
880 intval($datarray['wall']),
881 intval($datarray['gravity']),
882 dbesc($datarray['network']),
883 intval($datarray['contact-id']),
884 dbesc($datarray['owner-name']),
885 dbesc($datarray['owner-link']),
886 dbesc($datarray['owner-avatar']),
887 intval($datarray['owner-id']),
888 dbesc($datarray['author-name']),
889 dbesc($datarray['author-link']),
890 dbesc($datarray['author-avatar']),
891 intval($datarray['author-id']),
892 dbesc($datarray['created']),
893 dbesc($datarray['edited']),
894 dbesc($datarray['commented']),
895 dbesc($datarray['received']),
896 dbesc($datarray['changed']),
897 dbesc($datarray['uri']),
898 dbesc($datarray['thr-parent']),
899 dbesc($datarray['title']),
900 dbesc($datarray['body']),
901 dbesc($datarray['app']),
902 dbesc($datarray['location']),
903 dbesc($datarray['coord']),
904 dbesc($datarray['tag']),
905 dbesc($datarray['inform']),
906 dbesc($datarray['verb']),
907 dbesc($datarray['object-type']),
908 dbesc($datarray['postopts']),
909 dbesc($datarray['allow_cid']),
910 dbesc($datarray['allow_gid']),
911 dbesc($datarray['deny_cid']),
912 dbesc($datarray['deny_gid']),
913 intval($datarray['private']),
914 intval($datarray['pubmail']),
915 dbesc($datarray['attach']),
916 intval($datarray['bookmark']),
917 intval($datarray['origin']),
918 intval($datarray['moderated']),
919 dbesc($datarray['file']),
920 dbesc($datarray['rendered-html']),
921 dbesc($datarray['rendered-hash']),
922 intval($datarray['gcontact-id']),
923 dbesc($datarray['object']),
924 intval($datarray['parent']),
925 dbesc($datarray['parent-uri']),
926 dbesc($datarray['plink']),
927 intval($datarray['last-child']),
928 intval($datarray['visible'])
931 if (DBM::is_result($r)) {
932 $post_id = dba::lastInsertId();
934 logger('mod_item: unable to create post.');
940 logger('mod_item: unable to retrieve post that was just stored.');
941 notice(t('System error. Post not saved.') . EOL);
942 goaway($return_path);
946 logger('mod_item: saved item ' . $post_id);
948 $datarray["id"] = $post_id;
950 item_set_last_item($datarray);
952 // update filetags in pconfig
953 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
957 // This item is the last leaf and gets the comment box, clear any ancestors
958 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d AND `last-child` AND `id` != %d",
959 dbesc(datetime_convert()),
964 // update the commented timestamp on the parent
965 q("UPDATE `item` SET `visible` = 1, `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
966 dbesc(datetime_convert()),
967 dbesc(datetime_convert()),
971 if ($contact_record != $author) {
973 'type' => NOTIFY_COMMENT,
974 'notify_flags' => $user['notify-flags'],
975 'language' => $user['language'],
976 'to_name' => $user['username'],
977 'to_email' => $user['email'],
978 'uid' => $user['uid'],
980 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
981 'source_name' => $datarray['author-name'],
982 'source_link' => $datarray['author-link'],
983 'source_photo' => $datarray['author-avatar'],
984 'verb' => ACTIVITY_POST,
987 'parent_uri' => $parent_item['uri']
993 // Store the comment signature information in case we need to relay to Diaspora
994 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
999 $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d",
1003 if (($contact_record != $author) && !count($forum_contact)) {
1005 'type' => NOTIFY_WALL,
1006 'notify_flags' => $user['notify-flags'],
1007 'language' => $user['language'],
1008 'to_name' => $user['username'],
1009 'to_email' => $user['email'],
1010 'uid' => $user['uid'],
1011 'item' => $datarray,
1012 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
1013 'source_name' => $datarray['author-name'],
1014 'source_link' => $datarray['author-link'],
1015 'source_photo' => $datarray['author-avatar'],
1016 'verb' => ACTIVITY_POST,
1022 call_hooks('post_local_end', $datarray);
1024 if (strlen($emailcc) && $profile_uid == local_user()) {
1025 $erecips = explode(',', $emailcc);
1026 if (count($erecips)) {
1027 foreach ($erecips as $recip) {
1028 $addr = trim($recip);
1029 if (! strlen($addr)) {
1032 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
1034 $disclaimer .= sprintf( t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
1035 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
1036 if (!$datarray['title']=='') {
1037 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
1039 $subject = Email::encodeHeader('[Friendica]' . ' ' . sprintf( t('%s posted an update.'), $a->user['username']), 'UTF-8');
1041 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
1042 $html = prepare_body($datarray);
1043 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
1044 include_once 'include/html2plain.php';
1046 'fromName' => $a->user['username'],
1047 'fromEmail' => $a->user['email'],
1049 'replyTo' => $a->user['email'],
1050 'messageSubject' => $subject,
1051 'htmlVersion' => $message,
1052 'textVersion' => html2plain($html.$disclaimer)
1054 Emailer::send($params);
1059 if ($post_id == $parent) {
1060 add_thread($post_id);
1062 update_thread($parent, true);
1067 create_tags_from_item($post_id);
1068 create_files_from_item($post_id);
1070 // Insert an item entry for UID=0 for global entries.
1071 // We now do it in the background to save some time.
1072 // This is important in interactive environments like the frontend or the API.
1073 // We don't fork a new process since this is done anyway with the following command
1074 Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1076 // Call the background process that is delivering the item to the receivers
1077 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
1079 logger('post_complete');
1081 item_post_return(System::baseUrl(), $api_source, $return_path);
1085 function item_post_return($baseurl, $api_source, $return_path) {
1086 // figure out how to return, depending on from whence we came
1093 goaway($return_path);
1096 $json = array('success' => 1);
1097 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
1098 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
1101 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
1103 echo json_encode($json);
1109 function item_content(App $a) {
1111 if ((! local_user()) && (! remote_user())) {
1115 require_once 'include/security.php';
1118 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
1119 $o = drop_item($a->argv[2], !is_ajax());
1121 // ajax return: [<item id>, 0 (no perm) | <owner id>]
1122 echo json_encode(array(intval($a->argv[2]), intval($o)));
1130 * This function removes the tag $tag from the text $body and replaces it with
1131 * the appropiate link.
1133 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
1134 * @param unknown_type $body the text to replace the tag in
1135 * @param string $inform a comma-seperated string containing everybody to inform
1136 * @param string $str_tags string to add the tag to
1137 * @param integer $profile_uid
1138 * @param string $tag the tag to replace
1139 * @param string $network The network of the post
1141 * @return boolean true if replaced, false if not replaced
1143 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
1149 //is it a person tag?
1150 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
1151 $tag_type = substr($tag, 0, 1);
1152 //is it already replaced?
1153 if (strpos($tag, '[url=')) {
1154 //append tag to str_tags
1155 if (!stristr($str_tags, $tag)) {
1156 if (strlen($str_tags)) {
1162 // Checking for the alias that is used for OStatus
1163 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
1164 if (preg_match($pattern, $tag, $matches)) {
1166 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1167 normalise_link($matches[1]));
1168 if (!DBM::is_result($r)) {
1169 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1170 normalise_link($matches[1]));
1172 if (DBM::is_result($r)) {
1175 $data = Probe::uri($matches[1]);
1178 if ($data["alias"] != "") {
1179 $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
1180 if (!stristr($str_tags, $newtag)) {
1181 if (strlen($str_tags)) {
1184 $str_tags .= $newtag;
1192 //get the person's name
1193 $name = substr($tag, 1);
1195 // Sometimes the tag detection doesn't seem to work right
1196 // This is some workaround
1197 $nameparts = explode(" ", $name);
1198 $name = $nameparts[0];
1200 // Try to detect the contact in various ways
1201 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
1202 // Is it in format @user@domain.tld or @http://domain.tld/...?
1204 // First check the contact table for the address
1205 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1206 WHERE `addr` = '%s' AND `uid` = %d AND
1207 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1210 intval($profile_uid),
1211 dbesc(NETWORK_OSTATUS)
1214 // Then check in the contact table for the url
1215 if (!DBM::is_result($r)) {
1216 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1217 WHERE `nurl` = '%s' AND `uid` = %d AND
1218 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1220 dbesc(normalise_link($name)),
1221 intval($profile_uid),
1222 dbesc(NETWORK_OSTATUS)
1226 // Then check in the global contacts for the address
1227 if (!DBM::is_result($r)) {
1228 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1229 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1232 dbesc(NETWORK_OSTATUS)
1236 // Then check in the global contacts for the url
1237 if (!DBM::is_result($r)) {
1238 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1239 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1241 dbesc(normalise_link($name)),
1242 dbesc(NETWORK_OSTATUS)
1246 if (!DBM::is_result($r)) {
1247 $probed = Probe::uri($name);
1248 if ($result['network'] != NETWORK_PHANTOM) {
1249 GContact::update($probed);
1250 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1251 dbesc(normalise_link($probed["url"])));
1256 if (strrpos($name, '+')) {
1257 // Is it in format @nick+number?
1258 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1260 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1262 intval($profile_uid)
1266 // select someone by attag or nick and the name passed in the current network
1267 if(!DBM::is_result($r) && ($network != ""))
1268 $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",
1272 intval($profile_uid)
1275 //select someone from this user's contacts by name in the current network
1276 if (!DBM::is_result($r) && ($network != "")) {
1277 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1280 intval($profile_uid)
1284 // select someone by attag or nick and the name passed in
1285 if(!DBM::is_result($r)) {
1286 $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",
1289 intval($profile_uid)
1293 // select someone from this user's contacts by name
1294 if(!DBM::is_result($r)) {
1295 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1297 intval($profile_uid)
1302 if (DBM::is_result($r)) {
1303 if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1307 if (isset($r[0]["id"])) {
1308 $inform .= 'cid:' . $r[0]["id"];
1309 } elseif (isset($r[0]["notify"])) {
1310 $inform .= $r[0]["notify"];
1313 $profile = $r[0]["url"];
1314 $alias = $r[0]["alias"];
1315 $newname = $r[0]["nick"];
1316 if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1317 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1318 $newname = $r[0]["name"];
1322 //if there is an url for this persons profile
1323 if (isset($profile) && ($newname != "")) {
1325 // create profile link
1326 $profile = str_replace(',', '%2c', $profile);
1327 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1328 $body = str_replace($tag_type . $name, $newtag, $body);
1329 // append tag to str_tags
1330 if (! stristr($str_tags, $newtag)) {
1331 if (strlen($str_tags)) {
1334 $str_tags .= $newtag;
1338 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1339 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1341 if (strlen($alias)) {
1342 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1343 if (! stristr($str_tags, $newtag)) {
1344 if (strlen($str_tags)) {
1347 $str_tags .= $newtag;
1353 return array('replaced' => $replaced, 'contact' => $r[0]);