function serialize() { $this->createPayload(); logIO("O", $this->payload); return $this->payload; }
/** * Method "ngg.getImages" * Return the list of all images inside a gallery * * @since 1.4 * * @param array $args Method parameters. * - int blog_id * - string username * - string password * - int gallery_id * @return array with all images */ function getImages($args) { global $nggdb; require_once dirname(dirname(__FILE__)) . '/admin/functions.php'; // admin functions $this->escape($args); $blog_ID = (int) $args[0]; $username = $args[1]; $password = $args[2]; $gid = (int) $args[3]; if (!($user = $this->login($username, $password))) { return $this->error; } // Look for the gallery , could we find it ? if (!($gallery = nggdb::find_gallery($gid))) { return new IXR_Error(404, __('Could not find gallery ' . $gid)); } // Now check if you have the correct capability for this gallery if (!nggAdmin::can_manage_this_gallery($gallery->author)) { logIO('O', '(NGG) User does not have upload_files capability'); $this->error = new IXR_Error(401, __('You are not allowed to upload files to this gallery.')); return $this->error; } // get picture values $picture_list = $nggdb->get_gallery($gid, 'pid', 'ASC', false); return $picture_list; }
/** * blogger.getRecentPosts retieves X most recent posts. * * This API call is not documented on * {@link http://www.blogger.com/developers/api/1_docs/} * @see http://www.sixapart.com/developers/xmlrpc/blogger_api/bloggergetrecentposts.html * * @param xmlrpcmsg XML-RPC Message * 0 appkey (string): Unique identifier/passcode of the application sending the post. * (See access info {@link http://www.blogger.com/developers/api/1_docs/#access} .) * 1 blogid (string): Unique identifier of the blog the post will be added to. * Currently ignored in b2evo, in favor of the category. * 2 username (string): Login for a Blogger user who has permission to edit the given * post (either the user who originally created it or an admin of the blog). * 3 password (string): Password for said username. * 4 numposts (integer): number of posts to retrieve. * @return xmlrpcresp XML-RPC Response */ function blogger_getrecentposts($m) { global $xmlrpcerruser, $DB; // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 2, 3))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // GET BLOG: /** * @var Blog */ if (!($Blog =& xmlrpcs_get_Blog($m, 1))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } $numposts = $m->getParam(4); $numposts = $numposts->scalarval(); // Get the posts to display: load_class('items/model/_itemlist.class.php', 'ItemList'); $MainList = new ItemList2($Blog, NULL, NULL, $numposts); // Protected and private get checked by statuses_where_clause(). $statuses = array('published', 'redirected', 'protected', 'private'); if ($current_User->check_perm('blog_ismember', 'view', false, $Blog->ID)) { // These statuses require member status: $statuses = array_merge($statuses, array('draft', 'deprecated')); } logIO('Statuses: ' . implode(', ', $statuses)); $MainList->set_filters(array('visibility_array' => $statuses, 'order' => 'DESC', 'unit' => 'posts')); // Run the query: $MainList->query(); logIO('Items:' . $MainList->result_num_rows); $data = array(); while ($Item =& $MainList->get_item()) { logIO('Item:' . $Item->title . ' - Issued: ' . $Item->issue_date . ' - Modified: ' . $Item->datemodified); $post_date = mysql2date('U', $Item->issue_date); $post_date = gmdate('Ymd', $post_date) . 'T' . gmdate('H:i:s', $post_date); $content = '<title>' . $Item->title . '</title>'; $content .= '<category>' . $Item->main_cat_ID . '</category>'; $content .= $Item->content; // Load Item's creator User: $Item->get_creator_User(); $authorname = $Item->creator_User->get('preferredname'); $data[] = new xmlrpcval(array('authorName' => new xmlrpcval($authorname), 'userid' => new xmlrpcval($Item->creator_user_ID), 'dateCreated' => new xmlrpcval($post_date, 'dateTime.iso8601'), 'content' => new xmlrpcval($content), 'postid' => new xmlrpcval($Item->ID)), 'struct'); } $resp = new xmlrpcval($data, 'array'); logIO('OK.'); return new xmlrpcresp($resp); }
/** * mt.publishPost * * @see http://www.sixapart.com/developers/xmlrpc/movable_type_api/mtpublishpost.html * * @param xmlrpcmsg XML-RPC Message * 0 postid (string): Unique identifier of the post to publish * 1 username (string): Login for a user who is member of the blog. * 2 password (string): Password for said username. */ function mt_publishPost($m) { global $localtimenow, $DB; // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 1, 2))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } logIO('mt_publishPost: Login OK'); // GET POST: /** * @var Item */ if (!($edited_Item =& xmlrpcs_get_Item($m, 0))) { // Failed, return (last) error: return xmlrpcs_resperror(); } if (!$current_User->check_perm('item_post!published', 'edit', false, $edited_Item)) { return xmlrpcs_resperror(3); // Permission denied } logIO('mt_publishPost: Permission granted'); logIO('mt_publishPost: Old post status: ' . $edited_Item->status); $edited_Item->set('status', 'published'); //$edited_Item->set( 'datestart', date('Y-m-d H:i:s', $localtimenow) ); if ($edited_Item->dbupdate() === false) { // Could not update item... return xmlrpcs_resperror(99, 'Database error: ' . $DB->last_error); // DB error } logIO('mt_publishPost: Item published.'); // Execute or schedule notifications & pings: logIO('mt_publishPost: Handling notifications...'); $edited_Item->handle_post_processing(false, false); logIO('mt_publishPost: OK.'); return new xmlrpcresp(new xmlrpcval(1, 'boolean')); }
/** * metaweblog.getPost retieves a given post. * * @see http://www.xmlrpc.com/metaWeblogApi#basicEntrypoints * * @param xmlrpcmsg XML-RPC Message * 0 postid (string): Unique identifier of the post * 1 username (string): Login for a Blogger user who has permission to edit the given * post (either the user who originally created it or an admin of the blog). * 2 password (string): Password for said username. * @return xmlrpcresp XML-RPC Response */ function mw_getpost($m) { global $xmlrpcerruser; // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 1, 2))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // GET POST: /** * @var Item */ if (!($edited_Item =& xmlrpcs_get_Item($m, 0))) { // Failed, return (last) error: return xmlrpcs_resperror(); } // CHECK PERMISSION: (we need at least one post/edit status) if (!$current_User->check_perm('blog_post_statuses', 1, false, $edited_Item->blog_ID)) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } logIO('Permission granted.'); $post_date = mysql2date("U", $edited_Item->issue_date); $post_date = gmdate("Ymd", $post_date) . "T" . gmdate("H:i:s", $post_date); $struct = new xmlrpcval(array('link' => new xmlrpcval($edited_Item->get_permanent_url()), 'title' => new xmlrpcval($edited_Item->title), 'description' => new xmlrpcval($edited_Item->content), 'dateCreated' => new xmlrpcval($post_date, "dateTime.iso8601"), 'userid' => new xmlrpcval($edited_Item->creator_user_ID), 'postid' => new xmlrpcval($edited_Item->ID), 'content' => new xmlrpcval($edited_Item->content), 'permalink' => new xmlrpcval($edited_Item->get_permanent_url()), 'categories' => new xmlrpcval($edited_Item->main_cat_ID)), "struct"); $resp = $struct; logIO('OK.'); return new xmlrpcresp($resp); }
function pingback_ping($m) { // original code by Mort // (http://mort.mine.nu:8080) global $wpdb; global $wp_version; if (!get_settings('use_pingback')) { return new xmlrpcresp(new xmlrpcval('Sorry, this weblog does not allow you to pingback its posts.')); } $title = ''; $pagelinkedfrom = $m->getParam(0); $pagelinkedfrom = $pagelinkedfrom->scalarval(); $pagelinkedto = $m->getParam(1); $pagelinkedto = $pagelinkedto->scalarval(); $pagelinkedfrom = addslashes(str_replace('&', '&', $pagelinkedfrom)); $pagelinkedto = preg_replace('#&([^amp\\;])#is', '&$1', $pagelinkedto); $messages = array(htmlentities('Pingback from ' . $pagelinkedfrom . ' to ' . $pagelinkedto . ' registered. Keep the web talking! :-)'), htmlentities("We can't find the URL to the post you are trying to " . "link to in your entry. Please check how you wrote the post's permalink in your entry."), htmlentities("We can't find the post you are trying to link to." . " Please check the post's permalink.")); $message = $messages[0]; // Check if the page linked to is in our site $pos1 = strpos($pagelinkedto, str_replace('http://', '', str_replace('www.', '', wp_siteurl()))); if ($pos1) { // let's find which post is linked to $urltest = parse_url($pagelinkedto); if ($post_ID = url_to_postid($pagelinkedto)) { $way = 'url_to_postid()'; } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) { // the path defines the post_ID (archives/p/XXXX) $blah = explode('/', $match[0]); $post_ID = $blah[1]; $way = 'from the path'; } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) { // the querystring defines the post_ID (?p=XXXX) $blah = explode('=', $match[0]); $post_ID = $blah[1]; $way = 'from the querystring'; } elseif (isset($urltest['fragment'])) { // an #anchor is there, it's either... if (intval($urltest['fragment'])) { // ...an integer #XXXX (simpliest case) $post_ID = $urltest['fragment']; $way = 'from the fragment (numeric)'; } elseif (preg_match('/post-[0-9]+/', $urltest['fragment'])) { // ...a post id in the form 'post-###' $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']); $way = 'from the fragment (post-###)'; } elseif (is_string($urltest['fragment'])) { // ...or a string #title, a little more complicated $title = preg_replace('/[^a-zA-Z0-9]/', '.', $urltest['fragment']); $sql = "SELECT ID FROM " . wp_table('posts') . " WHERE post_title RLIKE '" . addslashes($title) . "'"; $post_ID = $wpdb->get_var($sql) or die("Query: {$sql}\n\nError: "); $way = 'from the fragment (title)'; } } else { // TODO: Attempt to extract a post ID from the given URL $post_ID = -1; $way = 'no match'; } logIO('O', "(PB) URI='{$pagelinkedto}' ID='{$post_ID}' Found='{$way}'"); $sql = "SELECT post_author FROM " . wp_table('posts') . " WHERE ID = {$post_ID}"; $result = $wpdb->get_results($sql); if ($wpdb->num_rows) { // Let's check that the remote site didn't already pingback this entry $sql = 'SELECT * FROM ' . wp_table('comments') . ' WHERE comment_post_ID = ' . $post_ID . ' AND comment_author_url = \'' . $pagelinkedfrom . '\' AND comment_content LIKE \'%<pingback />%\''; $result = $wpdb->get_results($sql); if ($wpdb->num_rows || 1 == 1) { // very stupid, but gives time to the 'from' server to publish ! sleep(1); // Let's check the remote site require_once XOOPS_ROOT_PATH . '/class/snoopy.php'; $snoopy = new Snoopy(); if ($snoopy->fetch($pagelinkedfrom)) { $linea = $snoopy->results; } else { $linea = ''; } logIO('O', "(PB) CHARSET='" . $GLOBALS['blog_charset']); $linea = mb_conv($linea, $GLOBALS['blog_charset'], 'auto'); // Work around bug in strip_tags(): $linea = str_replace('<!DOCTYPE', '<DOCTYPE', $linea); $linea = strip_tags($linea, '<title><a>'); $linea = strip_all_but_one_link($linea, $pagelinkedto); // I don't think we need this? -- emc3 if (empty($matchtitle)) { preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle); } $pos2 = strpos($linea, $pagelinkedto); $pos3 = strpos($linea, str_replace('http://www.', 'http://', $pagelinkedto)); logIO('O', "(PB) POS='{$pos2}, {$pos3}'"); if (is_integer($pos2) || is_integer($pos3)) { //debug_fwrite($log, 'The page really links to us :)'."\n"); $pos4 = is_integer($pos2) ? $pos2 : $pos3; $start = $pos4 - 50; if (function_exists('mb_convert_encoding')) { $tmp1 = mb_strcut($linea, 0, $start, $GLOBALS['blog_charset']); } else { $tmp1 = substr($linea, 0, $start); } if (preg_match('/<[^>]*?$/', $tmp1, $match)) { logIO('O', "(PB) MATCH='{$match[0]}"); $offset = strlen($match[0]); } else { $offset = 0; } if (function_exists('mb_convert_encoding')) { $context = mb_strcut($linea, $start - $offset, 150 + $offset, $GLOBALS['blog_charset']); } else { $context = substr($linea, $star - $offsett, 150 + $offset); } $context = str_replace("\n", ' ', $context); $context = str_replace('&', '&', $context); logIO('O', "(PB) CONTENT='{$context}"); } else { logIO('O', "(PB) CONTEXT=The page doesn't link to us, here's an excerpt"); exit; } // fclose($fp); if (!empty($context)) { // Check if pings are on, inelegant exit $pingstatus = $wpdb->get_var("SELECT ping_status FROM " . wp_table('posts') . " WHERE ID = {$post_ID}"); if ('closed' == $pingstatus) { logIO('O', '(PB) Sorry, pings are turned off for this post.'); exit; } $pagelinkedfrom = preg_replace('#&([^amp\\;])#is', '&$1', $pagelinkedfrom); $title = !strlen($matchtitle[1]) ? $pagelinkedfrom : $matchtitle[1]; $context = strip_tags($context); $context = '<pingback />[...] ' . htmlspecialchars(trim($context)) . ' [...]'; $context = format_to_post($context); $original_pagelinkedfrom = $pagelinkedfrom; $pagelinkedfrom = addslashes($pagelinkedfrom); $original_title = $title; $title = addslashes(strip_tags(trim($title))); $now = current_time('mysql', 0); if (get_settings('comment_moderation') == 'manual') { $approved = 0; } else { if (get_settings('comment_moderation') == 'auto') { $approved = 0; } else { // none $approved = 1; } } $consulta = $wpdb->query("INSERT INTO " . wp_table('comments') . " \n\t\t\t\t\t\t(comment_post_ID, comment_author, comment_author_url, comment_date, comment_content,comment_approved, comment_type) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t({$post_ID}, '{$title}', '{$pagelinkedfrom}', '{$now}', '{$context}', '{$approved}', 'pingback')\n\t\t\t\t\t\t"); $comment_ID = $wpdb->get_var('SELECT last_insert_id()'); do_action('pingback_post', $comment_ID); if (get_settings('moderation_notify') && !$approved) { wp_notify_moderator($comment_ID, 'pingback'); } if (get_settings('comments_notify') && $approved) { wp_notify_postauthor($comment_ID, 'pingback'); } } else { // URL pattern not found $message = "Page linked to: {$pagelinkedto}\nPage linked from:" . " {$pagelinkedfrom}\nTitle: {$title}\nContext: {$context}\n\n" . $messages[1]; } } else { // We already have a Pingback from this URL $message = "Sorry, you already did a pingback to {$pagelinkedto} from {$pagelinkedfrom}."; } } else { // Post_ID not found $message = $messages[2]; //debug_fwrite($log, 'Post doesn\'t exist'."\n"); } } return new xmlrpcresp(new xmlrpcval($message)); }
function pingback_ping($args) { global $wpdb, $wp_version; $this->escape($args); $pagelinkedfrom = $args[0]; $pagelinkedto = $args[1]; $title = ''; $pagelinkedfrom = str_replace('&', '&', $pagelinkedfrom); $pagelinkedto = preg_replace('#&([^amp\\;])#is', '&$1', $pagelinkedto); $error_code = -1; // Check if the page linked to is in our site $pos1 = strpos($pagelinkedto, str_replace(array('http://www.', 'http://', 'https://www.', 'https://'), '', get_settings('home'))); if (!$pos1) { return new IXR_Error(0, 'Is there no link to us?'); } // let's find which post is linked to // FIXME: does url_to_postid() cover all these cases already? // if so, then let's use it and drop the old code. $urltest = parse_url($pagelinkedto); if ($post_ID = url_to_postid($pagelinkedto)) { $way = 'url_to_postid()'; } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) { // the path defines the post_ID (archives/p/XXXX) $blah = explode('/', $match[0]); $post_ID = $blah[1]; $way = 'from the path'; } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) { // the querystring defines the post_ID (?p=XXXX) $blah = explode('=', $match[0]); $post_ID = $blah[1]; $way = 'from the querystring'; } elseif (isset($urltest['fragment'])) { // an #anchor is there, it's either... if (intval($urltest['fragment'])) { // ...an integer #XXXX (simpliest case) $post_ID = $urltest['fragment']; $way = 'from the fragment (numeric)'; } elseif (preg_match('/post-[0-9]+/', $urltest['fragment'])) { // ...a post id in the form 'post-###' $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']); $way = 'from the fragment (post-###)'; } elseif (is_string($urltest['fragment'])) { // ...or a string #title, a little more complicated $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']); $sql = "SELECT ID FROM {$wpdb->posts} WHERE post_title RLIKE '{$title}'"; if (!($post_ID = $wpdb->get_var($sql))) { // returning unknown error '0' is better than die()ing return new IXR_Error(0, ''); } $way = 'from the fragment (title)'; } } else { // TODO: Attempt to extract a post ID from the given URL return new IXR_Error(33, 'The specified target URI cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'); } $post_ID = (int) $post_ID; logIO("O", "(PB) URI='{$pagelinkedto}' ID='{$post_ID}' Found='{$way}'"); $post = get_post($post_ID); if (!$post) { // Post_ID not found return new IXR_Error(33, 'The specified target URI cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'); } if ($post_ID == url_to_postid($pagelinkedfrom)) { return new IXR_Error(0, 'The source URI and the target URI cannot both point to the same resource.'); } // Check if pings are on if ('closed' == $post->ping_status) { return new IXR_Error(33, 'The specified target URI cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'); } // Let's check that the remote site didn't already pingback this entry $result = $wpdb->get_results("SELECT * FROM {$wpdb->comments} WHERE comment_post_ID = '{$post_ID}' AND comment_author_url = '{$pagelinkedfrom}'"); if ($wpdb->num_rows) { // We already have a Pingback from this URL return new IXR_Error(48, 'The pingback has already been registered.'); } // very stupid, but gives time to the 'from' server to publish ! sleep(1); // Let's check the remote site $linea = wp_remote_fopen($pagelinkedfrom); if (!$linea) { return new IXR_Error(16, 'The source URI does not exist.'); } // Work around bug in strip_tags(): $linea = str_replace('<!DOC', '<DOC', $linea); $linea = preg_replace('/[\\s\\r\\n\\t]+/', ' ', $linea); // normalize spaces $linea = preg_replace("/ <(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/", "\n\n", $linea); preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle); $title = $matchtitle[1]; if (empty($title)) { return new IXR_Error(32, 'We cannot find a title on that page.'); } $linea = strip_tags($linea, '<a>'); // just keep the tag we need $p = explode("\n\n", $linea); $sem_regexp_pb = "/(\\/|\\\\|\\*|\\?|\\+|\\.|\\^|\\\$|\\(|\\)|\\[|\\]|\\||\\{|\\})/"; $sem_regexp_fix = "\\\\\$1"; $link = preg_replace($sem_regexp_pb, $sem_regexp_fix, $pagelinkedfrom); $finished = false; foreach ($p as $para) { if ($finished) { continue; } if (strstr($para, $pagelinkedto)) { $context = preg_replace("/.*<a[^>]+" . $link . "[^>]*>([^>]+)<\\/a>.*/", "\$1", $para); $excerpt = strip_tags($para); $excerpt = trim($excerpt); $use = preg_quote($context); $excerpt = preg_replace("|.*?\\s(.{0,100}{$use}.{0,100})\\s|s", "\$1", $excerpt); $finished = true; } } if (empty($context)) { // URL pattern not found return new IXR_Error(17, 'The source URI does not contain a link to the target URI, and so cannot be used as a source.'); } $pagelinkedfrom = preg_replace('#&([^amp\\;])#is', '&$1', $pagelinkedfrom); $context = '[...] ' . wp_specialchars($excerpt) . ' [...]'; $original_pagelinkedfrom = $pagelinkedfrom; $pagelinkedfrom = $wpdb->escape($pagelinkedfrom); $original_title = $title; $comment_post_ID = $post_ID; $comment_author = $title; $comment_author_url = $pagelinkedfrom; $comment_content = $context; $comment_type = 'pingback'; $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_content', 'comment_type'); wp_new_comment($commentdata); do_action('pingback_post', $wpdb->insert_id); return "Pingback from {$pagelinkedfrom} to {$pagelinkedto} registered. Keep the web talking! :-)"; }
function bloggernewpost($m) { global $xmlrpcerruser; // import user errcode value global $blog_ID, $cache_userdata, $tableposts, $use_rss, $use_weblogsping, $post_autobr; global $post_default_title, $post_default_category; global $cafelogID, $sleep_after_edit; $err = ""; dbconnect(); $username = $m->getParam(2); $password = $m->getParam(3); $content = $m->getParam(4); $username = $username->scalarval(); $password = $password->scalarval(); $content = $content->scalarval(); if (user_pass_ok($username, $password)) { $userdata = get_userdatabylogin($username); $user_ID = $userdata["ID"]; $user_level = $userdata["user_level"]; if ($user_level < 1) { return new xmlrpcresp(0, $xmlrpcerruser + 1, "Sorry, level 0 users can not post"); } $post_title = addslashes(xmlrpc_getposttitle($content)); $post_category = xmlrpc_getpostcategory($content); $content = xmlrpc_removepostdata($content); $content = format_to_post($content); $time_difference = get_settings("time_difference"); $now = date("Y-m-d H:i:s", time() + $time_difference * 3600); $sql = "INSERT INTO {$tableposts} (post_author, post_date, post_content, post_title, post_category) VALUES ('{$user_ID}','{$now}','{$content}','{$post_title}','{$post_category}')"; $result = mysql_query($sql); if (!$result) { return new xmlrpcresp(0, $xmlrpcerruser + 2, "For some strange yet very annoying reason, your entry couldn't be posted."); } $post_ID = mysql_insert_id(); if (!isset($blog_ID)) { $blog_ID = 1; } if (isset($sleep_after_edit) && $sleep_after_edit > 0) { sleep($sleep_after_edit); } rss_update($blog_ID); pingWeblogs($blog_ID); pingCafelog($cafelogID, $post_title, $post_ID); pingBlogs($blog_ID); pingback($content, $post_ID); logIO("O", "Posted ! ID: {$post_ID}"); return new xmlrpcresp(new xmlrpcval("{$post_ID}")); } else { logIO("O", "Wrong username/password combination <b>{$username} / {$password}</b>"); return new xmlrpcresp(0, $xmlrpcerruser + 3, 'Wrong username/password combination ' . $username . ' / ' . starify($password)); } }
/** * mt.getCategoryList * * @see http://www.sixapart.com/developers/xmlrpc/movable_type_api/mtgetcategorylist.html * * @param xmlrpcmsg XML-RPC Message * 0 blogid (string): Unique identifier of the blog to query * 1 username (string): Login for a Blogger user who is member of the blog. * 2 password (string): Password for said username. */ function mt_getCategoryList($m) { logIO("mt_getCategoryList start"); return _b2_or_mt_get_categories('mt', $m); }
function bpt_upload($args) { try { global $wpdb; global $wp_xmlrpc_server; // Decode arguments $blog_ID = (int) $args[0]; $username = $wpdb->escape($args[1]); $password = $wpdb->escape($args[2]); $data = $args[3]; $name = sanitize_file_name($data['name']); $type = $data['type']; $bits = $data['bits']; logIO('O', 'bpt.upload ' . $name . ' ' . strlen($bits) . ' bytes'); // Check credentials if (!($user = $wp_xmlrpc_server->login($username, $password))) { logIO('O', 'bpt.upload invalid login'); return $wp_xmlrpc_server->error; } do_action('xmlrpc_call', 'metaWeblog.newMediaObject'); // Check user capabilities if (!current_user_can('upload_files')) { logIO('O', 'bpt.upload no capability'); return new IXR_Error(401, __('You are not allowed to upload files to this site.')); } if ($error = apply_filters('pre_upload_error', false)) { return new IXR_Error(500, $error); } // Find post $attached = $wpdb->get_row("SELECT ID, post_parent FROM {$wpdb->posts}" . " WHERE post_title = '{$name}'" . " AND post_type = 'attachment'"); if (empty($attached)) { get_currentuserinfo(); global $user_ID; $upload_dir = wp_upload_dir(); // Create new draft post $post_data = array('post_title' => basename($name, '.gpx'), 'post_content' => '<a href="' . $upload_dir['url'] . '/' . $name . '">' . $name . '</a>', 'post_status' => 'draft', 'post_author' => $user_ID); $post_ID = wp_insert_post($post_data); logIO('O', 'bpt.upload post=' . $post_ID); } else { $post_ID = $attached->post_parent; wp_delete_attachment($attached->ID); logIO('O', 'bpt.upload deleted attachment id=' . $attached->ID . ' post=' . $post_ID); } // Save file $upload = wp_upload_bits($name, NULL, $bits); if (!empty($upload['error'])) { $error = sprintf(__('Could not write file %1$s (%2$s)'), $name, $upload['error']); logIO('O', 'bpt.upload ' . $error); return new IXR_Error(500, $error); } // Attach file $attachment = array('post_title' => $name, 'post_content' => '', 'post_type' => 'attachment', 'post_parent' => $post_ID, 'post_mime_type' => $type, 'guid' => $upload['url']); $id = wp_insert_attachment($attachment, $upload['file'], $post_ID); wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $upload['file'])); logIO('O', 'bpt.upload attachment=' . $id); // Handle upload return apply_filters('wp_handle_upload', array('file' => $name, 'url' => $upload['url'], 'type' => $type), 'upload'); } catch (Exception $e) { // What? logIO('O', 'bpt.upload exception' . $e->getMessage()); return new IXR_Error(500, $e->getMessage()); } }
/** * b2.getPostURL * * @param xmlrpcmsg XML-RPC Message * 0 ? NO LONGER USED (was: blogid (string): Unique identifier of the blog to query) * 1 ? (string) * 2 username (string): Login for a Blogger user who is member of the blog. * 3 password (string): Password for said username.193 * * 4 post_ID (string): Post to query * @return xmlrpcresp XML-RPC Response */ function b2_getposturl($m) { global $xmlrpcerruser; global $siteurl; // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 2, 3))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // GET POST: /** * @var Item */ if (!($edited_Item =& xmlrpcs_get_Item($m, 4))) { // Failed, return (last) error: return xmlrpcs_resperror(); } // CHECK PERMISSION: (we need at least one post/edit status) if (!$current_User->check_perm('blog_post_statuses', 1, false, $edited_Item->blog_ID)) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } logIO('Permission granted.'); logIO('OK.'); return new xmlrpcresp(new xmlrpcval($edited_Item->get_permanent_url())); }
function pingback_ping($args) { // original code by Mort (http://mort.mine.nu:8080 -- site seems dead) // refactored to return error codes and avoid deep ifififif headaches global $wpdb, $wp_version; $pagelinkedfrom = $args[0]; $pagelinkedto = $args[1]; $title = ''; $pagelinkedfrom = str_replace('&', '&', $pagelinkedfrom); $pagelinkedto = preg_replace('#&([^amp\;])#is', '&$1', $pagelinkedto); $error_code = -1; // Check if the page linked to is in our site $pos1 = strpos($pagelinkedto, str_replace('http://', '', str_replace('www.', '', get_settings('home')))); if(!$pos1) { return new IXR_Error(0, ''); } // let's find which post is linked to // FIXME: does url_to_postid() cover all these cases already? // if so, then let's use it and drop the old code. $urltest = parse_url($pagelinkedto); if ($post_ID = url_to_postid($pagelinkedto)) { $way = 'url_to_postid()'; } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) { // the path defines the post_ID (archives/p/XXXX) $blah = explode('/', $match[0]); $post_ID = $blah[1]; $way = 'from the path'; } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) { // the querystring defines the post_ID (?p=XXXX) $blah = explode('=', $match[0]); $post_ID = $blah[1]; $way = 'from the querystring'; } elseif (isset($urltest['fragment'])) { // an #anchor is there, it's either... if (intval($urltest['fragment'])) { // ...an integer #XXXX (simpliest case) $post_ID = $urltest['fragment']; $way = 'from the fragment (numeric)'; } elseif (preg_match('/post-[0-9]+/',$urltest['fragment'])) { // ...a post id in the form 'post-###' $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']); $way = 'from the fragment (post-###)'; } elseif (is_string($urltest['fragment'])) { // ...or a string #title, a little more complicated $title = preg_replace('/[^a-zA-Z0-9]/', '.', $urltest['fragment']); $sql = "SELECT ID FROM $wpdb->posts WHERE post_title RLIKE '$title'"; if (! ($post_ID = $wpdb->get_var($sql)) ) { // returning unknown error '0' is better than die()ing return new IXR_Error(0, ''); } $way = 'from the fragment (title)'; } } else { // TODO: Attempt to extract a post ID from the given URL return new IXR_Error(33, 'The specified target URI cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'); } logIO("O","(PB) URI='$pagelinkedto' ID='$post_ID' Found='$way'"); $sql = 'SELECT post_author FROM '.$wpdb->posts.' WHERE ID = '.$post_ID; $result = $wpdb->get_results($sql); if (!$wpdb->num_rows) { // Post_ID not found return new IXR_Error(33, 'The specified target URI cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'); } // Let's check that the remote site didn't already pingback this entry $result = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post_ID' AND comment_author_url = '$pagelinkedfrom'"); if ($wpdb->num_rows) { // We already have a Pingback from this URL return new IXR_Error(48, 'The pingback has already been registered.'); } // very stupid, but gives time to the 'from' server to publish ! sleep(1); // Let's check the remote site $linea = wp_remote_fopen( $pagelinkedfrom ); if ( !$linea ) return new IXR_Error(16, 'The source URI does not exist.'); // Work around bug in strip_tags(): $linea = str_replace('<!DOCTYPE','<DOCTYPE',$linea); $linea = strip_tags($linea, '<title><a>'); $linea = strip_all_but_one_link($linea, $pagelinkedto); // I don't think we need this? -- emc3 //$linea = preg_replace('#&([^amp\;])#is', '&$1', $linea); if ( empty($matchtitle) ) { preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle); } $pos2 = strpos($linea, $pagelinkedto); $pos3 = strpos($linea, str_replace('http://www.', 'http://', $pagelinkedto)); if (is_integer($pos2) || is_integer($pos3)) { // The page really links to us :) $pos4 = (is_integer($pos2)) ? $pos2 : $pos3; $start = $pos4-100; $context = substr($linea, $start, 250); $context = str_replace("\n", ' ', $context); $context = str_replace('&', '&', $context); } if (empty($context)) { // URL pattern not found return new IXR_Error(17, 'The source URI does not contain a link to the target URI, and so cannot be used as a source.'); } // Check if pings are on $pingstatus = $wpdb->get_var("SELECT ping_status FROM $wpdb->posts WHERE ID = $post_ID"); if ('closed' == $pingstatus) { return new IXR_Error(33, 'The specified target URI cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'); } $pagelinkedfrom = preg_replace('#&([^amp\;])#is', '&$1', $pagelinkedfrom); $title = (!strlen($matchtitle[1])) ? $pagelinkedfrom : $matchtitle[1]; $original_context = strip_tags($context); $context = '[...] '; $context .= wp_specialchars($original_context); $context .= ' [...]'; $original_pagelinkedfrom = $pagelinkedfrom; $pagelinkedfrom = addslashes($pagelinkedfrom); $original_title = $title; $comment_post_ID = $post_ID; $comment_author = $title; $comment_author_url = $pagelinkedfrom; $comment_content = $context; $comment_type = 'pingback'; $pingstatus = $wpdb->get_var("SELECT ping_status FROM $wpdb->posts WHERE ID = $post_ID"); if ('open' != $pingstatus) die('Sorry, pingbacks are closed for this item.'); $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_content', 'comment_type'); wp_new_comment($commentdata); do_action('pingback_post', $wpdb->insert_id); return "Pingback from $pagelinkedfrom to $pagelinkedto registered. Keep the web talking! :-)"; }
/** * b2.getPostURL * * @param xmlrpcmsg XML-RPC Message * 0 ? NO LONGER USED (was: blogid (string): Unique identifier of the blog to query) * 1 ? (string) * 2 username (string): Login for a Blogger user who is member of the blog. * 3 password (string): Password for said username.193 * * 4 post_ID (string): Post to query * @return xmlrpcresp XML-RPC Response */ function b2_getposturl($m) { // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 2, 3))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // GET POST: /** * @var Item */ if (!($edited_Item =& xmlrpcs_get_Item($m, 4))) { // Failed, return (last) error: return xmlrpcs_resperror(); } // CHECK PERMISSION: (user needs to be able to view the item) if (!xmlrpcs_can_view_item($edited_Item, $User)) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } logIO('OK.'); return new xmlrpcresp(new xmlrpcval($edited_Item->get_permanent_url())); }
/** * metaWeblog.getPost retieves a given post. * * @see http://www.xmlrpc.com/metaWeblogApi#basicEntrypoints * * @param xmlrpcmsg XML-RPC Message * 0 postid (string): Unique identifier of the post * 1 username (string): Login for a Blogger user who has permission to edit the given * post (either the user who originally created it or an admin of the blog). * 2 password (string): Password for said username. * @return xmlrpcresp XML-RPC Response */ function mw_getpost($m) { // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 1, 2))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // GET POST: /** * @var Item */ if (!($edited_Item =& xmlrpcs_get_Item($m, 0))) { // Failed, return (last) error: return xmlrpcs_resperror(); } // CHECK PERMISSION: if (!xmlrpcs_can_view_item($edited_Item, $current_User)) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } $item = _wp_mw_get_item_struct($edited_Item); logIO('OK.'); return new xmlrpcresp(new xmlrpcval($item, 'struct')); }
/** * Execute a method invoked by the client, checking parameters used * @param mixed $m either an xmlrpcmsg obj or a method name * @param array $params array with method parameters as php types (if m is method name only) * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only) * @return xmlrpcresp * @access private */ function execute($m, $params = null, $paramtypes = null) { if (is_object($m)) { $methName = $m->method(); } else { $methName = $m; } logIO($methName, true); $sysCall = $this->allow_system_funcs && strpos($methName, "system.") === 0; $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap; if (!isset($dmap[$methName]['function'])) { // No such method logIO('No such method:' . $methName); return new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['unknown_method'], $GLOBALS['xmlrpcstr']['unknown_method']); } // Check signature if (isset($dmap[$methName]['signature'])) { $sig = $dmap[$methName]['signature']; if (is_object($m)) { list($ok, $errstr) = $this->verifySignature($m, $sig); } else { list($ok, $errstr) = $this->verifySignature($paramtypes, $sig); } if (!$ok) { // Didn't match. logIO('Invalid signature.'); return new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['incorrect_params'], $GLOBALS['xmlrpcstr']['incorrect_params'] . ": {$errstr}"); } } $func = $dmap[$methName]['function']; // let the 'class::function' syntax be accepted in dispatch maps if (is_string($func) && strpos($func, '::')) { $func = explode('::', $func); } // verify that function to be invoked is in fact callable if (!is_callable($func)) { error_log("XML-RPC: xmlrpc_server::execute: function {$func} registered as method handler is not callable"); return new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method"); } // If debug level is 3, we should catch all errors generated during // processing of user function, and log them as part of response if ($this->debug > 2) { $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler'); } if (is_object($m)) { if ($sysCall) { $r = call_user_func($func, $this, $m); } else { $r = call_user_func($func, $m); } if (!is_a($r, 'xmlrpcresp')) { error_log("XML-RPC: xmlrpc_server::execute: function {$func} registered as method handler does not return an xmlrpcresp object"); if (is_a($r, 'xmlrpcval')) { $r =& new xmlrpcresp($r); } else { $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object"); } } } else { // call a 'plain php' function if ($sysCall) { array_unshift($params, $this); $r = call_user_func_array($func, $params); } else { // 3rd API convention for method-handling functions: EPI-style if ($this->functions_parameters_type == 'epivals') { $r = call_user_func_array($func, array($methName, $params, $this->user_data)); // mimic EPI behaviour: if we get an array that looks like an error, make it // an eror response if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r)) { $r =& new xmlrpcresp(0, (int) $r['faultCode'], (string) $r['faultString']); } else { // functions using EPI api should NOT return resp objects, // so make sure we encode the return type correctly $r =& new xmlrpcresp(php_xmlrpc_encode($r, array('extension_api'))); } } else { $r = call_user_func_array($func, $params); } } // the return type can be either an xmlrpcresp object or a plain php value... if (!is_a($r, 'xmlrpcresp')) { // what should we assume here about automatic encoding of datetimes // and php classes instances??? $r =& new xmlrpcresp(php_xmlrpc_encode($r, array('auto_dates'))); } } if ($this->debug > 2) { // note: restore the error handler we found before calling the // user func, even if it has been changed inside the func itself if ($GLOBALS['_xmlrpcs_prev_ehandler']) { set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']); } else { restore_error_handler(); } } return $r; }
/** * Modified image upload based off of xmlrpc newMediaObject function. * Adds ability to include alt title, caption, and description to attachment */ public function skyword_newMediaObject($args) { $login = $this->login($args); if ('success' == $login['status']) { global $wpdb; $data = $args[3]; $name = sanitize_file_name($data['name']); $type = $data['type']; $bits = $data['bits']; $title = $data['title']; $caption = $data['caption']; $alttext = $data['alttext']; $description = $data['description']; if (!isset($title)) { $title = $name; } logIO('O', '(MW) Received ' . strlen($bits) . ' bytes'); do_action('xmlrpc_call', 'metaWeblog.newMediaObject'); if ($upload_err = apply_filters('pre_upload_error', false)) { return new IXR_Error(500, $upload_err); } $upload = wp_upload_bits($name, NULL, $bits); if (!empty($upload['error'])) { $errorString = sprintf(__('Could not write file %1$s (%2$s)'), $name, $upload['error']); logIO('O', '(MW) ' . $errorString); return new IXR_Error(500, $errorString); } // Construct the attachment array // attach to post_id 0 $post_id = 0; $attachment = array('post_title' => $title, 'post_content' => '', 'post_type' => 'attachment', 'post_parent' => $post_id, 'post_mime_type' => $type, 'post_excerpt' => $caption, 'post_content' => $description, 'guid' => $upload['url']); // Save the data $id = wp_insert_attachment($attachment, $upload['file'], $post_id); wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $upload['file'])); //adds alt text as meta add_post_meta($id, "_wp_attachment_image_alt", $alttext, false); return apply_filters('wp_handle_upload', array('file' => $name, 'url' => $upload['url'], 'type' => $type), 'upload'); } else { return $login['message']; } }
/** * Edit an Item and return an XML-RPC response * * @param Item * @param string HTML * @param string HTML * @param string date * @param integer main category * @param array of integers : extra categories * @param string status * @return xmlrpcmsg */ function xmlrpcs_edit_item(&$edited_Item, $post_title, $content, $post_date, $main_cat, $cat_IDs, $status) { /** * @var User */ global $current_User; global $Messages; global $DB; // CHECK HTML SANITY: if (($post_title = check_html_sanity($post_title, 'xmlrpc_posting')) === false) { return xmlrpcs_resperror(21, $Messages->get_string('Invalid post title, please correct these errors:', '')); } if (($content = check_html_sanity($content, 'xmlrpc_posting')) === false) { return xmlrpcs_resperror(22, $Messages->get_string('Invalid post contents, please correct these errors:' . "\n", '', NULL, " // \n", 'xmlrpc')); } // UPDATE POST IN DB: $edited_Item->set('title', $post_title); $edited_Item->set('content', $content); $edited_Item->set('status', $status); if (!empty($post_date)) { $edited_Item->set('issue_date', $post_date); } if (!empty($main_cat)) { // Update cats: $edited_Item->set('main_cat_ID', $main_cat); } if (!empty($cat_IDs)) { // Extra-Cats: $edited_Item->set('extra_cat_IDs', $cat_IDs); } $edited_Item->dbupdate(); if ($DB->error) { // DB error return xmlrpcs_resperror(99, 'Error while updating item: ' . $DB->last_error); } // Execute or schedule notifications & pings: logIO('Handling notifications...'); $edited_Item->handle_post_processing(); logIO('OK.'); return new xmlrpcresp(new xmlrpcval(1, 'boolean')); }
* * @uses $xmlrpc_logging * @package NXTClass * @subpackage Logging * * @param string $io Whether input or output * @param string $msg Information describing logging reason. * @return bool Always return true */ function logIO($io, $msg) { global $xmlrpc_logging; if ($xmlrpc_logging) { $fp = fopen("../xmlrpc.log", "a+"); $date = gmdate("Y-m-d H:i:s "); $iot = $io == "I" ? " Input: " : " Output: "; fwrite($fp, "\n\n" . $date . $iot . $msg); fclose($fp); } return true; } if (isset($HTTP_RAW_POST_DATA)) { logIO("I", $HTTP_RAW_POST_DATA); } // Make sure nxt_die output is XML add_filter('nxt_die_handler', '_xmlrpc_nxt_die_filter'); // Allow for a plugin to insert a different class to handle requests. $nxt_xmlrpc_server_class = apply_filters('nxt_xmlrpc_server_class', 'nxt_xmlrpc_server'); $nxt_xmlrpc_server = new $nxt_xmlrpc_server_class(); // Fire off the request $nxt_xmlrpc_server->serve_request();
/** * Deletes given Item * * @return xmlrpcresp XML-RPC Response (bool) */ function xmlrpcs_delete_item(&$edited_Item) { global $current_User, $DB; // CHECK PERMISSION: if (!$current_User->check_perm('item_post!CURSTATUS', 'delete', false, $edited_Item)) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } logIO('Permission granted.'); // DELETE POST FROM DB: $edited_Item->dbdelete(); if ($DB->error) { return xmlrpcs_resperror(99, 'DB error: ' . $DB->last_error); // user error 9 } logIO('OK.'); return new xmlrpcresp(new xmlrpcval(1, 'boolean')); }
function express_uploadFile($args) { global $wpdb; global $wp_xmlrpc_server; $blog_ID = (int) $args[0]; $username = $wpdb->escape($args[1]); $password = $wpdb->escape($args[2]); $data = $args[3]; $name = sanitize_file_name($data['name']); $type = $data['type']; $bits = $data['bits']; logIO('O', '(MW) Received ' . strlen($bits) . ' bytes'); if (!($user = $wp_xmlrpc_server->login($username, $password))) { return $wp_xmlrpc_server->error; } do_action('xmlrpc_call', 'metaWeblog.newMediaObject'); if (!current_user_can('upload_files')) { logIO('O', '(MW) User does not have upload_files capability'); return new IXR_Error(401, __('You are not allowed to upload files to this site.')); } if ($upload_err = apply_filters("pre_upload_error", false)) { return new IXR_Error(500, $upload_err); } if (!empty($data["overwrite"]) && $data["overwrite"] == true) { // Get postmeta info on the object. $old_file = $wpdb->get_row("\n\t\t\tSELECT ID\n\t\t\tFROM {$wpdb->posts}\n\t\t\tWHERE post_title = '{$name}'\n\t\t\t\tAND post_type = 'attachment'\n\t\t"); // Delete previous file. wp_delete_attachment($old_file->ID); // Make sure the new name is different by pre-pending the // previous post id. $filename = preg_replace("/^wpid\\d+-/", "", $name); $name = "wpid{$old_file->ID}-{$filename}"; } $upload = wp_upload_bits($name, $type, $bits); if (!empty($upload['error'])) { $errorString = sprintf(__('Could not write file %1$s (%2$s)'), $name, $upload['error']); logIO('O', '(MW) ' . $errorString); return new IXR_Error(500, $errorString); } // Construct the attachment array // attach to post_id 0 $post_id = 0; $attachment = array('post_title' => $name, 'post_content' => '', 'post_type' => 'attachment', 'post_parent' => $post_id, 'post_mime_type' => $type, 'guid' => $upload['url']); // Save the data $id = wp_insert_attachment($attachment, $upload['file'], $post_id); wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $upload['file'])); return apply_filters('wp_handle_upload', array('file' => $name, 'url' => $upload['url'], 'type' => $type, 'id' => $id)); }
function pingback_ping($m) { // original code by Mort // (http://mort.mine.nu:8080) global $tableposts, $tablecomments, $comments_notify, $wpdb; global $siteurl, $blogfilename, $wp_version, $use_pingback; global $HTTP_SERVER_VARS, $wpdb; if (!$use_pingback) { return new xmlrpcresp(new xmlrpcval('Sorry, this weblog does not allow you to pingback its posts.')); } //$log = debug_fopen('./xmlrpc.log', 'w'); $title = ''; $pagelinkedfrom = $m->getParam(0); $pagelinkedfrom = $pagelinkedfrom->scalarval(); $pagelinkedto = $m->getParam(1); $pagelinkedto = $pagelinkedto->scalarval(); $pagelinkedfrom = str_replace('&', '&', $pagelinkedfrom); $pagelinkedto = preg_replace('#&([^amp\\;])#is', '&$1', $pagelinkedto); //debug_fwrite($log, 'BEGIN '.time().' - '.date('Y-m-d H:i:s')."\n\n"); //debug_fwrite($log, 'Page linked from: '.$pagelinkedfrom."\n"); //debug_fwrite($log, 'Page linked to: '.$pagelinkedto."\n"); $messages = array(htmlentities("Pingback from " . $pagelinkedfrom . " to " . $pagelinkedto . " registered. Keep the web talking! :-)"), htmlentities("We can't find the URL to the post you are trying to " . "link to in your entry. Please check how you wrote the post's permalink in your entry."), htmlentities("We can't find the post you are trying to link to." . " Please check the post's permalink.")); $message = $messages[0]; // Check if the page linked to is in our site $pos1 = strpos($pagelinkedto, str_replace('http://', '', str_replace('www.', '', $siteurl))); if ($pos1) { // let's find which post is linked to $urltest = parse_url($pagelinkedto); if ($post_ID = url_to_postid($pagelinkedto)) { $way = 'url_to_postid()'; } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) { // the path defines the post_ID (archives/p/XXXX) $blah = explode('/', $match[0]); $post_ID = $blah[1]; $way = 'from the path'; } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) { // the querystring defines the post_ID (?p=XXXX) $blah = explode('=', $match[0]); $post_ID = $blah[1]; $way = 'from the querystring'; } elseif (isset($urltest['fragment'])) { // an #anchor is there, it's either... if (intval($urltest['fragment'])) { // ...an integer #XXXX (simpliest case) $post_ID = $urltest['fragment']; $way = 'from the fragment (numeric)'; } elseif (preg_match('/post-[0-9]+/', $urltest['fragment'])) { // ...a post id in the form 'post-###' $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']); $way = 'from the fragment (post-###)'; } elseif (is_string($urltest['fragment'])) { // ...or a string #title, a little more complicated $title = preg_replace('/[^a-zA-Z0-9]/', '.', $urltest['fragment']); $sql = "SELECT ID FROM {$tableposts} WHERE post_title RLIKE '{$title}'"; $post_ID = $wpdb->get_var($sql) or die("Query: {$sql}\n\nError: "); $way = 'from the fragment (title)'; } } else { // TODO: Attempt to extract a post ID from the given URL $post_ID = -1; $way = 'no match'; } logIO("O", "(PB) URI='{$pagelinkedto}' ID='{$post_ID}' Found='{$way}'"); //debug_fwrite($log, "Found post ID $way: $post_ID\n"); $sql = 'SELECT post_author FROM ' . $tableposts . ' WHERE ID = ' . $post_ID; $result = $wpdb->get_results($sql); if ($wpdb->num_rows) { //debug_fwrite($log, 'Post exists'."\n"); // Let's check that the remote site didn't already pingback this entry $sql = 'SELECT * FROM ' . $tablecomments . ' WHERE comment_post_ID = ' . $post_ID . ' AND comment_author_url = \'' . $pagelinkedfrom . '\' AND comment_content LIKE \'%<pingback />%\''; $result = $wpdb->get_results($sql); if ($wpdb->num_rows || 1 == 1) { // very stupid, but gives time to the 'from' server to publish ! sleep(1); // Let's check the remote site $fp = @fopen($pagelinkedfrom, 'r'); $puntero = 4096; while ($remote_read = fread($fp, $puntero)) { $linea .= $remote_read; } // Work around bug in strip_tags(): $linea = str_replace('<!DOCTYPE', '<DOCTYPE', $linea); $linea = strip_tags($linea, '<title><a>'); $linea = strip_all_but_one_link($linea, $pagelinkedto); // I don't think we need this? -- emc3 //$linea = preg_replace('#&([^amp\;])#is', '&$1', $linea); if (empty($matchtitle)) { preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle); } $pos2 = strpos($linea, $pagelinkedto); $pos3 = strpos($linea, str_replace('http://www.', 'http://', $pagelinkedto)); if (is_integer($pos2) || is_integer($pos3)) { //debug_fwrite($log, 'The page really links to us :)'."\n"); $pos4 = is_integer($pos2) ? $pos2 : $pos3; $start = $pos4 - 100; $context = substr($linea, $start, 250); $context = str_replace("\n", ' ', $context); $context = str_replace('&', '&', $context); } else { //debug_fwrite($log, 'The page doesn\'t link to us, here\'s an excerpt :'."\n\n".$linea."\n\n"); } //} //debug_fwrite($log, '*****'."\n\n"); fclose($fp); if (!empty($context)) { // Check if pings are on, inelegant exit $pingstatus = $wpdb->get_var("SELECT ping_status FROM {$tableposts} WHERE ID = {$post_ID}"); if ('closed' == $pingstatus) { die('Sorry, pings are turned off for this post.'); } $pagelinkedfrom = preg_replace('#&([^amp\\;])#is', '&$1', $pagelinkedfrom); $title = !strlen($matchtitle[1]) ? $pagelinkedfrom : $matchtitle[1]; $original_context = $context; $context = '<pingback />[...] ' . addslashes(trim($context)) . ' [...]'; $context = format_to_post($context); $original_pagelinkedfrom = $pagelinkedfrom; $pagelinkedfrom = addslashes($pagelinkedfrom); $original_title = $title; $title = addslashes(strip_tags(trim($title))); $now = current_time('mysql'); $consulta = $wpdb->query("INSERT INTO {$tablecomments} \n\t\t\t\t\t\t(comment_post_ID, comment_author, comment_author_url, comment_date, comment_content) \n\t\t\t\t\t\tVALUES \n\t\t\t\t\t\t({$post_ID}, '{$title}', '{$pagelinkedfrom}', '{$now}', '{$context}')\n\t\t\t\t\t\t"); $comment_ID = $wpdb->get_var('SELECT last_insert_id()'); if ($comments_notify) { wp_notify_postauthor($comment_ID, 'pingback'); } } else { // URL pattern not found $message = "Page linked to: {$pagelinkedto}\nPage linked from:" . " {$pagelinkedfrom}\nTitle: {$title}\nContext: {$context}\n\n" . $messages[1]; } } else { // We already have a Pingback from this URL $message = "Sorry, you already did a pingback to {$pagelinkedto}" . " from {$pagelinkedfrom}."; } } else { // Post_ID not found $message = $messages[2]; //debug_fwrite($log, 'Post doesn\'t exist'."\n"); } } return new xmlrpcresp(new xmlrpcval($message)); }
/** * wp.getOptions * * @see http://codex.wordpress.org/XML-RPC_wp#wp.getOptions * * Note: If passing in a struct, search for options listed within it. * * @param xmlrpcmsg XML-RPC Message * 0 blogid (int): Unique identifier of the blog. * 1 username (string): User login. * 2 password (string): Password for said username. * 3 options (struct) */ function wp_getoptions($m) { global $Settings; // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 1, 2))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // GET BLOG: /** * @var Blog */ if (!($Blog =& xmlrpcs_get_Blog($m, 0))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } if (isset($m->params[3])) { $options = $m->getParam(3); $options = xmlrpc_decode_recurse($options); } $defaults = array('software_name' => array('desc' => 'Software Name', 'value' => 'WordPress'), 'software_version' => array('desc' => 'Software Version', 'value' => '3.3.2'), 'blog_url' => array('desc' => 'Site URL', 'value' => $Blog->gen_blogurl()), 'blog_title' => array('desc' => 'Site TitleL', 'value' => $Blog->get('name')), 'blog_tagline' => array('desc' => 'Site Tagline', 'value' => $Blog->get('tagline')), 'date_format' => array('desc' => 'Date Format', 'value' => locale_datefmt()), 'time_format' => array('desc' => 'Time Format', 'value' => locale_timefmt()), 'users_can_register' => array('desc' => 'Allow new users to sign up', 'value' => $Settings->get('newusers_canregister')), 'thumbnail_crop' => array('desc' => 'Crop thumbnail to exact dimensions', 'value' => false), 'thumbnail_size_w' => array('desc' => 'Thumbnail Width', 'value' => '160'), 'thumbnail_size_h' => array('desc' => 'Thumbnail Height', 'value' => '160'), 'medium_size_w' => array('desc' => 'Medium size image width', 'value' => '320'), 'medium_size_h' => array('desc' => 'Medium size image height', 'value' => '320'), 'large_size_w' => array('desc' => 'Large size image width', 'value' => '720'), 'large_size_h' => array('desc' => 'Large size image height', 'value' => '500')); $data = array(); if (empty($options)) { // No specific options where asked for, return all of them foreach ($defaults as $k => $opt) { $data[$k] = new xmlrpcval(array('desc' => new xmlrpcval($opt['desc']), 'readonly' => new xmlrpcval(true, 'boolean'), 'value' => new xmlrpcval($opt['value'])), 'struct'); } logIO('Retrieving all options'); } else { foreach ($options as $k) { if (!isset($defaults[$k])) { continue; } $data[$k] = new xmlrpcval(array('desc' => new xmlrpcval($defaults[$k]['desc']), 'readonly' => new xmlrpcval(true, 'boolean'), 'value' => new xmlrpcval($defaults[$k]['value'])), 'struct'); logIO('Retrieving option: ' . $k); } } logIO('OK.'); return new xmlrpcresp(new xmlrpcval($data, 'struct')); }
function pingback_ping($args) { global $wpdb, $wp_version; $this->escape($args); $pagelinkedfrom = $args[0]; $pagelinkedto = $args[1]; $title = ''; $pagelinkedfrom = str_replace('&', '&', $pagelinkedfrom); $pagelinkedto = str_replace('&', '&', $pagelinkedto); $pagelinkedto = str_replace('&', '&', $pagelinkedto); $error_code = -1; // Check if the page linked to is in our site $pos1 = strpos($pagelinkedto, str_replace(array('http://www.', 'http://', 'https://www.', 'https://'), '', get_option('home'))); if (!$pos1) { return new IXR_Error(0, __('Is there no link to us?')); } // let's find which post is linked to // FIXME: does url_to_postid() cover all these cases already? // if so, then let's use it and drop the old code. $urltest = parse_url($pagelinkedto); if ($post_ID = url_to_postid($pagelinkedto)) { $way = 'url_to_postid()'; } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) { // the path defines the post_ID (archives/p/XXXX) $blah = explode('/', $match[0]); $post_ID = (int) $blah[1]; $way = 'from the path'; } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) { // the querystring defines the post_ID (?p=XXXX) $blah = explode('=', $match[0]); $post_ID = (int) $blah[1]; $way = 'from the querystring'; } elseif (isset($urltest['fragment'])) { // an #anchor is there, it's either... if (intval($urltest['fragment'])) { // ...an integer #XXXX (simpliest case) $post_ID = (int) $urltest['fragment']; $way = 'from the fragment (numeric)'; } elseif (preg_match('/post-[0-9]+/', $urltest['fragment'])) { // ...a post id in the form 'post-###' $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']); $way = 'from the fragment (post-###)'; } elseif (is_string($urltest['fragment'])) { // ...or a string #title, a little more complicated $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']); $sql = "SELECT ID FROM {$wpdb->posts} WHERE post_title RLIKE '{$title}'"; if (!($post_ID = $wpdb->get_var($sql))) { // returning unknown error '0' is better than die()ing return new IXR_Error(0, ''); } $way = 'from the fragment (title)'; } } else { // TODO: Attempt to extract a post ID from the given URL return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.')); } $post_ID = (int) $post_ID; logIO("O", "(PB) URL='{$pagelinkedto}' ID='{$post_ID}' Found='{$way}'"); $post = get_post($post_ID); if (!$post) { // Post_ID not found return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.')); } if ($post_ID == url_to_postid($pagelinkedfrom)) { return new IXR_Error(0, __('The source URL and the target URL cannot both point to the same resource.')); } // Check if pings are on if ('closed' == $post->ping_status) { return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.')); } // Let's check that the remote site didn't already pingback this entry $result = $wpdb->get_results("SELECT * FROM {$wpdb->comments} WHERE comment_post_ID = '{$post_ID}' AND comment_author_url = '{$pagelinkedfrom}'"); if ($wpdb->num_rows) { // We already have a Pingback from this URL return new IXR_Error(48, __('The pingback has already been registered.')); } // very stupid, but gives time to the 'from' server to publish ! sleep(1); // Let's check the remote site $linea = wp_remote_fopen($pagelinkedfrom); if (!$linea) { return new IXR_Error(16, __('The source URL does not exist.')); } // Work around bug in strip_tags(): $linea = str_replace('<!DOC', '<DOC', $linea); $linea = preg_replace('/[\\s\\r\\n\\t]+/', ' ', $linea); // normalize spaces $linea = preg_replace("/ <(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/", "\n\n", $linea); preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle); $title = $matchtitle[1]; if (empty($title)) { return new IXR_Error(32, __('We cannot find a title on that page.')); } $linea = strip_tags($linea, '<a>'); // just keep the tag we need $p = explode("\n\n", $linea); $preg_target = preg_quote($pagelinkedto); foreach ($p as $para) { if (strpos($para, $pagelinkedto) !== false) { // it exists, but is it a link? preg_match("|<a[^>]+?" . $preg_target . "[^>]*>([^>]+?)</a>|", $para, $context); // If the URL isn't in a link context, keep looking if (empty($context)) { continue; } // We're going to use this fake tag to mark the context in a bit // the marker is needed in case the link text appears more than once in the paragraph $excerpt = preg_replace('|\\</?wpcontext\\>|', '', $para); // prevent really long link text if (strlen($context[1]) > 100) { $context[1] = substr($context[1], 0, 100) . '...'; } $marker = '<wpcontext>' . $context[1] . '</wpcontext>'; // set up our marker $excerpt = str_replace($context[0], $marker, $excerpt); // swap out the link for our marker $excerpt = strip_tags($excerpt, '<wpcontext>'); // strip all tags but our context marker $excerpt = trim($excerpt); $preg_marker = preg_quote($marker); $excerpt = preg_replace("|.*?\\s(.{0,100}{$preg_marker}.{0,100})\\s.*|s", '$1', $excerpt); $excerpt = strip_tags($excerpt); // YES, again, to remove the marker wrapper break; } } if (empty($context)) { // Link to target not found return new IXR_Error(17, __('The source URL does not contain a link to the target URL, and so cannot be used as a source.')); } $pagelinkedfrom = str_replace('&', '&', $pagelinkedfrom); $context = '[...] ' . wp_specialchars($excerpt) . ' [...]'; $original_pagelinkedfrom = $pagelinkedfrom; $pagelinkedfrom = $wpdb->escape($pagelinkedfrom); $original_title = $title; $comment_post_ID = (int) $post_ID; $comment_author = $title; $this->escape($comment_author); $comment_author_url = $pagelinkedfrom; $comment_content = $context; $this->escape($comment_content); $comment_type = 'pingback'; $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_content', 'comment_type'); $comment_ID = wp_new_comment($commentdata); do_action('pingback_post', $comment_ID); return sprintf(__('Pingback from %1$s to %2$s registered. Keep the web talking! :-)'), $pagelinkedfrom, $pagelinkedto); }
/** * blogger.getRecentPosts retieves X most recent posts. * * This API call is not documented on * {@link http://www.blogger.com/developers/api/1_docs/} * @see http://www.sixapart.com/developers/xmlrpc/blogger_api/bloggergetrecentposts.html * * @param xmlrpcmsg XML-RPC Message * 0 appkey (string): Unique identifier/passcode of the application sending the post. * (See access info {@link http://www.blogger.com/developers/api/1_docs/#access} .) * 1 blogid (string): Unique identifier of the blog the post will be added to. * Currently ignored in b2evo, in favor of the category. * 2 username (string): Login for a Blogger user who has permission to edit the given * post (either the user who originally created it or an admin of the blog). * 3 password (string): Password for said username. * 4 numposts (integer): number of posts to retrieve. * @return xmlrpcresp XML-RPC Response */ function blogger_getrecentposts($m) { global $xmlrpcerruser, $DB; // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 2, 3))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // GET BLOG: /** * @var Blog */ if (!($Blog =& xmlrpcs_get_Blog($m, 1))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // CHECK PERMISSION: (we need at least one post/edit status) // (we should be able to see all even if we cannot edit the particular status of a post) if (!$current_User->check_perm('blog_post_statuses', 1, false, $Blog->ID)) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } logIO('Permission granted.'); $numposts = $m->getParam(4); $numposts = $numposts->scalarval(); // Get the posts to display: load_class('items/model/_itemlist.class.php'); $MainList =& new ItemList2($Blog, NULL, NULL, $numposts); $MainList->set_filters(array('visibility_array' => array('published', 'protected', 'private', 'draft', 'deprecated', 'redirected'), 'order' => 'DESC', 'unit' => 'posts')); // Run the query: $MainList->query(); xmlrpc_debugmsg('Items:' . $MainList->result_num_rows); $data = array(); while ($Item =& $MainList->get_item()) { xmlrpc_debugmsg('Item:' . $Item->title . ' - Issued: ' . $Item->issue_date . ' - Modified: ' . $Item->mod_date); $post_date = mysql2date("U", $Item->issue_date); $post_date = gmdate("Ymd", $post_date) . "T" . gmdate("H:i:s", $post_date); $content = '<title>' . $Item->title . '</title>'; $content .= '<category>' . $Item->main_cat_ID . '</category>'; $content .= $Item->content; // Load Item's creator User: $Item->get_creator_User(); $authorname = $Item->creator_User->get('preferredname'); $data[] = new xmlrpcval(array("authorName" => new xmlrpcval($authorname), "userid" => new xmlrpcval($Item->creator_user_ID), "dateCreated" => new xmlrpcval($post_date, "dateTime.iso8601"), "content" => new xmlrpcval($content), "postid" => new xmlrpcval($Item->ID)), "struct"); } $resp = new xmlrpcval($data, "array"); logIO('OK.'); return new xmlrpcresp($resp); }