GinkoLab

Recherche & Développement sur les Applications Internet Riches, Flex, AIR, Flash

mai 21st, 2010

Cet exemple est réalisé avec Flash Builder 4, et cette fois-ci, n’utilise pas J-AMFPHP.

le Main.mxml :

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
			   xmlns:s="library://ns.adobe.com/flex/spark"
			   xmlns:mx="library://ns.adobe.com/flex/halo" width="350" height="250"
			   creationComplete="init()" backgroundColor="#E1E4F2">

	<fx:Declarations>
		<s:HTTPService id="serv" url="http://localhost/joomla15/createNewUser.php" method="POST" resultFormat="text"/>
		<s:HTTPService id="serv_user" url="http://localhost/joomla15/connectJoomla.php" resultFormat="text"/>
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			import mx.controls.Alert;
			import mx.managers.CursorManager;
			import mx.rpc.AsyncToken;
			import mx.rpc.events.FaultEvent;
			import mx.rpc.events.ResultEvent;

			private var obj:Object;
			[Bindable]
			private var userIn:String;

			private function init():void
			{
				var token:AsyncToken = serv_user.send();
				token.addResponder( new mx.rpc.Responder( tokenResultHandler, faultHandler ) );

				obj = new Object();
				serv.addEventListener(ResultEvent.RESULT, resultHandler );
				serv.addEventListener(FaultEvent.FAULT, faultHandler );
			}

			protected function button1_clickHandler(event:MouseEvent):void
			{
				obj.nom = ti_nom.text;
				obj.prenom = ti_prenom.text;
				obj.mail = ti_mail.text;
				obj.username = ti_username.text;
				obj.pass = ti_pass.text;
				// si les champs sont vides... don't send !!!
				serv.send( obj );

				CursorManager.setBusyCursor();
				initTextInput();
			}
			private function tokenResultHandler( evt:ResultEvent ):void
			{
				userIn = evt.result.toString();
			}

			protected function resultHandler( evt:ResultEvent ):void
			{
				if( evt.token.message.body.nom != "" )
				{
					CursorManager.removeBusyCursor();
					Alert.show( "L'utilisateur '"+ evt.token.message.body.username+ "' a bien été ajouté", "Avertissement." );
				}

			}
			protected function faultHandler( evt:FaultEvent ):void
			{
				Alert.show( evt.fault.toString() );
			}
			protected function initTextInput( ):void
			{
				ti_mail.text = "";
				ti_nom.text = "";
				ti_pass.text = "";
				ti_prenom.text = "";
				ti_username.text = "";
			}

		]]>
	</fx:Script>
	<s:HGroup width="100%" height="30" verticalAlign="middle" paddingLeft="10">
		<s:Label text="Bonjour "/>
		<s:Label text="{userIn}" fontWeight="bold"/>
	</s:HGroup>

	<s:Button label="Create User" click="button1_clickHandler(event)" x="134" y="222"/>
	<mx:Form width="100%" x="0" y="60" height="172">
		<mx:FormItem label="Nom: " width="100%" color="#000000">
			<s:TextInput id="ti_nom" width="190"/>
		</mx:FormItem>
		<mx:FormItem label="Prénom: " width="100%">
			<s:TextInput id="ti_prenom" width="190"/>
		</mx:FormItem>
		<mx:FormItem label="Email: " width="100%">
			<s:TextInput id="ti_mail" width="190"/>
		</mx:FormItem>
		<mx:FormItem label="Nom d'Utilisateur: " width="100%">
			<s:TextInput id="ti_username" width="190"/>
		</mx:FormItem>
		<mx:FormItem label="Mot de Passe: " width="100%">
			<mx:TextInput id="ti_pass"  width="190" displayAsPassword="true"/>
		</mx:FormItem>
	</mx:Form>
	<s:Label x="9" y="25" text="Maintenat que tu es loggué, tu peux créer de nouveaux users." color="#44559D"/>

</s:Application>

le fichier connectJoomla.php qui renvoie le User connecté :

<?php
define( '_JEXEC', 1 );
define( '_VALID_MOS', 1 );

define( 'JPATH_BASE', realpath(dirname(__FILE__) .'/' ) );
define( 'DS', DIRECTORY_SEPARATOR );

//as seen on http://forum.joomla.org/viewtopic.php?f=304&t=263491

require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

/**
 * check_joomla_login
 *
 * @return BOOL
 *
 * USAGE EXAMPLE
 * echo (check_joomla_login())?"Logged in" : "Not logged in";
 **/
echo (check_joomla_login());

function check_joomla_login(){

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();

$user =& JFactory::getUser();
$session =& JFactory::getSession();

return $user->username;
}

et pour finir, createNewUser.php, (récupéré ici je crois, et modifié pour les besoins de la cause) qui va donc créer un nouvel utilisateur dans la base de Joomla :

<?php
define( '_JEXEC', 1 );
define( '_VALID_MOS', 1 );
// JPATH_BASE should point to Joomla root directory
// if you app is placed into a subfolder in Joomla root, the path will look like dirname(__FILE__) . '/..'
define( 'JPATH_BASE', realpath(dirname(__FILE__) .'/' ) );
define( 'DS', DIRECTORY_SEPARATOR );

//as seen on http://forum.joomla.org/viewtopic.php?f=304&t=263491

require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();

/*-------------------------------ADDED----------------------------------------------------------------------*/
$firstname = $_POST['prenom'];
$lastname = $_POST['nom'];
$username = $_POST['username'];
$email = $_POST['mail'];
//$usertype = $_POST['register'];
$password =  $_POST['pass'];
/*-------------------------------END ADDED----------------------------------------------------------------------*/

/*
I handle this code as if it is a snippet of a method or function!!
First set up some variables/objects
*/
// get the ACL
$acl =& JFactory::getACL();

/* get the com_user params */

jimport('joomla.application.component.helper'); // include libraries/application/component/helper.php
$usersParams = &JComponentHelper::getParams( 'com_users' ); // load the Params

// "generate" a new JUser Object
$user = JFactory::getUser(0); // it's important to set the "0" otherwise your admin user information will be loaded

$data = array(); // array for all user settings

// get the default usertype
$usertype = $usersParams->get("new_usertype");
if (!$usertype) {
    $usertype = "Registered";
}
// set up the main user information
$data["name"] = $firstname." ".$lastname; // add first- and lastname
$data["username"] = $username; // add username
$data["email"] = $email; // add email
$data["gid"] = $acl->get_group_id( "", $usertype, "ARO" );  // generate the gid from the usertype

/* no need to add the usertype, it will be generated automaticaly from the gid */

$data["password"] = $password; // set the password
$data["password2"] = $password; // confirm the password
$data["sendEmail"] = 1; // should the user receive system mails?

/* Now we can decide, if the user will need an activation */

$useractivation = $usersParams->get( "useractivation" ); // in this example, we load the config-setting
if ($useractivation == 1) { // yeah we want an activation

    jimport("joomla.user.helper"); // include libraries/user/helper.php
    $data["block"] = 0; //si à 1 user pas "enabled" dans "User Manager" //1 ??  block the User
    $data["activation"] =JUtility::getHash( JUserHelper::genRandomPassword() ); // set activation hash (don't forget to send an activation email)
}
else { // no we need no activation

    $data["block"] = 1; //donc je mets ici à 1 pour bloquer //0 ?? don't block the user
}

if (!$user->bind($data)) { // now bind the data to the JUser Object, if it not works....

    JError::raiseWarning("", JText::_( $user->getError())); // ...raise an Warning
    return false; // if you're in a method/function return false
}

if (!$user->save()) { // if the user is NOT saved...

    JError::raiseWarning("", JText::_( $user->getError())); // ...raise an Warning
    return false; // if you're in a method/function return false
}

return $user; // else return the new JUser object

La copie d’écran :

Et quelques précisions :

- Le Main.swf est placé dans Joomla_Root/mondossier
- connectJoomla.php et createNewUser.php sont placés eux à la racine de Joomla (Joomla_Root/)

  • GinkoAdmin (10)
  • 5 Responses to “ Intégrer Flex dans Joomla (suite) via un HTTPService ”

    1. Nico dit :

      Génial, je vais tester aussi.
      Je me demande quelle est la méthode la meilleure…D’un côté avec J-AMFPHP on fait des plugins sous Joomla! donc les “paquets” sont mieux identifiables, mais je me pose la question de la maintenance de J-AMFPHP en cas de mise à jour de AMFPHP…
      D’un autre côté, on peut créer plus facilement des panneaux dans le backoffice j’ai l’impression avec cette méthode, et interconnecter avec d’autres applis aussi…
      Hmm, vraiment très intéressant ces tutoriaux !

    2. admin dit :

      D’après ce que j’en sais, plus de mises à jour d’AMFPHP… Donc à priori idem pour J-AMFPHP.
      Ces librairies datent un peu, et ne sont plus développées certainement à cause du Zend_AMF, intégré au Zend Framework, lui-même intégré à Flash Builder 4.
      C’est Wade Arnold je crois (à vérifier) qui est à l’origine d’AMFPHP, et qui maintenant s’occupe surtout de Zend_AMF.
      De notre côté on attend toujours le fameux “browser” qu’il y avait dans AMFPHP, et qui était bien pratique pour “débugguer”… Wade Arnold avait commencer à travailler là-dessus pour l’intégrer à Zend_AMF, mais apparemment ce n’est plus d’actualité…?
      Pour l’utilisation de J-AMFPHP, je cite ici Christopher Garvis (j’ai la flemme de traduire…) :
      “AMFPHP is intended more to work outside of Joomla. Like say you want to give you Joomla site an AIR app or you want your website to be a flex app but use the Joomla as your backend/db. Very powerful but not always the best answer”

    3. admin dit :

      RECTIFICATION !

      AMFPHP revient à la vie, ici, ici et ici

    4. Nico dit :

      Ha, très bonne nouvelle ça ! :)

    5. Kim Hansen dit :

      Merci por cette example!

      My French is very rusty, so I will continue in English.

      We have successfully used J-Amfphp to integrate Joomla! with Flex in our application JEPUM – Joomla Easy Picture Uploader and Manager.

      But you are very right that J-Amfphp has not and is not being maintained at all. It hasn’t been touched since 2008.

      Nevertheless, with a couple of changes, it is possible to make it work.

    Leave a Reply