Note: You are currently viewing documentation for Moodle 3.4. Up-to-date documentation for the latest stable version of Moodle is likely available here: AMF Moodle.

AMF Moodle

From MoodleDocs
Credits

This page was started on 9th October 2008 by Matt Bury

  • Please note: If you want to use ActionScript 2.0 (Flash 8 and under), please refer to Development:AMFPHP.


What is AMFPHP?

Action Message Format PHP

AMFPHP is a widely used open source remoting server that allows Flash and Flex client-side applications to call PHP methods directly, as if they were native Flash/Flex ActionScript methods. It is fast and lightweight and presents an efficient, simple and easy to implement method of communicating with PHP and databases.

Preserved Data Types

AMFPHP preserves the following data types between ActionScript and PHP:

  • Array
  • Bitmap
  • ByteArray
  • int
  • Number
  • Object
  • Recordset (mysql_result)
  • String
  • XML (ActionScript 3.0 also supports E4X notation)

Note: Please add to this list if you have successfully tested data types using AMFPHP 1.9.beta+ and ActionScript 3.0.

AMFPHP automatically converts data types between ActionScript and PHP to their native equivalents. For example, it can convert a PHP array into and ActionScript array or a PHP resource, such as a mysql_result into an Actionscript Recordset.

AMF0 and AMF3

Previous versions of Flash, using ActionScript 2.0 (versions 6, 7 and 8), use AMF0. ActionScript 3.0, Flash CS3+ and Flex, use AMF3 by default but can also use AMF0. What's the difference? AMF3 is compressed and therefore faster. For more details look here.

What is AMF Moodle?

AMF Moodle is a new project (9th October 2008) which aims to integrate Flash and Flex with Moodle's API. The aim is to build a library of services that Flash and Flex developers can use to create secure client-side applications that can interact with Moodle. The first step will be to create a Moodle module that facilitates deploying custom made, generic Flash and Flex e-learning interactions in Moodle courses and recording user interaction results in the Moodle gradebook.

AMF Moodle Outline

There is a summary of some of the specifications for the new AMF Moodle on the Talk:AMF_Moodle comments page that are under discussion. Once we have a more definite specification, it will be transferred to here. Please feel free to comment, make requests, ask questions etc. on the comments page. It'll really help us alot.

AMF Moodle Participants

The project's participants at the moment are: Matt Bury, Jamie Pratt and Marcus Potter.

You can find the project home page at code.google.com.

Find the AMF Moodle discussion thread here.

For further discussion, please use the Talk:AMF_Moodle page comments tab for this wiki page.

What Are the Differences between Using AMFPHP and SCORM?

Several Moodle developers and contributors have asked the question, "If you want to deploy Flash in Moodle, why not use SCORM?" The following is a comparison, posted by Jamie Pratt in the Moodle General Developer Forum, highlighting the advantages and disadvantages of using SCORM and how AMF Moodle would be able to address some of those shortcomings.

Advantages of SCORM

  • portability
  • defined API
  • familiar to some developers
  • package all necessary content in a known format easily uploadable and automatically included in course.

Disadvantages of SCORM

  • From what I've heard there are some issues when trying to get SCORM working across platforms because of incorrect implementation of the standard in the ?packager?, ?in the lms? and/or in the SCORM content.
  • The SCORM API is very limited?
  • The SCORM API is javascript. Flash remoting such as AMF allows a robust way of communicating directly from Flash to the server.
  • Content must be packaged. Needs an extra application to package the content.
  • Display options are limited? Must use frames?
  • It is possible to reuse one Flash object in several moodle activity modules. Flash objects might be quite large. It is great to be able to have one object which will be cached once by the user's browser and then have it load data from the server eg. a list of words or whatever, configuration options to make effectively unique activity instances from one flash object.
  • From what I've understood, the SCORM API requires answers to questions and marking must be done on the client side and grades be sent to the LMS through the API. Isn't this a problem in some cases since a clever student might be able to spoof a grade being sent to the server and/or be able to inspect the data in the browser using commonly available tools and be able to see the answers to questions?

Installing AMFPHP in Moodle

Download

  • Download the latest version of AMFPHP, currently version 1.9.beta (SourceForge repository).
  • Unzip the file and find the directory amfphp.
  • Upload the amfphp directory to ***MOODLEROOT***/lib/

Edit gateway.php

  • Find the file ***MOODLEROOT***/lib/amfphp/gateway.php and open it in your favourite text/PHP editor
  • At the beginning of the code, add the line: include_once "../../config.php";
  • Find and edit the line: $gateway->setClassPath($servicesPath); and change it to: $gateway->setClassPath($CFG->dirroot."/lib/amfphp/services/");
  • Upload the edited ***MOODLEROOT***/lib/amfphp/gateway.php file.
  • That's it!

Setting PHP 5 as Default

Please note: AMFPHP requires PHP 5 to run. Many servers run both PHP 4 and 5, but have them set to run PHP 4 by default. If you experience problems, you may have to change the default PHP version in the ***MOODLEROOT***/lib/amfphp/ directory with an .htaccess file. The following is an example only. Please check that it is correct for your server configuration. If you have a hosted server, they'll probably have an example in their help files. For example:

  • Find the AMFPHP .htaccess file at ***MOODLEROOT***/lib/amfphp/.htaccess
  • Open it with a text editor. You'll see:
#If you're working with a server which doesn't seem to display errors and you don't 
#have access to httpd.conf and you have a good reason to develop remotely instead of
#locally, you may have luck with uploading this configuration file to the server

php_flag display_errors on
php_flag display_startup_errors on
php_value error_reporting 2047
  • Add another line of code to change the default PHP version setting for the amfphp directory:
#If you're working with a server which doesn't seem to display errors and you don't 
#have access to httpd.conf and you have a good reason to develop remotely instead of
#locally, you may have luck with uploading this configuration file to the server

php_flag display_errors on
php_flag display_startup_errors on
php_value error_reporting 2047

SetEnv DEFAULT_PHP_VERSION 5

Testing AMFPHP in Moodle

Here is an example of a simple AMF Moodle service that checks the login status of your browser.

  • Create a new document in your preferred text/PHP editor
  • Copy and paste the code and save it as UserName.php
  • Upload it to ***MOODLEROOT***/lib/amfphp/services/

Now is a good time to find out if your server is running the correct PHP version. If your server is running PHP 4 by default, you'll get error messages caused by the "public" namespace.

  • Navigate to the PHP page you just uploaded in your browser: ***MOODLEROOT***/lib/amfphp/services/UserName.php
  • If there are no error messages then you can continue to the "Testing AMFPHP in Flash" section
<?php
class UserName
{
	public function __construct()
	{
		
	}
	/**
	*checks whether you're logged in to Moodle
	*@returns user login status
	*/
    function loggedInAs() {
        global $USER;
        if (isguestuser()){
            return get_string('loggedinasguest', 'moodle');
        }else if (isloggedin()){
            return get_string('loggedinas', 'moodle', fullname($USER));
        } else {
            return get_string('loggedinnot');
        }
    }
}
?>

Testing AMFPHP in Flash

Please note: Flash CS3 and Flex come with the necessary classes for using AMFPHP already installed. It is not necessary to install any new classes!

  • Open the Flash CS3 IDE
  • Create a new ActionScript 3.0 class document
  • Copy and past the code below and save it as UserName.as
  • Create a new ActionScript 3.0 FLA document
  • In Properties > Document class: type UserName.as
  • Save the FLA file as UserName.fla in the same directory as UserName.as
  • Publish the UserName.swf, AC_RunActiveContent.js and UserName.html files
  • Upload the published files to your server
  • In your browser, navigate to the location of the UserName.html page
  • Try logging in and out of Moodle to see the change in your login status

ActionScript 3.0 Document Class

package {
	
	import flash.display.Sprite;
	import flash.text.*;
	import flash.events.MouseEvent;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.net.Responder;
	
	public class UserName extends Sprite {
		
		private var _format:TextFormat;
		private var _display:TextField;
		private var _call:Sprite;
		private var _gateway:NetConnection;
		private var _responder:Responder;
		
		public function UserName() {
			initFormat();
			initDisplay();
			initCall();
			initGateway();
		}
		
		// create text format object
		private function initFormat():void {
			_format = new TextFormat();
			_format.font = "Trebuchet MS";
			_format.size = 15;
			_format.bold = true;
		}
		
		// create text field to display results
		private function initDisplay():void {
			_display = new TextField();
			_display.autoSize = TextFieldAutoSize.LEFT;
			_display.multiline = true;
			_display.x = 10;
			_display.y = 10;
			_display.defaultTextFormat = _format;
			_display.text = "Click on \"Call UserName.php\" to test.";
			addChild(_display);
		}
		
		// create text button to call UserName.php
		private function initCall():void {
			_call = new Sprite();
			_call.mouseChildren = false;
			_call.buttonMode = true;
			_call.addEventListener(MouseEvent.MOUSE_DOWN, callDownHandler);
			var btn:TextField = new TextField();
			btn.autoSize = TextFieldAutoSize.LEFT;
			btn.border = true;
			btn.background = true;
			btn.backgroundColor = 0xdddddd;
			btn.defaultTextFormat = _format;
			btn.text = " Call UserName.php ";
			btn.x = (stage.stageWidth - btn.width) - 10;
			btn.y = stage.stageHeight - 30;
			_call.addChild(btn);
			addChild(_call);
		}
		
		// depress call button and call UserName.loggedInAs method
		private function callDownHandler(event:MouseEvent):void {
			_call.removeEventListener(MouseEvent.MOUSE_DOWN, callDownHandler);
			stage.addEventListener(MouseEvent.MOUSE_UP, callUpHandler);
			_call.x += 2;
			_call.y += 2;
			_gateway.call("UserName.loggedInAs",_responder);
			_display.appendText("\n  Calling UserName.loggedInAs ... ");
		}
		
		// reset call button
		private function callUpHandler(event:MouseEvent):void {
			_call.addEventListener(MouseEvent.MOUSE_DOWN, callDownHandler);
			stage.removeEventListener(MouseEvent.MOUSE_UP, callUpHandler);
			_call.x -= 2;
			_call.y -= 2;
		}
		
		// connect to AMFPHP gateway
		private function initGateway():void {
			_gateway = new NetConnection();
			// Edit the following line to reflect your server configuration
			_gateway.connect("http://***MOODLEROOT***/lib/amfphp/gateway.php");
			_gateway.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			_responder = new Responder(onResult,onFault);
		}
		
		// show returned results
		private function onResult(res:Object):void {
			_display.appendText("\n  " + String(res));
		}
		
		// show details if call is unsuccessful
		private function onFault(res:Object):void {
			for(var i:String in res) {
				_display.appendText("\n  " + String(res[i]));
			}
		}
		
		// show all net status events (can be status or error events)
		function netStatusHandler(event:NetStatusEvent):void {
			for(var i:String in event.info) {
				_display.appendText("\n" + String(event.info[i]));
			}
		}
	}
}

AMF Moodle Service Library

AMFPHP Service Browser

AMFPHP 1.9.beta comes with a Flex service browser ready installed. It allows you to see your library of services in the ***MOODLEROOT***/lib/amfphp/services/ directory and call them. It also displays error messages very well. It's an ideal tool for checking out your services before your write Flash and Flex applications that call them.

VERY IMPORTANT!

DO NOT leave the service browser installed on a production server (i.e. public). It will leave your service library and therefore your Moodle API and databases exposed to the public!

List Of AMF Moodle Services

  • User.php - returns user login status, returns an array of config settings you can set, returns a value of a config setting, sets a value of a config setting
  • UserName.php - returns user login status

User.php Updated

If you've already seen the tutorials in Development:AMFPHP, here's an updated version of User.php that works with AMFPHP 1.9.beta. As with UserName.php, upload it tothe services directory at ***MOODLEROOT***/lib/amfphp/services/. You can test it by navigating to ***MOODLEROOT***/lib/amfphp/browser/index.html and selecting User from the menu of services.

User.php Script

<?php
class User
{
	public function __construct()
	{
		
	}
    /**
     * Returns string indicating whether a user is logged in.
     * @access remote
     */
    function loggedInAs() {
        global $USER;
        if (isguestuser()){
            return get_string('loggedinasguest', 'moodle');
        }else if (isloggedin()){
            return get_string('loggedinas', 'moodle', fullname($USER));
        } else {
            return get_string('loggedinnot');
        }
    }
    /**
     * Returns an array of config settings you can set.
     * @access remote
     */
    function configSettings() {
        return array_keys(get_user_preferences());

    }
    /**
     * Returns a value of a config setting.
     * @param string name
     * @access remote
     */
    function getConfigSetting($name) {
        $name = clean_param($name, PARAM_ALPHAEXT);
        return get_user_preferences($name);
    }
    /**
     * sets a value of a config setting.
     * @param string name
     * @param string value
     * @access remote
     */
    function setConfigSetting($name, $value) {
        $name = clean_param($name, PARAM_ALPHAEXT);
        $value = clean_param($value, PARAM_NOTAGS);
        return set_user_preference($name, $value);
    }
}
?>

Useful Links

AMFPHP

Sir Lee Brimelow's video tutorials

Learn how to install AMFPHP and create a simple service that sends email.

In this tutorial he shows you how to directly return database records to Flash using AMFPHP.

Alessandro Crugnola's tutorials

AMF Moodle

Adobe ActionScript 3.0 Language Reference

The two most important classes related to AMFPHP are:


AMFPHP Is Fast

There's always someone who'll play with a new toy and push it until it breaks. AMFPHP can go pretty fast! Check out this blog article.