NOUVELLE VERSION !!! Des nouvelles classes de partout, et des supers procédures SQL.

This commit is contained in:
Mysaa
2021-06-06 13:03:33 +02:00
parent e59898b0bb
commit 3488323439
59 changed files with 2906 additions and 1403 deletions
+27
View File
@@ -0,0 +1,27 @@
<?php
class Article {
public static function getNewest($count){
$req = $GLOBALS['bdd']->prepare('SELECT * FROM articles ORDER BY lastNoticeableChangeDate DESC LIMIT '.intval($count));
$req->execute();
$reps = array();
while($rep = $req->fetch()){
$reps[] = array();
$reps[count($reps)-1]['title'] = $rep['title'];
$reps[count($reps)-1]['short'] = $rep['short'];
$reps[count($reps)-1]['text'] = $rep['text'];
$reps[count($reps)-1]['picPath'] = $rep['picPath'];
}
return $reps;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
class Discussion{
public static function createDiscussion($sid,$mdp,$name){
$sid = intval($pseudo);
$mdp = PDO::quote(strval($mdp));
$name = PDO::quote(strval($name));
$rep = $GLOBALS['bdd']->exec('CALL `CreateDiscussion`('.$sid.','.$mdp.','.$name.', @p3 , @p4); SELECT @p3 AS ndiscutID , ID AS outputCode , errorMessage AS message , htmlErrorMessage AS htmlMessage FROM errorReturns WHERE ID = @p4;')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode'],$rep['message'],$rep['htmlMessage']);
return $rep['ndiscutId'];
}
public static function getMessages($sid,$mdp,$did){
$GLOBALS['bdd']->exec('CREATE TEMPORARY TABLE smz (ID INT,senderID INT,senderPseudo VARCHAR(255),texte TEXT,sendTime DATETIME,rights INT(1))');
$req = $GLOBALS['bdd']->prepare('CALL `GetDiscutMessages`(:sid,:mdp,:did, @o)');
$req->bindValue(':sid', $sid);
$req->bindValue(':mdp', $mdp);
$req->bindValue(':did', $did);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
$req = $GLOBALS['bdd']->query('SELECT * FROM smz');
$jmsgs = array();
while($rep=$req->fetch()){
$jmsg = array();
$jmsg['messageID'] = $rep['ID'];
$jmsg['senderID'] = $rep['senderID'];
$jmsg['pseudo'] = $rep['senderPseudo'];
$jmsg['texte'] = $rep['texte'];
$jmsg['sendTime'] = $rep['sendTime'];
$jmsg['sendTimestamp'] = strToTime($rep['sendTime']);
$jmsg['rights'] = $rep['rights'] == 1;
$jmsgs[] = $jmsg;
}
return $jmsgs;
}
public static function getVisibleDiscuts($sid,$mdp){
$GLOBALS['bdd']->exec('CREATE TEMPORARY TABLE discuts (ID INT,name VARCHAR(255),creatorPseudo VARCHAR(255))');
//$rep = $GLOBALS['bdd']->exec('INSERT @t');
$req = $GLOBALS['bdd']->prepare('CALL `GetVisibleDiscuts`(:sid, :mdp, @o, @canCreate)');
$req->bindValue(':sid', $sid);
$req->bindValue(':mdp', $mdp);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode, @canCreate AS canCreate')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
$out = array();
$out['canCreate'] = $rep['canCreate'] == 1;
$req = $GLOBALS['bdd']->query('SELECT * FROM discuts');
$out['discuts'] = array();
while($rep = $req->fetch()){
$dout = array();
$dout['ID'] = intval($rep['ID']);
$dout['name'] = $rep['name'];
$dout['creatorPseudo'] = $rep['creatorPseudo'];
$out['discuts'][] = $dout;
}
return $out;
}
public static function getDiscutInfo($sessionID,$sessionPassword,$did){
$req = $GLOBALS['bdd']->prepare('CALL `GetDiscutInfo`(:ssi,:ssp,:did,@o,@c);');
$req->bindValue(':ssi', $sessionID);
$req->bindValue(':ssp', $sessionPassword);
$req->bindValue(':did', $did);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode, @c AS connected')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
$out = array();
$out['connected'] = $rep['connected'] == 1;
$out['ID'] = intval($did);
return $out;
}
const MALFORMED_DATE = 'La date de cr&eacute;ation doit &ecirc;tre de la forme "AAAA:MM:JJ hh:mm:ss"';
const DATE_CREATION_CHANGED = 'La date de cr&eacute;ation a bien &eacute;t&eacute; chang&eacute;e';
}
+88
View File
@@ -0,0 +1,88 @@
<?php
class Langage{
//FIXME const
public static $java;
public static $vba;
public static $languages = array();
protected $ID;
protected $name;
protected $avalivableFiles;//String "jar xlsx javadoc" in constructor , stored as a string array
public function __construct($ID,$name,$avalivableFiles){
$this->ID = $ID;
$this->name = $name;
$this->avalivableFiles = explode(" ",$avalivableFiles);
Langage::$languages[] = $this;
}
public function getID(){
return $this->ID;
}
public function getName(){
return $this->name;
}
public function getAvalivableFiles(){
return $this->avalivableFiles;
}
public function isJarAvalivable(){
return in_array("jar",$this->avalivableFiles);
}
public function isJavaAvalivable(){
return in_array("java",$this->avalivableFiles);
}
public function isJavadocAvalivable(){
return in_array("javadoc",$this->avalivableFiles);
}
public function isXlsmAvalivable(){
return in_array("xlsm",$this->avalivableFiles);
}
public function isVbAvalivable(){
return in_array("vb",$this->avalivableFiles);
}
public function isJarAccessible($fileAccessibility){
return $this->isJarAvalivable() AND ($fileAccessibility >> array_search("jar",$this->avalivableFiles)) % 2 === 1;
}
public function isJavaAccessible($fileAccessibility){
return $this->isJavaAvalivable() AND ($fileAccessibility >> array_search("java",$this->avalivableFiles)) % 2 === 1;
}
public function isJavadocAccessible($fileAccessibility){
return $this->isJavadocAvalivable() AND ($fileAccessibility >> array_search("javadoc",$this->avalivableFiles)) % 2 === 1;
}
public function isXlsmAccessible($fileAccessibility){
return $this->isXlsmAvalivable() AND ($fileAccessibility >> array_search("xlsm",$this->avalivableFiles)) % 2 === 1;
}
public function isVbAccessible($fileAccessibility){
return $this->isVbAvalivable() AND ($fileAccessibility >> array_search("vb",$this->avalivableFiles)) % 2 === 1;
}
public static function getFromID($ID){
foreach(Langage::$languages AS $language){
if($language->getID() == $ID)
return $language;
}
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){
$languages = array();
foreach($versions AS $version)
array_push($languages,$version->getLanguage());
$languages = array_unique($languages,SORT_REGULAR);
return $languages;
}
}
Langage::$java = new Langage(0, "Java", "jar java javadoc");
Langage::$vba = new Langage(1, "VBA", "xlsm vb");
+327
View File
@@ -0,0 +1,327 @@
<?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 !';
}
+75
View File
@@ -0,0 +1,75 @@
<?php
class Membre {
const DEFAULT_BANNER = "pictures/bande.png";
public static function registerPerson($pseudo,$password){
$req = $GLOBALS['bdd']->prepare('CALL `RegisterPerson`(:ps,:pw,@o);');
$req->bindValue(':ps', $pseudo);
$req->bindValue(':pw', $password);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode, @sid AS membreId')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
}
public static function headerInfos($sessionID,$sessionPassword){
$req = $GLOBALS['bdd']->prepare('CALL `HeaderInfos`(:ssi,:ssp,@o,@c,@p);');
$req->bindValue(':ssi', $sessionID);
$req->bindValue(':ssp', $sessionPassword);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode, @c AS connected, @p AS pseudo')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
$out = array();
$out['connected'] = $rep['connected'] == 1;
$out['pseudo'] = $rep['pseudo'];
return $out;
}
public static function checkLogin($pseudo,$sessionPassword){
$req = $GLOBALS['bdd']->prepare('CALL `CheckLogin`(:ssps,:sspw,@o,@sid);');
$req->bindValue(':ssps', $pseudo);
$req->bindValue(':sspw', $sessionPassword);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode, @sid AS membreId')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
return $rep['membreId'];
}
public static function checkIdLogin($sid,$sessionPassword){
$req = $GLOBALS['bdd']->prepare('CALL `CheckIdLogin`(:sid,:sspw,@o);');
$req->bindValue(':sid', $sid);
$req->bindValue(':sspw', $sessionPassword);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
}
public static function changePassword($sid,$rmdp,$mdp){
var_dump($sid);
var_dump($rmdp);
var_dump($mdp);
$req = $GLOBALS['bdd']->prepare('CALL `ChangePassword`(:ssi,:rmdp,:nmdp,@o);');
$req->bindValue(':ssi', $sid);
$req->bindValue(':rmdp', $rmdp);
$req->bindValue(':nmdp', $mdp);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
class Message{
public static function postMessage($sid,$mdp,$did,$text){
$req = $GLOBALS['bdd']->prepare('CALL `PostMessage`(:sid,:mdp,:did,:text,@o);');
$req->bindValue(':sid', $sid);
$req->bindValue(':mdp', $mdp);
$req->bindValue(':did', $did);
$req->bindValue(':text', $text);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
}
public static function deleteMessage($sid,$mdp,$mid){
$req = $GLOBALS['bdd']->prepare('CALL `DeleteMessage`(:sid,:mdp,:mid,@o);');
$req->bindValue(':sid', $sid);
$req->bindValue(':mdp', $mdp);
$req->bindValue(':mid', $mid);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
}
}
+96
View File
@@ -0,0 +1,96 @@
<?php
class Projet{
public static function getAuthorizedProjectsForPresentation($sid,$mdp){
$GLOBALS['bdd']->exec('CREATE TEMPORARY TABLE projects (projectID INT,projectName VARCHAR(255),versionID INT,versionName VARCHAR(255))');
//$rep = $GLOBALS['bdd']->exec('INSERT @t');
$req = $GLOBALS['bdd']->prepare('CALL `GetAuthorizedProjectsForPresentation`(:sid, :mdp, @o)');
$req->bindValue(':sid', $sid);
$req->bindValue(':mdp', $mdp);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
$req = $GLOBALS['bdd']->query('SELECT * FROM projects');
$out = array();
while($rep = $req->fetch()){
$pout = array();
$pout['projectID'] = $rep['projectID'];
$pout['projectName'] = $rep['projectName'];
$pout['versionID'] = $rep['versionID'];
$pout['versionName'] = $rep['versionName'];
$out[] = $pout;
}
return $out;
}
public static function getPublicProjectsForPresentation($sid,$mdp){
$GLOBALS['bdd']->exec('CREATE TEMPORARY TABLE projects (projectID INT,projectName VARCHAR(255),versionID INT,versionName VARCHAR(255))');
//$rep = $GLOBALS['bdd']->exec('INSERT @t');
$req = $GLOBALS['bdd']->prepare('CALL `GetPublicProjectsForPresentation`(:sid, :mdp, @o)');
$req->bindValue(':sid', $sid);
$req->bindValue(':mdp', $mdp);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
$req = $GLOBALS['bdd']->query('SELECT * FROM projects');
$out = array();
while($rep = $req->fetch()){
$pout = array();
$pout['projectID'] = $rep['projectID'];
$pout['projectName'] = $rep['projectName'];
$pout['versionID'] = $rep['versionID'];
$pout['versionName'] = $rep['versionName'];
$out[] = $pout;
}
return $out;
}
public static function showProject($sid,$mdp,$pid){
$GLOBALS['bdd']->exec('CREATE TEMPORARY TABLE verzions (language INT,ID INT,name VARCHAR(255));
CREATE TEMPORARY TABLE sowners (pseudo VARCHAR(255));');
$req = $GLOBALS['bdd']->prepare('CALL `PresentProject`(:sid, :mdp, :pid, @o, @public, @name, @ownerID, @ownerPseudo)');
$req->bindValue(':sid', $sid);
$req->bindValue(':mdp', $mdp);
$req->bindValue(':pid', $pid);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode,@public AS public,@name AS name,@ownerPseudo AS ownerPseudo,@ownerID AS ownerID')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
//Output
$out = array();
$out['public'] = $rep['public'] == 1;
$out['name'] = $rep['name'];
$out['ownerID'] = $rep['ownerID'];
$out['ownerPseudo'] = $rep['ownerPseudo'];
$req = $GLOBALS['bdd']->query('SELECT * FROM sowners');
$out['sowners'] = array();
while($rep = $req->fetch()){
$sowner = array();
$sowner['pseudo'] = $rep['pseudo'];
$out['sowners'][] = $sowner;
}
$req = $GLOBALS['bdd']->query('SELECT * FROM verzions');
$out['versions'] = array();
while($rep = $req->fetch()){
$version = array();
$version['language'] = $rep['language'];
$version['ID'] = $rep['ID'];
$version['name'] = $rep['name'];
$out['versions'][] = $version;
}
return $out;
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
class SQLProcessingException extends Exception{
private $errorCode;
private $Dmessage;
private $htmlMessage;
private $preferredRedirection;
public function __construct($errorCode){
$req = $GLOBALS['bdd']->prepare('SELECT errorMessage,htmlErrorMessage,preferredRedirection FROM errorReturns WHERE ID=?');
$req->execute(array(intval($errorCode)));
$rep = $req->fetch();
$this->errorCode = $errorCode;
$this->Dmessage = $rep['errorMessage'];
$this->htmlMessage = $rep['htmlErrorMessage'] ?? $rep['errorMessage'];
$this->preferredRedirection = (empty($rep['preferredRedirection'] != ""))?NULL:$rep['preferredRedirection'];
parent::__construct('Erreur '.$errorCode.' : '.$this->Dmessage);
error_log($this);
}
public function getPreferredRedirection(){
return $this->preferredRedirection;
}
public function getHtmlMessage(){
return $this->htmlMessage;
}
}
+153
View File
@@ -0,0 +1,153 @@
<?php
class InvalidOperatorException extends Exception{
public $type;
public $operator;
public function __construct ($type,$operator){
parent::__construct('Invalid operator "'.$operator.'" for the type '.$type);
}
}
class Utility{
/*
* <> ou !=
...les deux valeurs ne sont pas égales
<
...la valeur de gauche est strictement inférieure à celle de droite
>
...la valeur de gauche est strictement supérieure à celle de droite
<=
...la valeur de gauche est strictement inférieure ou égale à celle de droite
>=
...la valeur de gauche est strictement supérieure ou égale à celle de droite
BETWEEN..AND
...la valeur testée est située entre deux valeurs données
IN
...la valeur testée se situe dans une liste valeurs données
NOT IN
...la valeur testée ne se situe pas dans une liste de valeurs données
LIKE
...la valeur de gauche correspond à celle de droite (celle de droite peux utiliser le caractère % pour simuler n'importe quel nombre de caractère, et _ pour un seul caractère
NOT LIKE
...les deux valeurs ne correspondent pas
REGEXP ou RLIKE
...la valeur de gauche correspond à l'expression régulière donnée
NOT REGEXP
...la valeur de gauche ne correspond pas à l'expression régulière donnée
*/
public static function getIntegerSqlOperator($operator){
switch ($operator){
case '=':
return '=';
case '<':
return '<';
case '>':
return '>';
case '<=':
return '<=';
case '>=':
return '>=';
case '=<':
return '<=';
case '<>':
return '<>';
case '!=':
return '!=';
case '!<':
return '!<';
case '!>':
return '!>';
default:
throw new InvalidOperatorException('integer',$operator);
}
}
public static function getStringSqlOperator($operator){
switch ($operator){
case '=':
return '=';
case '&like;':
return 'LIKE';
default:
throw new InvalidOperatorException('string',$operator);
}
}
public static function getDateSqlOperator($operator){
switch ($operator){
case '=':
return '=';
case '<':
return '<';
case '>':
return '>';
case '<=':
return '<=';
case '>=':
return '>=';
case '=<':
return '<=';
case '<>':
return '<>';
case '!=':
return '!=';
case '!<':
return '!<';
case '!>':
return '!>';
default:
throw new InvalidOperatorException('date',$operator);
}
}
public static function arrayIfNot($var){
if(!is_array($var))
return $var!=NULL?array($var):NULL;
return $var;
}
public static function getHierarchicCouple(){
return array("Pr&eacute;sident","Ministres");
}
public static function sqlProcedure($procedureName,$params,$output){
$Nparams = array();
$Oparams = array();
foreach($params AS $value)
switch(gettype($value)){
case 'boolean':$Nparams[]=($value)?'TRUE':'FALSE';break;
case 'integer':$Nparams[]=strval($value);break;
case 'double':$Nparams[]=strval($value);break;
case 'string':$Nparams[]=PDO::quote($value);break;
default:$Nparams[]='NULL';break;
}
for($i=0;$i<count($output);$i++){
$Nparams[]='@'.strval($i);
$Oparams[]='@'.strval($i).' AS '.PDO::quote($output[$i]);
}
$rep = $GLOBALS['bdd']->exec('CALL '.PDO::quote($procedureName).'('.implode($Nparams,',').'); SELECT @p2 AS `outputCode`;');
}
const SUCESSFULLY_REGISTERED = 'Vous avez d&eacute;j&agrave; &eacute;t&eacute; correctement inscrit sur bernard.com';
const SUCESSFULLY_LOGGED_IN = 'Vous &ecirc;tes bien connect&eacute; (vous l\'avez &eacute;t&eacute; et le serez &eacute;galement)!';
const SUCESSFULLY_CHANGED_PASSWORD = 'Vos dispositifs d\'identification ont &eacute;t&eacute; correctement chang&eacute;s';
const SUCESSFULLY_CREATED_DISCUSSION = 'C\'est fait !!! (la cr&eacute;ation de ta discussion bien s&ucirc;r)';
const LOGIN_NEEDED_FOR_PROJECTS = 'Je veut bien &ecirc;tre un site web parfait, mais j\'aimerai bien qut tu te conn&egrave;cte pour que je puisse te montrer tes projets';
}
+58
View File
@@ -0,0 +1,58 @@
<?php
class Version{
public static function editVersion ($sid,$mdp,$v,$name,$langage,$tags,$insertIndex){
$sid = intval($sid);
$mdp = $GLOBALS['bdd']->quote(strval($mdp));
$v = intval($v);
$name = $name?$GLOBALS['bdd']->quote(strval($name)):'NULL';
$langage = $langage?intval($langage):'NULL';
$tags = $tags?$GLOBALS['bdd']->quote($tags):'NULL';
$insertIndex = $insertIndex?intval($insertIndex):'NULL';
$rep = $GLOBALS['bdd']->exec('CALL `EditVersion`('.$sid.','.$mdp.','.$v.','.$name.','.$langage.','.$tags.','.$insertIndex.', @p8); SELECT ID AS outputCode , errorMessage AS message , htmlErrorMessage AS htmlMessage FROM errorReturns WHERE ID = @p8;')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode'],$rep['message'],$rep['htmlMessage']);
}
public static function showVersion($sid,$mdp,$vid){
$GLOBALS['bdd']->exec('CREATE TEMPORARY TABLE verzions (language INT,ID INT,name VARCHAR(255));');
$req = $GLOBALS['bdd']->prepare('CALL `PresentVersion`(:sid, :mdp, :vid, @o, @su,@ssu,@langageID,@projectName,@name,@fileAccessibility,@projectID,@tags)');
$req->bindValue(':sid', $sid);
$req->bindValue(':mdp', $mdp);
$req->bindValue(':vid', $vid);
$req->execute();
$rep = $GLOBALS['bdd']->query('SELECT @o AS outputCode,@su AS su,@ssu AS ssu,@langageID AS langage,@projectName AS projectName,@name AS name,@fileAccessibility AS fileAccessibility,@projectID AS projectID,@tags AS tags')->fetch();
if($rep['outputCode'] != 42)throw new SQLProcessingException($rep['outputCode']);
//Output
$out = array();
$out['su'] = $rep['su'] == 1;
$out['ssu'] = $rep['ssu'] == 1;
$out['langage'] = $rep['langage'];
$out['projectName'] = $rep['projectName'];
$out['name'] = $rep['name'];
$out['ID'] = $vid;
$out['fileAccessibility'] = $rep['fileAccessibility'];
$out['projectID'] = $rep['projectID'];
$out['alpha'] = ($rep['tags'] >> 0) % 2 === 1;
$out['beta'] = ($rep['tags'] >> 1) % 2 === 1;
$out['release'] = ($rep['tags'] >> 2) % 2 === 1;
$out['bugged'] = ($rep['tags'] >> 3) % 2 === 1;
$req = $GLOBALS['bdd']->query('SELECT * FROM verzions');
$out['brothers'] = array();
while($rep = $req->fetch()){
$version = array();
$version['language'] = $rep['language'];
$version['ID'] = $rep['ID'];
$version['name'] = $rep['name'];
$out['brothers'][] = $version;
}
return $out;
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
try{
$link = mysql_connect("localhost", "u890869027", "*******************");
//$GLOBALS['bdd'] = new PDO('mysql:host=localhost;dbname=u890869027_bcom2;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());
}
//TODO in the classes , do more test of exists in setters
include_once 'clazz/2/Utility.class.php';
include_once 'clazz/2/Langage.class.php';
include_once 'clazz/2/Membre.class.php';
include_once 'clazz/2/Discussion.class.php';
include_once 'clazz/2/Message.class.php';
include_once 'clazz/2/Projet.class.php';
include_once 'clazz/2/Article.class.php';
//TODO Use class's consts for file names
include_once 'clazz/2/Version.class.php';
-47
View File
@@ -1,47 +0,0 @@
<?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
@@ -0,0 +1,327 @@
<?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 !';
}
-720
View File
@@ -1,720 +0,0 @@
<?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
@@ -1,18 +0,0 @@
<?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;
}
}
+23 -37
View File
@@ -9,71 +9,57 @@ class InvalidOperatorException extends Exception{
}
class Utility{
public static const PasswordMissmatch = 'Tu auras du rentrer deux fois le m&ecirc;me mot de passe (tu permet aussi de rendre le champs "Recopier le mot de passe" utile)';
public static const InvalidPseudo = 'Le pseudo sera incorrect : Les seuls caract&egrave;res autoris&eacute;s sont :<br/>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
public static const InvalidPassword = 'Le mot de passe fut incorrect : Les seuls caract&egrave;res autoris&eacute;s sont :<br/>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_&&eacute;&egrave;&agrave;&ugrave;&ccedil;&mu;"#\'{}()[]|^@+=$*!:/;.,?'
public static function isPseudoValid($pseudo){
return preg_match ( "#^[a-zA-Z0-9\\-_]+$#", $pseudo ) === 1;
}
public static function isPasswordValid($password){
return preg_match ( "#^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\\-_&\"\\#'{}()[\\]|\\^@+=\$*!:/;.,?]+$#", $password ) === 1;
}
/*
* <> ou !=
...les deux valeurs ne sont pas égales
...les deux valeurs ne sont pas égales
<
...la valeur de gauche est strictement inférieure à celle de droite
...la valeur de gauche est strictement inférieure à celle de droite
>
...la valeur de gauche est strictement supérieure à celle de droite
...la valeur de gauche est strictement supérieure à celle de droite
<=
...la valeur de gauche est strictement inférieure ou égale à celle de droite
...la valeur de gauche est strictement inférieure ou égale à celle de droite
>=
...la valeur de gauche est strictement supérieure ou égale à celle de droite
...la valeur de gauche est strictement supérieure ou égale à celle de droite
BETWEEN..AND
...la valeur testée est située entre deux valeurs données
...la valeur testée est située entre deux valeurs données
IN
...la valeur testée se situe dans une liste valeurs données
...la valeur testée se situe dans une liste valeurs données
NOT IN
...la valeur testée ne se situe pas dans une liste de valeurs données
...la valeur testée ne se situe pas dans une liste de valeurs données
LIKE
...la valeur de gauche correspond à celle de droite (celle de droite peux utiliser le caractère % pour simuler n'importe quel nombre de caractère, et _ pour un seul caractère
...la valeur de gauche correspond à celle de droite (celle de droite peux utiliser le caractère % pour simuler n'importe quel nombre de caractère, et _ pour un seul caractère
NOT LIKE
...les deux valeurs ne correspondent pas
REGEXP ou RLIKE
...la valeur de gauche correspond à l'expression régulière donnée
...la valeur de gauche correspond à l'expression régulière donnée
NOT REGEXP
...la valeur de gauche ne correspond pas à l'expression régulière donnée
...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){
+10 -10
View File
@@ -1,19 +1,19 @@
<?php
try{
$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=127.0.0.1;dbname=u890869027_bcom;charset=utf8;port=3306', '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());
}
//TODO in the classes , do more test of exists in setters
include_once 'clazz/Utility.class.php';
include_once 'clazz/Langage.class.php';
include_once 'clazz/Membre.class.php';
include_once 'clazz/Discussion.class.php';
include_once 'clazz/Message.class.php';
include_once 'clazz/Projet.class.php';
include_once 'clazz/Article.class.php';
include_once 'clazz/2/SQLProcessingException.class.php';
include_once 'clazz/2/Utility.class.php';
include_once 'clazz/2/Langage.class.php';
include_once 'clazz/2/Membre.class.php';
include_once 'clazz/2/Discussion.class.php';
include_once 'clazz/2/Message.class.php';
include_once 'clazz/2/Projet.class.php';
include_once 'clazz/2/Article.class.php';
//TODO Use class's consts for file names
include_once 'clazz/Version.class.php';
include_once 'clazz/2/Version.class.php';
+19
View File
@@ -0,0 +1,19 @@
<?php
try{
$GLOBALS['bdd'] = new PDO('mysql:host=localhost;dbname=u890869027_bcom2;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());
}
//TODO in the classes , do more test of exists in setters
include_once 'clazz/Utility.class.php';
include_once 'clazz/Langage.class.php';
include_once 'clazz/Membre.class.php';
include_once 'clazz/Discussion.class.php';
include_once 'clazz/Message.class.php';
include_once 'clazz/Projet.class.php';
include_once 'clazz/Article.class.php';
//TODO Use class's consts for file names
include_once 'clazz/Version.class.php';