Browse Source

Remplace chaque tabulation par 4 espaces

find . -type f -print -o -path './.git' -prune -o -path './cache' -prune | xargs xargs sed -i -e 's/\t/    /g'
git checkout templates/marigolds/favicon.png
git checkout RainTPL.php
git checkout SimplePie.class.php
Christophe HENRY 5 years ago
parent
commit
0622ef0888

+ 77 - 77
Configuration.class.php

@@ -9,83 +9,83 @@
 
 class Configuration extends MysqlEntity{
 
-	protected $id,$key,$value,$confTab;
-	protected $TABLE_NAME = 'configuration';
-	protected $CLASS_NAME = 'Configuration';
-	protected $object_fields =
-	array(
-		'id'=>'key',
-		'key'=>'longstring',
-		'value'=>'longstring'
-	);
-
-	function __construct(){
-		parent::__construct();
-	}
-
-	public function getAll(){
-
-		if(!isset($_SESSION['configuration'])){
-
-		$configurationManager = new Configuration();
-		$configs = $configurationManager->populate();
-		$confTab = array();
-
-		foreach($configs as $config){
-			$this->confTab[$config->getKey()] = $config->getValue();
-		}
-
-		$_SESSION['configuration'] = serialize($this->confTab);
-
-		}else{
-			$this->confTab = unserialize($_SESSION['configuration']);
-		}
-	}
-
-	public function get($key){
-
-		return (isset($this->confTab[$key])?$this->confTab[$key]:'');
-	}
-
-	public function put($key,$value){
-		$configurationManager = new Configuration();
-		if (isset($this->confTab[$key])){
-			$configurationManager->change(array('value'=>$value),array('key'=>$key));
-		} else {
-			$configurationManager->add($key,$value);
-		}
-		$this->confTab[$key] = $value;
-		unset($_SESSION['configuration']);
-	}
-
-	public function add($key,$value){
-		$config = new Configuration();
-		$config->setKey($key);
-		$config->setValue($value);
-		$config->save();
-		$this->confTab[$key] = $value;
-		unset($_SESSION['configuration']);
-	}
-
-	function getId(){
-		return $this->id;
-	}
-
-	function getKey(){
-		return $this->key;
-	}
-
-	function setKey($key){
-		$this->key = $key;
-	}
-
-	function getValue(){
-		return $this->value;
-	}
-
-	function setValue($value){
-		$this->value = $value;
-	}
+    protected $id,$key,$value,$confTab;
+    protected $TABLE_NAME = 'configuration';
+    protected $CLASS_NAME = 'Configuration';
+    protected $object_fields =
+    array(
+        'id'=>'key',
+        'key'=>'longstring',
+        'value'=>'longstring'
+    );
+
+    function __construct(){
+        parent::__construct();
+    }
+
+    public function getAll(){
+
+        if(!isset($_SESSION['configuration'])){
+
+        $configurationManager = new Configuration();
+        $configs = $configurationManager->populate();
+        $confTab = array();
+
+        foreach($configs as $config){
+            $this->confTab[$config->getKey()] = $config->getValue();
+        }
+
+        $_SESSION['configuration'] = serialize($this->confTab);
+
+        }else{
+            $this->confTab = unserialize($_SESSION['configuration']);
+        }
+    }
+
+    public function get($key){
+
+        return (isset($this->confTab[$key])?$this->confTab[$key]:'');
+    }
+
+    public function put($key,$value){
+        $configurationManager = new Configuration();
+        if (isset($this->confTab[$key])){
+            $configurationManager->change(array('value'=>$value),array('key'=>$key));
+        } else {
+            $configurationManager->add($key,$value);
+        }
+        $this->confTab[$key] = $value;
+        unset($_SESSION['configuration']);
+    }
+
+    public function add($key,$value){
+        $config = new Configuration();
+        $config->setKey($key);
+        $config->setValue($value);
+        $config->save();
+        $this->confTab[$key] = $value;
+        unset($_SESSION['configuration']);
+    }
+
+    function getId(){
+        return $this->id;
+    }
+
+    function getKey(){
+        return $this->key;
+    }
+
+    function setKey($key){
+        $this->key = $key;
+    }
+
+    function getValue(){
+        return $this->value;
+    }
+
+    function setValue($value){
+        $this->value = $value;
+    }
 
 
 

+ 167 - 167
Event.class.php

@@ -8,173 +8,173 @@
 
 class Event extends MysqlEntity{
 
-	protected $id,$title,$guid,$content,$description,$pudate,$link,$feed,$category,$creator,$unread,$favorite;
-	protected $TABLE_NAME = 'event';
-	protected $CLASS_NAME = 'Event';
-	protected $object_fields =
-	array(
-		'id'=>'key',
-		'guid'=>'longstring',
-		'title'=>'string',
-		'creator'=>'string',
-		'content'=>'longstring',
-		'description'=>'longstring',
-		'link'=>'longstring',
-		'unread'=>'integer',
-		'feed'=>'integer',
-		'unread'=>'integer',
-		'favorite'=>'integer',
-		'pubdate'=>'integer',
-		'syncId'=>'integer',
-	);
-
-	protected $object_fields_index =
-	array(
-		'feed'=>'index',
-		'unread'=>'index',
-		'favorite'=>'index'
-	);
-
-	function __construct($guid=null,$title=null,$description=null,$content=null,$pubdate=null,$link=null,$category=null,$creator=null){
-
-		$this->guid = $guid;
-		$this->title = $title;
-		$this->creator = $creator;
-		$this->content = $content;
-		$this->description = $description;
-		$this->pubdate = $pubdate;
-		$this->link = $link;
-		$this->category = $category;
-		parent::__construct();
-	}
-
-
-	function getEventCountPerFolder(){
-		$events = array();
-		$results = $this->customQuery('SELECT COUNT('.MYSQL_PREFIX.$this->TABLE_NAME.'.id),'.MYSQL_PREFIX.'feed.folder FROM '.MYSQL_PREFIX.$this->TABLE_NAME.' INNER JOIN '.MYSQL_PREFIX.'feed ON ('.MYSQL_PREFIX.'event.feed = '.MYSQL_PREFIX.'feed.id) WHERE '.MYSQL_PREFIX.$this->TABLE_NAME.'.unread=1 GROUP BY '.MYSQL_PREFIX.'feed.folder');
-		while($item = mysql_fetch_array($results)){
-			$events[$item[1]] = $item[0];
-		}
-
-		return $events;
-	}
-
-	function setId($id){
-		$this->id = $id;
-	}
-
-	function getCreator(){
-		return $this->creator;
-	}
-
-	function setCreator($creator){
-		$this->creator = $creator;
-	}
-
-	function getCategory(){
-		return $this->category;
-	}
-
-	function setCategory($category){
-		$this->category = $category;
-	}
-
-	function getDescription(){
-		return $this->description;
-	}
-
-	function setDescription($description,$encoding = true){
-		$this->description = $description;
-	}
-
-	function getPubdate($format=false){
-		if($this->pubdate!=0){
-		return ($format!=false?date($format,$this->pubdate):$this->pubdate);
-		}else{
-			return '';
-		}
-	}
-
-	function getPubdateWithInstant($instant){
-		$alpha = $instant - $this->pubdate;
-		if ($alpha < 86400 ){
-			$hour = floor($alpha/3600);
-			$alpha = ($hour!=0?$alpha-($hour*3600):$alpha);
-			$minuts = floor($alpha/60);
-			return 'il y a '.($hour!=0?$hour.'h et':'').' '.$minuts.'min';
-		}else{
-			return 'le '.$this->getPubdate('d/m/Y à H:i:s');
-		}
-	}
-
-	function setPubdate($pubdate){
-		$this->pubdate = (is_numeric($pubdate)?$pubdate:strtotime($pubdate));
-	}
-
-	function getLink(){
-		return $this->link;
-	}
-
-	function setLink($link){
-		$this->link = $link;
-	}
-
-	function getId(){
-		return $this->id;
-	}
-
-	function getTitle(){
-		return $this->title;
-	}
-
-	function setTitle($title){
-		$this->title = $title;
-	}
-
-	function getContent(){
-		return $this->content;
-	}
-
-	function setContent($content,$encoding=true){
-		$this->content = $content;
-	}
-
-
-	function getGuid(){
-		return $this->guid;
-	}
-
-	function setGuid($guid){
-		$this->guid = $guid;
-	}
-
-	function getSyncId(){
-		return $this->syncId;
-	}
-
-	function setSyncId($syncId){
-		$this->syncId = $syncId;
-	}
-
-	function getUnread(){
-		return $this->unread;
-	}
-
-	function setUnread($unread){
-		$this->unread = $unread;
-	}
-	function setFeed($feed){
-		$this->feed = $feed;
-	}
-	function getFeed(){
-		return $this->feed;
-	}
-	function setFavorite($favorite){
-		$this->favorite = $favorite;
-	}
-	function getFavorite(){
-		return $this->favorite;
-	}
+    protected $id,$title,$guid,$content,$description,$pudate,$link,$feed,$category,$creator,$unread,$favorite;
+    protected $TABLE_NAME = 'event';
+    protected $CLASS_NAME = 'Event';
+    protected $object_fields =
+    array(
+        'id'=>'key',
+        'guid'=>'longstring',
+        'title'=>'string',
+        'creator'=>'string',
+        'content'=>'longstring',
+        'description'=>'longstring',
+        'link'=>'longstring',
+        'unread'=>'integer',
+        'feed'=>'integer',
+        'unread'=>'integer',
+        'favorite'=>'integer',
+        'pubdate'=>'integer',
+        'syncId'=>'integer',
+    );
+
+    protected $object_fields_index =
+    array(
+        'feed'=>'index',
+        'unread'=>'index',
+        'favorite'=>'index'
+    );
+
+    function __construct($guid=null,$title=null,$description=null,$content=null,$pubdate=null,$link=null,$category=null,$creator=null){
+
+        $this->guid = $guid;
+        $this->title = $title;
+        $this->creator = $creator;
+        $this->content = $content;
+        $this->description = $description;
+        $this->pubdate = $pubdate;
+        $this->link = $link;
+        $this->category = $category;
+        parent::__construct();
+    }
+
+
+    function getEventCountPerFolder(){
+        $events = array();
+        $results = $this->customQuery('SELECT COUNT('.MYSQL_PREFIX.$this->TABLE_NAME.'.id),'.MYSQL_PREFIX.'feed.folder FROM '.MYSQL_PREFIX.$this->TABLE_NAME.' INNER JOIN '.MYSQL_PREFIX.'feed ON ('.MYSQL_PREFIX.'event.feed = '.MYSQL_PREFIX.'feed.id) WHERE '.MYSQL_PREFIX.$this->TABLE_NAME.'.unread=1 GROUP BY '.MYSQL_PREFIX.'feed.folder');
+        while($item = mysql_fetch_array($results)){
+            $events[$item[1]] = $item[0];
+        }
+
+        return $events;
+    }
+
+    function setId($id){
+        $this->id = $id;
+    }
+
+    function getCreator(){
+        return $this->creator;
+    }
+
+    function setCreator($creator){
+        $this->creator = $creator;
+    }
+
+    function getCategory(){
+        return $this->category;
+    }
+
+    function setCategory($category){
+        $this->category = $category;
+    }
+
+    function getDescription(){
+        return $this->description;
+    }
+
+    function setDescription($description,$encoding = true){
+        $this->description = $description;
+    }
+
+    function getPubdate($format=false){
+        if($this->pubdate!=0){
+        return ($format!=false?date($format,$this->pubdate):$this->pubdate);
+        }else{
+            return '';
+        }
+    }
+
+    function getPubdateWithInstant($instant){
+        $alpha = $instant - $this->pubdate;
+        if ($alpha < 86400 ){
+            $hour = floor($alpha/3600);
+            $alpha = ($hour!=0?$alpha-($hour*3600):$alpha);
+            $minuts = floor($alpha/60);
+            return 'il y a '.($hour!=0?$hour.'h et':'').' '.$minuts.'min';
+        }else{
+            return 'le '.$this->getPubdate('d/m/Y à H:i:s');
+        }
+    }
+
+    function setPubdate($pubdate){
+        $this->pubdate = (is_numeric($pubdate)?$pubdate:strtotime($pubdate));
+    }
+
+    function getLink(){
+        return $this->link;
+    }
+
+    function setLink($link){
+        $this->link = $link;
+    }
+
+    function getId(){
+        return $this->id;
+    }
+
+    function getTitle(){
+        return $this->title;
+    }
+
+    function setTitle($title){
+        $this->title = $title;
+    }
+
+    function getContent(){
+        return $this->content;
+    }
+
+    function setContent($content,$encoding=true){
+        $this->content = $content;
+    }
+
+
+    function getGuid(){
+        return $this->guid;
+    }
+
+    function setGuid($guid){
+        $this->guid = $guid;
+    }
+
+    function getSyncId(){
+        return $this->syncId;
+    }
+
+    function setSyncId($syncId){
+        $this->syncId = $syncId;
+    }
+
+    function getUnread(){
+        return $this->unread;
+    }
+
+    function setUnread($unread){
+        $this->unread = $unread;
+    }
+    function setFeed($feed){
+        $this->feed = $feed;
+    }
+    function getFeed(){
+        return $this->feed;
+    }
+    function setFavorite($favorite){
+        $this->favorite = $favorite;
+    }
+    function getFavorite(){
+        return $this->favorite;
+    }
 
 }
 

+ 281 - 281
Feed.class.php

@@ -8,287 +8,287 @@
 
 class Feed extends MysqlEntity{
 
-	protected $id,$name,$url,$events=array(),$description,$website,$folder,$lastupdate;
-	protected $TABLE_NAME = 'feed';
-	protected $CLASS_NAME = 'Feed';
-	protected $object_fields =
-	array(
-		'id'=>'key',
-		'name'=>'string',
-		'description'=>'longstring',
-		'website'=>'longstring',
-		'url'=>'longstring',
-		'lastupdate'=>'string',
-		'folder'=>'integer'
-	);
-
-	protected $object_fields_index =
-	array(
-		'folder'=>'index'
-	);
-
-	protected $error = '';
-
-	function __construct($name=null,$url=null){
-		$this->name = $name;
-		$this->url = $url;
-		parent::__construct();
-	}
-
-	/** @TODO: ne faire qu'un seul chargement avec SimplePie et récupérer les
-	même informations. Mettre le chargement en cache au moins d'une méthode
-	loadLeed() qui ne chargera qu'une seule fois. Voire même en déclenchement
-	retardé, au dernier moment. */
-	function getInfos(){
-		$xml = @simplexml_load_file($this->url);
-		if($xml!=false){
-			$this->name = array_shift ($xml->xpath('channel/title'));
-			$this->description = array_shift ($xml->xpath('channel/description'));
-			$this->website = array_shift ($xml->xpath('channel/link'));
-		}
-	}
-
-	function getError() { return $this->error; }
-
-	/*@TODO: fournir un extrait quand il 'y a pas de description. De même pour les médias.
-	@TODO: SimplePie remplace "é" par "&eacute;", il ne devrait pas le faire.
-	J'ai testé set_stupidly_fast(true) sans succès.
-	Il encadre les descriptions avec <div>, absents dans le source du flux.
-	@TODO: la vérification de doublon est sous la responsabilité de l'appelant.
-	Il serait peut-être utile de faire une méthode add() qui vérifie, plante si
-	nécessaire, et appelle parse(). Impossible de vérifier dans parse() même
-	car elle est appelée aussi pour autre chose que l'ajout.
-	*/
-	function parse($syncId,&$nbEvents =0, $enableCache=true, $forceFeed=false){
-		$nbEvents = 0;
-		assert('is_int($syncId) && $syncId>0');
-		if (empty($this->id) || 0 == $this->id) {
-			/* Le flux ne dispose pas pas d'id !. Ça arrive si on appelle
-			parse() sans avoir appelé save() pour un nouveau flux.
-			@TODO: un create() pour un nouveau flux ? */
-			$msg = 'Empty or null id for a feed! '
-				  .'See '.__FILE__.' on line '.__LINE__;
-			error_log($msg, E_USER_ERROR);
-			die($msg); // Arrêt, sinon création événements sans flux associé.
-		}
-		$feed = new SimplePie();
-		$feed->enable_cache($enableCache);
-		$feed->force_feed($forceFeed);
-		$feed->set_feed_url($this->url);
-		$feed->set_useragent('Mozilla/4.0 Leed (LightFeed Agrgegator) '.VERSION_NAME.' by idleman http://projet.idleman.fr/leed');
-		if (!$feed->init()) {
-			$this->error = $feed->error;
-			$this->lastupdate = $_SERVER['REQUEST_TIME'];
-			$this->save();
-			return false;
-		}
-
-		$feed->handle_content_type(); // UTF-8 par défaut pour SimplePie
-
-		if($this->name=='') $this->name = $feed->get_title();
-		if($this->name=='') $this->name = $this->url;
-		$this->website = $feed->get_link();
-		$this->description = $feed->get_description();
-
-		$items = $feed->get_items();
-		$eventManager = new Event();
-
-		$events = array();
-		$iEvents = 0;
-		foreach($items as $item){
-			// Ne retient que les 100 premiers éléments de flux.
-			if ($iEvents++>=100) break;
-
-			// Si le guid existe déjà, on évite de le reparcourir.
-			$alreadyParsed = $eventManager->load(array('guid'=>$item->get_id(), 'feed'=>$this->id));
-			if (isset($alreadyParsed)&&($alreadyParsed!=false)) {
-				$events[]=$alreadyParsed->getId();
-				continue;
-			}
-
-			// Initialisation des informations de l'événement (élt. de flux)
-			$event = new Event();
-			$event->setSyncId($syncId);
-			$event->setGuid($item->get_id());
-			$event->setTitle($item->get_title());
-			$event->setPubdate($item->get_date());
-			$event->setCreator(
-				''==$item->get_author()
-					? ''
-					: $item->get_author()->name
-			);
-			$event->setLink($item->get_permalink());
-
-			$event->setFeed($this->id);
-			$event->setUnread(1); // inexistant, donc non-lu
-
-			//Gestion de la balise enclosure pour les podcasts et autre cochonneries :)
-			$enclosure = $item->get_enclosure();
-			if($enclosure!=null && $enclosure->link!=''){
-				$enclosureName = substr(
-					$enclosure->link,
-					strrpos($enclosure->link, '/')+1,
-					strlen($enclosure->link)
-				);
-				$enclosureArgs = strpos($enclosureName, '?');
-				if($enclosureArgs!==false)
-					$enclosureName = substr($enclosureName,0,$enclosureArgs);
-				$enclosureFormat = isset($enclosure->handler)
-					? $enclosure->handler
-					: substr($enclosureName, strrpos($enclosureName,'.')+1);
-
-				$enclosure ='<div class="enclosure"><h1>Fichier média :</h1><a href="'.$enclosure->link.'"> '.$enclosureName.'</a> <span>(Format '.strtoupper($enclosureFormat).', '.Functions::convertFileSize($enclosure->length).')</span></div>';
-			}else{
-				$enclosure = '';
-			}
-
-			$event->setContent($item->get_content().$enclosure);
-			$event->setDescription($item->get_description().$enclosure);
-
-			if(trim($event->getDescription())=='')
-				$event->setDescription(
-					substr($event->getContent(),0,300)
-					.'…<br><a href="'.$event->getLink()
-					.'">Lire la suite de l\'article</a>'
-				);
-			if(trim($event->getContent())=='')
-				$event->setContent($event->getDescription());
-
-			$event->setCategory($item->get_category());
-			$event->save();
-			$nbEvents++;
-		}
-
-		$listid = "";
-		foreach($events as $item){
-			$listid.=','.$item;
-		}
-		$query='UPDATE `'.MYSQL_PREFIX.'event` SET syncId='.$syncId.' WHERE id in (0'.$listid.');';
-		$myQuery = $this->customQuery($query);
-
-		$this->lastupdate = $_SERVER['REQUEST_TIME'];
-		$this->save();
-		return true;
-	}
-
-
-	function removeOldEvents($maxEvent, $currentSyncId){
-		if ($maxEvent<=0) return;
-		$eventManager = new Event();
-		$nbLines = $eventManager->rowCount(array(
-			'feed'=>$this->id,
- 			'unread'=>0,
-			'favorite'=>0,
-		));
-		$limit = $nbLines - $maxEvent;
-		if ($limit<=0) return;
-		$tableEvent = '`'.MYSQL_PREFIX."event`";
-		$query = "
-			DELETE FROM {$tableEvent} WHERE feed={$this->id} AND favorite!=1 AND unread!=1 AND syncId!={$currentSyncId} ORDER BY pubDate ASC LIMIT {$limit}
-		";
-		///@TODO: escape the variables inside mysql
- 		$this->customExecute($query);
-	}
-
-	function setId($id){
-		$this->id = $id;
-	}
-
-	function getDescription(){
-		return $this->description;
-	}
-
-	function setDescription($description){
-		$this->description = $description;
-	}
-	function getWebSite(){
-		return $this->website;
-	}
-
-	function setWebSite($website){
-		$this->website = $website;
-	}
-
-	function getId(){
-		return $this->id;
-	}
-
-	function getUrl(){
-		return $this->url;
-	}
-
-	function setUrl($url){
-		$this->url = $url;
-	}
-
-	function getName(){
-		return (trim($this->name)!='' ? $this->name:$this->url);
-	}
-
-	function setName($name){
-		$this->name = $name;
-	}
-
-
-	function getEvents($start=0,$limit=10000,$order,$columns='*'){
-		$eventManager = new Event();
-		$events = $eventManager->loadAllOnlyColumn($columns,array('feed'=>$this->getId()),$order,$start.','.$limit);
-		return $events;
-	}
-
-	function countUnreadEvents(){
-		$unreads = array();
-		$results = Feed::customQuery("SELECT COUNT(".MYSQL_PREFIX."event.id), ".MYSQL_PREFIX."event.feed FROM ".MYSQL_PREFIX."event WHERE ".MYSQL_PREFIX."event.unread = 1 GROUP BY ".MYSQL_PREFIX."event.feed") ;
-		if($results!=false){
-			while($item = mysql_fetch_array($results)){
-				$unreads[$item[1]] = $item[0];
-			}
-		}
-		return $unreads;
-	}
-
-	function getFeedsPerFolder(){
-		$feedsFolderMap = array();
-		$feedsIdMap = array();
-
-		$results = Feed::customQuery("SELECT ".MYSQL_PREFIX."feed.name AS name, ".MYSQL_PREFIX."feed.id   AS id, ".MYSQL_PREFIX."feed.url  AS url, ".MYSQL_PREFIX."folder.id AS folder FROM ".MYSQL_PREFIX."feed INNER JOIN ".MYSQL_PREFIX."folder ON ( ".MYSQL_PREFIX."feed.folder = ".MYSQL_PREFIX."folder.id ) ORDER BY ".MYSQL_PREFIX."feed.name ;");
-		if($results!=false){
-			while($item = mysql_fetch_array($results)){
-				$name = $item['name'];
-				$feedsIdMap[$item['id']]['name'] = $name;
-
-
-				$feedsFolderMap[$item['folder']][$item['id']]['id'] = $item['id'];
-				$feedsFolderMap[$item['folder']][$item['id']]['name'] = $name;
-				$feedsFolderMap[$item['folder']][$item['id']]['url'] = $item['url'];
-
-			}
-		}
-		$feeds['folderMap'] = $feedsFolderMap;
-		$feeds['idMap'] = $feedsIdMap;
-		return $feeds;
-	}
-
-	function getFolder(){
-		return $this->folder;
-	}
-
-	function setFolder($folder){
-		$this->folder = $folder;
-	}
-
-	function getLastupdate(){
-		return $this->lastUpdate;
-	}
-
-	function setLastupdate($lastupdate){
-		$this->lastupdate = $lastupdate;
-	}
-
-	/** @returns vrai si l'url n'est pas déjà connue .*/
-	function notRegistered() {
-		return $this->rowCount(array('url' => $this->url)) == 0;
-	}
+    protected $id,$name,$url,$events=array(),$description,$website,$folder,$lastupdate;
+    protected $TABLE_NAME = 'feed';
+    protected $CLASS_NAME = 'Feed';
+    protected $object_fields =
+    array(
+        'id'=>'key',
+        'name'=>'string',
+        'description'=>'longstring',
+        'website'=>'longstring',
+        'url'=>'longstring',
+        'lastupdate'=>'string',
+        'folder'=>'integer'
+    );
+
+    protected $object_fields_index =
+    array(
+        'folder'=>'index'
+    );
+
+    protected $error = '';
+
+    function __construct($name=null,$url=null){
+        $this->name = $name;
+        $this->url = $url;
+        parent::__construct();
+    }
+
+    /** @TODO: ne faire qu'un seul chargement avec SimplePie et récupérer les
+    même informations. Mettre le chargement en cache au moins d'une méthode
+    loadLeed() qui ne chargera qu'une seule fois. Voire même en déclenchement
+    retardé, au dernier moment. */
+    function getInfos(){
+        $xml = @simplexml_load_file($this->url);
+        if($xml!=false){
+            $this->name = array_shift ($xml->xpath('channel/title'));
+            $this->description = array_shift ($xml->xpath('channel/description'));
+            $this->website = array_shift ($xml->xpath('channel/link'));
+        }
+    }
+
+    function getError() { return $this->error; }
+
+    /*@TODO: fournir un extrait quand il 'y a pas de description. De même pour les médias.
+    @TODO: SimplePie remplace "é" par "&eacute;", il ne devrait pas le faire.
+    J'ai testé set_stupidly_fast(true) sans succès.
+    Il encadre les descriptions avec <div>, absents dans le source du flux.
+    @TODO: la vérification de doublon est sous la responsabilité de l'appelant.
+    Il serait peut-être utile de faire une méthode add() qui vérifie, plante si
+    nécessaire, et appelle parse(). Impossible de vérifier dans parse() même
+    car elle est appelée aussi pour autre chose que l'ajout.
+    */
+    function parse($syncId,&$nbEvents =0, $enableCache=true, $forceFeed=false){
+        $nbEvents = 0;
+        assert('is_int($syncId) && $syncId>0');
+        if (empty($this->id) || 0 == $this->id) {
+            /* Le flux ne dispose pas pas d'id !. Ça arrive si on appelle
+            parse() sans avoir appelé save() pour un nouveau flux.
+            @TODO: un create() pour un nouveau flux ? */
+            $msg = 'Empty or null id for a feed! '
+                  .'See '.__FILE__.' on line '.__LINE__;
+            error_log($msg, E_USER_ERROR);
+            die($msg); // Arrêt, sinon création événements sans flux associé.
+        }
+        $feed = new SimplePie();
+        $feed->enable_cache($enableCache);
+        $feed->force_feed($forceFeed);
+        $feed->set_feed_url($this->url);
+        $feed->set_useragent('Mozilla/4.0 Leed (LightFeed Agrgegator) '.VERSION_NAME.' by idleman http://projet.idleman.fr/leed');
+        if (!$feed->init()) {
+            $this->error = $feed->error;
+            $this->lastupdate = $_SERVER['REQUEST_TIME'];
+            $this->save();
+            return false;
+        }
+
+        $feed->handle_content_type(); // UTF-8 par défaut pour SimplePie
+
+        if($this->name=='') $this->name = $feed->get_title();
+        if($this->name=='') $this->name = $this->url;
+        $this->website = $feed->get_link();
+        $this->description = $feed->get_description();
+
+        $items = $feed->get_items();
+        $eventManager = new Event();
+
+        $events = array();
+        $iEvents = 0;
+        foreach($items as $item){
+            // Ne retient que les 100 premiers éléments de flux.
+            if ($iEvents++>=100) break;
+
+            // Si le guid existe déjà, on évite de le reparcourir.
+            $alreadyParsed = $eventManager->load(array('guid'=>$item->get_id(), 'feed'=>$this->id));
+            if (isset($alreadyParsed)&&($alreadyParsed!=false)) {
+                $events[]=$alreadyParsed->getId();
+                continue;
+            }
+
+            // Initialisation des informations de l'événement (élt. de flux)
+            $event = new Event();
+            $event->setSyncId($syncId);
+            $event->setGuid($item->get_id());
+            $event->setTitle($item->get_title());
+            $event->setPubdate($item->get_date());
+            $event->setCreator(
+                ''==$item->get_author()
+                    ? ''
+                    : $item->get_author()->name
+            );
+            $event->setLink($item->get_permalink());
+
+            $event->setFeed($this->id);
+            $event->setUnread(1); // inexistant, donc non-lu
+
+            //Gestion de la balise enclosure pour les podcasts et autre cochonneries :)
+            $enclosure = $item->get_enclosure();
+            if($enclosure!=null && $enclosure->link!=''){
+                $enclosureName = substr(
+                    $enclosure->link,
+                    strrpos($enclosure->link, '/')+1,
+                    strlen($enclosure->link)
+                );
+                $enclosureArgs = strpos($enclosureName, '?');
+                if($enclosureArgs!==false)
+                    $enclosureName = substr($enclosureName,0,$enclosureArgs);
+                $enclosureFormat = isset($enclosure->handler)
+                    ? $enclosure->handler
+                    : substr($enclosureName, strrpos($enclosureName,'.')+1);
+
+                $enclosure ='<div class="enclosure"><h1>Fichier média :</h1><a href="'.$enclosure->link.'"> '.$enclosureName.'</a> <span>(Format '.strtoupper($enclosureFormat).', '.Functions::convertFileSize($enclosure->length).')</span></div>';
+            }else{
+                $enclosure = '';
+            }
+
+            $event->setContent($item->get_content().$enclosure);
+            $event->setDescription($item->get_description().$enclosure);
+
+            if(trim($event->getDescription())=='')
+                $event->setDescription(
+                    substr($event->getContent(),0,300)
+                    .'…<br><a href="'.$event->getLink()
+                    .'">Lire la suite de l\'article</a>'
+                );
+            if(trim($event->getContent())=='')
+                $event->setContent($event->getDescription());
+
+            $event->setCategory($item->get_category());
+            $event->save();
+            $nbEvents++;
+        }
+
+        $listid = "";
+        foreach($events as $item){
+            $listid.=','.$item;
+        }
+        $query='UPDATE `'.MYSQL_PREFIX.'event` SET syncId='.$syncId.' WHERE id in (0'.$listid.');';
+        $myQuery = $this->customQuery($query);
+
+        $this->lastupdate = $_SERVER['REQUEST_TIME'];
+        $this->save();
+        return true;
+    }
+
+
+    function removeOldEvents($maxEvent, $currentSyncId){
+        if ($maxEvent<=0) return;
+        $eventManager = new Event();
+        $nbLines = $eventManager->rowCount(array(
+            'feed'=>$this->id,
+             'unread'=>0,
+            'favorite'=>0,
+        ));
+        $limit = $nbLines - $maxEvent;
+        if ($limit<=0) return;
+        $tableEvent = '`'.MYSQL_PREFIX."event`";
+        $query = "
+            DELETE FROM {$tableEvent} WHERE feed={$this->id} AND favorite!=1 AND unread!=1 AND syncId!={$currentSyncId} ORDER BY pubDate ASC LIMIT {$limit}
+        ";
+        ///@TODO: escape the variables inside mysql
+         $this->customExecute($query);
+    }
+
+    function setId($id){
+        $this->id = $id;
+    }
+
+    function getDescription(){
+        return $this->description;
+    }
+
+    function setDescription($description){
+        $this->description = $description;
+    }
+    function getWebSite(){
+        return $this->website;
+    }
+
+    function setWebSite($website){
+        $this->website = $website;
+    }
+
+    function getId(){
+        return $this->id;
+    }
+
+    function getUrl(){
+        return $this->url;
+    }
+
+    function setUrl($url){
+        $this->url = $url;
+    }
+
+    function getName(){
+        return (trim($this->name)!='' ? $this->name:$this->url);
+    }
+
+    function setName($name){
+        $this->name = $name;
+    }
+
+
+    function getEvents($start=0,$limit=10000,$order,$columns='*'){
+        $eventManager = new Event();
+        $events = $eventManager->loadAllOnlyColumn($columns,array('feed'=>$this->getId()),$order,$start.','.$limit);
+        return $events;
+    }
+
+    function countUnreadEvents(){
+        $unreads = array();
+        $results = Feed::customQuery("SELECT COUNT(".MYSQL_PREFIX."event.id), ".MYSQL_PREFIX."event.feed FROM ".MYSQL_PREFIX."event WHERE ".MYSQL_PREFIX."event.unread = 1 GROUP BY ".MYSQL_PREFIX."event.feed") ;
+        if($results!=false){
+            while($item = mysql_fetch_array($results)){
+                $unreads[$item[1]] = $item[0];
+            }
+        }
+        return $unreads;
+    }
+
+    function getFeedsPerFolder(){
+        $feedsFolderMap = array();
+        $feedsIdMap = array();
+
+        $results = Feed::customQuery("SELECT ".MYSQL_PREFIX."feed.name AS name, ".MYSQL_PREFIX."feed.id   AS id, ".MYSQL_PREFIX."feed.url  AS url, ".MYSQL_PREFIX."folder.id AS folder FROM ".MYSQL_PREFIX."feed INNER JOIN ".MYSQL_PREFIX."folder ON ( ".MYSQL_PREFIX."feed.folder = ".MYSQL_PREFIX."folder.id ) ORDER BY ".MYSQL_PREFIX."feed.name ;");
+        if($results!=false){
+            while($item = mysql_fetch_array($results)){
+                $name = $item['name'];
+                $feedsIdMap[$item['id']]['name'] = $name;
+
+
+                $feedsFolderMap[$item['folder']][$item['id']]['id'] = $item['id'];
+                $feedsFolderMap[$item['folder']][$item['id']]['name'] = $name;
+                $feedsFolderMap[$item['folder']][$item['id']]['url'] = $item['url'];
+
+            }
+        }
+        $feeds['folderMap'] = $feedsFolderMap;
+        $feeds['idMap'] = $feedsIdMap;
+        return $feeds;
+    }
+
+    function getFolder(){
+        return $this->folder;
+    }
+
+    function setFolder($folder){
+        $this->folder = $folder;
+    }
+
+    function getLastupdate(){
+        return $this->lastUpdate;
+    }
+
+    function setLastupdate($lastupdate){
+        $this->lastupdate = $lastupdate;
+    }
+
+    /** @returns vrai si l'url n'est pas déjà connue .*/
+    function notRegistered() {
+        return $this->rowCount(array('url' => $this->url)) == 0;
+    }
 
 }
 

+ 83 - 83
Folder.class.php

@@ -8,89 +8,89 @@
 
 class Folder extends MysqlEntity{
 
-	protected $id,$name,$parent,$isopen;
-	protected $TABLE_NAME = 'folder';
-	protected $CLASS_NAME = 'Folder';
-	protected $object_fields =
-	array(
-		'id'=>'key',
-		'name'=>'string',
-		'parent'=>'integer',
-		'isopen'=>'integer'
-	);
-
-	function unreadCount(){
-		$results = $this->customQuery('SELECT COUNT('.MYSQL_PREFIX.'event.id) FROM '.MYSQL_PREFIX.'event INNER JOIN '.MYSQL_PREFIX.'feed ON ('.MYSQL_PREFIX.'event.feed = '.MYSQL_PREFIX.'feed.id) WHERE '.MYSQL_PREFIX.'event.unread=1 AND '.MYSQL_PREFIX.'feed.folder = '.$this->getId());
-		$number = mysql_fetch_array($results);
-		return $number[0];
-	}
-
-
-	function getEvents($start=0,$limit=10000,$order,$columns='*'){
-		$eventManager = new Event();
-		$objects = array();
-		$results = $this->customQuery('SELECT '.$columns.' FROM '.MYSQL_PREFIX.'event INNER JOIN '.MYSQL_PREFIX.'feed ON ('.MYSQL_PREFIX.'event.feed = '.MYSQL_PREFIX.'feed.id) WHERE '.MYSQL_PREFIX.'event.unread=1 AND '.MYSQL_PREFIX.'feed.folder = '.$this->getId().' ORDER BY '.$order.' LIMIT '.$start.','.$limit);
-		if($results!=false){
-			while($item = mysql_fetch_array($results)){
-				$object = new Event();
-					foreach($object->getObject_fields() as $field=>$type){
-						$setter = 'set'.ucFirst($field);
-						if(isset($item[$field])) $object->$setter($item[$field]);
-					}
-					$objects[] = $object;
-					unset($object);
-			}
-		}
-
-		return $objects;
-	}
-
-	function __construct(){
-		parent::__construct();
-	}
-
-	function setId($id){
-		$this->id = $id;
-	}
-
-	function getFeeds(){
-		$feedManager = new Feed();
-		return $feedManager->loadAll(array('folder'=>$this->getId()),'name');
-	}
-
-	function getFolders(){
-		$folderManager = new Folder();
-		return $folderManager->loadAll(array('parent'=>$this->getId()));
-	}
-
-
-	function getId(){
-		return $this->id;
-	}
-
-	function getName(){
-		return $this->name;
-	}
-
-	function setName($name){
-		$this->name = $name;
-	}
-
-	function getParent(){
-		return $this->parent;
-	}
-
-	function setParent($parent){
-		$this->parent = $parent;
-	}
-
-	function getIsopen(){
-		return $this->isopen;
-	}
-
-	function setIsopen($isopen){
-		$this->isopen = $isopen;
-	}
+    protected $id,$name,$parent,$isopen;
+    protected $TABLE_NAME = 'folder';
+    protected $CLASS_NAME = 'Folder';
+    protected $object_fields =
+    array(
+        'id'=>'key',
+        'name'=>'string',
+        'parent'=>'integer',
+        'isopen'=>'integer'
+    );
+
+    function unreadCount(){
+        $results = $this->customQuery('SELECT COUNT('.MYSQL_PREFIX.'event.id) FROM '.MYSQL_PREFIX.'event INNER JOIN '.MYSQL_PREFIX.'feed ON ('.MYSQL_PREFIX.'event.feed = '.MYSQL_PREFIX.'feed.id) WHERE '.MYSQL_PREFIX.'event.unread=1 AND '.MYSQL_PREFIX.'feed.folder = '.$this->getId());
+        $number = mysql_fetch_array($results);
+        return $number[0];
+    }
+
+
+    function getEvents($start=0,$limit=10000,$order,$columns='*'){
+        $eventManager = new Event();
+        $objects = array();
+        $results = $this->customQuery('SELECT '.$columns.' FROM '.MYSQL_PREFIX.'event INNER JOIN '.MYSQL_PREFIX.'feed ON ('.MYSQL_PREFIX.'event.feed = '.MYSQL_PREFIX.'feed.id) WHERE '.MYSQL_PREFIX.'event.unread=1 AND '.MYSQL_PREFIX.'feed.folder = '.$this->getId().' ORDER BY '.$order.' LIMIT '.$start.','.$limit);
+        if($results!=false){
+            while($item = mysql_fetch_array($results)){
+                $object = new Event();
+                    foreach($object->getObject_fields() as $field=>$type){
+                        $setter = 'set'.ucFirst($field);
+                        if(isset($item[$field])) $object->$setter($item[$field]);
+                    }
+                    $objects[] = $object;
+                    unset($object);
+            }
+        }
+
+        return $objects;
+    }
+
+    function __construct(){
+        parent::__construct();
+    }
+
+    function setId($id){
+        $this->id = $id;
+    }
+
+    function getFeeds(){
+        $feedManager = new Feed();
+        return $feedManager->loadAll(array('folder'=>$this->getId()),'name');
+    }
+
+    function getFolders(){
+        $folderManager = new Folder();
+        return $folderManager->loadAll(array('parent'=>$this->getId()));
+    }
+
+
+    function getId(){
+        return $this->id;
+    }
+
+    function getName(){
+        return $this->name;
+    }
+
+    function setName($name){
+        $this->name = $name;
+    }
+
+    function getParent(){
+        return $this->parent;
+    }
+
+    function setParent($parent){
+        $this->parent = $parent;
+    }
+
+    function getIsopen(){
+        return $this->isopen;
+    }
+
+    function setIsopen($isopen){
+        $this->isopen = $isopen;
+    }
 
 
 

+ 346 - 346
Functions.class.php

@@ -8,352 +8,352 @@
 
 class Functions
 {
-	private $id;
-	public $debug=0;
-
-	/**
-	 * Securise la variable utilisateur entrée en parametre
-	 * @author Valentin
-	 * @param<String> variable a sécuriser
-	 * @param<Integer> niveau de securisation
-	 * @return<String> variable securisée
-	 */
-
-	public static function secure($var,$level = 1){
-		$var = htmlspecialchars($var, ENT_QUOTES, "UTF-8");
-		if($level<1)$var = mysql_real_escape_string($var);
-		if($level<2)$var = addslashes($var);
-		return $var;
-	}
-
-
-	/**
-	 * Return l'environnement/serveur sur lequel on se situe, permet de changer les
-	 * connexions bdd en fonction de la dev, la préprod ou la prod
-	 */
-	public static function whereImI(){
-
-		$maps = array (
-		'LOCAL'=>array('localhost','127.0.0.1','0.0.0.1','::0.0.0.0'),
-		'LAN'=>array('192.168.10.','valentin'),
-		'PWAN'=>array('test.sys1.fr'),
-		'WAN'=>array('www.sys1.fr'),
-		);
-
-
-		$return = 'UNKNOWN';
-		foreach($maps as $map=>$values){
-
-			foreach($values as $ip){
-				$pos = strpos(strtolower($_SERVER['HTTP_HOST']),$ip);
-				if ($pos!==false){
-					$return = $map;
-				}
-			}
-		}
-		return $return;
-	}
-
-	public static function isLocal($perimeter='LOCAL'){
-		$return = false;
-
-		$localTab = array('localhost','127.0.0.1','0.0.0.1','::0.0.0.0');
-		$lanTab = array('192.168.10.','valentin');
-
-		switch($perimeter){
-			case 'LOCAL':
-				foreach($localTab as $ip){
-					$pos = strpos(strtolower($_SERVER['HTTP_HOST']),$ip);
-					if ($pos!==false){
-						$return = true;
-					}
-				}
-				break;
-			case 'LAN':
-				foreach($lanTab as $ip){
-					$pos = strpos(strtolower($_SERVER['HTTP_HOST']),$ip);
-					if ($pos!==false){
-						$return = true;
-					}
-				}
-				break;
-			case 'ALL':
-				foreach($localTab as $ip){
-					$pos = strpos(strtolower($_SERVER['HTTP_HOST']),$ip);
-					if ($pos!==false){
-						$return = true;
-					}
-				}
-				foreach($lanTab as $ip){
-					$pos = strpos(strtolower($_SERVER['HTTP_HOST']),$ip);
-					if ($pos!==false){
-						$return = true;
-					}
-				}
-				break;
-		}
-
-		return $return;
-	}
-
-
-	/**
-	 * Convertis la chaine passée en timestamp quel que soit sont format
-	 * (prend en charge les formats type dd-mm-yyy , dd/mm/yyy, yyyy/mm/ddd...)
-	 */
-	public static function toTime($string){
-		$string = str_replace('/','-',$string);
-		$string = str_replace('\\','-',$string);
-
-		$string = str_replace('Janvier','Jan',$string);
-		$string = str_replace('Fevrier','Feb',$string);
-		$string = str_replace('Mars','Mar',$string);
-		$string = str_replace('Avril','Apr',$string);
-		$string = str_replace('Mai','May',$string);
-		$string = str_replace('Juin','Jun',$string);
-		$string = str_replace('Juillet','Jul',$string);
-		$string = str_replace('Aout','Aug',$string);
-		$string = str_replace('Septembre','Sept',$string);
-		$string = str_replace('Octobre','Oct',$string);
-		$string = str_replace('Novembre','Nov',$string);
-		$string = str_replace('Decembre','Dec',$string);
-		return strtotime($string);
-	}
-
-	/**
-	 * Recupere l'ip de l'internaute courant
-	 * @author Valentin
-	 * @return<String> ip de l'utilisateur
-	 */
-
-	public static function getIP(){
-		if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
-			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];}
-			elseif(isset($_SERVER['HTTP_CLIENT_IP'])){
-				$ip = $_SERVER['HTTP_CLIENT_IP'];}
-				else{ $ip = $_SERVER['REMOTE_ADDR'];}
-				return $ip;
-	}
-
-	/**
-	 * Retourne une version tronquée au bout de $limit caracteres de la chaine fournie
-	 * @author Valentin
-	 * @param<String> message a tronquer
-	 * @param<Integer> limite de caracteres
-	 * @return<String> chaine tronquée
-	 */
-	public static function truncate($msg,$limit){
-		if(mb_strlen($msg)>$limit){
-			$fin='…' ;
-			$nb=$limit-mb_strlen($fin) ;
-		}else{
-			$nb=mb_strlen($msg);
-			$fin='';
-		}
-		return mb_substr($msg, 0, $nb).$fin;
-	}
-
-
-	function getExtension($fileName){
-		$dot = explode('.',$fileName);
-		return $dot[sizeof($dot)-1];
-	}
-
-	/**
-	 * Definis si la chaine fournie est existante dans la reference fournie ou non
-	 * @param unknown_type $string
-	 * @param unknown_type $reference
-	 * @return false si aucune occurence du string, true dans le cas contraire
-	 */
-	public static function contain($string,$reference){
-		$return = true;
-		$pos = strpos($reference,$string);
-		if ($pos === false) {
-			$return = false;
-		}
-		return strtolower($return);
-	}
-
-	/**
-	 * Définis si la chaine passée en parametre est une url ou non
-	 */
-	public static function isUrl($url){
-		$return =false;
-		if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {
-			$return =true;
-		}
-		return $return;
-	}
-
-	/**
-	 * Définis si la chaine passée en parametre est une couleur héxadécimale ou non
-	 */
-	public static function isColor($color){
-		$return =false;
-		if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $color)) {
-			$return =true;
-		}
-		return $return;
-	}
-
-	/**
-	 * Définis si la chaine passée en parametre est un mail ou non
-	 */
-	public static function isMail($mail){
-		$return =false;
-		if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
-			$return =true;
-		}
-		return $return;
-	}
-
-	/**
-	 * Définis si la chaine passée en parametre est une IP ou non
-	 */
-	public static function isIp($ip){
-		$return =false;
-		if (preg_match('^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$',$ip)) {
-			$return =true;
-		}
-		return $return;
-	}
-
-	public static function sourceName($string){
-		$name = strtolower($string);
-		$name = str_replace(' ','-',$name);
-		$name = str_replace('&#039;','-',$name);
-		$name = str_replace('\'','-',$name);
-		$name = str_replace(',','-',$name);
-		$name = str_replace(':','-',$name);
-		$name = str_replace('&agrave;','a',$name);
-		$name = trim($name);
-		$name = html_entity_decode($name,null,'UTF-8');
-		return $name;
-	}
-
-	public static function makeCookie($name, $value, $expire='') {
-		if($expire == '') {
-			setcookie($name, $value, mktime(0,0,0, date("d"),
-			date("m"), (date("Y")+1)),'/');
-		}else {
-			setcookie($name, '', mktime(0,0,0, date("d"),
-			date("m"), (date("Y")-1)),'/');
-		}
-	}
-
-	public static function destroyCookie($name){
-		Fonction::makeCookie($name,'',time()-3600);
-		unset($_COOKIE[$name]);
-	}
-
-	public static function wordwrap($str, $width = 75, $break = "\n", $cut = false)
-	{
-		$str = html_entity_decode($str);
-		$str =  htmlentities (wordwrap($str,$width,$break,$cut));
-		$str = str_replace('&lt;br/&gt;','<br/>',$str);
-		$str = str_replace('&amp;','&',$str);
-		return $str;
-	}
-
-	public static function createFile($filePath,$content){
-		$fichier = fopen($filePath,"w+");
-		$fwriteResult = fwrite($fichier,$content);
-		fclose($fichier);
-	}
-
-
-
-	public static function convertFileSize($bytes)
-	{
-		 if($bytes<1024){
-		 	return round(($bytes / 1024), 2).' o';
-		 }elseif(1024<$bytes && $bytes<1048576){
-		 	return round(($bytes / 1024), 2).' ko';
-		 }elseif(1048576<$bytes && $bytes<1073741824){
-		 	return round(($bytes / 1024)/1024, 2).' Mo';
-		 }elseif(1073741824<$bytes){
-		 	return round(($bytes / 1024)/1024/1024, 2).' Go';
-		 }
-	}
-
-
-	public static function hexaValue($str){
-		$code = dechex(crc32($str));
-		  $code = substr($code, 0, 6);
-		  return $code;
-	}
-
-	public static function scanRecursiveDir($dir){
-		$files = scandir($dir);
-		$allFiles = array();
-		foreach($files as $file){
-			if($file!='.' && $file!='..'){
-				if(is_dir($dir.$file)){
-					$allFiles = array_merge($allFiles,Fonction::scanRecursiveDir($dir.$file));
-				}else{
-					$allFiles[]=str_replace('//','/',$dir.'/'.$file);
-				}
-			}
-		}
-		return $allFiles;
-	}
-
-	/** Permet la sortie directe de texte à l'écran, sans tampon.
-		Source : http://php.net/manual/fr/function.flush.php
-	*/
-	public static function triggerDirectOutput() {
-		// La ligne de commande n'en a pas besoin.
-		if ('cli'==php_sapi_name()) return;
-		if (function_exists('apache_setenv')) {
-			/* Selon l'hébergeur la fonction peut être désactivée. Alors Php
-			   arrête le programme avec l'erreur :
-			   "PHP Fatal error:  Call to undefined function apache_setenv()".
-			*/
-			@apache_setenv('no-gzip', 1);
-		}
-		@ini_set('zlib.output_compression', 0);
-		@ini_set('implicit_flush', 1);
-		for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
-		ob_implicit_flush(1);
-	}
-
-	public static function relativePath($from, $to, $ps = '/') {
-		$arFrom = explode($ps, rtrim($from, $ps));
-		$arTo = explode($ps, rtrim($to, $ps));
-		while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0])) {
-			array_shift($arFrom);
-			array_shift($arTo);
-		}
-		return str_pad("", count($arFrom) * 3, '..'.$ps).implode($ps, $arTo);
-	}
-
-
-	// Nettoyage de l'url avant la mise en base
-	public static function clean_url( $url ) {
-		$url = str_replace('&amp;', '&', $url);
-		return $url;
-	}
-
-
-
-	/**
-	* Méthode de test de connexion.
-	* @return true si ok
-	* @param server
-	* @param login
-	* @param pass
-	* @param db facultatif, si précisé alors tente de la séléctionner
-	*/
-	public static function testDb($server, $login, $pass, $db=null) {
-		/* Méthode hors des classes dédiées aux BDD afin de supporter le moins
-		   de dépendances possibles. En particulier, pas besoin que le fichier
-		   de configuration existe. */
-		$link = mysql_connect($server, $login, $pass);
-		if (false===$link) return false;
-		if (!is_null($db) && false===mysql_select_db($db, $link)) return false;
-		mysql_close($link);
-		return true;
-	}
+    private $id;
+    public $debug=0;
+
+    /**
+     * Securise la variable utilisateur entrée en parametre
+     * @author Valentin
+     * @param<String> variable a sécuriser
+     * @param<Integer> niveau de securisation
+     * @return<String> variable securisée
+     */
+
+    public static function secure($var,$level = 1){
+        $var = htmlspecialchars($var, ENT_QUOTES, "UTF-8");
+        if($level<1)$var = mysql_real_escape_string($var);
+        if($level<2)$var = addslashes($var);
+        return $var;
+    }
+
+
+    /**
+     * Return l'environnement/serveur sur lequel on se situe, permet de changer les
+     * connexions bdd en fonction de la dev, la préprod ou la prod
+     */
+    public static function whereImI(){
+
+        $maps = array (
+        'LOCAL'=>array('localhost','127.0.0.1','0.0.0.1','::0.0.0.0'),
+        'LAN'=>array('192.168.10.','valentin'),
+        'PWAN'=>array('test.sys1.fr'),
+        'WAN'=>array('www.sys1.fr'),
+        );
+
+
+        $return = 'UNKNOWN';
+        foreach($maps as $map=>$values){
+
+            foreach($values as $ip){
+                $pos = strpos(strtolower($_SERVER['HTTP_HOST']),$ip);
+                if ($pos!==false){
+                    $return = $map;
+                }
+            }
+        }
+        return $return;
+    }
+
+    public static function isLocal($perimeter='LOCAL'){
+        $return = false;
+
+        $localTab = array('localhost','127.0.0.1','0.0.0.1','::0.0.0.0');
+        $lanTab = array('192.168.10.','valentin');
+
+        switch($perimeter){
+            case 'LOCAL':
+                foreach($localTab as $ip){
+                    $pos = strpos(strtolower($_SERVER['HTTP_HOST']),$ip);
+                    if ($pos!==false){
+                        $return = true;
+                    }
+                }
+                break;
+            case 'LAN':
+                foreach($lanTab as $ip){
+                    $pos = strpos(strtolower($_SERVER['HTTP_HOST']),$ip);
+                    if ($pos!==false){
+                        $return = true;
+                    }
+                }
+                break;
+            case 'ALL':
+                foreach($localTab as $ip){
+                    $pos = strpos(strtolower($_SERVER['HTTP_HOST']),$ip);
+                    if ($pos!==false){
+                        $return = true;
+                    }
+                }
+                foreach($lanTab as $ip){
+                    $pos = strpos(strtolower($_SERVER['HTTP_HOST']),$ip);
+                    if ($pos!==false){
+                        $return = true;
+                    }
+                }
+                break;
+        }
+
+        return $return;
+    }
+
+
+    /**
+     * Convertis la chaine passée en timestamp quel que soit sont format
+     * (prend en charge les formats type dd-mm-yyy , dd/mm/yyy, yyyy/mm/ddd...)
+     */
+    public static function toTime($string){
+        $string = str_replace('/','-',$string);
+        $string = str_replace('\\','-',$string);
+
+        $string = str_replace('Janvier','Jan',$string);
+        $string = str_replace('Fevrier','Feb',$string);
+        $string = str_replace('Mars','Mar',$string);
+        $string = str_replace('Avril','Apr',$string);
+        $string = str_replace('Mai','May',$string);
+        $string = str_replace('Juin','Jun',$string);
+        $string = str_replace('Juillet','Jul',$string);
+        $string = str_replace('Aout','Aug',$string);
+        $string = str_replace('Septembre','Sept',$string);
+        $string = str_replace('Octobre','Oct',$string);
+        $string = str_replace('Novembre','Nov',$string);
+        $string = str_replace('Decembre','Dec',$string);
+        return strtotime($string);
+    }
+
+    /**
+     * Recupere l'ip de l'internaute courant
+     * @author Valentin
+     * @return<String> ip de l'utilisateur
+     */
+
+    public static function getIP(){
+        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
+            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];}
+            elseif(isset($_SERVER['HTTP_CLIENT_IP'])){
+                $ip = $_SERVER['HTTP_CLIENT_IP'];}
+                else{ $ip = $_SERVER['REMOTE_ADDR'];}
+                return $ip;
+    }
+
+    /**
+     * Retourne une version tronquée au bout de $limit caracteres de la chaine fournie
+     * @author Valentin
+     * @param<String> message a tronquer
+     * @param<Integer> limite de caracteres
+     * @return<String> chaine tronquée
+     */
+    public static function truncate($msg,$limit){
+        if(mb_strlen($msg)>$limit){
+            $fin='…' ;
+            $nb=$limit-mb_strlen($fin) ;
+        }else{
+            $nb=mb_strlen($msg);
+            $fin='';
+        }
+        return mb_substr($msg, 0, $nb).$fin;
+    }
+
+
+    function getExtension($fileName){
+        $dot = explode('.',$fileName);
+        return $dot[sizeof($dot)-1];
+    }
+
+    /**
+     * Definis si la chaine fournie est existante dans la reference fournie ou non
+     * @param unknown_type $string
+     * @param unknown_type $reference
+     * @return false si aucune occurence du string, true dans le cas contraire
+     */
+    public static function contain($string,$reference){
+        $return = true;
+        $pos = strpos($reference,$string);
+        if ($pos === false) {
+            $return = false;
+        }
+        return strtolower($return);
+    }
+
+    /**
+     * Définis si la chaine passée en parametre est une url ou non
+     */
+    public static function isUrl($url){
+        $return =false;
+        if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {
+            $return =true;
+        }
+        return $return;
+    }
+
+    /**
+     * Définis si la chaine passée en parametre est une couleur héxadécimale ou non
+     */
+    public static function isColor($color){
+        $return =false;
+        if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $color)) {
+            $return =true;
+        }
+        return $return;
+    }
+
+    /**
+     * Définis si la chaine passée en parametre est un mail ou non
+     */
+    public static function isMail($mail){
+        $return =false;
+        if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
+            $return =true;
+        }
+        return $return;
+    }
+
+    /**
+     * Définis si la chaine passée en parametre est une IP ou non
+     */
+    public static function isIp($ip){
+        $return =false;
+        if (preg_match('^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$',$ip)) {
+            $return =true;
+        }
+        return $return;
+    }
+
+    public static function sourceName($string){
+        $name = strtolower($string);
+        $name = str_replace(' ','-',$name);
+        $name = str_replace('&#039;','-',$name);
+        $name = str_replace('\'','-',$name);
+        $name = str_replace(',','-',$name);
+        $name = str_replace(':','-',$name);
+        $name = str_replace('&agrave;','a',$name);
+        $name = trim($name);
+        $name = html_entity_decode($name,null,'UTF-8');
+        return $name;
+    }
+
+    public static function makeCookie($name, $value, $expire='') {
+        if($expire == '') {
+            setcookie($name, $value, mktime(0,0,0, date("d"),
+            date("m"), (date("Y")+1)),'/');
+        }else {
+            setcookie($name, '', mktime(0,0,0, date("d"),
+            date("m"), (date("Y")-1)),'/');
+        }
+    }
+
+    public static function destroyCookie($name){
+        Fonction::makeCookie($name,'',time()-3600);
+        unset($_COOKIE[$name]);
+    }
+
+    public static function wordwrap($str, $width = 75, $break = "\n", $cut = false)
+    {
+        $str = html_entity_decode($str);
+        $str =  htmlentities (wordwrap($str,$width,$break,$cut));
+        $str = str_replace('&lt;br/&gt;','<br/>',$str);
+        $str = str_replace('&amp;','&',$str);
+        return $str;
+    }
+
+    public static function createFile($filePath,$content){
+        $fichier = fopen($filePath,"w+");
+        $fwriteResult = fwrite($fichier,$content);
+        fclose($fichier);
+    }
+
+
+
+    public static function convertFileSize($bytes)
+    {
+         if($bytes<1024){
+             return round(($bytes / 1024), 2).' o';
+         }elseif(1024<$bytes && $bytes<1048576){
+             return round(($bytes / 1024), 2).' ko';
+         }elseif(1048576<$bytes && $bytes<1073741824){
+             return round(($bytes / 1024)/1024, 2).' Mo';
+         }elseif(1073741824<$bytes){
+             return round(($bytes / 1024)/1024/1024, 2).' Go';
+         }
+    }
+
+
+    public static function hexaValue($str){
+        $code = dechex(crc32($str));
+          $code = substr($code, 0, 6);
+          return $code;
+    }
+
+    public static function scanRecursiveDir($dir){
+        $files = scandir($dir);
+        $allFiles = array();
+        foreach($files as $file){
+            if($file!='.' && $file!='..'){
+                if(is_dir($dir.$file)){
+                    $allFiles = array_merge($allFiles,Fonction::scanRecursiveDir($dir.$file));
+                }else{
+                    $allFiles[]=str_replace('//','/',$dir.'/'.$file);
+                }
+            }
+        }
+        return $allFiles;
+    }
+
+    /** Permet la sortie directe de texte à l'écran, sans tampon.
+        Source : http://php.net/manual/fr/function.flush.php
+    */
+    public static function triggerDirectOutput() {
+        // La ligne de commande n'en a pas besoin.
+        if ('cli'==php_sapi_name()) return;
+        if (function_exists('apache_setenv')) {
+            /* Selon l'hébergeur la fonction peut être désactivée. Alors Php
+               arrête le programme avec l'erreur :
+               "PHP Fatal error:  Call to undefined function apache_setenv()".
+            */
+            @apache_setenv('no-gzip', 1);
+        }
+        @ini_set('zlib.output_compression', 0);
+        @ini_set('implicit_flush', 1);
+        for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
+        ob_implicit_flush(1);
+    }
+
+    public static function relativePath($from, $to, $ps = '/') {
+        $arFrom = explode($ps, rtrim($from, $ps));
+        $arTo = explode($ps, rtrim($to, $ps));
+        while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0])) {
+            array_shift($arFrom);
+            array_shift($arTo);
+        }
+        return str_pad("", count($arFrom) * 3, '..'.$ps).implode($ps, $arTo);
+    }
+
+
+    // Nettoyage de l'url avant la mise en base
+    public static function clean_url( $url ) {
+        $url = str_replace('&amp;', '&', $url);
+        return $url;
+    }
+
+
+
+    /**
+    * Méthode de test de connexion.
+    * @return true si ok
+    * @param server
+    * @param login
+    * @param pass
+    * @param db facultatif, si précisé alors tente de la séléctionner
+    */
+    public static function testDb($server, $login, $pass, $db=null) {
+        /* Méthode hors des classes dédiées aux BDD afin de supporter le moins
+           de dépendances possibles. En particulier, pas besoin que le fichier
+           de configuration existe. */
+        $link = mysql_connect($server, $login, $pass);
+        if (false===$link) return false;
+        if (!is_null($db) && false===mysql_select_db($db, $link)) return false;
+        mysql_close($link);
+        return true;
+    }
 
 }
 ?>

+ 190 - 190
MysqlConnector.class.php

@@ -1,199 +1,199 @@
 <?php
 
 /*
-	@nom: mysql
-	@auteur: Idleman (idleman@idleman.fr)
-	@date de création:
-	@description: Classe de gestion des connexions Mysql
+    @nom: mysql
+    @auteur: Idleman (idleman@idleman.fr)
+    @date de création:
+    @description: Classe de gestion des connexions Mysql
 */
 
 class MysqlConnector
 {
-	private $id;
-	private $hote;
-	private $login;
-	private $mdp;
-	private $bdd;
-	private $port;
-	public $debug=0;
-	private $connection = null;
-	public static $instance = null;
-
-	private function __construct(){
-		$this->connect();
-	}
-
-
-
-	/**
-	* Methode de recuperation unique de l'instance
-	* @author Valentin CARRUESCO
-	* @category Singleton
-	* @param <Aucun>
-	* @return <mysql> $instance
-	*/
-
-	public static function getInstance(){
-
-		if (MysqlConnector::$instance === null) {
-			MysqlConnector::$instance = new self();
-		}
-		return MysqlConnector::$instance;
-	}
-
-
-
-	public function connect(){
-		$this->connection = mysql_connect(MYSQL_HOST,MYSQL_LOGIN,MYSQL_MDP);
-		mysql_query('SET NAMES utf8');
-		mysql_select_db(MYSQL_BDD,$this->connection);
-	}
-
-
-
-	public function __toString(){
-		$retour = "";
-		$retour .= "instance de la classe MysqlConnector : <br/>";
-		$retour .= '$hote : '.$this->hote.'<br/>';
-		$retour .= '$login : '.$this->login.'<br/>';
-		$retour .= '$mdp : '.$this->mdp.'<br/>';
-		$retour .= '$bdd : '.$this->bdd.'<br/>';
-		$retour .= '$port : '.$this->port.'<br/>';
-		return $retour;
-	}
-
-	private  function __clone(){
-		//Action lors du clonage de l'objet
-	}
-
-	// ACCESSEURS
-
-	public function getId(){
-		return $this->id;
-	}
-
-	public function setId($id){
-		$this->id = $id;
-	}
-
-	/**
-	* Méthode de récuperation de l'attribut hote de la classe Mysql
-	* @author Valentin CARRUESCO
-	* @category Accesseur
-	* @param Aucun
-	* @return <Attribute> hote
-	*/
-
-	public function getHote(){
-		return $this->hote;
-	}
-
-	/**
-	* Méthode de définition de l'attribut hote de la classe Mysql
-	* @author Valentin CARRUESCO
-	* @category Accesseur
-	* @param <Attribute> $hote
-	* @return Aucun retour
-	*/
-
-	public function setHote($hote){
-		$this->hote = $hote;
-	}
-
-	/**
-	* Méthode de récuperation de l'attribut login de la classe Mysql
-	* @author Valentin CARRUESCO
-	* @category Accesseur
-	* @param Aucun
-	* @return <Attribute> login
-	*/
-
-	public function getLogin(){
-		return $this->login;
-	}
-
-	/**
-	* Méthode de définition de l'attribut login de la classe Mysql
-	* @author Valentin CARRUESCO
-	* @category Accesseur
-	* @param <Attribute> $login
-	* @return Aucun retour
-	*/
-
-	public function setLogin($login){
-		$this->login = $login;
-	}
-
-	/**
-	* Méthode de récuperation de l'attribut mdp de la classe Mysql
-	* @author Valentin CARRUESCO
-	* @category Accesseur
-	* @param Aucun
-	* @return <Attribute> mdp
-	*/
-
-	public function getMdp(){
-		return $this->mdp;
-	}
-
-	/**
-	* Méthode de définition de l'attribut mdp de la classe Mysql
-	* @author Valentin CARRUESCO
-	* @category Accesseur
-	* @param <Attribute> $mdp
-	* @return Aucun retour
-	*/
-
-	public function setMdp($mdp){
-		$this->mdp = $mdp;
-	}
-
-	/**
-	* Méthode de récuperation de l'attribut bdd de la classe Mysql
-	* @author Valentin CARRUESCO
-	* @category Accesseur
-	* @param Aucun
-	* @return <Attribute> bdd
-	*/
-
-	public function getBdd(){
-		return $this->bdd;
-	}
-
-	/**
-	* Méthode de définition de l'attribut bdd de la classe Mysql
-	* @author Valentin CARRUESCO
-	* @category Accesseur
-	* @param <Attribute> $bdd
-	* @return Aucun retour
-	*/
-
-	public function setBdd($bdd){
-		$this->bdd = $bdd;
-	}
-
-	/**
-	* Méthode de récuperation de l'attribut port de la classe Mysql
-	* @author Valentin CARRUESCO
-	* @category Accesseur
-	* @param Aucun
-	* @return <Attribute> port
-	*/
-
-	public function getPort(){
-		return $this->port;
-	}
-
-	/**
-	* Méthode de définition de l'attribut port de la classe Mysql
-	* @author Valentin CARRUESCO
-	* @category Accesseur
-	* @param <Attribute> $port
-	* @return Aucun retour
-	*/
-
-	public function setPort($port){
-		$this->port = $port;
-	}
+    private $id;
+    private $hote;
+    private $login;
+    private $mdp;
+    private $bdd;
+    private $port;
+    public $debug=0;
+    private $connection = null;
+    public static $instance = null;
+
+    private function __construct(){
+        $this->connect();
+    }
+
+
+
+    /**
+    * Methode de recuperation unique de l'instance
+    * @author Valentin CARRUESCO
+    * @category Singleton
+    * @param <Aucun>
+    * @return <mysql> $instance
+    */
+
+    public static function getInstance(){
+
+        if (MysqlConnector::$instance === null) {
+            MysqlConnector::$instance = new self();
+        }
+        return MysqlConnector::$instance;
+    }
+
+
+
+    public function connect(){
+        $this->connection = mysql_connect(MYSQL_HOST,MYSQL_LOGIN,MYSQL_MDP);
+        mysql_query('SET NAMES utf8');
+        mysql_select_db(MYSQL_BDD,$this->connection);
+    }
+
+
+
+    public function __toString(){
+        $retour = "";
+        $retour .= "instance de la classe MysqlConnector : <br/>";
+        $retour .= '$hote : '.$this->hote.'<br/>';
+        $retour .= '$login : '.$this->login.'<br/>';
+        $retour .= '$mdp : '.$this->mdp.'<br/>';
+        $retour .= '$bdd : '.$this->bdd.'<br/>';
+        $retour .= '$port : '.$this->port.'<br/>';
+        return $retour;
+    }
+
+    private  function __clone(){
+        //Action lors du clonage de l'objet
+    }
+
+    // ACCESSEURS
+
+    public function getId(){
+        return $this->id;
+    }
+
+    public function setId($id){
+        $this->id = $id;
+    }
+
+    /**
+    * Méthode de récuperation de l'attribut hote de la classe Mysql
+    * @author Valentin CARRUESCO
+    * @category Accesseur
+    * @param Aucun
+    * @return <Attribute> hote
+    */
+
+    public function getHote(){
+        return $this->hote;
+    }
+
+    /**
+    * Méthode de définition de l'attribut hote de la classe Mysql
+    * @author Valentin CARRUESCO
+    * @category Accesseur
+    * @param <Attribute> $hote
+    * @return Aucun retour
+    */
+
+    public function setHote($hote){
+        $this->hote = $hote;
+    }
+
+    /**
+    * Méthode de récuperation de l'attribut login de la classe Mysql
+    * @author Valentin CARRUESCO
+    * @category Accesseur
+    * @param Aucun
+    * @return <Attribute> login
+    */
+
+    public function getLogin(){
+        return $this->login;
+    }
+
+    /**
+    * Méthode de définition de l'attribut login de la classe Mysql
+    * @author Valentin CARRUESCO
+    * @category Accesseur
+    * @param <Attribute> $login
+    * @return Aucun retour
+    */
+
+    public function setLogin($login){
+        $this->login = $login;
+    }
+
+    /**
+    * Méthode de récuperation de l'attribut mdp de la classe Mysql
+    * @author Valentin CARRUESCO
+    * @category Accesseur
+    * @param Aucun
+    * @return <Attribute> mdp
+    */
+
+    public function getMdp(){
+        return $this->mdp;
+    }
+
+    /**
+    * Méthode de définition de l'attribut mdp de la classe Mysql
+    * @author Valentin CARRUESCO
+    * @category Accesseur
+    * @param <Attribute> $mdp
+    * @return Aucun retour
+    */
+
+    public function setMdp($mdp){
+        $this->mdp = $mdp;
+    }
+
+    /**
+    * Méthode de récuperation de l'attribut bdd de la classe Mysql
+    * @author Valentin CARRUESCO
+    * @category Accesseur
+    * @param Aucun
+    * @return <Attribute> bdd
+    */
+
+    public function getBdd(){
+        return $this->bdd;
+    }
+
+    /**
+    * Méthode de définition de l'attribut bdd de la classe Mysql
+    * @author Valentin CARRUESCO
+    * @category Accesseur
+    * @param <Attribute> $bdd
+    * @return Aucun retour
+    */
+
+    public function setBdd($bdd){
+        $this->bdd = $bdd;
+    }
+
+    /**
+    * Méthode de récuperation de l'attribut port de la classe Mysql
+    * @author Valentin CARRUESCO
+    * @category Accesseur
+    * @param Aucun
+    * @return <Attribute> port
+    */
+
+    public function getPort(){
+        return $this->port;
+    }
+
+    /**
+    * Méthode de définition de l'attribut port de la classe Mysql
+    * @author Valentin CARRUESCO
+    * @category Accesseur
+    * @param <Attribute> $port
+    * @return Aucun retour
+    */
+
+    public function setPort($port){
+        $this->port = $port;
+    }
 }
 ?>

+ 423 - 423
MysqlEntity.class.php

@@ -2,434 +2,434 @@
 require_once('constant.php');
 require_once('MysqlConnector.class.php');
 /*
-	@nom: MysqlEntity
-	@auteur: Valentin CARRUESCO (valentincarruesco@yahoo.fr)
-	@date de création: 16/04/2012 02:34:15
-	@description: Classe parent de tous les modèles (classe entitées) liées a la base de donnée,
-	 cette classe est configuré pour agir avec une base MySQL, mais il est possible de redefinir ses codes SQL pour l'adapter à un autre SGBD sans affecter
-	 le reste du code du projet.
+    @nom: MysqlEntity
+    @auteur: Valentin CARRUESCO (valentincarruesco@yahoo.fr)
+    @date de création: 16/04/2012 02:34:15
+    @description: Classe parent de tous les modèles (classe entitées) liées a la base de donnée,
+     cette classe est configuré pour agir avec une base MySQL, mais il est possible de redefinir ses codes SQL pour l'adapter à un autre SGBD sans affecter
+     le reste du code du projet.
 
 */
 
 class MysqlEntity
 {
 
-	private $debug = false;
-	private $debugAllQuery = false;
-
-
-	function sgbdType($type){
-		$return = false;
-		switch($type){
-			case 'string':
-			case 'timestamp':
-				$return = 'VARCHAR(225) CHARACTER SET utf8 COLLATE utf8_general_ci';
-			break;
-			case 'longstring':
-				$return = 'TEXT CHARACTER SET utf8 COLLATE utf8_general_ci';
-			break;
-			case 'key':
-				$return = 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY';
-			break;
-			case 'object':
-			case 'integer':
-				$return = 'INT(11)';
-			break;
-			case 'boolean':
-				$return = 'INT(1)';
-			break;
-			default;
-				$return = 'TEXT CHARACTER SET utf8 COLLATE utf8_general_ci';
-			break;
-		}
-		return $return ;
-	}
-
-	/**
-	 * Protège une variable pour MySQL
-	 */
-	protected function secure($value, $field){
-		$type = false;
-
-		// ce champ n'existe pas : on le considère comme une chaîne de caractères
-		if (isset($this->object_fields[$field]))
-			$type = $this->object_fields[$field];
-
-		$return = false;
-		switch($type){
-			case 'key':
-			case 'object':
-			case 'integer':
-			case 'boolean':
-				$return = intval($value);
-			break;
-			case 'string':
-			case 'timestamp':
-			case 'longstring':
-			default;
-				$return = mysql_real_escape_string((string)$value);
-			break;
-		}
-		return $return ;
-	}
-
-	public function __construct(){
-		MysqlConnector::getInstance();
-	}
-
-	public function __destruct(){
-
-	}
-
-	// GESTION SQL
-
-	/**
-	* Methode de suppression de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param <String> $debug=false active le debug mode (0 ou 1)
-	* @return Aucun retour
-	*/
-	public function destroy($debug=false)
-	{
-		$query = 'DROP TABLE IF EXISTS '.MYSQL_PREFIX.$this->TABLE_NAME.';';
-		if($this->debug)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$query.'<br>'.mysql_error();
-		$myQuery = $this->customQuery($query);
-	}
-
-	/**
-	* Methode de nettoyage de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param <String> $debug=false active le debug mode (0 ou 1)
-	* @return Aucun retour
-	*/
-	public function truncate($debug=false)
-	{
-			$query = 'TRUNCATE TABLE '.MYSQL_PREFIX.$this->TABLE_NAME.';';
-			if($this->debug)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$query.'<br>'.mysql_error();
-			$myQuery = $this->customQuery($query);
-	}
-
-	/**
-	* Methode de creation de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param <String> $debug=false active le debug mode (0 ou 1)
-	* @return Aucun retour
-	*/
-	public function create($debug=false){
-		$query = 'CREATE TABLE IF NOT EXISTS `'.MYSQL_PREFIX.$this->TABLE_NAME.'` (';
-
-		$i=false;
-		foreach($this->object_fields as $field=>$type){
-			if($i){$query .=',';}else{$i=true;}
-			$query .='`'.$field.'`  '. $this->sgbdType($type).'  NOT NULL';
-		}
-		if (isset($this->object_fields_index)){
-			foreach($this->object_fields_index as $field=>$type){
-				$query .= ',KEY `index'.$field.'` (`'.$field.'`)';
-			}
-		}
-		$query .= ')
-		ENGINE InnoDB,
-		DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci
-		;';
-		if($this->debug)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$query.'<br>'.mysql_error();
-		$myQuery = $this->customQuery($query);
-	}
-
-	public function massiveInsert($events){
-		if (empty($events)) return;
-		$query = 'INSERT INTO `'.MYSQL_PREFIX.$this->TABLE_NAME.'`(';
-			$i=false;
-			foreach($this->object_fields as $field=>$type){
-				if($type!='key'){
-					if($i){$query .=',';}else{$i=true;}
-					$query .='`'.$field.'`';
-				}
-			}
-			$query .=') select';
-			$u = false;
-
-			foreach($events as $event){
-
-					if($u){$query .=' union select ';}else{$u=true;}
-
-					$i=false;
-					foreach($event->object_fields as $field=>$type){
-						if($type!='key'){
-							if($i){$query .=',';}else{$i=true;}
-							$query .='"'.$this->secure($event->$field, $field).'"';
-						}
-					}
-
-
-			}
-
-			$query .=';';
-			if($this->debug)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$query.'<br>'.mysql_error();
-
-		$this->customQuery($query);
-	}
-
-	/**
-	* Methode d'insertion ou de modifications d'elements de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param  Aucun
-	* @return Aucun retour
-	*/
-	public function save(){
-		if(isset($this->id)){
-			$query = 'UPDATE `'.MYSQL_PREFIX.$this->TABLE_NAME.'`';
-			$query .= ' SET ';
-
-			$i=false;
-			foreach($this->object_fields as $field=>$type){
-				if($i){$query .=',';}else{$i=true;}
-				$id = $this->$field;
-				$query .= '`'.$field.'`="'.$this->secure($id, $field).'"';
-			}
-
-			$query .= ' WHERE `id`="'.$this->id.'";';
-		}else{
-			$query = 'INSERT INTO `'.MYSQL_PREFIX.$this->TABLE_NAME.'`(';
-			$i=false;
-			foreach($this->object_fields as $field=>$type){
-				if($i){$query .=',';}else{$i=true;}
-				$query .='`'.$field.'`';
-			}
-			$query .=')VALUES(';
-			$i=false;
-			foreach($this->object_fields as $field=>$type){
-				if($i){$query .=',';}else{$i=true;}
-				$query .='"'.$this->secure($this->$field, $field).'"';
-			}
-
-			$query .=');';
-		}
-		if($this->debug)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$query.'<br>'.mysql_error();
-		$this->customQuery($query);
-		$this->id =  (!isset($this->id)?mysql_insert_id():$this->id);
-	}
-
-	/**
-	* Méthode de modification d'éléments de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param <Array> $colonnes=>$valeurs
-	* @param <Array> $colonnes (WHERE) =>$valeurs (WHERE)
-	* @param <String> $operation="=" definis le type d'operateur pour la requete select
-	* @param <String> $debug=false active le debug mode (0 ou 1)
-	* @return Aucun retour
-	*/
-	public function change($columns,$columns2,$operation='=',$debug=false){
-		$query = 'UPDATE `'.MYSQL_PREFIX.$this->TABLE_NAME.'` SET ';
-		$i=false;
-		foreach ($columns as $column=>$value){
-			if($i){$query .=',';}else{$i=true;}
-			$query .= '`'.$column.'`="'.$this->secure($value, $column).'" ';
-		}
-		$query .=' WHERE ';
-
-		$i = false;
-		foreach ($columns2 as $column=>$value){
-			if($i){$query .='AND ';}else{$i=true;}
-			$query .= '`'.$column.'`'.$operation.'"'.$this->secure($value, $column).'" ';
-		}
-		if($this->debug)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$query.'<br>'.mysql_error();
-		$this->customQuery($query);
-	}
-
-	/**
-	* Méthode de selection de tous les elements de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param <String> $ordre=null
-	* @param <String> $limite=null
-	* @param <String> $debug=false active le debug mode (0 ou 1)
-	* @return <Array<Entity>> $Entity
-	*/
-	public function populate($order=null,$limit=null,$debug=false){
-		$results = $this->loadAll(array(),$order,$limit,'=',$debug);
-		return $results;
-	}
-
-	/**
-	* Méthode de selection multiple d'elements de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param <Array> $colonnes (WHERE)
-	* @param <Array> $valeurs (WHERE)
-	* @param <String> $ordre=null
-	* @param <String> $limite=null
-	* @param <String> $operation="=" definis le type d'operateur pour la requete select
-	* @param <String> $debug=false active le debug mode (0 ou 1)
-	* @return <Array<Entity>> $Entity
-	*/
-	public function loadAll($columns,$order=null,$limit=null,$operation="=",$debug=false,$selColumn='*'){
-		$objects = array();
-		$whereClause = '';
-
-			if($columns!=null && sizeof($columns)!=0){
-			$whereClause .= ' WHERE ';
-				$i = false;
-				foreach($columns as $column=>$value){
-					if($i){$whereClause .=' AND ';}else{$i=true;}
-					$whereClause .= '`'.$column.'`'.$operation.'"'.$this->secure($value, $column).'"';
-				}
-			}
-			$query = 'SELECT '.$selColumn.' FROM `'.MYSQL_PREFIX.$this->TABLE_NAME.'` '.$whereClause.' ';
-			if($order!=null) $query .='ORDER BY '.$order.' ';
-			if($limit!=null) $query .='LIMIT '.$limit.' ';
-			$query .=';';
-
-			if($this->debug)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$query.'<br>'.mysql_error();
-			$execQuery = $this->customQuery($query);
-			while($queryReturn = mysql_fetch_assoc($execQuery)){
-
-				$object = new $this->CLASS_NAME();
-				foreach($this->object_fields as $field=>$type){
-					if(isset($queryReturn[$field])) $object->$field = $queryReturn[$field];
-				}
-				$objects[] = $object;
-				unset($object);
-			}
-			return $objects;
-	}
-
-		public function loadAllOnlyColumn($selColumn,$columns,$order=null,$limit=null,$operation="=",$debug=false){
-		$objects = $this->loadAll($columns,$order,$limit,$operation,$debug,$selColumn);
-		if(count($objects)==0)$objects = array();
-		return $objects;
-	}
-
-
-	/**
-	* Méthode de selection unique d'élements de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param <Array> $colonnes (WHERE)
-	* @param <Array> $valeurs (WHERE)
-	* @param <String> $operation="=" definis le type d'operateur pour la requete select
-	* @param <String> $debug=false active le debug mode (0 ou 1)
-	* @return <Entity> $Entity ou false si aucun objet n'est trouvé en base
-	*/
-	public function load($columns,$operation='=',$debug=false){
-		$objects = $this->loadAll($columns,null,1,$operation,$debug);
-		if(!isset($objects[0]))$objects[0] = false;
-		return $objects[0];
-	}
-
-	/**
-	* Méthode de selection unique d'élements de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param <Array> $colonnes (WHERE)
-	* @param <Array> $valeurs (WHERE)
-	* @param <String> $operation="=" definis le type d'operateur pour la requete select
-	* @param <String> $debug=false active le debug mode (0 ou 1)
-	* @return <Entity> $Entity ou false si aucun objet n'est trouvé en base
-	*/
-	public function getById($id,$operation='=',$debug=false){
-		return $this->load(array('id'=>$id),$operation,$debug);
-	}
-
-	/**
-	* Methode de comptage des éléments de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param <String> $debug=false active le debug mode (0 ou 1)
-	* @return<Integer> nombre de ligne dans l'entité'
-	*/
-	public function rowCount($columns=null)
-	{
-		$whereClause ='';
-		if($columns!=null){
-			$whereClause = ' WHERE ';
-			$i=false;
-			foreach($columns as $column=>$value){
-					if($i){$whereClause .=' AND ';}else{$i=true;}
-					$whereClause .= '`'.$column.'`="'.$this->secure($value, $column).'"';
-			}
-		}
-		$query = 'SELECT COUNT(1) FROM '.MYSQL_PREFIX.$this->TABLE_NAME.$whereClause;
-		if($this->debug)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$query.'<br>'.mysql_error();
-		$myQuery = $this->customQuery($query);
-		$number = mysql_fetch_array($myQuery);
-		return $number[0];
-	}
-
-	/**
-	* Méthode de suppression d'éléments de l'entité
-	* @author Valentin CARRUESCO
-	* @category manipulation SQL
-	* @param <Array> $colonnes (WHERE)
-	* @param <Array> $valeurs (WHERE)
-	* @param <String> $operation="=" definis le type d'operateur pour la requete select
-	* @param <String> $debug=false active le debug mode (0 ou 1)
-	* @return Aucun retour
-	*/
-	public function delete($columns,$operation='=',$debug=false){
-		$whereClause = '';
-
-			$i=false;
-			foreach($columns as $column=>$value){
-				if($i){$whereClause .=' AND ';}else{$i=true;}
-				$whereClause .= '`'.$column.'`'.$operation.'"'.$this->secure($value, $column).'"';
-			}
-			$query = 'DELETE FROM `'.MYSQL_PREFIX.$this->TABLE_NAME.'` WHERE '.$whereClause.' ;';
-			if($this->debug)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$query.'<br>'.mysql_error();
-			$this->customQuery($query);
-
-	}
-
-	///@TODO: pourquoi deux méthodes différentes qui font la même chose ?
-	public function customExecute($request){
-		if($this->debugAllQuery)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$request.'<br>'.mysql_error();
-		$result = mysql_query($request);
-		if (false===$result) {
-			throw new Exception(mysql_error());
-		}
-		return $result;
-	}
-	public function customQuery($request){
-		if($this->debugAllQuery)echo '<hr>'.$this->CLASS_NAME.' ('.__METHOD__ .') : Requete --> '.$request.'<br>'.mysql_error();
-		$result = mysql_query($request);
-		if (false===$result) {
-			throw new Exception(mysql_error());
-		}