Extension:API Query Extension

From MediaWiki.org
Jump to: navigation, search
MediaWiki extensions manual - list
Crystal Clear action run.png
API Query Extension

Release status: stable

AQE Screenshot 1.0.png
Implementation Tag
Description Displays results from MediaWiki Query API within an article in blogroll format.
Author(s) Andreas Rindler (LindeleTalk)
Last version 1.0 (16/11/2007)
MediaWiki 1.11
License LGPL
Download No link
Parameters

$wgAQETarget (specify target wiki)

Check usage (experimental)

Contents

[edit] What can this extension do?

This extension allows users to display results from the MediaWiki Query API in a simple text box within an article page. Users configure query parameters that get passed to the extension. The extension creates a server side http call to the target wiki's (e.g. http://mike2.openmethodology.org) Query API and displays the results in the article.

[edit] Usage

This extension would be used in a mashup between several wikis. For example, it can be put on a category page on one wiki to perform a query to another wiki to display all articles of the same category that exist on the other wiki. For MIKE2.0 we display all articles of certain categories on MIKE2.0 in our internal wiki. This saves users time when trying to find articles across wikis that share the same categories.

Here is an example how to use it within an article:

<apiquery displaytype="blogroll" title="MIKE2.0 Articles in this category:">
action=query;
list=categorymembers;
cmcategory=Data Warehousing;
cmlimit=500;
</apiquery>

[edit] Installation

To install this extension:

  1. Add the following to LocalSettings.php:
require_once('extensions/apiqueryextension/apiqueryextension.php');
$wgAQETarget = 'http://mike2.openmethodology.org/';
  1. Create a folder apiqueryextension in your MediaWiki extensions folder.
  2. Copy/paste the below PHP code into a text editor and save the file as apiqueryextension.php in the apiqueryextension folder.
  3. Copy/paste the CSS code into a text editor and save the file as apiqueryextension.css in the same folder.


Note

MediaWiki allows administrators to disable the Query API. MW versions 1.10 and earlier had a security bug in the API and many sites that have not upgraded to the latest version of MW might have simply disabled the API.

[edit] Configuration parameters

$wgAQETarget - Specify the target wiki which will be queried by the extensions.


[edit] PHP Code

<?php
 
 /**
 * Mediawiki API Query Extension : "Display results from query API".
 * Copyright (C) 2007 Andreas Rindler
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 **/
 
 
 /**
 *
 * @version 1.0
 * @author Andreas Rindler, <mediawiki at jenandi dot com>, <http://www.foolnology.com>
 * @copyright Andreas Rindler 2007
 * @Only implements the Query Lists API in current version. Future release might include other query types.
 **/
 
$wdVersion = '1.0';
$wdAQEDebug = true;
 
$wgExtensionCredits['other'][] = array
  (
   'name' => "Api Query Extension",
   'version' => $wdVersion,
   'author' => 'Andreas Rindler <mediawiki at jenandi dot com>',
   'url' => 'http://www.mediawiki.org/wiki/Extension:API_Query_Extension',
   'description' => 'Display results from API query'
   );
 
 
$wgExtensionFunctions[] = "wfApiQueryExtension";
 
function wfApiQueryExtension() {
    global $wgParser;
    $wgParser->setHook( "apiquery", "displayQueryResults" );
}
 
# The callback function for converting the input text to HTML output
function displayQueryResults( $input, $argv, &$parser ) {
        global $wgScriptPath, $wgOut, $wgAQETarget;
 
        //DEFAULTS
        $wgDisplayType  = 'blogroll';
        $wgFormat               = 'format=xml';
        $wgTitle                = 'MediaWiki Category Links:';
        $wgCategory             = '';
        $output                 = '';
 
        //get user configuration
        //if(array_key_exists('displaytype',$argv)){       //NOT IMPLEMENTED YET
        //      $wgDisplayType = mysql_real_escape_string(trim($argv['displaytype']));
        //}
        if(array_key_exists('title',$argv)){
                $wgTitle = mysql_real_escape_string(trim($argv['title']));
        }
        $input = trim($input);
 
        //Check that at least one parameter is configured
        $intParams = 0;
        str_replace( ';',';',$input,$intParams);
        if ($intParams ==0) {
                $output = '<b>APIQuery Configuration Error</b> - You need to configure parameters like: action=query; list=categorymembers; cmcategory=Information; cmlimit=500;';
        }
        else { //EXECUTE MAIN CODE
 
                //add ? sign to post string
                $wgRequest = '?';
 
                //get all options from user input and concatenate them as the post string
                $wgOptionsTemp = explode(';',rtrim($input,';'));
                foreach( $wgOptionsTemp as $key => $value ) {
                        //$wgRequest .= mysql_real_escape_string(trim($value)) . '&';
                        if (strpos($value, 'cmcategory') !== false) {
                                // do not use != instead!!
                                $wgCategory = explode('=',$value);
                                $wgCategory = $wgCategory[1];
 
                        }
                        //escape spaces in the URL. urlencode() failed here for unknown reasons. TODO
                        $wgRequest .= str_replace( ' ', '%20',trim($value)) . '&';
                }
 
                //add format request. Ampersand character is already added from loop above
                $wgRequest .= $wgFormat;
 
                //Create link to stylesheet
                $output .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"" . $wgScriptPath . "/extensions/apiqueryextension/apiqueryextension.css\"/>";
 
                //send request to target wiki and retrieve response
                $wgResponse = get_web_page($wgAQETarget . 'api.php' . $wgRequest);
 
                //Create div to display the results
                $output .= "<div id=\"apiquery\"><span id=\"aqe_title\">". $wgTitle ."</span> (Want to go directly to the category page? Click <a href=\"" . $wgAQETarget . "index.php/Category:" .$wgCategory. "\" target=\"_blank\">here</a>!)<br>";
 
                $doc = new DOMDocument();
                $doc->preserveWhiteSpace = FALSE;
 
                try {
                    $doc->loadXML(trim($wgResponse['content']));
                } catch (Exception $e) {
                    error_log( "Exception caught");
                    error_log($e->getMessage());
                }
 
                try {
                        $links = $doc->getElementsByTagName("cm");
                } catch (Exception $e) {
                        error_log($e->getMessage());
                }
 
                foreach($links as $link){
                        $output .= '<a href="' .$wgAQETarget . 'index.php/' .  $link->getAttribute('title') . '">'. $link->getAttribute('title') . '</a><br>';  
                }
                $output .= "</div>";
 
        }
        //Inject into page
        return $output;
}
 
/**
 * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
 * array containing the HTTP server response header fields and content.
 */
function get_web_page( $url ){
 
        //set up options for the http call
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
    );
 
        //initiate and send post
    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );
 
        //prepare content
    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
 
    return $header;
}
 
?>

[edit] CSS Code

/* Mediawiki API Query Extension
 *
 * @author Andreas Rindler (mediawiki at jenandi dot com)
 * @licence GNU General Public Licence 2.0 or later
 * @description 
 *
*/
 
        /*Results DIV*/
        #apiquery {
          font-weight: normal;
          display: block;
          max-height: 300px;
                margin-top: 1.0em;
                margin-right: 0pt;
                margin-bottom: 1pt;
                margin-left: 0.1em;
                padding-top: 0pt;
                padding-right: 0em;
                padding-bottom: 1.5em;
                padding-left: 0.2em;
                border: 1px solid #c21731;
                overflow: auto;            
        }
        #aqe_title {
          color: #2d5381;
          font-size: large;
        }

[edit] See also

Personal tools
Namespaces

Variants
Actions
Navigation
Support
Download
Development
Communication
Print/export
Toolbox