[WordPress] WordPress から backlog API を叩く

<?php
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
add_filter( 'http_request_args', function( $args, $url ) {
if ( false !== strpos($url, 'example.backlog.jp') ) {
$args['headers']['Authorization'] = 'Basic '. base64_encode('backlog_user' . ':' . 'backlog_passwd');
}
return $args;
}, 10, 2 );
$ixr_client = new WP_HTTP_IXR_Client( 'https://example.backlog.jp/XML-RPC&#39; );
if ( !$ixr_client->query('backlog.getProjects') ) {
var_dump($ixr_client->getErrorCode());
}
print_r($ixr_client->getResponse());

view raw
gistfile1.php
hosted with ❤ by GitHub

参考
backlog API
WordPress – XMLRPC – IXR client and http Basic Authentication

Contact Form 7 に来たお問い合わせ内容で、Backlog に課題を自動作成するサンプル

<?php
/*
Plugin Name: WP CF7 to Backlog
Plugin URI:
Description:
Author: wokamoto
Version: 0.0.1
*/
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
// new cf7_to_backlog('backlog_spacename', 'backlog_user', 'backlog_passwd', 'backlog_projectkey', (int)backlog_userid);
class cf7_to_backlog {
const API_URL = 'https://%s.backlog.jp/XML-RPC&#39;;
const DEFAULT_TITLE = 'CF7 からの問い合わせ';
private $ixr;
private $backlog_api;
private $backlog_user;
private $backlog_pass;
private $backlog_project;
private $backlog_assignerId;
function __construct( $space_name, $user, $pass, $project_key, $assigner = null ){
add_filter ( 'http_request_args', array($this, 'http_request_args'), 10, 2 );
$this->backlog_api = sprintf(self::API_URL, $space_name);
$this->backlog_user = $user;
$this->backlog_pass = $pass;
$this->ixr = new WP_HTTP_IXR_Client($this->backlog_api);
$this->backlog_project = $this->get_project_id($project_key);
$this->backlog_assignerId = apply_filters('cf7_to_backlog::assigner', intval($assigner));
add_action( 'wpcf7_submit', array($this, 'wpcf7_backlog_submit'), 10, 2 );
add_filter( 'cf7_to_backlog::summary', array($this, 'issue_title') );
}
private function get_project_id( $project_key ){
$this->ixr->query('backlog.getProject', $project_key);
if ( $this->ixr->isError() )
return new WP_Error('get_project_id', $this->ixr->getErrorMessage());
$res = $this->ixr->getResponse();
return
!isset($res['id'])
? new WP_Error('get_project_id', 'unknown error')
: intval($res['id']);
}
private function create_issue($args = array()){
$args['projectId'] = $this->backlog_project;
$args['assignerId']= $this->backlog_assignerId;
$args['summary'] = apply_filters( 'cf7_to_backlog::summary', isset($args['summary']) ? $args['summary'] : self::DEFAULT_TITLE );
$args['due_date'] = apply_filters( 'cf7_to_backlog::due_date', date("Ymd",strtotime("+1 day")) );
$args['issueType'] = apply_filters( 'cf7_to_backlog::issueType', 'タスク' );
$this->ixr->query('backlog.createIssue', $args);
if ( $this->ixr->isError() )
return new WP_Error('create_issue', $this->ixr->getErrorMessage());
return $this->ixr->getResponse();
}
public function issue_title($summary) {
return
$summary != '[your-subject]'
? $summary
: self::DEFAULT_TITLE;
}
public function http_request_args( $args, $url ) {
if ( false !== strpos($url, $this->backlog_api) ) {
$args['headers']['Authorization'] = 'Basic '. base64_encode("{$this->backlog_user}:{$this->backlog_pass}");
}
return $args;
}
public function wpcf7_backlog_submit( $contactform, $result ) {
$cases = (array) apply_filters( 'cf7_to_backlog::submit_if', array( 'mail_sent', 'mail_failed' ) );
if ( empty( $result['status'] ) || ! in_array( $result['status'], $cases ) )
return;
if ( empty( $contactform->posted_data ) )
return;
$fields_senseless = $contactform->form_scan_shortcode(
array( 'type' => array( 'captchar', 'quiz', 'acceptance' ) ) );
$exclude_names = array();
foreach ( $fields_senseless as $tag )
$exclude_names[] = $tag['name'];
$posted_data = $contactform->posted_data;
foreach ( $posted_data as $key => $value ) {
if ( '_' == substr( $key, 0, 1 ) || in_array( $key, $exclude_names ) )
unset( $posted_data[$key] );
}
$email = $this->wpcf7_get_value( 'email', $contactform );
$name = $this->wpcf7_get_value( 'name', $contactform );
$subject = $this->wpcf7_get_value( 'subject', $contactform );
$special_mail_tags = array( 'remote_ip', 'user_agent', 'url', 'date', 'time',
'post_id', 'post_name', 'post_title', 'post_url', 'post_author', 'post_author_email' );
$akismet = isset( $contactform->akismet ) ? (array) $contactform->akismet : null;
$content = '';
$fields = $this->array_flatten( $posted_data );
$fields = array_filter( array_map( 'trim', $fields ) );
$content = implode( "\n", $fields );
$this->create_issue(array(
'summary' => $subject,
'description' => $content,
));
}
private function wpcf7_get_value( $field, $contactform ) {
if ( empty( $field ) || empty( $contactform ) )
return false;
$value = '';
if ( in_array( $field, array( 'email', 'name', 'subject' ) ) ) {
$templates = $contactform->additional_setting( 'flamingo_' . $field );
if ( empty( $templates[0] ) ) {
$template = sprintf( '[your-%s]', $field );
} else {
$template = trim( wpcf7_strip_quote( $templates[0] ) );
}
$value = $contactform->replace_mail_tags( $template );
}
$value = apply_filters( 'cf7_to_backlog::wpcf7_get_value', $value, $field, $contactform );
return $value;
}
private function array_flatten( $input ) {
if ( ! is_array( $input ) )
return array( $input );
$output = array();
foreach ( $input as $value )
$output = array_merge( $output, $this->array_flatten( $value ) );
return $output;
}
}

view raw
gistfile1.php
hosted with ❤ by GitHub

[WordPress] XMLRPC を拡張する

XMLRPC を拡張するプラグインの作り方、あとでメインブログに清書します。

プラグイン本体

<?php
/*
Plugin Name: Ex XMLRPC
Version: 0.0.1
Plugin URI: 
Description: 
Author: wokamoto
Author URI: http://dogmap.jp/
*/
function wpex_xmlrpc_server($class_name) {
	if (!class_exists('wpex_xmlrpc_server'))
		require_once 'class-wpex-xmlrpc-server.php';
	return 'wpex_xmlrpc_server';
}
add_filter('wp_xmlrpc_server_class', 'wpex_xmlrpc_server');
?>

class-wpex-xmlrpc-server.php

<?php
class wpex_xmlrpc_server extends wp_xmlrpc_server {
	function __construct() {
		parent::__construct();
		$this->methods['wpex.getWpVersion'] = 'this:wp_getVersions';
	}

	public function wp_getVersions( $args ) {
		global $wp_version, $wpdb;

		if ( count((array) $args) > 2 ) {
			$this->escape( $args );
			$blog_id = (int) $args[0];
			$username = $args[1];
			$password = $args[2];
		} else {
			return $this->error;
		}

		if ( !$user = $this->login($username, $password) )
			return array(
				'wp' => $wp_version ,
				'php' => PHP_VERSION ,
				'mysql' => $wpdb->db_version() ,
				);
		} else {
			return $this->error;
		}
	}
}

確認方法

<?php
require_once("XML/RPC.php");

$host = "example.com";
$xmlrpc_path = "/xmlrpc.php";
$appkey = '';
$user = 'username';
$passwd ='yourpassword';

$c = new XML_RPC_client($xmlrpc_path, $host, 80);
$appkey = new XML_RPC_Value($appkey, 'string');
$username = new XML_RPC_Value( $user, 'string' );
$passwd = new XML_RPC_Value( $passwd, 'string' );

// blog ID の取得
$message = new XML_RPC_Message(
	'blogger.getUsersBlogs',
	array($appkey, $username, $passwd)
	);
$result = $c->send($message);
if( !$result )
	exit('Could not connect to the server.');
else if( $result->faultCode() )
	exit($result->faultString());
$blogs = XML_RPC_decode($result->value());
$blog_id = new XML_RPC_Value($blogs[0]["blogid"], "string");

// 拡張された XMLRPC メソッド wpex.getWpVersion の取得
$message = new XML_RPC_Message(
	'wpex.getWpVersion',
	array($blog_id, $username, $passwd)
	);
$result = $c->send($message);
if( !$result )
	exit('Could not connect to the server.');
else if( $result->faultCode() )
	exit($result->faultString());
var_dump(XML_RPC_decode($result->value()));
?>

実行結果

array(3) {
  ["wp"]=>
  string(5) "3.2.1"
  ["php"]=>
  string(5) "5.3.6"
  ["mysql"]=>
  string(6) "5.5.14"
}

追記:
こんな面倒なことしなくても xmlrpc_methods ってフィルタに引っ掛ければ良いだけだった…orz
WordPressにおけるXMLRPCの開発・・メソッドの増やし方とか – それ図解で。・・・tohokuaikiのチラシの裏