Nouvelle classe Membre, différente. D'autres modifs....

This commit is contained in:
Mysaa
2021-06-06 12:54:42 +02:00
parent 38ec48c9fc
commit e59898b0bb
42 changed files with 2006 additions and 455 deletions
+1 -2
View File
@@ -23,7 +23,7 @@ class Article {
$this->text = $rep['text'];
$this->postDate = $rep['postDate'];
$this->lastNoticeableChangeDate = $rep['lastNoticeableChangeDate'];
$this->lastChange = $rep['lastChange'];
$this->lastChange = $rep['lastChangeDate'];
$this->picPath = $rep['picPath'];
}else{
$this->valid = FALSE;
@@ -119,7 +119,6 @@ class Article {
$req = $GLOBALS['bdd']->prepare('SELECT * FROM articles ORDER BY lastNoticeableChangeDate DESC LIMIT '.intval($count));
$req->execute();
$reps = array();
$GLOBALS['bdd']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
while($rep = $req->fetch()){
$reps[] = new Article($rep['ID']);
}
+7 -1
View File
@@ -49,7 +49,13 @@ class Langage{
if($language->getID() == $ID)
return $language;
}
//var_dump(Langage::$languages);
return NULL;
}
public static function getFromName($name){
foreach(Langage::$languages AS $language){
if($language->getName() == $name)
return $language;
}
return NULL;
}
public static function getLanguagesFromVersions($versions){
+47
View File
@@ -0,0 +1,47 @@
<?php
class MegaFile{
protected $ID;
protected $where;
protected $args;
public function __construct($where,$args = array()){
$this->where = $where;
$this->args = $args;
}
public function is(){
$req = $GLOBALS['bdd']->prepare('SELECT COUNT(ID) AS count FROM megaFile WHERE ' . $where);//TODO changeto megaFileSSSSS
$req->execute($args);
return !!$req->fetch();
}
public static function addVersionFile($version,$fileType,$publicy){
try {
$path = '/Root/bernard.com/projets/' .
$version->getProject()->getName() . '/' .
$version->getLanguage()->getName() . '/' .
$version->getName().'/';
$pathFile = MegaFile::getFromPath($path);
if($pathFile->is())
return USED_PATH;
$pathFile = new MegaFile('fileType=? AND ');
if($pathFile->is())
return USED_PATH;
$req = $GLOBALS['bdd']->prepare('INSERT INTO megaFile (fileType,path,publicy) VALUES (?,?,?)');//TODO changeto megaFileSSSSS
$req->execute(array($fileType,$path,$publicy));
}catch(NoneObjectCallException $e){
return NONE_VERSION;
}
}
public static function getFromPath($path){
return new MegaFile('path=?',array($path));
}
public const NONE_VERSION = "sshfzrgh";
}
-327
View File
@@ -1,327 +0,0 @@
<?php
class Membre {
protected $ID;
protected $accountID;
protected $accountPassword;
protected $owner;
protected $liberties;// [ [ read , read ],[ write , write ] ]
protected $path;
protected $size;
protected $valid;
public function __construct($ID) {
$this->ID = $ID;
$req = $GLOBALS['bdd']->prepare('SELECT * FROM megaStockages WHERE ID=?');
$req->execute(array($ID));
if($rep = $req->fetch()){
$this->valid = TRUE;
$this->accountID = $rep['accountID'];
$this->accountPassword = $rep['accountPassword'];
$this->owner = new Membre($rep['owner']);
$this->liberties = /* TODO parse liberties */$rep['liberties'];
$this->path = $rep['path'];
$this->size = $rep['size'];
}else{
$this->valid = FALSE;
}
}
public function __toString(){
$out = 'MegaStockage\n';
$out .= '\tID:' . $this->ID . '\n';
$out .= '\tAccount ID:' . $this->accountID . '\n';
$out .= '\tAccount password' . $this->adminLevel . '\n';
$out .= '\tOwner:' . $this->owner->__toString() . '\n';
$out .= '\tLiberties:' . $this->liberties . '\n';
$out .= '\tPath:' . $this->path . '\n';
$out .= '\tSize:' . $this->size . '\n';
return $out;
}
public function exists(){
return $this->valid;
}
//Getters
//TODO gen getters
//Useful getters
public function canRead($he){
$read = $this->liberties[0];
if($read=='public')
return TRUE;
else if(in_array($he->getID(),$read)
return TRUE;
return FALSE;
}
public function canWrite($he){
$write = $this->liberties[1];
if($write=='public')
return TRUE;
else if(in_array($he->getID(),$write)
return TRUE;
return FALSE;
}
//Setters
public function setAttribute($attribute,$value,$valueType){
//TODO todo
$json=FALSE;
switch ($attribute){
case 'ID':
if($valueType !== '0'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = intval($value);
break;
case 'pseudo':
if($valueType !== '"'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($value).'"';
break;
case 'hashedPseudo':
if($valueType !== '"'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($value).'"';
break;
case 'adminLevel':
if($valueType !== '0'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = intval($value);
break;
case 'dateCreation':
if($valueType !== '"'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.$value.'"';
break;
case 'requiredBanner'://FIXME jsonMysqlProblem
$json=TRUE;
if($valueType !== '"'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($value).'"';
break;
case 'personnalMessage':
$json=TRUE;
if($valueType !== '"'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($value).'"';
break;
default:
echo 'Undefined attribute "'.$attribute.'" for the class Membre';
exit;
}
$restrictionValues[] = $value;
if($json){
//TODO Set command for json
}else{
$command = 'UPDATE membres SET ' . $attribute . '=' . $value . ' WHERE ID=' . $this->ID;
}
echo $command.'</br>';
$req = $GLOBALS['bdd']->prepare($command);
$req->execute(array());
if($req->errorInfo()[0] != 0){
echo 'Eine MYSQL Exception hat geworft. Einschuldigung';
exit;
}
}
/**
*
* @return Objects which matchs the specified restrictions
*/
public static function getFromAttributes($restrictions){
$whereCommands = array();
$restrictionValues = array();
foreach ($restrictions as $restriction){
$whereCommand = NULL;
$attribute = $restriction[0];
$json = FALSE;
$operator = NULL;
$value = NULL;
try {
switch ($attribute){
case 'ID':
if($restriction[2][0] !== '0'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = intval($restriction[2][1]);
$operator = Utility::getIntegerSqlOperator($restriction[1]);
break;
case 'pseudo':
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
case 'hashedPseudo':
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
case 'adminLevel':
if($restriction[2][0] !== '0'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = intval($restriction[2][1]);
$operator = Utility::getIntegerSqlOperator($restriction[1]);
break;
case 'dateCreation':
if($restriction[2][0] !== '"'){//TODO add type date
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.$restriction[2][1].'"';
$operator = Utility::getDateSqlOperator($restriction[1]);
break;
case 'requiredBanner'://FIXME jsonMysqlProblem
$json=TRUE;
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
case 'personnalMessage':
$json=TRUE;
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
default:
echo 'Undefined attribute "'.$attribute.'" for the class Membre';
exit;
}
}catch(InvalidOperatorException $e){
echo $e->getMessage().' when reading attribute "'.$attribute.'"';
exit;
}
$restrictionValues[] = $value;
if($json){
$whereCommand = '((data->"$.'.$attribute.'" IS NOT NULL) AND (data->"$.'.$attribute.'" '.$operator.' ? ))';
}else{
$whereCommand = $attribute . ' ' . $operator . ' ' . $value;
}
$whereCommands[] = $whereCommand;
}
$wherePart = "";
if(count($whereCommands) >0)
$wherePart = 'WHERE '.implode(' AND ',$whereCommands);
$command = 'SELECT * FROM membres '.$wherePart;
$req = $GLOBALS['bdd']->prepare($command);
$req->execute($restrictionValues);
echo $command.'</br>';
if($req->errorInfo()[0] != 0)
echo 'Erreur SQL, veuillez verifier les selecteurs';
$out = array();
while($rep = $req->fetch())
$out[] = new Membre($rep['ID']);
//Choose return value
switch(count($out)){
case 0:
return NULL;
case 1:
return $out[0];
default:
return $out;
}
}
public static function getFromPseudo($pseudo){
return Membre::getFromAttributes(array(['pseudo','=',['"',$pseudo]]));
}
public static function getFromAdminLevel($level){
return Membre::getFromAttributes(array(['adminLevel','=',['0',$level]]));
}
public static function getFromDateCreation($date){
return Membre::getFromAttributes(array(['dateCreation','=',['0',$date]]));
}
public static function getCreatedLaterThan($date){
return Membre::getFromAttributes(array(['dateCreation','>',['"',$date]]));
}
public static function getCreatedEarlierThan($date){
return Membre::getFromAttributes(array(['dateCreation','<',['"',$date]]));
}
public static function getAdminGreaterThan($min){
return Membre::getFromAttributes(array(['adminLevel','>',['0',$min]]));
}
public static function getAdminLowerThan($max){
return Membre::getFromAttributes(array(['adminLevel','<',['0',$max]]));
}
public static function me(){
if(!isset($_SESSION['session_id']))
return NULL;
$me = new Membre($_SESSION['session_id']);
if(!$me->exists())
return NULL;
return $me;
}
//Membre creator
public static function registerPerson($pseudo, $mdp) {
if (Membre::getFromPseudo($pseudo))
return Membre::USED_USERNAME;
$req = $GLOBALS ['bdd']->prepare ('INSERT INTO membres(pseudo,mdp,date_creation) VALUES (?,?,NOW())');
$req->execute (array($pseudo,password_hash( $mdp, PASSWORD_DEFAULT)));
return Membre::PERSON_REGISTERED;
}
//Operateurs
public function __is_identical($copain){
return $this->getID() == $copain->getID();
}
//Outputs texts
//changePassword
const PASSWORD_TOO_LONG = 'Le mot de passe est trop long ! (Max : 255 caract&egrave;res)';
const PASSWORD_CHANGED = 'Le mot de passe a bien &eacute;t&eacute; chang&eacute;';
//registerPerson
const USED_USERNAME = 'Le pseudonyme est d&eacute;j&agrave; utilis&eacute;';
const PERSON_REGISTERED = 'Le membre a bien &eacute;t&eacute; inscrit !';
}
+1 -1
View File
@@ -297,7 +297,7 @@ class Membre {
$command = 'SELECT * FROM membres '.$wherePart;
$req = $GLOBALS['bdd']->prepare($command);
$req->execute($restrictionValues);
echo $command.'</br>';
//echo $command.'</br>';
if($req->errorInfo()[0] != 0)
echo 'Erreur SQL, veuillez verifier les selecteurs';
$out = array();
+720
View File
@@ -0,0 +1,720 @@
<?php
class Membre {
const DEFAULT_BANNER = "pictures/bande.png";
protected $ID = NULL;
protected $IDLoaded = FALSE;
protected $pseudo = NULL;
protected $pseudoLoaded = FALSE;
protected $hashedPassword = NULL;
protected $hashedPasswordLoaded = FALSE;
protected $adminLevel = NULL;
protected $adminLevelLoaded = FALSE;
protected $dateCreation = NULL;
protected $dateCreationLoaded = FALSE;
protected $requiredBanner = NULL;
protected $requiredBannerLoaded = FALSE;
protected $personnalMessage;
protected $personnalMessageLoaded = FALSE;
protected $count = NULL;
protected $where;
protected $whereArgs;
protected const ATTRIBUTES = array('ID','pseudo','hashedPassword','dateCreation','adminLevel','data');
protected function __construct($where,$whereArgs = array()) {
$this->where = $where;
$this->whereArgs = $whereArgs;
}
public static function me(){
if(!isset($_SESSION['session_id']))
return NO_SESSION_ID;
return new Membre('WHERE ID=?');
}
public static function getFromAttributes($restrictions){
$whereCommands = array();
$restrictionValues = array();
foreach ($restrictions as $restriction){
$whereCommand = NULL;
$attribute = $restriction[0];
$json = FALSE;
$operator = NULL;
$value = NULL;
try {
switch ($attribute){
case 'ID':
if($restriction[2][0] !== '0'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = intval($restriction[2][1]);
$operator = Utility::getIntegerSqlOperator($restriction[1]);
break;
case 'pseudo':
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
case 'hashedPseudo':
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
case 'adminLevel':
if($restriction[2][0] !== '0'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = intval($restriction[2][1]);
$operator = Utility::getIntegerSqlOperator($restriction[1]);
break;
case 'dateCreation':
if($restriction[2][0] !== '"'){//TODO add type date
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.$restriction[2][1].'"';
$operator = Utility::getDateSqlOperator($restriction[1]);
break;
case 'requiredBanner'://FIXME jsonMysqlProblem
$json=TRUE;
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
case 'personnalMessage':
$json=TRUE;
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
default:
echo 'Undefined attribute "'.$attribute.'" for the class Membre';
exit;
}
}catch(InvalidOperatorException $e){
echo $e->getMessage().' when reading attribute "'.$attribute.'"';
exit;
}
$restrictionValues[] = $value;
if($json){
$whereCommand = '((data->"$.'.$attribute.'" IS NOT NULL) AND (data->"$.'.$attribute.'" '.$operator.' ? ))';
}else{
$whereCommand = $attribute . ' ' . $operator . ' ' . $value;
}
$whereCommands[] = $whereCommand;
}
$wherePart = "";
if(count($whereCommands) >0)
$wherePart = 'WHERE '.implode(' AND ',$whereCommands);
$command = 'SELECT * FROM membres '.$wherePart;
$req = $GLOBALS['bdd']->prepare($command);
$req->execute($restrictionValues);
//echo $command.'</br>';
if($req->errorInfo()[0] != 0)
echo 'Erreur SQL, veuillez verifier les selecteurs';
$out = array();
while($rep = $req->fetch())
$out[] = new Membre($rep['ID']);
//Choose return value
switch(count($out)){
case 0:
return NULL;
case 1:
return $out[0];
default:
return $out;
}
}
public static function with($conditions){//[ { 'adminLevel' , '>=' , 24 } , { requiredBanner , '/home/banner.png' } , { email } ]
$wheres = array();
$whereAttributes = array();
foreach($conditions as $condition){
//TODO support custom conditions (OR, NAND)
//TODO test !is_array()
switch(count($condition)){
case 0:
throw new MalformedConditionException($conditions,'Une condition ne peut pas être NULL , voyons ...'));
break;
case 1:
assert(in_array($condition[0],Membre::ATTRIBUTES),new MalformedConditionException($conditions,'$condition[0] n\'est pas un attribut de la classe membre !'));
$wheres[] = $condition[0] . ' NOT NULL';
break;
case 2:
assert(in_array($condition[0],Membre::ATTRIBUTES),new MalformedConditionException($conditions,'$condition[0] n\'est pas un attribut de la classe membre !'));
$wheres[] = $condition[0] . ' = ?';
$whereAttributes[] = $condition[1];
break;
case 3:
assert(in_array($condition[0],Membre::ATTRIBUTES),new MalformedConditionException($conditions,'$condition[0] n\'est pas un attribut de la classe membre !'));
$operator = Utility::getSqlOperator($condition[2]);
assert($operator !== NULL,new MalformedConditionException($conditions,'$condition[2] n\'est pas un opérateur valide !'));
$wheres[] = $condition[0] . ' ' . $operator . ' ?';
$whereAttributes[] = $condition[1];
break;
default:
throw new MalformedConditionException($conditions,'Cette version du site ne comprends pas encore les conditions avec plus de trois paramètres (' . json_encode($condition); . ')');
}
}
$where = implode(' AND ',$wheres);
return new Membre($where,$whereAttributes);
}
public static function withPseudo($pseudo){
return new Membre('WHERE pseudo=?',array($pseudo));
}
public static function withAdminLevel($level){
return new Membre('WHERE adminLevel=?',array($level));
}
public static function withAdminLevelGreaterThan($level){
return new Membre('WHERE adminLevel>?',array($level));
}
public static function withAdminLevelLowerThan($level){
return new Membre('WHERE adminLevel<?',array($level));
}
public static function withDateCreation($date){
return new Membre('WHERE dateCreation=?',array($pseudo));
}
public static function withDateCreationLaterThan($date){
return new Membre('WHERE dateCreation>?',array($pseudo));
}
public static function withDateCreationEarlierThan($date){
return new Membre('WHERE dateCreation<?',array($pseudo));
}
public function checkPassword($password) {
return password_verify ($password, $this->getHashedPassword() );
}
public function __toString(){
return 'Membre with "' . $where . '" args:{' . $whereArgs . '}';
}
/**
@returns
Si le Membre est unique et que le dernier paramètre est faux (valeur par défaut)
@return [ 'ID' => 12 , 'pseudo' => "Mysaa" ]
Si le Membre est plurier ou si le dernier paramètre est vrai
@return [ { 'ID' => 12 , 'pseudo' => "Mysaa" } , { 'ID' => 11 , 'pseudo' => "Zlopeg" } ]
**/
public function get(){
$objects = func_get_args();
assert(count($objects) < 1, new BadMethodCallException('La methode get requiert au moins un argument'));
$array = end($objects);
if(gettype($array) !== 'boolean')
$array=FALSE;
else
array_pop($objects);
assert(count($objectsCount) < 1, new BadMethodCallException('La methode get requiert au moins un nom de paramètre à retourner !'));
$toAsk = array();
$toGive = array();
foreach($objects as $object){
assert(!is_string($object), new InvalidArgumentException('"$object" n\'est pas une chaine de caractère ... ça devrait'))
assert(in_array($object,Membre::ATTRIBUTES),new InvalidArgumentException('$object n\'est pas un attribut de la classe membre !'));
if($this->{$object . 'Loaded'})
array_push($toGive,$object);
else
array_push($toAsk,$object);
}
$result = array();
if(count($toAsk)>0){
$req = $GLOBALS['bdd']->prepare('SELECT ' . implode(',',$toAsk) . 'FROM membres WHERE ' . $this->where);
$req->execute($this->whereArgs);
$sqlResult = $req->fetchAll(PDO::FETCH_COLUMN | PDO::FETCH_GROUP);
foreach($toAsk as $item){
if(!isset($this->count))$this->count = count($item);
$this->$item = $sqlResult[$item];
$this->{$item . 'Loaded'} = TRUE;
$result[$item] = $sqlResult[$item];
}
}
foreach($toGive as $item)
$result[$item] = $this->$item;
/* RETURN */
if(count($result) === 0)
return $array?array():NULL;
$return = array()
if(!$array AND $this->count === 1)
foreach($result as $item => $values)$return[$key] = $values[0];
else
foreach($result as $key=>$res)
for($i=0;$i<$this->count;$i++)
$return[$i][$key] = $res[$i]
return $return;
}
public function count(){
if($this->count)return $this->count;
$req = $GLOBALS['bdd']->prepare('SELECT COUNT(*) AS count FROM membres WHERE ' . $this->where);
$req->execute($this->whereArgs);
return $req->fetch()['count'];
}
public function __call($funcName,$params){
if(preg_match('^get',$funcName)){// TODO Support multi get ("getPseudoAndAdminLevel")
$attributeName = lcfirst(substr($funcName,3))
assert(in_array($attributeName,Membre::ATTRIBUTES), new BadMethodCallException('$attributeName n\'est pas un attribut de la classe membre !'));
$return = call_user_func_array(array($this,'get'),array($attributeName));
return (count($return)===1)?$return[0]:$return;
}
}
public function get(){
$objects = func_get_args();
assert(count($objects) < 2, new BadMethodCallException('La methode set requiert au moins deux argument'));
$objectsCount = count($objects);
assert($objectsCount % 2 === 0, new BadMethodCallException('La methode set requiert un nombre pair d\'arguments'));
foreach($objects as $object){
assert(!is_string($object), new InvalidArgumentException('"$object" n\'est pas une chaine de caractère ... ça devrait'))
assert(in_array($object,Membre::ATTRIBUTES),new InvalidArgumentException('$object n\'est pas un attribut de la classe membre !'));
if($this->{$object . 'Loaded'})//FIXME to complete get -> set
array_push($toGive,$object);
else
array_push($toAsk,$object);
}
$result = array();
if(count($toAsk)>0){
$req = $GLOBALS['bdd']->prepare('SELECT ' . implode(',',$toAsk) . 'FROM membres WHERE ' . $this->where);
$req->execute($this->whereArgs);
$sqlResult = $req->fetchAll(PDO::FETCH_COLUMN | PDO::FETCH_GROUP);
foreach($toAsk as $item){
if(!isset($this->count))$this->count = count($item);
$this->$item = $sqlResult[$item];
$this->{$item . 'Loaded'} = TRUE;
$result[$item] = $sqlResult[$item];
}
}
foreach($toGive as $item)
$result[$item] = $this->$item;
/* RETURN */
if(count($result) === 0)
return $array?array():NULL;
$return = array()
if(!$array AND $this->count === 1)
foreach($result as $item => $values)$return[$key] = $values[0];
else
foreach($result as $key=>$res)
for($i=0;$i<$this->count;$i++)
$return[$i][$key] = $res[$i]
return $return;
}
private function decodeData($data) {
$jsonData = json_decode ( $data ,TRUE);
// Set the data's required_banner if it is defined , otherwise sets the DEFAULT_BANNER
$this->requiredBanner = $jsonData ['requiredBanner'] ?? self::DEFAULT_BANNER;
$this->personnalMessage = $jsonData ['personnalMessage'] ?? NULL;
}
//Getters
public function getID(){
return $this->ID;
}
public function getPseudo(){
return $this->pseudo;
}
public function getAdminLevel() {
return $this->adminLevel;
}
public function getDateCreation(){
return $this->dateCreation;
}
public function getRequiredBanner() {
return $this->requiredBanner;
}
public function getPersonnalMessage(){
return $this->personnalMessage;
}
//Useful getters
public function isAdminLevelLowerThan($max){
return $this->adminLevel<$max;
}
public function isAdminLevelGreaterThan($min){
return $this->adminLevel>$min;
}
public function isAdminLevelLowerOrEqualThan($max){
return $this->adminLevel<$max;
}
public function isAdminLevelGreaterOrEqualThan($min){
return $this->adminLevel>$max;
}
public function hasPersonnalMessage() {
return isset ( $this->personnalMessage );
}
public function showPersonnalMessage() {
$msg = $this->personnalMessage;
$this->setPersonnalMessage = NULL;
return $msg;
}
//Setters
public function changePassword($newPassword){
if(strlen($newPassword)>255)
return Membre::PASSWORD_TOO_LONG;
$req = $GLOBALS['bdd']->prepare('UPDATE membres SET hashedPassword=? WHERE ID=?');
$req->execute(array(password_hash ( $newPassword, PASSWORD_DEFAULT ),$this->ID));
return Membre::PASSWORD_CHANGED;
}
public function setAttribute($attribute,$value,$valueType){
$json=FALSE;
switch ($attribute){
case 'ID':
if($valueType !== '0'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = intval($value);
break;
case 'pseudo':
if($valueType !== '"'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($value).'"';
break;
case 'hashedPseudo':
if($valueType !== '"'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($value).'"';
break;
case 'adminLevel':
if($valueType !== '0'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = intval($value);
break;
case 'dateCreation':
if($valueType !== '"'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.$value.'"';
break;
case 'requiredBanner'://FIXME jsonMysqlProblem
$json=TRUE;
if($valueType !== '"'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($value).'"';
break;
case 'personnalMessage':
$json=TRUE;
if($valueType !== '"'){
echo 'Error : the type "'.$valueType.'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($value).'"';
break;
default:
echo 'Undefined attribute "'.$attribute.'" for the class Membre';
exit;
}
$restrictionValues[] = $value;
if($json){
//TODO Set command for json
}else{
$command = 'UPDATE membres SET ' . $attribute . '=' . $value . ' WHERE ID=' . $this->ID;
}
echo $command.'</br>';
$req = $GLOBALS['bdd']->prepare($command);
$req->execute(array());
if($req->errorInfo()[0] != 0){
echo 'Eine MYSQL Exception hat geworft. Einschuldigung';
exit;
}
}
/**
*
* @return Objects which matchs the specified restrictions
*/
public static function getFromAttributes($restrictions){
$whereCommands = array();
$restrictionValues = array();
foreach ($restrictions as $restriction){
$whereCommand = NULL;
$attribute = $restriction[0];
$json = FALSE;
$operator = NULL;
$value = NULL;
try {
switch ($attribute){
case 'ID':
if($restriction[2][0] !== '0'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = intval($restriction[2][1]);
$operator = Utility::getIntegerSqlOperator($restriction[1]);
break;
case 'pseudo':
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
case 'hashedPseudo':
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
case 'adminLevel':
if($restriction[2][0] !== '0'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = intval($restriction[2][1]);
$operator = Utility::getIntegerSqlOperator($restriction[1]);
break;
case 'dateCreation':
if($restriction[2][0] !== '"'){//TODO add type date
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.$restriction[2][1].'"';
$operator = Utility::getDateSqlOperator($restriction[1]);
break;
case 'requiredBanner'://FIXME jsonMysqlProblem
$json=TRUE;
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
case 'personnalMessage':
$json=TRUE;
if($restriction[2][0] !== '"'){
echo 'Error : the type "'.$restriction[2][0].'" is not allowed for the attribute '.$attribute;
exit;
}
$value = '"'.strval($restriction[2][1]).'"';
$operator = Utility::getStringSqlOperator($restriction[1]);
break;
default:
echo 'Undefined attribute "'.$attribute.'" for the class Membre';
exit;
}
}catch(InvalidOperatorException $e){
echo $e->getMessage().' when reading attribute "'.$attribute.'"';
exit;
}
$restrictionValues[] = $value;
if($json){
$whereCommand = '((data->"$.'.$attribute.'" IS NOT NULL) AND (data->"$.'.$attribute.'" '.$operator.' ? ))';
}else{
$whereCommand = $attribute . ' ' . $operator . ' ' . $value;
}
$whereCommands[] = $whereCommand;
}
$wherePart = "";
if(count($whereCommands) >0)
$wherePart = 'WHERE '.implode(' AND ',$whereCommands);
$command = 'SELECT * FROM membres '.$wherePart;
$req = $GLOBALS['bdd']->prepare($command);
$req->execute($restrictionValues);
//echo $command.'</br>';
if($req->errorInfo()[0] != 0)
echo 'Erreur SQL, veuillez verifier les selecteurs';
$out = array();
while($rep = $req->fetch())
$out[] = new Membre($rep['ID']);
//Choose return value
switch(count($out)){
case 0:
return NULL;
case 1:
return $out[0];
default:
return $out;
}
}
public static function getFromPseudo($pseudo){
return Membre::getFromAttributes(array(['pseudo','=',['"',$pseudo]]));
}
public static function getFromAdminLevel($level){
return Membre::getFromAttributes(array(['adminLevel','=',['0',$level]]));
}
public static function getFromDateCreation($date){
return Membre::getFromAttributes(array(['dateCreation','=',['0',$date]]));
}
public static function getCreatedLaterThan($date){
return Membre::getFromAttributes(array(['dateCreation','>',['"',$date]]));
}
public static function getCreatedEarlierThan($date){
return Membre::getFromAttributes(array(['dateCreation','<',['"',$date]]));
}
public static function getAdminGreaterThan($min){
return Membre::getFromAttributes(array(['adminLevel','>',['0',$min]]));
}
public static function getAdminLowerThan($max){
return Membre::getFromAttributes(array(['adminLevel','<',['0',$max]]));
}
//Membre creator
public static function registerPerson($pseudo, $mdp) {
if (Membre::getFromPseudo($pseudo))
return Membre::USED_USERNAME;
$req = $GLOBALS ['bdd']->prepare ('INSERT INTO membres(pseudo,mdp,date_creation) VALUES (?,?,NOW())');
$req->execute (array($pseudo,password_hash( $mdp, PASSWORD_DEFAULT)));
return Membre::PERSON_REGISTERED;
}
//Operateurs
public function __is_identical($copain){
return $this->getID() == $copain->getID();
}
//Outputs texts
const NO_SESSION_ID = 0;
//changePassword
const PASSWORD_TOO_LONG = 'Le mot de passe est trop long ! (Max : 255 caract&egrave;res)';
const PASSWORD_CHANGED = 'Le mot de passe a bien &eacute;t&eacute; chang&eacute;';
//registerPerson
const USED_USERNAME = 'Le pseudonyme est d&eacute;j&agrave; utilis&eacute;';
const PERSON_REGISTERED = 'Le membre a bien &eacute;t&eacute; inscrit !';
}
+18
View File
@@ -0,0 +1,18 @@
<?php
class NoneObjectCallException extends Exception
{
public function __construct($message, $code = 0)
{
parent::__construct($message, $code);
}
public function __construct($functionName, $className, $code = 0)
{
parent::__construct('You tried to call the function ' . $functionName . ' on a ' . $className . 'pointing on nothing. Try catch me the next time !', $code);
}
public function __toString()
{
return $this->message;
}
}
+57 -7
View File
@@ -20,7 +20,7 @@ class Projet{
$this->owner = new Membre($rep['ownerID']);
$this->dateCreation = $rep['dateCreation'];
$this->secondaryOwners = array();
foreach (explode(';',$rep['secondaryOwnersID']) AS $secondaryOwner)
foreach (($rep['secondaryOwnersID']!="")?explode(';',$rep['secondaryOwnersID']):[] AS $secondaryOwner)
$this->secondaryOwners[] = new Membre($secondaryOwner);
$this->publik = $rep['public'];
}else{
@@ -40,6 +40,7 @@ class Projet{
foreach($this->secondaryOwners AS $secondaryOwner)
$out .= '\tSecondary owner:{' . substr(str_replace('\n\t',';',$secondaryOwner->__toString()),0,-1) . '}\n';
$out .= '\tDate of creation:' . $this->dateCreation . '\n';
$out .= '\tPublic:' . $this->publik == "1" . '\n';
return $out;
}
@@ -65,7 +66,7 @@ class Projet{
}
public function isPublic(){
return $this->publik == 1;
return $this->publik;
}
@@ -78,9 +79,21 @@ class Projet{
public function setSecondaryOwners($secondaryOwners){
$this->secondaryOwners = $secondaryOwners;
$secondaryOwnersID = array();
foreach($secondaryOwners AS $secondaryOwner)$secondaryOwnersID[] = $secondaryOwner->getID();
$req = $GLOBALS['bdd']->prepare('UPDATE projets SET secondaryOwners=? WHERE ID=?');
$req->execute(array(implode(';',$secondaryOwnersID),$this->ID));
foreach($secondaryOwners as $secondaryOwner)$secondaryOwnersID[] = $secondaryOwner->getID();
$req = $GLOBALS['bdd']->prepare('UPDATE projets SET secondaryOwnersID=? WHERE ID=?');
$req->execute(array(implode(';',$secondaryOwnersID),$this->getID()));
}
public function setPublicy($publicy){
$this->publik = $publicy;
$req = $GLOBALS['bdd']->prepare('UPDATE projets SET public=? WHERE ID=?');
$req->execute(array($publicy?1:0,$this->getID()));
}
public function setOwner($nOwner){
$this->owner = $nOwner;
$req = $GLOBALS['bdd']->prepare('UPDATE projets SET ownerID=? WHERE ID=?');
$req->execute(array($nOwner->getID(),$this->getID()));
}
public function addSecondaryOwner($secondaryOwner){
@@ -159,7 +172,7 @@ class Projet{
}
public static function getWhichHeCanAccess($he){
//TODO Faire la selection directement grâce à une requette SQL
//TODO Faire la selection directement gràce à une reqete SQL
$req = $GLOBALS['bdd']->prepare('SELECT * FROM projets');
$req->execute(array());
$out = array();
@@ -184,7 +197,7 @@ class Projet{
$out = array();
while ( $rep = $req->fetch()) {
$projet = new Projet($rep['ID']);
if ($he?$he->isAdminLevelGreaterThan(12):FALSE || $projet->isPublic())
if ($he?$he->isAdminLevelGreaterThan(12):FALSE || $projet->isPublic() == '1')
$out[] = $projet;
}
switch(count($out)){
@@ -197,5 +210,42 @@ class Projet{
}
}
public function delete(){
$req = $GLOBALS['bdd']->prepare('DELETE FROM projets WHERE ID=?');
$req->execute(array($this->getID()));
$this->valid = FALSE;
}
public function newVersion($name,$langage,$tags,$insertIndex){
if(Version::getFromProjectAndName($this, $name))
return USED_NAME;
if(!preg_match("#^[a-zA-Z0-9\\-_+ ]+$#", $name ))
return INVALID_NAME;
if(Version::getFromProjectLanguageAndVersionAbs($this,$langage, $insertIndex))
return USED_INDEX;
$req = $GLOBALS['bdd']->prepare('INSERT INTO versions (name,sendDate,publicFiles,tags,projectID,languageID,versionAbs) VALUES (?,NOW(),"",?,?,?,?)');
$req->execute(array($name,$tags,$this->getID(),$langage->getID(),$insertIndex));
return VERSION_CREATED;
}
public function editVersion($versionToEdit,$name,$langage,$tags,$insertIndex){
$namedVersion = Version::getFromProjectAndName($this, $name);
if(($namedVersion)?$namedVersion->getID() != $versionToEdit->getID():FALSE)
return USED_NAME;
if(!preg_match("#^[a-zA-Z0-9\\-_+ ]+$#", $name ))
return INVALID_NAME;
$versionedVersion = Version::getFromProjectLanguageAndVersionAbs($this,$langage, $insertIndex);
if(($versionedVersion)?$versionedVersion->getID() != $versionToEdit->getID():FALSE)
return USED_INDEX;
$req = $GLOBALS['bdd']->prepare('UPDATE versions SET name=?,tags=?,languageID=?,versionAbs=? WHERE ID=?');
$req->execute(array($name,$tags,$langage->getID(),$insertIndex,$versionToEdit->getID()));
return VERSION_EDITED;
}
const INVALID_NAME = "sfygmal";
const USED_NAME = "cflmfyqsdlm";
const USED_INDEX = "jhmvm";
const VERSION_CREATED = "jzbtdbgv";
const VERSION_EDITED = "jzbqgsderftdbgv";
}
+31 -1
View File
@@ -48,6 +48,32 @@ NOT REGEXP
...la valeur de gauche ne correspond pas à l'expression régulière donnée
*/
public static function getSqlOperator($operator){
switch ($operator){
case '=':
return '=';
case '<':
return '<';
case '>':
return '>';
case '<=':
return '<=';
case '>=':
return '>=';
case '=<':
return '<=';
case '<>':
return '<>';
case '!=':
return '!=';
case '!<':
return '!<';
case '!>':
return '!>';
default:
return NULL;
}
}
public static function getIntegerSqlOperator($operator){
switch ($operator){
@@ -116,8 +142,12 @@ NOT REGEXP
public static function arrayIfNot($var){
if(!is_array($var))
return array($var);
return $var!=NULL?array($var):NULL;
return $var;
}
public static function getHierarchicCouple(){
return array("Pr&eacute;sident","Ministres");
}
}
+19
View File
@@ -258,6 +258,18 @@ class Version{
}
}
public static function getFromProjectAndName($project,$name){
$req = $GLOBALS['bdd']->prepare('SELECT * FROM versions WHERE projectID=? AND name=?');
$req->execute(array($project->getID(),$name));
return Version::versionGetterOutput($req);
}
public static function getFromProjectLanguageAndVersionAbs($project,$language,$versionAbs){
$req = $GLOBALS['bdd']->prepare('SELECT * FROM versions WHERE projectID=? AND languageID=? AND versionAbs=?');
$req->execute(array($project->getID(),$language->getID(),$versionAbs));
return Version::versionGetterOutput($req);
}
public static function getFromLanguage($language){
$req = $GLOBALS['bdd']->prepare('SELECT * FROM versions WHERE languageID=?');
$req->execute(array($language->getID()));
@@ -321,6 +333,13 @@ class Version{
return Version::versionGetterOutput($req);
}
public function delete(){
$req = $GLOBALS['bdd']->prepare('DELETE FROM versions WHERE ID=?');
$req->execute(array($this->getID()));
$this->valid = FALSE;
}
+2 -2
View File
@@ -1,8 +1,8 @@
<?php
try{
//$GLOBALS['bdd'] = new PDO('mysql:host=127.0.0.1;dbname=u890869027_bcom;charset=utf8', 'u890869027', '*******************');
$GLOBALS['bdd'] = new PDO('mysql:host=mysql.hostinger.fr;dbname=u890869027_bcom;charset=utf8', 'u890869027_bcom', '*******************');
$GLOBALS['bdd'] = new PDO('mysql:host=localhost;dbname=u890869027_bcom;charset=utf8', 'u890869027', '*******************', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));error_reporting(E_ALL);
//$GLOBALS['bdd'] = new PDO('mysql:host=mysql.hostinger.fr;dbname=u890869027_bcom;charset=utf8', 'u890869027_bcom', '*******************');
}catch(Exception $e){
die ('Erreur : ' . $e->getMessage());
}