2 of 2 found this page helpful

Writing a MindTouch extension in PHP

    In this tutorial, we will show you how to use the PHP extension for MindTouch. Now that we have the standard XML-RPC integrated into DekiScript, we can now use XML-RPC calls between our own PHP servers and MindTouch.

    If you don't have a seperate PHP server you can use the "config" directory of your MindTouch installation to process php files for your extension. When using the VMware Certified Virtual Appliance that directory is found at "/var/www/dekiwiki/config".

    (Note: because XML-RPC is also implemented now in DekiScript, we can also make calls using other languages too like Python, Perl, etc..)

         

    This tutorial will show you:

    • How to setup a XML-RPC PHP server that can communicate with MindTouch
    • How to make a PHP file that uses DekiExt.php to create a remote server extension

         

    Getting Started

    In order to make the MindTouch extension for PHP work, first make sure you have a PHP server running. In order for your PHP server to communicate with MindTouch via XML-RPC you need to download a XML-RPC library from Incutio. It's called Incutio XML-RPC Library  Right click on the link and Save As: IXR_Library.inc.php

     

    Once you've added that library into the directory you would like to work out of, you also need to copy DekiExt.php.


    Now that you have the necessary files needed for your PHP server, you can now write the PHP that will be used for your extension.

         

    Writing your PHP extension - Simple Case

    First, make sure you include the DekiExt.php file in your own .php file.

         

    include('DekiExt.php');

    Next, call the function DekiExt, which will help you create your extension. This part is required in order for your php extension to work. The DekiExt function takes in 3 parameters: title, extension metadata (optional), and an array mapping your extension functions to your functions in PHP. And the list of extension functions follows this format.

    DekiExt(
        
        // Title of your Deki Wiki Extension
        "Acme HelloWorld Service",                           
    
        // (Optional) Metadata about the Deki Wiki Extension
        null,
    
        // List of Extension Functions
        array(
            "sayHello():str" => "HelloWorld"
        )
    );

         

    The above DekiExt function is written with the most minimal amount of information possible to get MindTouch to run your PHP extension. Once you have that done, you can write your HelloWorld function:

    function HelloWorld()
    {
        return "Hello World";
    }

      To view the whole file: test.php

         

    With just those few lines of code put together, all you need to do next is register your newly created PHP file as a MindTouch extension. You do this by first going into your Control Panel page. On the Control Panel page, select the Extensions.

     

    When you're in the Extensions page, click Add Extension and fill in the input boxes with their appropriate information:

    • Type: In our case, we want to choose Remote.
    • Description: your extension name
    • URI: location of your extension
    • Status: enabled (default)

     

    Once this is done, you can now call your php HelloWorld function from any page in MindTouch. 

    Once you save your changes, the outcome of the HelloWorld function will show up on your MindTouch page:

    SimpleSample (1).jpg

         

         

    Writing your PHP extension - with Extension MetaData

    Next, we include some extension metadata to our DekiExt: description, copyright, uri.help, and namespace. For a full compilation of extension info types you can use.

    DekiExt(
        
        //Title of your Deki Wiki Extension
        "Mindtouch Deki Extension Php Service",                           
    
        //(Optional) Metadata about the Deki Wiki Extension
        array(
            "description" => "Extension to embed friendly Acme greetings.",               
            "copyright"   => "Copyright Acme Inc. 2008", 
            "uri.help"    => "http://acme.corp/HelloWorldHelp.html",
            "namespace"   => "test"
        ), 
    
        //List of Extension Functions
        array(
            "Greeting(first:str, last:str):str" => "myGreeting",          
        )
    );

    As you see, you can fill the extension with preset keys and values that will be added into the generated xml page when you register your PHP file as an extension. Once this is done, create the matching function derived from your last parameter in DekiExt:

    function myGreeting($args) 
    {
    	list($first, $last) = $args; 
    	return 'Hello World, my name is '.$first.' '.$last;
    }

    NOTE: when writing your functions, you can only put in one parameter. Because the IXR_Library treats the incoming XML-RPC params as an array isntead of parameters that are supposed to be mapped accordingly. As you will notice in the sample function, we tell the extension that the user will be passing in 2 parameters from MindTouch. However, on the PHP side, we will only take 1 parameter of type array. You can either handle the incoming array by calling it's incidies or remap it using list(p1, p2, p3, etc...) like in the function above.

    Like before in your simple sample, register your PHP file as a Remote extension in the Service Managment page and then call it in your MindTouch editor.

    When we have a namespace in our extension metadata, we call our function from MindTouch like this:

    {{namespace.functionName()}}

    SimpleSampleResult (1).jpg

         

    Writing your PHP extension - Advanced Sample

    In this sample, we will show you different ways you can use PHP to create a page with more functionality.

    Like before, add the include the DekiExt.php file and then create your own DekiExt function with the parameters you want. 

    DekiExt(
    
        //Title of your Deki Wiki Extension
        "Acme Php Service",
    
    
        array( 
            "description" => "date offset, random links, Phil's BBQ open hours, and email functions", 
            "copyright" => "Acme Random Functions 2000", 
            "uri.help" => "http://acme.org/AcmeHelp.html",
            "namespace" => "test"
        ), 
    	
        //List of Extension Functions
        array( 
            "time(days:num):str"                           => "daysLater",
            "randLink(random:bool, link:str):str"          => "randomTinyUrl",
            "philsOpen(day:str, open:str, closed:str):str" => "philsOpen",
            "send(to:str, subject:str, body:str):str"      => "sendEmail"
        )
    );

         

    Now that you have the DekiExt function setup, you can write your functions that match the function array you listed as a parameter in DekiExt.

    daysLater:

    calculates the date that is offset by the number of days you specify:

    function daysLater($arg)
    {
    	$offset = time() + ($arg * 24 * 60 * 60);
    	return  date('Y-m-d',$offset) ."\n";
    }
    randomTinyUrl:

    pulls random TinyUrls

    function randomTinyUrl($args)
    {
    	list($isRandom, $uri) = $args;
    	if($isRandom)
    		$seed = rand(0, 5000);
    	else
    		$seed = $uri;
    	return "http://tinyurl.com/".$seed;
    }
    philsOpen:

    tells you if Phil's BBQ is open today

    function philsOpen($arg)
    {
    	list($day, $opening, $closing) = $arg;
    	
    	$timestamp = time() -7*3600;
    	$now = gmdate('h a', $timestamp);
    	$today = gmdate('D', $timestamp);
    	$givenDay = gmdate('D', strtotime($day));
    	$open = gmdate('h a',strtotime($opening));
    	$close  = gmdate('h a',strtotime($closing));
    	if($open == $close)
    	{
    		return 'closed';
    	}
    	else if((strtotime($today) == strtotime($givenDay)))
    	{
    		if(strtotime($close)-strtotime($now) < 0)
    			return 'closed';
    		else
    			return 'open today, will close in: ' . gmdate('H',strtotime($close)-strtotime($now)). ' hours';
    	}
    	else
    	{
    		return $open . ' to ' . $close;
    	}
    }
    sendEmail:

    Email function

    function sendEmail($arg)
    {
    	list($to, $subject, $body) = $arg;
    
    	// Additional Headers
    	$headers = 'From: youremail@example.com'."\r\n".
    		'Cc: yourContact@example.com'."\r\n";
    
    	if(mail($to, $subject, $body, $headers))
    	{
    		return "Mail sent successfully.";
    	}
    	else
    	{
    		return "Was unable to send mail.";
    	}
    }

    To view the full file: DekiExtSample.php

         

    After you're done writing your PHP file, register it as a Remote extension in your Service Management page, like before in the Simple Sample Case . Once that is done, you can now access those functions anywhere in your page:

    adv_ex (1).jpg

         

         

         

    Returning XML From Your PHP Extension

    While XML-RPC does not support XML, DekiScript does, so you can actually return something in xml format. However, since the PHP server only handles the XML-RPC standard, we still cannot call a function using a parameter of type XML. 

    Like before, setup the DekiExt. Notice how the return is of type xml:

    DekiExt(
    		//title
    		"Mindtouch Extension Php Return XML Service", 
    
    		//extension options
    		array("namespace" => "xmlRetSample"), 
    
    		//function information to php function Name mapping 
    		array(
    			"formatReturn(first : str, last : str):xml" => "xmlReturn"
    		)
    );

    Next, we write out our xmlReturn function:

    function xmlReturn($args) 
     {
    	    list($first, $last) = $args;
    
    	
    	    $str ='<html><head>'.
    			'<script type="text/javascript" src="http://this_is_a_test/"></script>'.
    			'</head><body>'.
    			'<table border="1"><tr><td>'.$first.'<br/></td><td>'.
    			$last.'</td></tr></table></body></html>';
    
    	    return $str;
     }

     After that, Register your php extension, and call it like all the other extension samples.

    xmlRet.jpg

         

    Extension Function to Function Name Mapping Format

    function_name(parameter1:type, parameter2:type, parameter3:type ...etc....):return_type => your_php_function_name

    The types that are allowed for parameters and the return are: any, nil, num, str, bool, list,and map.

    There is also a special case with xml, while you can return something of xml type, you cannot give a parameter a xml type.

    NOTE: Even though the types uri exists in DekiScript, it cannot be used in PHP extensions since they are not supported by XML-RPC.

         

         

    Additional Extension Information

    The different kinds of extension metadata that can be set

         

    Extension Info Name Option Description Example
    title Required full name of the extension MindTouch Dapper Extension
    copyright Optional copyright notice Copyright MindTouch 2008
    description Optional description of the functionality contained in this extension This extension contains functions for embedding and processing dapps
    uri.license Optional uri to the license description page      
    uri.help Optional uri to the help documentation page      
    uri.logo Optional uri to extension logo (100x75px)      
    namespace Optional prefix for all extension functions dapper
    label Optional short title for extension; used by the extension dialog Dapper

         

    For more information, please refer to HERE.

         

    Conclusion

    Now that MindTouch is compatible with standards compliant XML-RPC, we can now call PHP functions located on our own server from MindTouch. In order to do this, we only need to add 2 php files, to act as a server that will communicated with MindTouch via XML-RPC and turn our DekiExt function parameter information into a extension xml page. From this, we can easily add our PHP file (with the required DekiExt information filled in) as a remote service and begin to use our own PHP functions within seconds.

    Was this page helpful?
    Tag page

    Files 7

    FileVersionSizeModified 
    Viewing 9 of 9 comments: view all
    I'm very happy with the php support. For me it was the only thing missing to get my extension added to the wiki.

    Only thing I could not get to work yet was the xml return type. The function returns an error: Function 'http://wiki.nx-solutions.com/config/...nyWikiDraw.rpc' failed with response: xdoc is empty

    Maybe good to add that you don't HAVE to serve the PHP from another server or through another virtualhost. The easiest way in my opinion is to add a extensions directory to the deki-hayes/config directory. The php scripts can then be accessed through http://deki.wiki.url/config/extensions/some.php

    Posted 20:51, 14 May 2008
    I had to apply the following patch to the DekiWiki.php: http://wiki.opengarden.org/@api/deki/files/2616/=DekiExt.php.patch

    This patch adds dl("xmlwriter.so") to get the xmlwriter functionality working properly and it fixes the output for functions with xml output
    Posted 17:16, 15 May 2008
    Thanks ajmhendriks, I just added the amendment that you can make your extension in the config file.
    Posted 10:00, 19 May 2008
    can't get this to work, posting a question in the thread at http://forums.opengarden.org/showthread.php?t=2544
    Posted 00:10, 30 May 2008
    Typo in source file. Issue has been corrected.
    Posted 06:19, 30 May 2008
    Can you add another page with detailed instructions on how to get perl scripts to work?
    Posted 08:37, 19 Jun 2008
    I had trouble getting PHP extensions going until I figured our server (CentOS 5) doesn't have the 'xmlwriter' PHP extension available. I have thus modified DekiExt.php to write the xml tags directly. See DekiExt-noXmlWriter.php (attached). Download then rename to DekiExt.php - it is functionally identical to the original except for removing the xmlwriter requirement.
    Posted 17:26, 15 Dec 2009
    @kenfortune I filed a bug report and attached your updated code to it. thanks!!
    Posted 09:39, 21 Dec 2009
    Can someone direct me on a more detailed tutorial of how to get this up and running. i'm trying to set up a quick HelloWorld extension to practice using PHP in my mindtouch intranet and I can't get it to work. I've uploaded the IXR_Library.inc.php, DekiExt.php, and created a test.php into my install of MindTouch (I've installed MindTouch on a Win2K3 server so I've put the files in C:\Program Files\MindTouch\MindTouch\web\config) and I've tried adding an extension but get the following error:

    FastCGI Error
    The FastCGI Handler was unable to process the request.

    Error Details:

    The FastCGI process exceeded configured activity timeout
    Error Number: 258 (0x80070102).
    Error Description: The wait operation timed out.

    HTTP Error 500 - Server Error.
    Internet Information Services (IIS)

    When I browse to my test.php site (http://localhost/config/test.php), I get the following:

    PHP Warning: Call-time pass-by-reference has been deprecated in C:\Program Files\MindTouch\MindTouch\web\config\DekiExt.php on line 250
    PHP Warning: Call-time pass-by-reference has been deprecated in C:\Program Files\MindTouch\MindTouch\web\config\DekiExt.php on line 250
    PHP Warning: Call-time pass-by-reference has been deprecated in C:\Program Files\MindTouch\MindTouch\web\config\DekiExt.php on line 348
    PHP Warning: Call-time pass-by-reference has been deprecated in C:\Program Files\MindTouch\MindTouch\web\config\DekiExt.php on line 348

    The same errors occur when browsing the DekiExt.php file

    Any guidance would be greatly appreciated.
    Posted 10:30, 17 Jun 2011
    Viewing 9 of 9 comments: view all
    You must login to post a comment.

    Copyright © 2011 MindTouch, Inc. Powered by