<?php
/**
 * @version 1.0 $Id: select.php 175 2009-11-07 10:24:30Z vistamedia $
 * @package Joomla
 * @subpackage FLEXIcontent
 * @subpackage plugin.select
 * @copyright (C) 2009 Emmanuel Danan - www.vistamedia.fr
 * @license GNU/GPL v2
 *
 * FLEXIcontent 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 General Public License for more details.
 */
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.event.plugin');

class rssItem{

	var $title;
	var $guid;
	var $link;
	var $thumbnail;
	var $content;
	var $mediaUrl;
	var $mediaPath;
	var $mediaType;
	var $mediaFile;
	var $used;
	var $mediaDate;
	var $mediaName;
	var $author;
	var $comment;

	function rssItem( $mediaPath,$mediaUrl,$media,$thumb,$EXIFfirst){
	
		$this->mediaName=$media;
		$this->mediaPath=$mediaPath;
		$this->mediaFile=$this->mediaPath.'/'.$this->mediaName;
		$this->mediaDate=filemtime( $this->mediaPath.'/'.$this->mediaName);

		$titles[] = str_replace(array(".", "_", "-", "png","jpg","flv", "gif","PNG","JPG", "GIF","FLV"), " ", $media);
		$authors[] = '';
		$comments[] = '';
		$itemTitle = '';
		$itemAuthor = '';
		$itemComment = '';
		// MOD_FBR begin
		if(in_array(strtolower(end(explode('.', $this->mediaName))), array('jpg', 'jpeg', 'tif', 'tiff'))){
      // Affichage des IPTC
      GetImageSize ($this->mediaFile,$infosIPTC);
      if (isset($infosIPTC["APP13"])) {
        $infoIPTC = iptcparse ($infosIPTC["APP13"]);         
        $titles[] = (isset($infoIPTC["2#105"][0])) ? $infoIPTC["2#105"][0] : '';
        $authors[] = (isset($infoIPTC["2#122"][0])) ? $infoIPTC["2#122"][0] : ';      	
        $comments[] = (isset($infoIPTC["2#120"][0])) ? $infoIPTC["2#120"][0] : ';      	
      }
		  // Affichage des EXIF
		  if($infosEXIF = exif_read_data($this->mediaFile, 'EXIF', true)){
		    $infoEXIF = $infosEXIF['IFD0'];
        $titles[] = (isset($infoEXIF['Title'])) ? $infoEXIF['Title'] : '';
        $authors[] = (isset($infoEXIF['Author'])) ? $infoEXIF['Author'] : '';
        $comments[] = (isset($infoEXIF['Comments'])) ? $infoEXIF['Comments'] : '';
		    if (isset($infosEXIF['WINXP'])) {
          $infoEXIF = $infosEXIF['WINXP'];
          $titles[] = (isset($infoEXIF['Title'])) ? $infoEXIF['Title'] : '';
          $authors[] = (isset($infoEXIF['Author'])) ? $infoEXIF['Author'] : '';
          $comments[] = (isset($infoEXIF['Comments'])) ? $infoEXIF['Comments'] : '';
        }
      } 
    }
    if (!$EXIFfirst){
      $titles=array_reverse($titles);
      $authors=array_reverse($authors);
      $comments=array_reverse($comments);
    }
    foreach ($titles as $title) {
      if ($title!='') $itemTitle=$title;
    }
    foreach ($authors as $author) {
      if ($author!='') $itemAuthor=$author;
    }
    foreach ($comments as $comment) {
      if ($comment!='') $itemComment=$comment;
    }
		
		$this->title ="<title>{$itemTitle}</title>";
		$this->author="<author>{$itemAuthor}</author>";
		$this->comment="<description>{$itemComment}</description>";
		$this->guid=md5($mediaPath.$media);
		$this->link="<link>".$this->cleanURL($mediaUrl."/".$media)."</link>";
		$this->thumbnail='<media:thumbnail url="'.$this->cleanURL($thumb).'"/>';
		if(substr(strtolower($media),-3) == 'flv'){
			$this->mediaType="video";
			$this->content='<media:content type="video/x-flv" url="'.$this->cleanURL($mediaUrl."/".$media).'"/>';
		}else{
			$this->mediaType="img";
			$this->content='<media:content url="'.$this->cleanURL($mediaUrl."/".$media).'"/>';
		}
		$this->mediaUrl=$this->cleanURL($mediaUrl."/".$media);
		
	}

	function getMediaName(){
		return $this->mediaName;
	}
	
	function getMediaUrl(){
		return $this->mediaUrl;
	}
	
	function getTitle(){
		return $this->title;
	}
	
	function getAuthor(){
		return $this->author;
	}
	
	function getComment(){
		return $this->comment;
	}
	
	function getGuidTag(){
		return '<guid>'.$this->guid.'</guid>';
	}
	
	function getGuid(){
		return $this->guid;
	}
	
	function getLink(){
	  return $this->link;
	}
	
	function getThumbnail(){
		return $this->thumbnail;
	}

	function getContent(){
		return $this->content;
	}

	function getMediaType(){
		return $this->MediaType;
	}

	function isVideo(){
		return $this->MediaType=="video" ;
	}

	function getMediaPath(){
		return $this->mediaPath;
	}

	function getMediaDate(){
		return $this->mediaDate;
	}

	function cleanURL($URLstring){
		return 'http:/'.preg_replace('#http:/+|/+|\\\+#','/',$URLstring);
	}

}
// end class rssItem

class plgFlexicontent_fieldsCoolirisgallery extends JPlugin {

	var $mosConfig_absolute_path = '';
	var $mosConfig_live_site = '';
	static $JSriptSelectAdded = 0;
	static $JSriptSwfObjectAdded = 0;
  static $allowedExt=array('JPG','PNG','GIF','PNG','FLV','FLW');
	
	function plgFlexicontent_fieldsCoolirisgallery( &$subject, $params ) {
		parent::__construct( $subject, $params );
    JPlugin::loadLanguage('plg_flexicontent_fields_coolirisgallery', JPATH_ADMINISTRATOR);
		$this->mosConfig_absolute_path = JPATH_SITE;
		$this->mosConfig_live_site = JURI::root(); //base url
		if(substr($this->mosConfig_live_site, -1)=="/") $this->mosConfig_live_site = substr($this->mosConfig_live_site, 0, -1);
		if(substr($this->mosConfig_absolute_path, -1)=="/") $this->mosConfig_absolute_path = substr($this->mosConfig_absolute_path, 0, -1);
	}

	function onDisplayField(&$field, $item){
		// execute the code only if the field type match the plugin type
		if($field->field_type != 'coolirisgallery') return;
		global $mainframe;

		// some parameter shortcuts
		$required = $field->parameters->get( 'required', 0 ) ;
		// Par défaut on récupère le paramétrage de Flexi pour le dossier des images !
    $basedir = $this->makeBaseDir($field->parameters->get( 'baseroot', 'images/stories' ),$item->created_by,'','');
						
		$required 	= $required ? 'class="required"' : null;

		// initialise property
		if(!$field->value || $field->value[0] == '') {
			$field->value[0] = 'locdir:'.$basedir;
		}
		
		$results = $this->getFileorDirList($basedir,0);
		$options = array();
		foreach($results as $result) {
			$options[] = JHTML::_('select.option', 'locdir:'.$result[0], $result[1]);
		}
 		$typegallery = array();
 		if (preg_match ( '#^locdir:|picassa:|flickr:#' , $field->value[0] , $typegallery)){
      switch ($typegallery[0]) {
        case 'locdir:':
      	  $options[] = JHTML::_('select.option', 'picassa:', 'picassa:');
      	  $options[] = JHTML::_('select.option', 'flickr:', 'flickr:');
        break;
        case 'picassa:':
      	  $options[] = JHTML::_('select.option', $field->value[0], $field->value[0]);
      	  $options[] = JHTML::_('select.option', 'flickr:', 'flickr:');
        break;
        case 'flickr:':
      	  $options[] = JHTML::_('select.option', $field->value[0], $field->value[0]);
      	  $options[] = JHTML::_('select.option', 'picassa:', 'picassa:');
        break;
      }
    }

		if(!plgFlexicontent_fieldsCoolirisgallery::$JSriptSelectAdded) {
			$mainframe->addCustomHeadTag('<script type="text/javascript">
          function FCCGProcessSelectValue(SelectObj){
            var SelectedValue = SelectObj.options[SelectObj.selectedIndex].value;
            var TypeGalerie = SelectedValue.substring(0, SelectedValue.indexOf(":"));
            var AncienneSaisie = "'.JText::_("FCCG_INVITEEMPTY").'";
            if (SelectedValue.indexOf(":")<=SelectedValue.length) AncienneSaisie = SelectedValue.substring(SelectedValue.indexOf(":")+1);
            switch (TypeGalerie) {
              case "picassa":
                var ResultatSaisie = window.prompt("'.JText::_("FCCG_INVITEPICASSA").'",AncienneSaisie);
                if (ResultatSaisie){
                  SelectObj.options[SelectObj.selectedIndex].value = "picassa:" + ResultatSaisie;
                  SelectObj.options[SelectObj.selectedIndex].text = "picassa:" + ResultatSaisie;
                }
                break;
              case "flickr":
                var ResultatSaisie = window.prompt("'.JText::_("FCCG_INVITEFLICKR").'",AncienneSaisie);
                if (ResultatSaisie){
                  SelectObj.options[SelectObj.selectedIndex].value = "flickr:" + ResultatSaisie;
                  SelectObj.options[SelectObj.selectedIndex].text = "flickr:" + ResultatSaisie;
                }
                break;
              case "locdir":
              default:
                break;
            }
          }</script>');
			plgFlexicontent_fieldsCoolirisgallery::$JSriptSelectAdded=1;
		}
		
		$field->html	= JHTML::_('select.genericlist', $options, $field->name, $required.' onchange="FCCGProcessSelectValue(this)" ', 'value', 'text', $field->value);
	}

	function onBeforeSaveField( $field, &$post, &$file ){
		// execute the code only if the field type match the plugin type
		if($field->field_type != 'coolirisgallery') return;
		if(!$post) return;
				
		// create the fulltext search index
		$searchindex = '';
		$field->search = $field->issearch ? $searchindex : '';
		
	}

	function onAfterSaveField( $field, &$post, &$file ){
		// execute the code only if the field type match the plugin type
		if($field->field_type != 'coolirisgallery') return;
		if(!$post) return;
		
		$this->makeGallery($field, $post,'', false, $field->name, $field->item_id, $this->getItemVersion($field->item_id));
		
		// create the fulltext search index
		$searchindex = '';
		$field->search = $field->issearch ? $searchindex : '';
		
	}

	function onDisplayFieldValue(&$field, $item, $values=null, $prop='display'){
		// execute the code only if the field type match the plugin type
		if($field->field_type != 'coolirisgallery') return;
		global $mainframe;

		$values = $values ? $values : $field->value ;
						
		//if($pretext) 	{ $pretext 	= $remove_space ? $pretext : $pretext . ' '; }
		//if($posttext) 	{ $posttext	= $remove_space ? $posttext : ' ' . $posttext; }
		if(!plgFlexicontent_fieldsCoolirisgallery::$JSriptSwfObjectAdded) {
			$mainframe->addCustomHeadTag('<script type="text/javascript" src="'.$this->mosConfig_live_site.'/plugins/flexicontent_fields/coolirisgallery/swfobject.js"></script>');
			plgFlexicontent_fieldsCoolirisgallery::$JSriptSwfObjectAdded=1;
		}

    $basedir = $this->makeBaseDir($field->parameters->get( 'baseroot', 'images/stories' ),$item->created_by,$item->cuname,$item->creator);
		$display = $this->makeGallery($field, $values[0], $basedir, true, $field->name, $item->id, $item->version);
		$field->{$prop}	= $display ? $display : '';
	}


	function onDisplayFilter(&$filter, $value=''){
		// execute the code only if the field type match the plugin type
		if($filter->field_type != 'coolirisgallery') return;

		$filter->html	= '';
	}
	
	// -----------------------------------------------------------
	// Specifics functions
	// -----------------------------------------------------------
	function makeGallery(&$field, $gallery, $basedir, $makeOutput = false, $fieldName, $itemId, $itemVersion){
	
		global $mainframe;
		// Paramètres de construction du flux mediaRss
		$thumbwidth=$field->parameters->get('thumbwidth', '200');
		$thumbheight = $field->parameters->get('thumbheight', '200');
		$resetRssOnSave= $field->parameters->get('resetRssonsave',1);
		$resetRssOnDisplay= $field->parameters->get('resetRssondisplay',1);
    $thumbprefix = strtoupper($field->parameters->get('thumbprefix','_THUMB_'));
		$imgignore="/".implode("|", array_merge(array($thumbprefix),explode(",",strtoupper($field->parameters->get('imgignore',$thumbprefix)))))."/i";       
 		$thumbauto=$field->parameters->get('thumbauto',1);
 		$sortorder=$field->parameters->get('sortorder',0);
 		$imgdataorder=$field->parameters->get('imgdataorder',0);
 		// Paramètres d'apparence contenant
		$albumwidth=$field->parameters->get('albumwidth', '600');
		$albumheight = $field->parameters->get('albumheight', '480');
		$bgalpha = $field->parameters->get('bgalpha', '0.0');
		$bgalphaenable = (($bgalpha!='0.0')&&($bgalpha!=''));
		$bgcolor = $field->parameters->get('bgcolor', '');
		$bgcolorenable = ($bgcolor!='');
		$glcolor = $field->parameters->get('glcolor', '');
		$glcolorenable = ($glcolor!='');
		$bgimage = $field->parameters->get('bgimage', '');
		$music=$field->parameters->get('music','');
		$logo=$field->parameters->get('logo','');
 		$displayfullscreen=$field->parameters->get('displayfullscreen',1);
		$intromode = $field->parameters->get('intromode', 'appear');
 		// Paramètres d'apparence contenu
		$imglink = $field->parameters->get('imglink', 0);
		$FBTWTlink = $field->parameters->get('fbtwtlink', 0);
		$displaycaption = $field->parameters->get('displaycaption', 1);
		$displaynavarrows = $field->parameters->get('displaynavarrows', 1);
		$displaytoolbarbg = $field->parameters->get('displaytoolbarbg', 1);
		$displayrowsnum = $field->parameters->get('displayrowsnum', '3');
		$cellborder = $field->parameters->get('cellborder', '0');
		$cellalpha = $field->parameters->get('cellalpha', '0.0');
		$cellwidth = $field->parameters->get('cellwidth', '430');
		$cellheight = $field->parameters->get('cellheight', '300');
		$cellespacingx = $field->parameters->get('cellespacingx', '0.18');
		$cellespacingy = $field->parameters->get('cellespacingy', '0.18');
		$style = $field->parameters->get('style', 'black');
		$tilt = $field->parameters->get('tilt', '0');
		$showdescription = $field->parameters->get('showdescription', 1);
		$showreflection = $field->parameters->get('showreflection', 1);
    // Variables de travail...
    // ...fabrication flux mediaRss
		$imgTag="";
		$rssText='';
		$rssFileName=str_replace("/ /","","FCCG_{$fieldName}_{$itemId}_{$itemVersion}.rss");
		// ...output
		$rssMediaFeed="";
 		$CoolirisContent="";
 		$swfCoolirisUrl = $this->mosConfig_live_site.'/plugins/flexicontent_fields/coolirisgallery/cooliris.swf';

 		$typegallery = array();
 		if (preg_match ( '#^locdir:|picassa:|flickr:#' , $gallery , $typegallery)){
      switch ($typegallery[0]) {
        case 'locdir:':
          $gallery = preg_replace('#^locdir:#','',$gallery);
          $bgimageUrl = $this->cleanURL($this->mosConfig_live_site.DS.$gallery.DS.$bgimage);
      		$bgimagePath=JPath::clean($this->mosConfig_absolute_path.DS.$gallery.DS.$bgimage);
          $bgimageenable=($bgimage!='')?file_exists($bgimagePath):0;
      		$musicUrl=$this->cleanURL($this->mosConfig_live_site.DS.$gallery.DS.$music);
      		$musicPath=JPath::clean($this->mosConfig_absolute_path.DS.$gallery.DS.$music);
      		$musicenable=($music!='')?file_exists($musicPath):0;
      		$logoUrl=$this->cleanURL($this->mosConfig_live_site.DS.$gallery.DS.$logo);
      		$logoPath=JPath::clean($this->mosConfig_absolute_path.DS.$gallery.DS.$logo);
      		$logoenable=($logo!='')?file_exists($logoPath):0;
      		$rssPath=JPath::clean($this->mosConfig_absolute_path.DS.$gallery.DS.$rssFileName);
      		$rssUrl=$this->cleanURL($this->mosConfig_live_site.DS.$gallery.DS.$rssFileName);
      		$rssMediaFeed = "feed:\"{$rssUrl}\"";
      		$locgallery = true;
          break;
        case 'picassa:':
          $gallery = preg_replace('#^picassa:#','',$gallery);
      		$rssMediaFeed = "feed:\"api://picasaweb.google.com/?".urlencode($gallery)."\"";
          $bgimageUrl = $this->cleanURL($this->mosConfig_live_site.DS.$basedir.DS.$bgimage);
      		$bgimagePath=JPath::clean($this->mosConfig_absolute_path.DS.$basedir.DS.$bgimage);
          $bgimageenable=($bgimage!='')?file_exists($bgimagePath):0;
      		$musicUrl=$this->cleanURL($this->mosConfig_live_site.DS.$basedir.DS.$music);
      		$musicPath=JPath::clean($this->mosConfig_absolute_path.DS.$basedir.DS.$music);
      		$musicenable=($music!='')?file_exists($musicPath):0;
      		$logoUrl=$this->cleanURL($this->mosConfig_live_site.DS.$basedir.DS.$logo);
      		$logoPath=JPath::clean($this->mosConfig_absolute_path.DS.$basedir.DS.$logo);
      		$logoenable=($logo!='')?file_exists($logoPath):0;
      		$locgallery = false;
          break;
        case 'flickr:':
          $gallery = preg_replace('#^flickr:#','',$gallery);
      		$rssMediaFeed = "feed:\"api://www.flickr.com/?".urlencode($gallery)."\"";
      		$locgallery = false;
      		$bgimageenable=false;
      		$musicenable=false;
      		$logoenable=false;
          break;
        default:
      		$rssMediaFeed = "--- erreur ---";
      		$locgallery = false;
      		$bgimageenable=false;
      		$musicenable=false;
      		$logoenable=false;
          break;
      }
    } else {
      return "Traitement de {$gallery} impossible !";
    }

    // Si besoin (ou demandé), on (re)génère le fichier de flux mediaRss
    if ($locgallery){
  		if (!file_exists($rssPath) || ($resetRssOnSave&&(!$makeOutput)) || ($resetRssOnDisplay&&$makeOutput)) {
    		unset($images);
    		$noimage=0;
    		$imagesDir= $gallery;
    		if(substr($imagesDir, -1)==DS) $imagesDir=ubstr($imagesDir, 0, -1);
    		$imgDir=$this->mosConfig_absolute_path.DS.$imagesDir;
    		$imgUrl=$this->mosConfig_live_site.DS.$imagesDir;
    		if (is_dir($imgDir)){
      		if ($dh = opendir($imgDir)) {
      			while (($f = readdir($dh)) !== false) {
      				$getExt = explode ('.', $f);
      				$getExt=strtoupper($getExt[count($getExt)-1]);
      				if(in_array($getExt,plgFlexicontent_fieldsCoolirisgallery::$allowedExt)&& !(preg_match($imgignore,strtoupper($f))) && ($f!=$logo)) {
      					$noimage++;
      					if(substr(strtolower($f),-3) == 'flv'){
      						$thumb=$playIco;
      					} else {
      						if($thumbauto ){
      							$thumb=$imgUrl."/".$this->createThumb($imgDir,$f,$thumbprefix,$thumbwidth);					
      						}else{
      							$thumb=$imgUrl."/".$f;
      						}
      					}
      					$images[] = new rssItem($imgDir,$imgUrl,$f,$thumb,$imgdataorder);
      				}
      			}
      			closedir($dh);
      		}  		
      		if($noimage >= 1){
      			switch ($sortorder) {
      				case 0:
      					break;
      				case 1:
      					usort($images, "cmpName");
      					break;
      				case 2:
      					usort($images, "cmpPath");
      					break;
      				case 3:
      					usort($images, "cmpDate");
      					break;
      				case 4:
      					usort($images, "cmpDateInverse");
      					break;
      			}
    				//Création du contenu du fichier rss
    				$rssText='<?xml version="1.0" encoding="utf-8" standalone="yes"'.'?'.'>
              <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss" xmlns:atom="http://www.w3.org/2005/Atom">
              <channel>';
    				if($musicenable){
    					$rssText.='
                <atom:link rel="enclosure" type="audio/mpeg" length="1337" href="'.$musicUrl.'" />';
    				}
    				if ($logoenable){
      				$rssText.='
                <atom:icon>'.$logoUrl.'</atom:icon>';
            }
    				for($a = 0;$a<$noimage;$a++) {
    					$rssText.='
                <item>
                  ';
    					if($displaycaption){
    						$rssText.=$images[$a]->getTitle().'
                  ';
    					}
    					$rssText.=$images[$a]->getComment().'
                  ';
    					$rssText.=$images[$a]->getGuidTag().'
                  ';
    					if($imglink){
    						$rssText.=$images[$a]->getLink().'
                  ';
    					}
    					$rssText.=$images[$a]->getThumbnail().'
                  '.$images[$a]->getContent().' 
                </item>';
    				}
    				$rssText.='
                </channel>
              </rss>';
            // Création et écriture du fichier de sortie  
    				$file_handle = fopen($rssPath, "w");
    				if ($file_handle) {
       				fwrite($file_handle, $rssText);
      				fclose($file_handle);
        		} else {
        			return "<br />Dir: ".$imgDir." - error writting mediaRss file!<br />";
            }
      		} else {
      			return "<br />Dir: ".$imgDir." contain no picture!<br />";
      		}
  			} else {
    			return "<br />Dir: ".$imgDir." inexistent!<br />";
        }
    	}
    }
    // Si le contenu du champ doit être élaboré
    if ($makeOutput) {
	    if ($locgallery) $mainframe->addCustomHeadTag('<link rel="alternate" href="'.$rssUrl.'"   type="application/rss+xml" />');
			$CoolirisContent.="
  <script type=\"text/javascript\">
        var flashvars = {
            {$rssMediaFeed},
            ".($bgcolorenable?"backgroundColor: \"#{$bgcolor}\", ":"")."intro: \"{$intromode}\", ".($bgalphaenable?"backgroundAlpha: \"#{$bgalpha}\", ":"")."showNavArrows: \"".($displaynavarrows?"true":"false")."\", shwoChrome: \"".($displaytoolbarbg?"true":"false")."\", numRows: \"{$displayrowsnum}\", ".($glcolorenable?"glowColor: \"#{$glcolor}\", ":"")."showDescription: \"".($showdescription?"true":"false")."\", showReflections: \"".($showreflection?"true":"false")."\", cellBorder: \"{$cellborder}\", cellContainerAlpha: \"{$cellalpha}\", cellWidth: \"{$cellwidth}\", cellHeight: \"{$cellheight}\", cellSpacingX: \"{$cellespacingx}\", cellSpacingY: \"{$cellespacingy}\",
            style: \"{$style}\", ".($bgimageenable?"backGroundImage: \"{$bgimageUrl}\", ":"").($musicenable?"backgroundMusic: \"{$musicUrl}\", ":"")."showItemEmbed:\"".($FBTWTlink?"true":"false")."\",showEmbed:\"".($FBTWTlink?"true":"false")."\",showLinkOut:\"".($imglink?"true":"false")."\",
            tilt: \"{$tilt}\"
        };
        var params = {
            allowFullScreen: \"".($displayfullscreen?"true":"false")."\", allowscriptaccess: \"always\"
        };
        swfobject.embedSWF(\"{$swfCoolirisUrl}\",
            \"wall\", \"{$albumwidth}\", \"{$albumheight}\", \"9.0.0\", \"\",
            flashvars, params);
  </script>
  <div id=\"wall\" style=\"width:{$albumwidth};height:{$albumheight}\"><!-- 3D Wall Goes Here --></div>
      ";
		}
// Conservation div avec définition largeur et hauteur.		
// <div id=\"wall\" style=\"width:{$albumwidth};height:{$albumheight}\"><!-- 3D Wall Goes Here --></div>
		
		return $CoolirisContent;

	}

	function getFileorDirList($basedir,$fileordir){
    $results = array();
    $this->list_dir($basedir, '', $fileordir, $results);
    return $results;
  }
  
  function list_dir($basedir, $subdir, $fileordir,&$results) {
    $dirpath = JPath::clean(JPATH_SITE.DS.$basedir.DS.$subdir);
    if ($dir = opendir($dirpath)) {
      while($entry = readdir($dir)) {
        if(!in_array($entry, array(".",".."))) {
          $entrypath = JPath::clean(JPATH_SITE.DS.$basedir.DS.$subdir.DS.$entry);
          if ((($fileordir==0) && is_dir($entrypath)) || (($fileordir==1) && is_file($entrypath))) {
            $results[]=array(JPath::clean($basedir.DS.$subdir.DS.$entry),JPath::clean($subdir.DS.$entry));
          }
          if(is_dir($entrypath)) $this->list_dir($basedir,$subdir.DS.$entry,$fileordir,$results);
        }
      }
      closedir($dir);
    }
  } 
  
  function makeBaseDir($source,$userid,$userpseudo,$username) {
  	$basedir = preg_replace_callback(
      '#\$user|\$userid|\$username#',
      create_function(
        '$matches',
        '$dbo = &JFactory::getDBO();
         $user = &JFactory::getUser();
         $replacestring = "";
         switch ($matches[0]){
          case "\$userid":
            $replacestring = "'.$userid.'";
            break;
          case "\$user":
            $replacestring = "'.$userpseudo.'";
            if ($replacestring==""){
              $dbo->setQuery("select username from #__users where id='.$userid.'");
              $replacestring=$dbo->loadResult();
            }
            break;
          case "\$username":
            $replacestring = "'.$username.'";
            if ($replacestring==""){
              $dbo->setQuery("select name from #__users where id='.$userid.'");
              $replacestring=$dbo->loadResult();
            }
            break;
          default:
            $replacestring = "--- erreur ---";
            break;
         }
         return $replacestring;'),
      $source);
    return $basedir;  
  }
  
  function getItemVersion($itemid){
    $dbo = &JFactory::getDBO();
    $dbo->setQuery("SELECT max(jfv.version_id)+1 FROM #__flexicontent_versions AS jfv WHERE jfv.item_id = '{$itemid}'");
    $itemversion = $dbo->loadResult();
    is_null($itemversion)?1:$itemversion;
    return $itemversion;
  }

  function cmpName($a, $b){
  	return strcasecmp($a->getMediaName(),$b->getMediaName());
  }
  
  function cmpDate($a, $b){
  	if ($a->getMediaDate()==$b->getMediaDate()) return 0;
  	if ($a->getMediaDate()> $b->getMediaDate()) return 1;
  	if ($a->getMediaDate()< $b->getMediaDate()) return -1;
  }
  
  function cmpDateInverse($a, $b){
  	if ($a->getMediaDate()==$b->getMediaDate()) return 0;
  	if ($a->getMediaDate()< $b->getMediaDate()) return 1;
  	if ($a->getMediaDate()> $b->getMediaDate()) return -1;
  }
  
  function cmpPath($a, $b){
  	return strcasecmp($a->getMediaPath().'/'.$a->getMediaName(),$b->getMediaPath().'/'.$b->getMediaName());
  }
  
	function createThumb($imgDir,$imgName,$thumbPrefix,$widthTumb){
	
		$Thumb_name="_".$thumbPrefix."_".$imgName;
		$file_thumb_name = $imgDir.DS.$Thumb_name;
		$file_name = $imgDir.DS.$imgName;
		$getExt    = explode ('.', $file_name);
		$file_type = strtolower($getExt[count($getExt)-1]);
		$file_size = filesize($imgDir.DS.$imgName);
		//	      $file_tmp  = $_FILES['vImage']['tmp_name'];
		$file_ext  = $getExt[count($getExt)-1];
        
		if (!file_exists($file_thumb_name)|| filemtime($file_name)>filemtime($file_thumb_name)){
			
			$ThumbWidth = $widthTumb;
			if($file_size){
			
				if($file_type == "jpg"){
					$new_img = imagecreatefromjpeg($file_name);
				}elseif($file_type == "png"){
					$new_img = imagecreatefrompng($file_name);
				}elseif($file_type == "gif"){
					$new_img = imagecreatefromgif($file_name);
				}
				//list the width and height and keep the height ratio.
				list($width, $height) = getimagesize($file_name);
				//calculate the image ratio
				$imgratio=$width/$height;
				if ($imgratio>1){
					$newwidth = $ThumbWidth;
					$newheight = $ThumbWidth/$imgratio;
				}else{
					$newheight = $ThumbWidth;
					$newwidth = $ThumbWidth*$imgratio;
				}
				//function for resize image.
				if (function_exists(imagecreatetruecolor)){
					$resized_img = imagecreatetruecolor($newwidth,$newheight);
				}
				//the resizing is going on here!
				imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
				//finally, save the image
				ImageJpeg ($resized_img,"$file_thumb_name");
				ImageDestroy ($resized_img);
				ImageDestroy ($new_img);
			}
		
		}
		if(file_exists($file_thumb_name)){
		return $Thumb_name;
		}
		else{
		  return $imgName;	
		}
	}
	
	function cleanURL($URLstring){
		return 'http:/'.preg_replace('#http:/+|/+|\\\+#','/',$URLstring);
	}
	
}