diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..031b40e --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,16 @@ +in(__DIR__. "/src") +; + +$config = new PhpCsFixer\Config(); +return $config->setRules([ + '@PSR12' => true, + 'multiline_comment_opening_closing' => true, + 'align_multiline_comment' => ['comment_type' => 'phpdocs_like'], + //'strict_param' => true, + 'array_syntax' => ['syntax' => 'short'], + ]) + ->setFinder($finder) +; diff --git a/src/Auth.php b/src/Auth.php index be8d649..615787c 100644 --- a/src/Auth.php +++ b/src/Auth.php @@ -1,28 +1,34 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** User authentication (abstract class) */ +/** + * User authentication (abstract class) + */ class Auth { - /** The application name */ + /** + * The application name + */ public $appName = null; - /** Display the authentication page - * The message is displayed to the user in case of error - * The url is the caller url to go back if authentication is correct - * @param string $baseURL The URL base to use for the links - * @param string|null $message Message to display to the user - * @param string|null $url URL to go back after successful authentication - * @param mixed $alreadyAuth If the user is already authenticated, the value - * will be displayed if the user is coming on the page. - */ + /** + * Display the authentication page + * The message is displayed to the user in case of error + * The url is the caller url to go back if authentication is correct + * @param string $baseURL The URL base to use for the links + * @param string|null $message Message to display to the user + * @param string|null $url URL to go back after successful authentication + * @param mixed $alreadyAuth If the user is already authenticated, the value + * will be displayed if the user is coming on the page. + */ public function pageHTML($baseURL, $message = "", $url = "", $alreadyAuth = false) { $res = ""; @@ -155,8 +161,9 @@ class Auth return $res; } - /** Establish the connection to authentication server - */ + /** + * Establish the connection to authentication server + */ public function connect() { throw new \Exception( @@ -168,12 +175,13 @@ class Auth ); } - /** Check if the email and password are correct - * Return TRUE if the authentication is correct - * Return an exception if there is a problem - * @param string $email Email to authenticate - * @param string $password Password to authenticate - */ + /** + * Check if the email and password are correct + * Return TRUE if the authentication is correct + * Return an exception if there is a problem + * @param string $email Email to authenticate + * @param string $password Password to authenticate + */ public function authentication($email, $password) { throw new \Exception(dgettext( @@ -182,8 +190,9 @@ class Auth ), 405); } - /** Return all the parameters recorded for the authenticate user - */ + /** + * Return all the parameters recorded for the authenticate user + */ public function getdetails() { throw new \Exception(dgettext( @@ -192,11 +201,12 @@ class Auth ), 405); } - /** Method to change the password - * @param string $oldpassword The old password (to check if the user have the - * rights to change the password) - * @param string $newpassword The new password to be recorded - */ + /** + * Method to change the password + * @param string $oldpassword The old password (to check if the user have the + * rights to change the password) + * @param string $newpassword The new password to be recorded + */ public function changepassword($oldpassword, $newpassword) { throw new \Exception(dgettext( @@ -205,12 +215,13 @@ class Auth ), 405); } - /** Method to overwrite the password (without oldpassword check) - * Must be reserved to the administrators. For the users, use changepassword - * method - * @param string $email the user identifier to select - * @param string $newpassword The new password to be recorded - */ + /** + * Method to overwrite the password (without oldpassword check) + * Must be reserved to the administrators. For the users, use changepassword + * method + * @param string $email the user identifier to select + * @param string $newpassword The new password to be recorded + */ public function overwritepassword($email, $newpassword) { throw new \Exception(dgettext( @@ -219,9 +230,10 @@ class Auth ), 405); } - /** List all the users available in the database - * Return firstname, lastname, mail, with mail is an array - */ + /** + * List all the users available in the database + * Return firstname, lastname, mail, with mail is an array + */ public function listusers() { throw new \Exception(dgettext( @@ -230,8 +242,9 @@ class Auth ), 405); } - /** Method to disconnect the authenticated user - */ + /** + * Method to disconnect the authenticated user + */ public function logout() { throw new \Exception(dgettext( diff --git a/src/Authentication.php b/src/Authentication.php index dbd7bf2..b8cead9 100644 --- a/src/Authentication.php +++ b/src/Authentication.php @@ -1,88 +1,113 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** All the authentication protocol */ +/** + * All the authentication protocol + */ class Authentication { - /** The email of the authenticated/nonauthenticated user */ + /** + * The email of the authenticated/nonauthenticated user + */ //private $email = "anonymous"; - /** The debug of the authentication methods */ + /** + * The debug of the authentication methods + */ public $debug = 0; - /** The route object */ + /** + * The route object + */ private $route; - /** Number of authentication maximum by minute */ + /** + * Number of authentication maximum by minute + */ public $ratelimitAuth = 3; - /** Directory to store the ratelimit files */ + /** + * Directory to store the ratelimit files + */ public $ratelimitDir = "/tmp/ratelimit/"; - /** The rest authentication methods. Can be post, session, http, shibboleth, - * jwt - * Attention : session case = CSRF ! - */ - public $restMethods = array("http", "jwt"); + /** + * The rest authentication methods. Can be post, session, http, shibboleth, + * jwt + * Attention : session case = CSRF ! + */ + public $restMethods = ["http", "jwt"]; - /** The html authentication methods. Can be : post, session, http, shibboleth, - * jwt - * The "post" is already used when using verifAuthLoginPage method (usually - * only in authentication page) - */ - public $htmlMethods = array("session"); + /** + * The html authentication methods. Can be : post, session, http, shibboleth, + * jwt + * The "post" is already used when using verifAuthLoginPage method (usually + * only in authentication page) + */ + public $htmlMethods = ["session"]; - /** The authentication methods. Can be ldap, sympa...*/ - public $authMethods = array(); + /** + * The authentication methods. Can be ldap, sympa... + */ + public $authMethods = []; - /** The authentication servers configuration - * array ("authXXXX" => array ( - * array ("ldapserver" => "ldaps://server.domain.fr", - * "ldapport" => 636, - * "ldaptimeout" => 5, - * "ldapauth" => "uid=XXX,dc=domain,dc=fr", - * "ldappwd" => "XXX", - * "ldapbase" => "", - * "ldapfilter" => "(mail=%s)", - * "ldapfield" => "mail", - * "ldapfiltersearch" => "(objectClass=inetOrgPerson)" - * ), - * ), - * ); - */ - public $authServers = array(); + /** + * The authentication servers configuration + * array ("authXXXX" => array ( + * array ("ldapserver" => "ldaps://server.domain.fr", + * "ldapport" => 636, + * "ldaptimeout" => 5, + * "ldapauth" => "uid=XXX,dc=domain,dc=fr", + * "ldappwd" => "XXX", + * "ldapbase" => "", + * "ldapfilter" => "(mail=%s)", + * "ldapfield" => "mail", + * "ldapfiltersearch" => "(objectClass=inetOrgPerson)" + * ), + * ), + * ); + */ + public $authServers = []; - /** The application Name displayed on authentication page */ + /** + * The application Name displayed on authentication page + */ public $appName = null; - /** The class and method to use to log the errors */ + /** + * The class and method to use to log the errors + */ public $loggingFunc; - /** The constructor - * @param object $route The route object - */ + /** + * The constructor + * @param object $route The route object + */ public function __construct($route) { $this->route = $route; - $this->loggingFunc = array($this, "logging"); + $this->loggingFunc = [$this, "logging"]; } /* public function email () { return $this->email; - }*/ + } + */ - /** Setter/Getter for debug - * @param integer|null $debug The debug value to get/set - * @return integer|self the actual value or this - */ + /** + * Setter/Getter for debug + * @param integer|null $debug The debug value to get/set + * @return integer|self the actual value or this + */ public function debug($debug = null) { if ($debug === null) { @@ -92,10 +117,11 @@ class Authentication return $this; } - /** Disconnect the user - * @param string|null $url The url to be redirected after a valid - * logout - */ + /** + * Disconnect the user + * @param string|null $url The url to be redirected after a valid + * logout + */ public function logout($url = "") { // TODO : Foreach authentication methods->logout (); @@ -163,10 +189,11 @@ class Authentication } } - /** Display the login page - * @param string|null $url The url to be redirected after a valid - * authentication - */ + /** + * Display the login page + * @param string|null $url The url to be redirected after a valid + * authentication + */ public function pageHTML($url = "") { // If the user is already connected, redirect to the main page of the site @@ -174,7 +201,7 @@ class Authentication session_start(); } $auth = new Auth(); - $authparams = new Authparams(array("session")); + $authparams = new Authparams(["session"]); if (isset($_SESSION["domframework"]["authentication"]["message"])) { $message = $_SESSION["domframework"]["authentication"]["message"]; } else { @@ -197,10 +224,11 @@ class Authentication ); } - /** Check the authentication page - * @param string|null $url The url to be redirected after a valid - * authentication - */ + /** + * Check the authentication page + * @param string|null $url The url to be redirected after a valid + * authentication + */ public function verifAuthLoginPage($url = "") { if (session_id() === "") { @@ -236,7 +264,7 @@ class Authentication $this->route->redirect("/authentication/$url", ""); } } - $authparams = new Authparams(array("post")); + $authparams = new Authparams(["post"]); $res = $this->verifAuth($authparams->email, $authparams->password); if (! is_array($res)) { if ($this->debug) { @@ -299,11 +327,12 @@ class Authentication } } - /** Check all the REST API - * @param boolean|null $savePassword return the user password if the - * authentication is valid - * @return array The details provided by the authentication mecanism - */ + /** + * Check all the REST API + * @param boolean|null $savePassword return the user password if the + * authentication is valid + * @return array The details provided by the authentication mecanism + */ public function verifAuthREST($savePassword = false) { if ($this->debug) { @@ -311,7 +340,7 @@ class Authentication print_r($this->restMethods, true) . ")\n"; } $authparams = new Authparams($this->restMethods); - $res = array("email" => "anonymous", "password" => "anonymous"); + $res = ["email" => "anonymous", "password" => "anonymous"]; if ( $authparams->email !== "anonymous" && $authparams->password !== "anonymous" @@ -336,12 +365,13 @@ class Authentication return $res; } - /** Return the JSON Web Token - * @param string|array $auth The user data to store in JSON Web Token cache. - * The $this->authServers["authjwt"]["algorithm"], - * $this->authServers["authjwt"]["cipherKey"] and - * $this->authServers["authjwt"]["serverKey"] can be set - */ + /** + * Return the JSON Web Token + * @param string|array $auth The user data to store in JSON Web Token cache. + * The $this->authServers["authjwt"]["algorithm"], + * $this->authServers["authjwt"]["cipherKey"] and + * $this->authServers["authjwt"]["serverKey"] can be set + */ public function createJwtToken($auth) { if (isset($this->authServers["authjwt"]["serverKey"])) { @@ -358,7 +388,7 @@ class Authentication if (isset($this->authServers["authjwt"]["cacheDir"])) { $cacheDir = $this->authServers["authjwt"]["cacheDir"]; } - $payloadArray = array(); + $payloadArray = []; $payloadArray["email"] = $auth; if (is_array($auth)) { $payloadArray = $auth; @@ -378,9 +408,10 @@ class Authentication } } - /** Check all the others pages of the site - * @return array The details provided by the authentication mecanism - */ + /** + * Check all the others pages of the site + * @return array The details provided by the authentication mecanism + */ public function verifAuthHTML() { // Do not force the session_start ! We don't want the cookie on all the @@ -395,8 +426,8 @@ class Authentication if ($this->debug) { echo "Anonymous\n"; } - return array("email" => "anonymous", "lastname" => "Anonymous", - "firstname" => "", "password" => ""); + return ["email" => "anonymous", "lastname" => "Anonymous", + "firstname" => "", "password" => ""]; } if ($this->debug) { echo "verifAuth ($authparams->email, $authparams->password)\n"; @@ -420,14 +451,15 @@ class Authentication return $res; } - /** Do the real authentication process on all the providers defined in the - * properties of the class. - * @param string $email The email to check - * @param string $password The password to check - * @return array containing the user data if the authentication is - * correct, - * an exception if noting is found - */ + /** + * Do the real authentication process on all the providers defined in the + * properties of the class. + * @param string $email The email to check + * @param string $password The password to check + * @return array containing the user data if the authentication is + * correct, + * an exception if noting is found + */ private function verifAuth($email, $password) { if ($this->debug) { @@ -469,7 +501,7 @@ class Authentication // If only one server is defined, the parameters can directely be pushed // to the classname if (! is_array(reset($authServers[$classname]))) { - $authServers[$classname] = array($authServers[$classname]); + $authServers[$classname] = [$authServers[$classname]]; } if ($this->debug >= 2) { echo "Authentication method=$method : authServers=" . @@ -523,9 +555,10 @@ class Authentication return dgettext("domframework", "Bad login/password"); } - /** Add the authentication routes to the routing model for HTML - * authentication. Not needed if using shibboleth, HTTP auth... - */ + /** + * Add the authentication routes to the routing model for HTML + * authentication. Not needed if using shibboleth, HTTP auth... + */ public function routes() { $authObj = $this; @@ -561,11 +594,12 @@ class Authentication $this->route->authenticationURL = "/authentication/"; } - /** The default method to display the error messages. - * Do not display the debug messages, and write the errors on screen - * @param integer $priority The priority of the message - * @param string $message The message to log - */ + /** + * The default method to display the error messages. + * Do not display the debug messages, and write the errors on screen + * @param integer $priority The priority of the message + * @param string $message The message to log + */ private function logging($priority, $message) { if ($this->debug === 0 && $priority > 4) { diff --git a/src/Authhtpasswd.php b/src/Authhtpasswd.php index 6585040..87f6b65 100644 --- a/src/Authhtpasswd.php +++ b/src/Authhtpasswd.php @@ -1,26 +1,34 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** User authentication against .htpasswd file - A .htpasswd can be created by the 'htpasswd' command for Apache, and contain - toto@toto.com:$2y$05$uHCUNqicE7Pku3MK1qZaDuJxP/pocqCcEAnacZBjsfWgW9EcuG5y2 - */ +/** + * User authentication against .htpasswd file + * A .htpasswd can be created by the 'htpasswd' command for Apache, and contain + * toto@toto.com:$2y$05$uHCUNqicE7Pku3MK1qZaDuJxP/pocqCcEAnacZBjsfWgW9EcuG5y2 + */ class Authhtpasswd extends Auth { - /** The .htpasswd file to use for authentication */ + /** + * The .htpasswd file to use for authentication + */ public $htpasswdFile; - /** The details to return if the user is authenticated */ + /** + * The details to return if the user is authenticated + */ private $details = null; - /** There is no real connection to htpasswd */ + /** + * There is no real connection to htpasswd + */ public function connect() { if (! file_exists($this->htpasswdFile)) { @@ -43,9 +51,11 @@ class Authhtpasswd extends Auth } } - /** Try to authenticate the email/password of the user - @param string $email Email to authenticate - @param string $password Password to authenticate */ + /** + * Try to authenticate the email/password of the user + * @param string $email Email to authenticate + * @param string $password Password to authenticate + */ public function authentication($email, $password) { // Redo the checks of connect to not have a property to add @@ -70,23 +80,27 @@ class Authhtpasswd extends Auth if (crypt($password, $cryptedPassword) !== $cryptedPassword) { throw new \Exception("Bad password for '$email'", 401); } - $this->details = array("email" => $email); + $this->details = ["email" => $email]; return true; } } throw new \Exception("Unable to find the user : '$email'", 401); } - /** Return all the parameters recorded for the authenticate user */ + /** + * Return all the parameters recorded for the authenticate user + */ public function getdetails() { return $this->details; } - /** Method to change the password - @param string $oldpassword The old password (to check if the user have the - rights to change the password) - @param string $newpassword The new password to be recorded */ + /** + * Method to change the password + * @param string $oldpassword The old password (to check if the user have the + * rights to change the password) + * @param string $newpassword The new password to be recorded + */ public function changepassword($oldpassword, $newpassword) { throw new \Exception( @@ -98,11 +112,13 @@ class Authhtpasswd extends Auth ); } - /** Method to overwrite the password (without oldpassword check) - Must be reserved to the administrators. For the users, use changepassword - method - @param string $email the user identifier to select - @param string $newpassword The new password to be recorded */ + /** + * Method to overwrite the password (without oldpassword check) + * Must be reserved to the administrators. For the users, use changepassword + * method + * @param string $email the user identifier to select + * @param string $newpassword The new password to be recorded + */ public function overwritepassword($email, $newpassword) { throw new \Exception( diff --git a/src/Authimap.php b/src/Authimap.php index 8954d19..baa603e 100644 --- a/src/Authimap.php +++ b/src/Authimap.php @@ -1,29 +1,44 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** User authentication against IMAP server */ +/** + * User authentication against IMAP server + */ class Authimap extends Auth { - /** IMAP server */ + /** + * IMAP server + */ public $imapServer = "localhost"; - /** IMAP TCP port (143 by default) */ + /** + * IMAP TCP port (143 by default) + */ public $imapPort = 143; - /** IMAP SSL connection */ + /** + * IMAP SSL connection + */ public $imapSSL = false; - /** IMAP SSL CheckCertificate */ + /** + * IMAP SSL CheckCertificate + */ public $imapSSLCheckCertificates = true; - /** The details available after authentication */ + /** + * The details available after authentication + */ private $details = null; - /** Check the availablity of the IMAP support in PHP */ + /** + * Check the availablity of the IMAP support in PHP + */ public function __construct() { if (!function_exists("imap_open")) { @@ -31,16 +46,20 @@ class Authimap extends Auth } } - /** Establish the connection to IMAP server. Don't do anything as the - needed parameters are username and password */ + /** + * Establish the connection to IMAP server. Don't do anything as the + * needed parameters are username and password + */ public function connect() { // Nothing to do } - /** Try to authenticate the email/password of the user - @param string $email Email to authenticate - @param string $password Password to authenticate */ + /** + * Try to authenticate the email/password of the user + * @param string $email Email to authenticate + * @param string $password Password to authenticate + */ public function authentication($email, $password) { $imap = new Imap( @@ -51,21 +70,25 @@ class Authimap extends Auth $this->imapSSL, $this->imapSSLCheckCertificates ); - $this->details = array("email" => $email); + $this->details = ["email" => $email]; // Let the throw Exception be catched by the parent return true; } - /** Return all the parameters recorded for the authenticate user */ + /** + * Return all the parameters recorded for the authenticate user + */ public function getdetails() { return $this->details; } - /** Method to change the password - @param string $oldpassword The old password (to check if the user have the - rights to change the password) - @param string $newpassword The new password to be recorded */ + /** + * Method to change the password + * @param string $oldpassword The old password (to check if the user have the + * rights to change the password) + * @param string $newpassword The new password to be recorded + */ public function changepassword($oldpassword, $newpassword) { throw new \Exception(dgettext( @@ -74,11 +97,13 @@ class Authimap extends Auth ), 405); } - /** Method to overwrite the password (without oldpassword check) - Must be reserved to the administrators. For the users, use changepassword - method - @param string $email the user identifier to select - @param string $newpassword The new password to be recorded */ + /** + * Method to overwrite the password (without oldpassword check) + * Must be reserved to the administrators. For the users, use changepassword + * method + * @param string $email the user identifier to select + * @param string $newpassword The new password to be recorded + */ public function overwritepassword($email, $newpassword) { throw new \Exception( @@ -90,8 +115,10 @@ class Authimap extends Auth ); } - /** List all the users available in the database - Return firstname, lastname, mail, with mail is an array */ + /** + * List all the users available in the database + * Return firstname, lastname, mail, with mail is an array + */ public function listusers() { throw new \Exception(dgettext( diff --git a/src/Authjwt.php b/src/Authjwt.php index 53ae76d..dc06b3c 100644 --- a/src/Authjwt.php +++ b/src/Authjwt.php @@ -1,10 +1,11 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; @@ -15,50 +16,59 @@ namespace Domframework; class Authjwt extends Auth { // PROPERTIES SET BY AUTH - /** The JSON Web Token Server key if used - */ + /** + * The JSON Web Token Server key if used + */ public $serverKey = null; - /** The cipher key to decrypt the token - */ + /** + * The cipher key to decrypt the token + */ public $cipherKey = null; - /** The allowed algorithms in array format - * If null, all the algorithms are allowed - * allowed : ['HS256', 'HS512', 'HS384'] - */ + /** + * The allowed algorithms in array format + * If null, all the algorithms are allowed + * allowed : ['HS256', 'HS512', 'HS384'] + */ public $allowedAlg = null; - /** The algorithm to use, in $allowedAlg list - */ + /** + * The algorithm to use, in $allowedAlg list + */ public $algorithm = "HS256"; - /** The directory to store the user credentials - */ + /** + * The directory to store the user credentials + */ public $cacheDir = "data/jwtCache"; // INTERNAL PROPERTIES - /** If the user is valid, return the payload in details - */ + /** + * If the user is valid, return the payload in details + */ private $payload = null; - /** Save the token - */ + /** + * Save the token + */ private $token = null; - /** No connection to JWT - */ + /** + * No connection to JWT + */ public function connect() { return true; } - /** Try to authenticate the email/password of the user - * If the token is valid, return all the data available in payload. Can - * return a value without email attribute ! - * @param string $email Email not used (wait for Bearer) - * @param string $password Password not used (wait for Bearer) - */ + /** + * Try to authenticate the email/password of the user + * If the token is valid, return all the data available in payload. Can + * return a value without email attribute ! + * @param string $email Email not used (wait for Bearer) + * @param string $password Password not used (wait for Bearer) + */ public function authentication($email, $password) { if (! isset($_SERVER["HTTP_AUTHENTICATION"])) { @@ -86,16 +96,17 @@ class Authjwt extends Auth $payload = $cachefile->read((string)$uuid); // The JWT was tested in authparams. End of process if (empty($uuid) || empty($payload) || ! key_exists("email", $payload)) { - return array("lastname" => "anonymous", + return ["lastname" => "anonymous", "firstname" => "", - "email" => "anonymous"); + "email" => "anonymous"]; } $this->payload = $payload; return $payload; } - /** Return all the parameters recorded for the authenticate user - */ + /** + * Return all the parameters recorded for the authenticate user + */ public function getdetails() { if ( @@ -103,18 +114,19 @@ class Authjwt extends Auth key_exists("email", $this->payload) && $this->payload["email"] === "anonymous" ) { - return array("lastname" => "anonymous", + return ["lastname" => "anonymous", "firstname" => "", - "email" => "anonymous"); + "email" => "anonymous"]; } return $this->payload; } - /** Save the auth data in cache directory and return the JWT token - * Do not allow to store data if the $auth is anonymous - * @param array $auth The authentication to save - * @return string JWT token - */ + /** + * Save the auth data in cache directory and return the JWT token + * Do not allow to store data if the $auth is anonymous + * @param array $auth The authentication to save + * @return string JWT token + */ public function createJwtToken($auth) { if ($this->serverKey === null) { @@ -145,11 +157,12 @@ class Authjwt extends Auth ); } - /** Method to change the password : unavailable in SESSION auth - * @param string $oldpassword The old password (to check if the user have the - * rights to change the password) - * @param string $newpassword The new password to be recorded - */ + /** + * Method to change the password : unavailable in SESSION auth + * @param string $oldpassword The old password (to check if the user have the + * rights to change the password) + * @param string $newpassword The new password to be recorded + */ public function changepassword($oldpassword, $newpassword) { throw new \Exception(dgettext( @@ -158,12 +171,13 @@ class Authjwt extends Auth ), 405); } - /** Method to overwrite the password (without oldpassword check) - * Must be reserved to the administrators. For the users, use changepassword - * method - * @param string $email the user identifier to select - * @param string $newpassword The new password to be recorded - */ + /** + * Method to overwrite the password (without oldpassword check) + * Must be reserved to the administrators. For the users, use changepassword + * method + * @param string $email the user identifier to select + * @param string $newpassword The new password to be recorded + */ public function overwritepassword($email, $newpassword) { throw new \Exception(dgettext( @@ -172,8 +186,9 @@ class Authjwt extends Auth ), 405); } - /** Remove the information from the session - */ + /** + * Remove the information from the session + */ public function logout() { if (! isset($_SERVER["HTTP_AUTHENTICATION"])) { diff --git a/src/Authldap.php b/src/Authldap.php index 48ba68c..4436f26 100644 --- a/src/Authldap.php +++ b/src/Authldap.php @@ -1,41 +1,68 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** User authentication against LDAP server */ +/** + * User authentication against LDAP server + */ class Authldap extends Auth { - /** LDAP server : can be ldaps://server.domain.tld if LDAPS */ + /** + * LDAP server : can be ldaps://server.domain.tld if LDAPS + */ public $ldapserver = "localhost"; - /** LDAP TCP Port (389 by default) */ + /** + * LDAP TCP Port (389 by default) + */ public $ldapport = 389; - /** LDAP Connection timeout (5s by default) */ + /** + * LDAP Connection timeout (5s by default) + */ public $ldaptimeout = 5; - /** LDAP authentication to search user */ + /** + * LDAP authentication to search user + */ public $ldapauth = ""; - /** LDAP authentication password */ + /** + * LDAP authentication password + */ public $ldappwd = ""; - /** LDAP Search base */ + /** + * LDAP Search base + */ public $ldapbase = ""; - /** Filter used to search user */ + /** + * Filter used to search user + */ public $ldapfilter = "(mail=%s)"; - /** Field used to identify a user */ + /** + * Field used to identify a user + */ public $ldapfield = "mail"; - /** Filter used to find the available data of an authenticated user */ + /** + * Filter used to find the available data of an authenticated user + */ public $ldapfiltersearch = "(objectClass=inetOrgPerson)"; - /** The opened LDAP connection identifier */ + /** + * The opened LDAP connection identifier + */ private $ldapconn = null; - /** The DN of the user when found */ + /** + * The DN of the user when found + */ private $ldapdnuser = null; - /** Check the availability of LDAP functions in PHP */ + /** + * Check the availability of LDAP functions in PHP + */ public function __construct() { if (!function_exists("ldap_connect")) { @@ -43,9 +70,11 @@ class Authldap extends Auth } } - /** Establish a connection to a LDAP server - $server can be "ldaps://ldap.domain:636" - If $user is "", there is no authentication (anonymous mode) */ + /** + * Establish a connection to a LDAP server + * $server can be "ldaps://ldap.domain:636" + * If $user is "", there is no authentication (anonymous mode) + */ public function connect() { $this->ldapconn = ldap_connect($this->ldapserver, $this->ldapport); @@ -61,9 +90,11 @@ class Authldap extends Auth } } - /** Try to authenticate the email/password of the user - @param string $email Email to authenticate - @param string $password Password to authenticate */ + /** + * Try to authenticate the email/password of the user + * @param string $email Email to authenticate + * @param string $password Password to authenticate + */ public function authentication($email, $password) { $filter = sprintf($this->ldapfilter, $email, $email, $email, $email); @@ -71,7 +102,7 @@ class Authldap extends Auth $this->ldapconn, $this->ldapbase, $filter, - array($this->ldapfield) + [$this->ldapfield] ); if ($search === false) { throw new \Exception("Unable to search in LDAP", 500); @@ -91,7 +122,9 @@ class Authldap extends Auth $this->ldapdnuser = $dn; } - /** Return all the parameters recorded for the authenticate user */ + /** + * Return all the parameters recorded for the authenticate user + */ public function getdetails() { if ($this->ldapdnuser === null) { @@ -106,20 +139,22 @@ class Authldap extends Auth throw new \Exception("Can not found the details for user", 401); } $data = ldap_get_entries($this->ldapconn, $search); - $res = array(); + $res = []; if (isset($data[0])) { - $res = array("lastname" => $data[0]["sn"][0], + $res = ["lastname" => $data[0]["sn"][0], "firstname" => $data[0]["givenname"][0], - "email" => $data[0]["mail"][0]); + "email" => $data[0]["mail"][0]]; } return $res; } - /** Method to change the password - @param string $oldpassword The old password (to check if the user have the - rights to change the password) - @param string $newpassword The new password to be recorded */ + /** + * Method to change the password + * @param string $oldpassword The old password (to check if the user have the + * rights to change the password) + * @param string $newpassword The new password to be recorded + */ public function changepassword($oldpassword, $newpassword) { throw new \Exception(dgettext( @@ -128,11 +163,13 @@ class Authldap extends Auth ), 405); } - /** Method to overwrite the password (without oldpassword check) - Must be reserved to the administrators. For the users, use changepassword - method - @param string $email the user identifier to select - @param string $newpassword The new password to be recorded */ + /** + * Method to overwrite the password (without oldpassword check) + * Must be reserved to the administrators. For the users, use changepassword + * method + * @param string $email the user identifier to select + * @param string $newpassword The new password to be recorded + */ public function overwritepassword($email, $newpassword) { throw new \Exception( @@ -144,8 +181,10 @@ class Authldap extends Auth ); } - /** List all the users available in the database - Return firstname, lastname, mail, with mail is an array */ + /** + * List all the users available in the database + * Return firstname, lastname, mail, with mail is an array + */ public function listusers() { if ($this->ldapconn === null) { @@ -155,13 +194,13 @@ class Authldap extends Auth $this->ldapconn, $this->ldapbase, $this->ldapfiltersearch, - array("mail", "sn", "givenname") + ["mail", "sn", "givenname"] ); if ($search === false) { throw new \Exception("Unable to search the users in LDAP", 500); } $info = ldap_get_entries($this->ldapconn, $search); - $data = array(); + $data = []; foreach ($info as $key => $vals) { if ($key === "count") { continue; @@ -170,9 +209,9 @@ class Authldap extends Auth isset($vals["sn"][0]) && isset($vals["givenname"][0]) && isset($vals["mail"]) ) { - $data[$key] = array("lastname" => $vals["sn"][0], + $data[$key] = ["lastname" => $vals["sn"][0], "firstname" => $vals["givenname"][0], - "email" => $vals["mail"][0]); + "email" => $vals["mail"][0]]; } unset($data[$key]["mail"]["count"]); @@ -181,7 +220,9 @@ class Authldap extends Auth return $data; } - /** Close the LDAP connection when closing the object or PHP */ + /** + * Close the LDAP connection when closing the object or PHP + */ public function __destruct() { if (isset($this->ldapconn)) { diff --git a/src/Authorization.php b/src/Authorization.php index 7229e61..d95d23f 100644 --- a/src/Authorization.php +++ b/src/Authorization.php @@ -1,100 +1,131 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** All the needed functions to authorize or deny access to an authenticated - user */ +/** + * All the needed functions to authorize or deny access to an authenticated + * user + */ class Authorization { - /** Separator between differents modules/objects */ + /** + * Separator between differents modules/objects + */ private $separator = "/"; - /** The user ID of the authenticated user */ + /** + * The user ID of the authenticated user + */ public $authiduser = ""; // user id - /** The groups ID of the authenticated user */ - public $authgroups = array(); // List of user's groups id + /** + * The groups ID of the authenticated user + */ + public $authgroups = []; // List of user's groups id - /** Establish a connexion to the authorization database */ + /** + * Establish a connexion to the authorization database + */ public function connect() { } - /** Create the structure to store the authorization database */ + /** + * Create the structure to store the authorization database + */ public function initialize() { } - /** Return if the user right is NONE, READ, WRITE, EXECUTE - if the object doesn't exists, or is not readable, throw an exception - @param string $object The object path to examine - @return string NONE, READ, WRITE, EXECUTE */ + /** + * Return if the user right is NONE, READ, WRITE, EXECUTE + * if the object doesn't exists, or is not readable, throw an exception + * @param string $object The object path to examine + * @return string NONE, READ, WRITE, EXECUTE + */ public function validate($object) { return "NONE"; } - /** Add a new object, with owner and group, and mode bits - @param string $object Object path to add - @param integer $owner Owner ID of the object - @param integer $group Group ID of the object - @param integer $modbits Bits of authorization */ + /** + * Add a new object, with owner and group, and mode bits + * @param string $object Object path to add + * @param integer $owner Owner ID of the object + * @param integer $group Group ID of the object + * @param integer $modbits Bits of authorization + */ public function add($object, $owner, $group, $modbits) { } - /** Remove the information about an object and all its sub-objects - @param string $object Object path to drop */ + /** + * Remove the information about an object and all its sub-objects + * @param string $object Object path to drop + */ public function drop($object) { } - /** Change the owner of an object - Need to be the root administrator - @param string $object Object path to add - @param integer $owner Owner ID of the object */ + /** + * Change the owner of an object + * Need to be the root administrator + * @param string $object Object path to add + * @param integer $owner Owner ID of the object + */ public function chown($object, $owner) { } - /** Change the group of an object - Need to be the owner of the object or the root administrator - @param string $object Object path to add - @param integer $group Group ID of the object */ + /** + * Change the group of an object + * Need to be the owner of the object or the root administrator + * @param string $object Object path to add + * @param integer $group Group ID of the object + */ public function chgrp($object, $group) { } - /** Change mode bits for an object - Need to be the owner of the object or the root administrator - @param string $object Object path to change - @param integer $mod Bits of authorization */ + /** + * Change mode bits for an object + * Need to be the owner of the object or the root administrator + * @param string $object Object path to change + * @param integer $mod Bits of authorization + */ public function chmod($object, $mod) { } - /** Return the mode bits for an object if all his parents are readable for - the user - @param string $object Object path to examine */ + /** + * Return the mode bits for an object if all his parents are readable for + * the user + * @param string $object Object path to examine + */ public function lsmod($object) { } - /** Return the owner for an object if all his parents are readable for - the user - @param string $object Object path to examine */ + /** + * Return the owner for an object if all his parents are readable for + * the user + * @param string $object Object path to examine + */ public function lsown($object) { } - /** Return the owner for an object if all his parents are readable for - the user - @param string $object Object path to examine */ + /** + * Return the owner for an object if all his parents are readable for + * the user + * @param string $object Object path to examine + */ public function lsgrp($object) { } diff --git a/src/Authorizationdb.php b/src/Authorizationdb.php index ad419d1..e80e3e5 100644 --- a/src/Authorizationdb.php +++ b/src/Authorizationdb.php @@ -1,30 +1,41 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** All the needed functions to authorize or deny access to an authenticated - user */ +/** + * All the needed functions to authorize or deny access to an authenticated + * user + */ class Authorizationdb extends Authorization { - /** Separator between differents modules/objects */ + /** + * Separator between differents modules/objects + */ private $separator = "/"; - /** Database PDO connector */ + /** + * Database PDO connector + */ private $db = null; - /** The prefix for the table */ + /** + * The prefix for the table + */ public $tableprefix = ""; - /** Establish a connexion to the authorization database - @param string $dsn The DSN needed to connect to database - @param string|null $username The username needed to connect to database - @param string|null $password The password needed to connect to database - @param string|null $driver_options The driver options need to connect to - database */ + /** + * Establish a connexion to the authorization database + * @param string $dsn The DSN needed to connect to database + * @param string|null $username The username needed to connect to database + * @param string|null $password The password needed to connect to database + * @param string|null $driver_options The driver options need to connect to + * database + */ public function connectdb( $dsn, $username = null, @@ -35,16 +46,18 @@ class Authorizationdb extends Authorization $this->db = new Dblayer($dsn, $username, $password, $driver_options); $this->db->table = "domframework_authorization"; $this->db->tableprefix = $this->tableprefix; - $this->db->fields = array( - "object" => array("varchar", "255", "not null"), - "ownerid" => array("integer", "not null"), - "groupid" => array("integer", "not null"), - "modbits" => array("integer", "not null")); + $this->db->fields = [ + "object" => ["varchar", "255", "not null"], + "ownerid" => ["integer", "not null"], + "groupid" => ["integer", "not null"], + "modbits" => ["integer", "not null"]]; $this->db->primary = "object"; - $this->db->unique = array("object"); + $this->db->unique = ["object"]; } - /** Create the structure to store the authorization database */ + /** + * Create the structure to store the authorization database + */ public function initialize() { if ($this->db === null) { @@ -54,18 +67,20 @@ class Authorizationdb extends Authorization ), 500); } $tables = $this->db->listTables(); - if (!in_array($this->db->tableprefix . $this->db->table, $tables)) { + if (!in_array($this->db->tableprefix . $this->db->table, $tables, true)) { $this->db->createTable(); - $first = array("object" => "/", "ownerid" => 0, "groupid" => 0, - "modbits" => 755); + $first = ["object" => "/", "ownerid" => 0, "groupid" => 0, + "modbits" => 755]; $this->db->create($first); } } - /** Return if the user right is NONE, READ, WRITE, EXECUTE - if the object doesn't exists, or is not readable, throw an exception - @param string $object The object path to examine - @return array with READ, WRITE, EXECUTE */ + /** + * Return if the user right is NONE, READ, WRITE, EXECUTE + * if the object doesn't exists, or is not readable, throw an exception + * @param string $object The object path to examine + * @return array with READ, WRITE, EXECUTE + */ public function validate($object) { if ($this->db === null) { @@ -98,7 +113,7 @@ class Authorizationdb extends Authorization // All the folder structure is accessible. Check if the object already // exists - $search = $this->db->read(array(array("object", $object))); + $search = $this->db->read([["object", $object]]); if (count($search) === 0) { throw new \Exception( sprintf( @@ -116,10 +131,10 @@ class Authorizationdb extends Authorization $groupid = intval($search["groupid"]); $modbits = octdec($search["modbits"]); if ($this->authiduser === 0) { - return array("READ", "WRITE", "EXECUTE"); + return ["READ", "WRITE", "EXECUTE"]; } - $res = array(); + $res = []; if ($this->authiduser === $ownerid) { if (($modbits & 0100) === 0100) { $res[] = "EXECUTE"; @@ -160,12 +175,14 @@ class Authorizationdb extends Authorization return array_unique($res); } - /** Add a new object, with ownerid and groupid, and mode bits - @param string $object Object path to add - @param integer $ownerid Owner ID of the object - @param integer $groupid Group ID of the object - @param integer $modbits Bits of authorization - @return boolean TRUE or an exception with the error message */ + /** + * Add a new object, with ownerid and groupid, and mode bits + * @param string $object Object path to add + * @param integer $ownerid Owner ID of the object + * @param integer $groupid Group ID of the object + * @param integer $modbits Bits of authorization + * @return boolean TRUE or an exception with the error message + */ public function add($object, $ownerid, $groupid, $modbits) { if ($this->db === null) { @@ -198,7 +215,7 @@ class Authorizationdb extends Authorization "Can't create object not owned by myself" ), 406); } - if ($this->authiduser !== 0 && !in_array($groupid, $this->authgroups)) { + if ($this->authiduser !== 0 && !in_array($groupid, $this->authgroups, true)) { throw new \Exception(dgettext( "domframework", "Can't create object with not owned group" @@ -212,7 +229,7 @@ class Authorizationdb extends Authorization // All the folder structure is accessible. Check if the object already // exists - $search = $this->db->read(array(array("object", $object))); + $search = $this->db->read([["object", $object]]); if (count($search)) { throw new \Exception( sprintf(dgettext( @@ -226,10 +243,10 @@ class Authorizationdb extends Authorization // All the folder structure is accessible. Check if we can add the file in // the last folder (Write modbit). Root can always write. if ($this->authiduser === 0) { - $this->db->create(array("object" => $object, + $this->db->create(["object" => $object, "ownerid" => $ownerid, "groupid" => $groupid, - "modbits" => $modbits)); + "modbits" => $modbits]); return true; } @@ -239,16 +256,18 @@ class Authorizationdb extends Authorization throw new \Exception($e->getMessage(), 405); } - $this->db->create(array("object" => $object, + $this->db->create(["object" => $object, "ownerid" => $ownerid, "groupid" => $groupid, - "modbits" => $modbits)); + "modbits" => $modbits]); return true; } - /** Remove the information about an object and all its sub-objects - @param string $object Object path to drop - @return boolean TRUE or an exception with the error message */ + /** + * Remove the information about an object and all its sub-objects + * @param string $object Object path to drop + * @return boolean TRUE or an exception with the error message + */ public function drop($object) { if ($this->db === null) { @@ -287,7 +306,7 @@ class Authorizationdb extends Authorization // All the folder structure is accessible. Check if the object already // exists - $search = $this->db->read(array(array("object", $object))); + $search = $this->db->read([["object", $object]]); if (count($search) === 0) { throw new \Exception(sprintf( dgettext( @@ -341,11 +360,13 @@ class Authorizationdb extends Authorization return true; } - /** Change the owner of an object - Need to be the root administrator - @param string $object Object path to add - @param integer $ownerid Owner ID of the object - @return boolean TRUE or an exception with the error message */ + /** + * Change the owner of an object + * Need to be the root administrator + * @param string $object Object path to add + * @param integer $ownerid Owner ID of the object + * @return boolean TRUE or an exception with the error message + */ public function chown($object, $ownerid) { if ($this->db === null) { @@ -384,7 +405,7 @@ class Authorizationdb extends Authorization // All the folder structure is accessible. Check if the object already // exists - $search = $this->db->read(array(array("object", $object))); + $search = $this->db->read([["object", $object]]); if (count($search) === 0) { throw new \Exception( sprintf(dgettext( @@ -395,15 +416,17 @@ class Authorizationdb extends Authorization ); } $search = reset($search); - $this->db->update($object, array("ownerid" => $ownerid)); + $this->db->update($object, ["ownerid" => $ownerid]); return true; } - /** Change the group of an object - Need to be the ownerid of the object or the root administrator - @param string $object Object path to add - @param integer $groupid Group ID of the object - @return boolean TRUE or an exception with the error message */ + /** + * Change the group of an object + * Need to be the ownerid of the object or the root administrator + * @param string $object Object path to add + * @param integer $groupid Group ID of the object + * @return boolean TRUE or an exception with the error message + */ public function chgrp($object, $groupid) { if ($this->db === null) { @@ -428,13 +451,13 @@ class Authorizationdb extends Authorization "Not authenticated" ), 401); } - if ($this->authiduser !== 0 && !in_array($groupid, $this->authgroups)) { + if ($this->authiduser !== 0 && !in_array($groupid, $this->authgroups, true)) { throw new \Exception(dgettext( "domframework", "The user must be in the wanted group" ), 405); } - if (!in_array("WRITE", $this->validate($object))) { + if (!in_array("WRITE", $this->validate($object), true)) { throw new \Exception(sprintf(dgettext( "domframework", "%s is write protected" @@ -448,7 +471,7 @@ class Authorizationdb extends Authorization // All the folder structure is accessible. Check if the object already // exists - $search = $this->db->read(array(array("object", $object))); + $search = $this->db->read([["object", $object]]); if (count($search) === 0) { throw new \Exception( sprintf(dgettext( @@ -459,15 +482,17 @@ class Authorizationdb extends Authorization ); } $search = reset($search); - $this->db->update($object, array("groupid" => $groupid)); + $this->db->update($object, ["groupid" => $groupid]); return true; } - /** Change mode bits for an object - Need to be the owner of the object or the root administrator - @param string $object Object path to change - @param integer $mod Bits of authorization - @return boolean TRUE or an exception with the error message */ + /** + * Change mode bits for an object + * Need to be the owner of the object or the root administrator + * @param string $object Object path to change + * @param integer $mod Bits of authorization + * @return boolean TRUE or an exception with the error message + */ public function chmod($object, $mod) { if ($this->db === null) { @@ -492,7 +517,7 @@ class Authorizationdb extends Authorization "Not authenticated" ), 401); } - if (!in_array("WRITE", $this->validate($object))) { + if (!in_array("WRITE", $this->validate($object), true)) { throw new \Exception(sprintf(dgettext( "domframework", "%s is write protected" @@ -506,7 +531,7 @@ class Authorizationdb extends Authorization // All the folder structure is accessible. Check if the object already // exists - $search = $this->db->read(array(array("object", $object))); + $search = $this->db->read([["object", $object]]); if (count($search) === 0) { throw new \Exception( sprintf(dgettext( @@ -518,14 +543,16 @@ class Authorizationdb extends Authorization } $search = reset($search); // TODO : Don't update if the user is not the owner of the file - $this->db->update($object, array("modbits" => $modbits)); + $this->db->update($object, ["modbits" => $modbits]); return true; } - /** Return the mode bits for an object if all his parents are readable for - the user - @param string $object Object path to examine - @return int|float the modbits or an exception with the error message */ + /** + * Return the mode bits for an object if all his parents are readable for + * the user + * @param string $object Object path to examine + * @return int|float the modbits or an exception with the error message + */ public function lsmod($object) { if ($this->db === null) { @@ -558,7 +585,7 @@ class Authorizationdb extends Authorization // All the folder structure is accessible. Check if the object already // exists - $search = $this->db->read(array(array("object", $object))); + $search = $this->db->read([["object", $object]]); if (count($search) === 0) { throw new \Exception( sprintf(dgettext( @@ -572,10 +599,12 @@ class Authorizationdb extends Authorization return octdec($search["modbits"]); } - /** Return the ownerid for an object if all his parents are readable for - the user - @param string $object Object path to examine - @return integer the ownerid or an exception with the error message */ + /** + * Return the ownerid for an object if all his parents are readable for + * the user + * @param string $object Object path to examine + * @return integer the ownerid or an exception with the error message + */ public function lsown($object) { if ($this->db === null) { @@ -608,7 +637,7 @@ class Authorizationdb extends Authorization // All the folder structure is accessible. Check if the object already // exists - $search = $this->db->read(array(array("object", $object))); + $search = $this->db->read([["object", $object]]); if (count($search) === 0) { throw new \Exception( sprintf(dgettext( @@ -622,10 +651,12 @@ class Authorizationdb extends Authorization return intval($search["ownerid"]); } - /** Return the groupid for an object if all his parents are readable for - the user - @param string $object Object path to examine - @return integer the groupid or an exception with the error message */ + /** + * Return the groupid for an object if all his parents are readable for + * the user + * @param string $object Object path to examine + * @return integer the groupid or an exception with the error message + */ public function lsgrp($object) { if ($this->db === null) { @@ -658,7 +689,7 @@ class Authorizationdb extends Authorization // All the folder structure is accessible. Check if the object already // exists - $search = $this->db->read(array(array("object", $object))); + $search = $this->db->read([["object", $object]]); if (count($search) === 0) { throw new \Exception( sprintf(dgettext( @@ -675,9 +706,11 @@ class Authorizationdb extends Authorization //////////////////// // TREE CHECK // //////////////////// - /** Check if all the parent objects are executable - @param string $object The object to test - @return boolean TRUE or an exception in case of error */ + /** + * Check if all the parent objects are executable + * @param string $object The object to test + * @return boolean TRUE or an exception in case of error + */ private function treecheckExecute($object) { if ($this->db === null) { @@ -687,7 +720,7 @@ class Authorizationdb extends Authorization ), 500); } // Search all the parents in an array - $parents = array(); + $parents = []; $par = $object; while ($par !== "/") { $par = dirname($par); @@ -758,13 +791,15 @@ class Authorizationdb extends Authorization return true; } - /** Check if the parent of object is writeable - @param string $object The object to found - @return boolean TRUE or an exception */ + /** + * Check if the parent of object is writeable + * @param string $object The object to found + * @return boolean TRUE or an exception + */ private function treecheckWrite($object) { $parent = dirname($object); - $search = $this->db->read(array(array("object", $parent))); + $search = $this->db->read([["object", $parent]]); $search = reset($search); $parentOwner = intval($search["ownerid"]); $parentGroup = intval($search["groupid"]); @@ -775,8 +810,8 @@ class Authorizationdb extends Authorization if ((($parentModbits & 0020) === 16)) { if ( - in_array($parentGroup, $this->authgroups) || - in_array(0, $this->authgroups) + in_array($parentGroup, $this->authgroups, true) || + in_array(0, $this->authgroups, true) ) { return true; } diff --git a/src/Authparams.php b/src/Authparams.php index 5ce680d..4e14eea 100644 --- a/src/Authparams.php +++ b/src/Authparams.php @@ -1,29 +1,39 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** Takes the email and the password of the user */ +/** + * Takes the email and the password of the user + */ class Authparams { - /** The email of the user when provided */ + /** + * The email of the user when provided + */ public $email = null; - /** The password of the user when provided */ + /** + * The password of the user when provided + */ public $password = null; - /** The method used to get the authentication data */ + /** + * The method used to get the authentication data + */ public $method = null; - /** Parse the different authentication processes to found the email/password - * of the user. - * If non is found, return "anonymous", "anonymous" - * @param array|null $authprocesses The authentication process to use - */ - public function __construct($authprocesses = array("session", "post")) + /** + * Parse the different authentication processes to found the email/password + * of the user. + * If non is found, return "anonymous", "anonymous" + * @param array|null $authprocesses The authentication process to use + */ + public function __construct($authprocesses = ["session", "post"]) { if (php_sapi_name() === "cli") { $this->email = "cli"; @@ -46,19 +56,21 @@ class Authparams } } - /** Get information from $POST variables - */ + /** + * Get information from $POST variables + */ public function post() { if (!isset($_POST["email"]) || !isset($_POST["password"])) { throw new \Exception("No POST provided", 403); } - return array("email" => trim($_POST["email"]), - "password" => $_POST["password"]); + return ["email" => trim($_POST["email"]), + "password" => $_POST["password"]]; } - /** Get information from previous recorded session - */ + /** + * Get information from previous recorded session + */ public function session() { if (!isset($_SESSION) || session_id() === "") { @@ -70,12 +82,13 @@ class Authparams ) { throw new \Exception("No previous email in session", 403); } - return array("email" => $_SESSION["domframework"]["auth"]["email"], - "password" => $_SESSION["domframework"]["auth"]["password"]); + return ["email" => $_SESSION["domframework"]["auth"]["email"], + "password" => $_SESSION["domframework"]["auth"]["password"]]; } - /** Get information from a HTTP authentication - */ + /** + * Get information from a HTTP authentication + */ public function http() { $realm = dgettext("domframework", "Restricted access"); @@ -88,13 +101,14 @@ class Authparams if (! array_key_exists("PHP_AUTH_PW", $_SERVER)) { $_SERVER["PHP_AUTH_PW"] = null; } - return array("email" => trim($_SERVER["PHP_AUTH_USER"]), - "password" => $_SERVER["PHP_AUTH_PW"]); + return ["email" => trim($_SERVER["PHP_AUTH_USER"]), + "password" => $_SERVER["PHP_AUTH_PW"]]; } } - /** Get the information from a shibboleth provider - */ + /** + * Get the information from a shibboleth provider + */ public function shibboleth() { if (! isset($_SERVER["Shib-Session-ID"])) { @@ -103,23 +117,24 @@ class Authparams if (! isset($_SERVER["mail"])) { throw new \Exception("No Shibboleth email provided", 403); } - return array("email" => $_SERVER["mail"], - "password" => "NONE IN SHIBBOLETH"); + return ["email" => $_SERVER["mail"], + "password" => "NONE IN SHIBBOLETH"]; } - /** Get the information from a Bearer Token - * The token MUST be set in HTTP Header : - * Authentication: Bearer - * Ex in curl : - * curl -s -u "login:password" -X POST \ - * http://localhost/rest/authentication/ | jq -r - * curl -s \ - * -H "Accept: application/json" \ - * -H "Authentication: Bearer {$BearerToken}" \ - * http://localhost/rest/api/ - * The real verification are done in authjwt, as we can not have the - * jwtServerKey defined in property : the execution is done in constructor - */ + /** + * Get the information from a Bearer Token + * The token MUST be set in HTTP Header : + * Authentication: Bearer + * Ex in curl : + * curl -s -u "login:password" -X POST \ + * http://localhost/rest/authentication/ | jq -r + * curl -s \ + * -H "Accept: application/json" \ + * -H "Authentication: Bearer {$BearerToken}" \ + * http://localhost/rest/api/ + * The real verification are done in authjwt, as we can not have the + * jwtServerKey defined in property : the execution is done in constructor + */ public function bearer() { if (! isset($_SERVER["HTTP_AUTHENTICATION"])) { @@ -129,7 +144,7 @@ class Authparams throw new \Exception("No Bearer Authentication available", 401); } $token = substr($_SERVER["HTTP_AUTHENTICATION"], 7); - return array("email" => "NOT YET VALID : TOKEN IN JWT", - "password" => "NONE IN JWT"); + return ["email" => "NOT YET VALID : TOKEN IN JWT", + "password" => "NONE IN JWT"]; } } diff --git a/src/Authsession.php b/src/Authsession.php index 9e62888..a1f19dc 100644 --- a/src/Authsession.php +++ b/src/Authsession.php @@ -1,17 +1,21 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** User authentication against SESSION */ +/** + * User authentication against SESSION + */ class Authsession extends Auth { - /** Check if there is already a session or the user can not be authenticated + /** + * Check if there is already a session or the user can not be authenticated */ public function __construct() { @@ -20,16 +24,19 @@ class Authsession extends Auth } } - /** No connection to session */ + /** + * No connection to session + */ public function connect() { return true; } - /** Try to authenticate the email/password of the user - * @param string $email Email to authenticate - * @param string $password Password to authenticate - */ + /** + * Try to authenticate the email/password of the user + * @param string $email Email to authenticate + * @param string $password Password to authenticate + */ public function authentication($email, $password) { if ( @@ -46,24 +53,27 @@ class Authsession extends Auth } } - /** Return all the parameters recorded for the authenticate user */ + /** + * Return all the parameters recorded for the authenticate user + */ public function getdetails() { if (! isset($_SESSION["domframework"]["auth"]["email"])) { - return array("lastname" => "anonymous", + return ["lastname" => "anonymous", "firstname" => "", - "email" => "anonymous"); + "email" => "anonymous"]; } - return array("lastname" => $_SESSION["domframework"]["auth"]["lastname"], + return ["lastname" => $_SESSION["domframework"]["auth"]["lastname"], "firstname" => $_SESSION["domframework"]["auth"]["firstname"], - "email" => $_SESSION["domframework"]["auth"]["email"]); + "email" => $_SESSION["domframework"]["auth"]["email"]]; } - /** Method to change the password : unavailable in SESSION auth - * @param string $oldpassword The old password (to check if the user have the - * rights to change the password) - * @param string $newpassword The new password to be recorded - */ + /** + * Method to change the password : unavailable in SESSION auth + * @param string $oldpassword The old password (to check if the user have the + * rights to change the password) + * @param string $newpassword The new password to be recorded + */ public function changepassword($oldpassword, $newpassword) { throw new \Exception( @@ -75,12 +85,13 @@ class Authsession extends Auth ); } - /** Method to overwrite the password (without oldpassword check) - * Must be reserved to the administrators. For the users, use changepassword - * method - * @param string $email the user identifier to select - * @param string $newpassword The new password to be recorded - */ + /** + * Method to overwrite the password (without oldpassword check) + * Must be reserved to the administrators. For the users, use changepassword + * method + * @param string $email the user identifier to select + * @param string $newpassword The new password to be recorded + */ public function overwritepassword($email, $newpassword) { throw new \Exception( @@ -92,23 +103,26 @@ class Authsession extends Auth ); } - /** Save the data in session - * @param string $email The email to store in the session - * @param string $password The password to store in the session - * @param string $lastname The lastname to store in the session - * @param string $firstname The firstname to store in the session - * @deprecated 0.23 */ + /** + * Save the data in session + * @param string $email The email to store in the session + * @param string $password The password to store in the session + * @param string $lastname The lastname to store in the session + * @param string $firstname The firstname to store in the session + * @deprecated 0.23 + */ public function savedatas($email, $password, $lastname, $firstname) { return $this->savedata($email, $password, $lastname, $firstname); } - /** Save the data in session - * @param string $email The email to store in the session - * @param string $password The password to store in the session - * @param string $lastname The lastname to store in the session - * @param string $firstname The firstname to store in the session - */ + /** + * Save the data in session + * @param string $email The email to store in the session + * @param string $password The password to store in the session + * @param string $lastname The lastname to store in the session + * @param string $firstname The firstname to store in the session + */ public function savedata($email, $password, $lastname, $firstname) { $_SESSION["domframework"]["auth"]["lastname"] = $lastname; @@ -117,7 +131,9 @@ class Authsession extends Auth $_SESSION["domframework"]["auth"]["password"] = $password; } - /** Remove the information from the session */ + /** + * Remove the information from the session + */ public function logout() { if (isset($_SESSION["domframework"]["auth"]["lastname"])) { diff --git a/src/Authshibboleth.php b/src/Authshibboleth.php index 6aeed93..f02e6cc 100644 --- a/src/Authshibboleth.php +++ b/src/Authshibboleth.php @@ -1,40 +1,61 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** User authentication against Shibboleth */ +/** + * User authentication against Shibboleth + */ class Authshibboleth extends Auth { - /** The Lastname parameter returned by Shibboleth server */ + /** + * The Lastname parameter returned by Shibboleth server + */ public $lastnameParam = "sn"; - /** The Firstname parameter returned by Shibboleth server */ + /** + * The Firstname parameter returned by Shibboleth server + */ public $firstnameParam = "givenName"; - /** The mail parameter returned by Shibboleth server */ + /** + * The mail parameter returned by Shibboleth server + */ public $mailParam = "mail"; - /** The others parameters returned by Shibboleth server */ - public $otherFields = array("ou", "o"); - /** The optional URL use to authenticate the users */ + /** + * The others parameters returned by Shibboleth server + */ + public $otherFields = ["ou", "o"]; + /** + * The optional URL use to authenticate the users + */ public $urlAuthentificated = ""; - /** The optional URL to disconnect the users */ + /** + * The optional URL to disconnect the users + */ public $urlLogout = ""; - /** The optional URL to change the user password */ + /** + * The optional URL to change the user password + */ public $urlPasswd = ""; - /** No connection to shibboleth */ + /** + * No connection to shibboleth + */ public function connect() { return true; } - /** Try to authenticate the email/password of the user - @param string $email Email to authenticate - @param string $password Password to authenticate */ + /** + * Try to authenticate the email/password of the user + * @param string $email Email to authenticate + * @param string $password Password to authenticate + */ public function authentication($email, $password) { if (!isset($_SERVER["mail"])) { @@ -46,17 +67,19 @@ class Authshibboleth extends Auth } } - /** Return all the parameters recorded for the authenticate user */ + /** + * Return all the parameters recorded for the authenticate user + */ public function getdetails() { if (! isset($_SERVER[$this->mailParam])) { - return array("lastname" => "anonymous", + return ["lastname" => "anonymous", "firstname" => "", - "email" => "anonymous"); + "email" => "anonymous"]; } - $res = array("lastname" => $_SERVER[$this->lastnameParam], + $res = ["lastname" => $_SERVER[$this->lastnameParam], "firstname" => $_SERVER[$this->firstnameParam], - "email" => $_SERVER[$this->mailParam]); + "email" => $_SERVER[$this->mailParam]]; foreach ($this->otherFields as $field) { if (array_key_exists($field, $_SERVER)) { $res[$field] = $_SERVER[$field]; @@ -65,10 +88,12 @@ class Authshibboleth extends Auth return $res; } - /** Method to change the password : unavailable in SESSION auth - @param string $oldpassword The old password (to check if the user have the - rights to change the password) - @param string $newpassword The new password to be recorded */ + /** + * Method to change the password : unavailable in SESSION auth + * @param string $oldpassword The old password (to check if the user have the + * rights to change the password) + * @param string $newpassword The new password to be recorded + */ public function changepassword($oldpassword, $newpassword) { // Redirect to Shibboleth IDP @@ -85,11 +110,13 @@ class Authshibboleth extends Auth $route->redirect($this->urlPasswdChange); } - /** Method to overwrite the password (without oldpassword check) - Must be reserved to the administrators. For the users, use changepassword - method - @param string $email the user identifier to select - @param string $newpassword The new password to be recorded */ + /** + * Method to overwrite the password (without oldpassword check) + * Must be reserved to the administrators. For the users, use changepassword + * method + * @param string $email the user identifier to select + * @param string $newpassword The new password to be recorded + */ public function overwritepassword($email, $newpassword) { throw new \Exception( @@ -101,7 +128,9 @@ class Authshibboleth extends Auth ); } - /** Remove the information from the session */ + /** + * Remove the information from the session + */ public function logout() { // Redirect to Shibboleth IDP diff --git a/src/Authsql.php b/src/Authsql.php index ba03e91..94b70f9 100644 --- a/src/Authsql.php +++ b/src/Authsql.php @@ -1,46 +1,77 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** User authentication against SQL database */ +/** + * User authentication against SQL database + */ class Authsql extends Auth { - /** The DSN to use to connect to SQL database */ + /** + * The DSN to use to connect to SQL database + */ public $dsn = null; - /** The username to connect to the database */ + /** + * The username to connect to the database + */ public $username = null; - /** The password to use to connecto to the database */ + /** + * The password to use to connecto to the database + */ public $password = null; - /** The driver options for the PDO driver */ + /** + * The driver options for the PDO driver + */ public $driver_options = null; - /** The table name to use */ + /** + * The table name to use + */ public $table = null; - /** The tableprefix text to prepend to table name (Should finish by _) - Just allow chars ! */ + /** + * The tableprefix text to prepend to table name (Should finish by _) + * Just allow chars ! + */ public $tableprefix = ""; - /** The password field name */ + /** + * The password field name + */ public $fieldPassword = "password"; - /** The identifier field name (maybe email) */ + /** + * The identifier field name (maybe email) + */ public $fieldIdentifier = "email"; - /** The field name containing the lastname of the user */ + /** + * The field name containing the lastname of the user + */ public $fieldLastname = null; - /** The field name containing the Firstname of the user */ + /** + * The field name containing the Firstname of the user + */ public $fieldFirstname = null; - /** The information fields (in an array) */ - public $fieldsInfo = array(); + /** + * The information fields (in an array) + */ + public $fieldsInfo = []; - /** The DBLayer pointer */ + /** + * The DBLayer pointer + */ private $db = null; - /** The details of the authenticated user */ + /** + * The details of the authenticated user + */ private $details = null; - /** Establish a connection to a SQL server */ + /** + * Establish a connection to a SQL server + */ public function connect() { if (! function_exists("openssl_random_pseudo_bytes")) { @@ -89,22 +120,24 @@ class Authsql extends Auth ), 500); } $fields = array_merge( - array($this->fieldIdentifier, $this->fieldPassword, - $this->fieldLastname, $this->fieldFirstname), + [$this->fieldIdentifier, $this->fieldPassword, + $this->fieldLastname, $this->fieldFirstname], $this->fieldsInfo ); $fields = array_flip($fields); foreach ($fields as $key => $val) { - $fields[$key] = array("varchar", "255"); + $fields[$key] = ["varchar", "255"]; } $this->db->table = $this->table; $this->db->fields = $fields; $this->db->primary = $this->fieldIdentifier; } - /** Try to authenticate the email/password of the user - @param string $email Email to authenticate - @param string $password Password to authenticate */ + /** + * Try to authenticate the email/password of the user + * @param string $email Email to authenticate + * @param string $password Password to authenticate + */ public function authentication($email, $password) { if ($this->db === null) { @@ -114,12 +147,12 @@ class Authsql extends Auth ), 500); } $data = $this->db->read( - array(array($this->fieldIdentifier, $email)), + [[$this->fieldIdentifier, $email]], array_merge( - array($this->fieldIdentifier, + [$this->fieldIdentifier, $this->fieldFirstname, $this->fieldLastname, - $this->fieldPassword), + $this->fieldPassword], $this->fieldsInfo ) ); @@ -160,16 +193,20 @@ class Authsql extends Auth $this->details = $content; } - /** Return all the parameters recorded for the authenticate user */ + /** + * Return all the parameters recorded for the authenticate user + */ public function getdetails() { return $this->details; } - /** Method to change the password - @param string $oldpassword The old password (to check if the user have the - rights to change the password) - @param string $newpassword The new password to be recorded */ + /** + * Method to change the password + * @param string $oldpassword The old password (to check if the user have the + * rights to change the password) + * @param string $newpassword The new password to be recorded + */ public function changepassword($oldpassword, $newpassword) { if ($this->db === null) { @@ -191,10 +228,10 @@ class Authsql extends Auth ); } $data = $this->db->read( - array(array($this->fieldIdentifier, - $this->details[$this->fieldIdentifier])), - array($this->fieldIdentifier, - $this->fieldPassword) + [[$this->fieldIdentifier, + $this->details[$this->fieldIdentifier]]], + [$this->fieldIdentifier, + $this->fieldPassword] ); $cryptedPassword = $data[0][$this->fieldPassword]; if (crypt($oldpassword, $cryptedPassword) !== $cryptedPassword) { @@ -206,16 +243,16 @@ class Authsql extends Auth $cost = 11; $salt = substr(base64_encode(openssl_random_pseudo_bytes(17)), 0, 22); $salt = str_replace("+", ".", $salt); - $param = '$' . implode('$', array( + $param = '$' . implode('$', [ "2y", //select the most secure version of blowfish (>=PHP 5.3.7) str_pad($cost, 2, "0", STR_PAD_LEFT), //add the cost in two digits $salt //add the salt - )); + ]); //now do the actual hashing $cryptpassword = crypt($newpassword, $param); $rc = $this->db->update( $this->details[$this->fieldIdentifier], - array($this->fieldPassword => $cryptpassword) + [$this->fieldPassword => $cryptpassword] ); if ($rc !== 1) { throw new \Exception(dgettext( @@ -225,11 +262,13 @@ class Authsql extends Auth } } - /** Method to overwrite the password (without oldpassword check) - Must be reserved to the administrators. For the users, use changepassword - method - @param string $email the user identifier to select - @param string $newpassword The new password to be recorded */ + /** + * Method to overwrite the password (without oldpassword check) + * Must be reserved to the administrators. For the users, use changepassword + * method + * @param string $email the user identifier to select + * @param string $newpassword The new password to be recorded + */ public function overwritepassword($email, $newpassword) { if ($this->db === null) { @@ -239,9 +278,9 @@ class Authsql extends Auth ), 500); } $data = $this->db->read( - array(array($this->fieldIdentifier, $email)), - array($this->fieldIdentifier, - $this->fieldPassword) + [[$this->fieldIdentifier, $email]], + [$this->fieldIdentifier, + $this->fieldPassword] ); if (count($data) === 0) { throw new \Exception(sprintf( @@ -255,16 +294,16 @@ class Authsql extends Auth $cost = 11; $salt = substr(base64_encode(openssl_random_pseudo_bytes(17)), 0, 22); $salt = str_replace("+", ".", $salt); - $param = '$' . implode('$', array( + $param = '$' . implode('$', [ "2y", //select the most secure version of blowfish (>=PHP 5.3.7) str_pad($cost, 2, "0", STR_PAD_LEFT), //add the cost in two digits $salt //add the salt - )); + ]); //now do the actual hashing $cryptpassword = crypt($newpassword, $param); $rc = $this->db->update( $email, - array($this->fieldPassword => $cryptpassword) + [$this->fieldPassword => $cryptpassword] ); if ($rc !== 1) { throw new \Exception(dgettext( @@ -273,8 +312,10 @@ class Authsql extends Auth ), 500); } } - /** List all the users available in the database - Return firstname, lastname, mail, with mail is an array */ + /** + * List all the users available in the database + * Return firstname, lastname, mail, with mail is an array + */ public function listusers() { if ($this->db === null) { @@ -284,9 +325,9 @@ class Authsql extends Auth ), 500); } $data = $this->db->read(null, array_merge( - array($this->fieldIdentifier, + [$this->fieldIdentifier, $this->fieldFirstname, - $this->fieldLastname), + $this->fieldLastname], $this->fieldsInfo )); return $data; diff --git a/src/Authsympa.php b/src/Authsympa.php index 4a945ed..3fceba2 100644 --- a/src/Authsympa.php +++ b/src/Authsympa.php @@ -1,47 +1,63 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** User authentication against SYMPA server - Sympa is a mailling list server. It can handle authentication with - - a username (a email adress) - - a password - - a list to check if the user is recorded in - - a Sympa SOAP server WSDL - - the part of list which should be test : subscriber, owner, editor - It use the SOAP protocol. So the PHP SOAP library is needed and the network - must be open between the Web server and the Sympa server. -POC : -$auth = new Authsympa (); -$auth->wsdl = "https://lists.domain.tld/sympa/wsdl"; -$auth->list = "listtest@lists.domain.tld"; -$auth->connect (); -var_dump ($auth->authentication ("user@domain.tld", "Pa$$word!")); -*/ +/** + * User authentication against SYMPA server + * Sympa is a mailling list server. It can handle authentication with + * - a username (a email adress) + * - a password + * - a list to check if the user is recorded in + * - a Sympa SOAP server WSDL + * - the part of list which should be test : subscriber, owner, editor + * It use the SOAP protocol. So the PHP SOAP library is needed and the network + * must be open between the Web server and the Sympa server. + * POC : + * $auth = new Authsympa (); + * $auth->wsdl = "https://lists.domain.tld/sympa/wsdl"; + * $auth->list = "listtest@lists.domain.tld"; + * $auth->connect (); + * var_dump ($auth->authentication ("user@domain.tld", "Pa$$word!")); + */ class Authsympa extends Auth { - /** URL of the WSDL Sympa server */ + /** + * URL of the WSDL Sympa server + */ public $wsdl = null; - /** Mailling list to be checked if user is present */ + /** + * Mailling list to be checked if user is present + */ public $list = null; - /** Function of the user in the mailling list - can be subscriber, owner, editor */ + /** + * Function of the user in the mailling list + * can be subscriber, owner, editor + */ public $function = "subscriber"; - /** Soap Client identifier */ + /** + * Soap Client identifier + */ private $client = null; - /** Temporary auth key used betwwen commands */ + /** + * Temporary auth key used betwwen commands + */ private $authkey = null; - /** Email of the user if the authentication is correct */ + /** + * Email of the user if the authentication is correct + */ private $details = null; - /** Check if the SOAP module is available in PHP */ + /** + * Check if the SOAP module is available in PHP + */ public function __construct() { if (! class_exists("SoapClient")) { @@ -52,7 +68,9 @@ class Authsympa extends Auth } } - /** Connect to the Sympa server */ + /** + * Connect to the Sympa server + */ public function connect() { if ($this->wsdl === null) { @@ -64,9 +82,11 @@ class Authsympa extends Auth $this->client = new \SoapClient($this->wsdl); } - /** Try to authenticate the email/password of the user - @param string $email Email to authenticate - @param string $password Password to authenticate */ + /** + * Try to authenticate the email/password of the user + * @param string $email Email to authenticate + * @param string $password Password to authenticate + */ public function authentication($email, $password) { if ($this->client === null) { @@ -95,7 +115,7 @@ class Authsympa extends Auth $email, $this->authkey, 'amI', - array($this->list, $this->function, $email) + [$this->list, $this->function, $email] ); if ($rc === null || $rc === false) { throw new \Exception(dgettext( @@ -103,20 +123,24 @@ class Authsympa extends Auth "User not in Sympa list or bad password" ), 401); } - $this->details = array("email" => $email); + $this->details = ["email" => $email]; return $rc; } - /** Return all the parameters recorded for the authenticate user */ + /** + * Return all the parameters recorded for the authenticate user + */ public function getdetails() { return $this->details; } - /** Method to change the password - @param string $oldpassword The old password (to check if the user have the - rights to change the password) - @param string $newpassword The new password to be recorded */ + /** + * Method to change the password + * @param string $oldpassword The old password (to check if the user have the + * rights to change the password) + * @param string $newpassword The new password to be recorded + */ public function changepassword($oldpassword, $newpassword) { throw new \Exception( @@ -128,11 +152,13 @@ class Authsympa extends Auth ); } - /** Method to overwrite the password (without oldpassword check) - Must be reserved to the administrators. For the users, use changepassword - method - @param string $email the user identifier to select - @param string $newpassword The new password to be recorded */ + /** + * Method to overwrite the password (without oldpassword check) + * Must be reserved to the administrators. For the users, use changepassword + * method + * @param string $email the user identifier to select + * @param string $newpassword The new password to be recorded + */ public function overwritepassword($email, $newpassword) { throw new \Exception( diff --git a/src/Authzgroups.php b/src/Authzgroups.php index bde8668..00e8233 100644 --- a/src/Authzgroups.php +++ b/src/Authzgroups.php @@ -1,15 +1,18 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** All the needed functions to authorize or deny access to an authenticated - user by its groups membership */ +/** + * All the needed functions to authorize or deny access to an authenticated + * user by its groups membership + */ class Authzgroups { /** @@ -17,28 +20,41 @@ class Authzgroups * @var string */ public $tableprefix = ""; - /** The dblayer object use to manage the Object table */ + /** + * The dblayer object use to manage the Object table + */ private $dbObject = null; - /** The dblayer object use to manage the Group table */ + /** + * The dblayer object use to manage the Group table + */ private $dbGroup = null; - /** The dblayer object use to manage the GroupMember table */ + /** + * The dblayer object use to manage the GroupMember table + */ private $dbGroupMember = null; - /** The dblayer object use to manage the Right table */ + /** + * The dblayer object use to manage the Right table + */ private $dbRight = null; - /** Set the debug level */ + /** + * Set the debug level + */ public $debug = 0; - /** A local cache of the rights if multiple tests are needed */ + /** + * A local cache of the rights if multiple tests are needed + */ private $rightCache = null; ///////////////////// // USER RIGHTS // ///////////////////// - /** Return an array with all the rights of the user in the module. - * Cache this information to be quicker with next requests - * Remove the entries where path is not at least readable - * @param string $module The module to use - * @param string $user The user to get the rights - */ + /** + * Return an array with all the rights of the user in the module. + * Cache this information to be quicker with next requests + * Remove the entries where path is not at least readable + * @param string $module The module to use + * @param string $user The user to get the rights + */ public function userrightsget($module, $user) { // if (isset ($_SESSION["domframework"]["authzgroups"][$module][$user])) @@ -99,7 +115,7 @@ class Authzgroups } throw new \Exception($e->getMessage(), 500); } - $res = array(); + $res = []; while ($d = $st->fetch(\PDO::FETCH_ASSOC)) { $res[$d["object"]] = $d["right"]; } @@ -126,47 +142,32 @@ class Authzgroups return $res; } - /** Return the right defined for this user in the module for one object - * @param string $module The module to use - * @param string $user The user to get the rights - * @param string $object The object to return the rights for the user - */ + /** + * Return the right defined for this user in the module for one object + * @param string $module The module to use + * @param string $user The user to get the rights + * @param string $object The object to return the rights for the user + */ public function allow($module, $user, $object) { $ressource = $this->userrightsget($module, $user); // The complete tree should not be readable for the user : it can have // access to a card, but not to all the cards (group -> reject, // group/XXX->allow) - /*// Limit to allowed trees : if a member of the path is not recorded (is - // unreadable), return NO. - // Can be the last entry (the complete object) too - $path = explode ("/", $object); - $completePath = "/"; - foreach ($path as $k=>$p) - { - if ($k>1) - $completePath .= "/"; - $completePath .= "$p"; - if (! isset ($ressource[$completePath])) - { - if ($this->debug) - echo "DEBUG allow : REJECT because $completePath is not found\n"; - return "NO"; - } - }*/ if (! isset($ressource[$object])) { return "NO"; } return $ressource[$object]; } - /** Return TRUE if the user right allow to see the object (RO or RW) - * Return a 403 Exception if the user don't have the right - * Return a 401 Exception if the user is not connected - * @param string $module The module to use - * @param string $user The user to get the rights - * @param string $object The object to check the rights for the user - */ + /** + * Return TRUE if the user right allow to see the object (RO or RW) + * Return a 403 Exception if the user don't have the right + * Return a 401 Exception if the user is not connected + * @param string $module The module to use + * @param string $user The user to get the rights + * @param string $object The object to check the rights for the user + */ public function accessRight($module, $user, $object) { if ($this->dbObject === null) { @@ -211,13 +212,14 @@ class Authzgroups throw new \Exception(dgettext("domframework", "Access forbidden"), 403); } - /** Return TRUE if the user right allow to edit the object (RW only) - * Return a 403 Exception if the user don't have the right - * Return a 401 Exception if the user is not connected - * @param string $module The module to use - * @param string $user The user to get the rights - * @param string $object The object to check the rights for the user - */ + /** + * Return TRUE if the user right allow to edit the object (RW only) + * Return a 403 Exception if the user don't have the right + * Return a 401 Exception if the user is not connected + * @param string $module The module to use + * @param string $user The user to get the rights + * @param string $object The object to check the rights for the user + */ public function accessWrite($module, $user, $object) { if ($this->dbObject === null) { @@ -265,14 +267,15 @@ class Authzgroups ); } - /** Return TRUE if the user right allow to see but without modification - * the object (RO only) - * Return a 403 Exception if the user don't have the right - * Return a 401 Exception if the user is not connected - * @param string $module The module to use - * @param string $user The user to get the rights - * @param string $object The object to check the rights for the user - */ + /** + * Return TRUE if the user right allow to see but without modification + * the object (RO only) + * Return a 403 Exception if the user don't have the right + * Return a 401 Exception if the user is not connected + * @param string $module The module to use + * @param string $user The user to get the rights + * @param string $object The object to check the rights for the user + */ public function accessReadOnly($module, $user, $object) { if ($this->dbObject === null) { @@ -320,14 +323,15 @@ class Authzgroups ///////////////////////// // DATABASE STORAGE // ///////////////////////// - /** Connect to the database before using it - * @param string $dsn The DSN to use to connect to the database - * @param string|null $username The username to use to connect to the - * database - * @param string|null $password The password to use to connect to the - * database - * @param array|null $driver_options The options to pass to PDO driver - */ + /** + * Connect to the database before using it + * @param string $dsn The DSN to use to connect to the database + * @param string|null $username The username to use to connect to the + * database + * @param string|null $password The password to use to connect to the + * database + * @param array|null $driver_options The options to pass to PDO driver + */ public function connect( $dsn, $username = null, @@ -338,35 +342,35 @@ class Authzgroups $this->dbObject->debug = $this->debug; $this->dbObject->table = "authzobject"; $this->dbObject->tableprefix = $this->tableprefix; - $this->dbObject->fields = array( - "idobject" => array("integer", "not null", "autoincrement"), - "module" => array("varchar", "255", "not null"), - "object" => array("varchar", "255", "not null"), - "comment" => array("varchar", "255")); + $this->dbObject->fields = [ + "idobject" => ["integer", "not null", "autoincrement"], + "module" => ["varchar", "255", "not null"], + "object" => ["varchar", "255", "not null"], + "comment" => ["varchar", "255"]]; $this->dbObject->primary = "idobject"; - $this->dbObject->unique = array("idobject", array("object", "module")); - $this->dbObject->titles = array( + $this->dbObject->unique = ["idobject", ["object", "module"]]; + $this->dbObject->titles = [ "idobject" => dgettext("domframework", "idobject"), "module" => dgettext("domframework", "Module"), "object" => dgettext("domframework", "Object"), - "comment" => dgettext("domframework", "Comment")); + "comment" => dgettext("domframework", "Comment")]; $this->dbGroup = new Dblayer($dsn, $username, $password, $driver_options); $this->dbGroup->debug = $this->debug; $this->dbGroup->table = "authzgroup"; $this->dbGroup->tableprefix = $this->tableprefix; - $this->dbGroup->fields = array( - "idgroup" => array("integer", "not null", "autoincrement"), - "module" => array("varchar", "255", "not null"), - "group" => array("varchar", "255", "not null"), - "comment" => array("varchar", "255")); + $this->dbGroup->fields = [ + "idgroup" => ["integer", "not null", "autoincrement"], + "module" => ["varchar", "255", "not null"], + "group" => ["varchar", "255", "not null"], + "comment" => ["varchar", "255"]]; $this->dbGroup->primary = "idgroup"; - $this->dbGroup->unique = array("idgroup", array("module", "group")); - $this->dbGroup->titles = array( + $this->dbGroup->unique = ["idgroup", ["module", "group"]]; + $this->dbGroup->titles = [ "idgroup" => dgettext("domframework", "idgroup"), "module" => dgettext("domframework", "Module"), "group" => dgettext("domframework", "Group"), - "comment" => dgettext("domframework", "Comment")); + "comment" => dgettext("domframework", "Comment")]; $this->dbGroupMember = new Dblayer( $dsn, @@ -377,59 +381,61 @@ class Authzgroups $this->dbGroupMember->debug = $this->debug; $this->dbGroupMember->table = "authzgroupmember"; $this->dbGroupMember->tableprefix = $this->tableprefix; - $this->dbGroupMember->fields = array( - "idgroupmember" => array("integer", "not null", "autoincrement"), - "user" => array("varchar", "255", "not null"), - "idgroup" => array("integer", "not null"), - "comment" => array("varchar", "255")); + $this->dbGroupMember->fields = [ + "idgroupmember" => ["integer", "not null", "autoincrement"], + "user" => ["varchar", "255", "not null"], + "idgroup" => ["integer", "not null"], + "comment" => ["varchar", "255"]]; $this->dbGroupMember->primary = "idgroupmember"; - $this->dbGroupMember->unique = array("idgroupmember", - array("user", "idgroup")); - $this->dbGroupMember->foreign = array( - "idgroup" => array("authzgroup", "idgroup", - "ON UPDATE CASCADE ON DELETE CASCADE")); - $this->dbGroupMember->titles = array( + $this->dbGroupMember->unique = ["idgroupmember", + ["user", "idgroup"]]; + $this->dbGroupMember->foreign = [ + "idgroup" => ["authzgroup", "idgroup", + "ON UPDATE CASCADE ON DELETE CASCADE"]]; + $this->dbGroupMember->titles = [ "idgroupmember" => dgettext("domframework", "idgroupmember"), "user" => dgettext("domframework", "User"), "idgroup" => dgettext("domframework", "idgroup"), - "comment" => dgettext("domframework", "Comment")); + "comment" => dgettext("domframework", "Comment")]; $this->dbRight = new Dblayer($dsn, $username, $password, $driver_options); $this->dbRight->debug = $this->debug; $this->dbRight->table = "authzright"; $this->dbRight->tableprefix = $this->tableprefix; - $this->dbRight->fields = array( - "idright" => array("integer", "not null", "autoincrement"), - "idgroup" => array("integer", "not null"), - "idobject" => array("integer", "not null"), - "right" => array("varchar", "2", "not null"), // RO, RW - "comment" => array("varchar", "255")); + $this->dbRight->fields = [ + "idright" => ["integer", "not null", "autoincrement"], + "idgroup" => ["integer", "not null"], + "idobject" => ["integer", "not null"], + "right" => ["varchar", "2", "not null"], // RO, RW + "comment" => ["varchar", "255"]]; $this->dbRight->primary = "idright"; - $this->dbRight->unique = array("idright", array("idgroup", "idobject")); - $this->dbRight->foreign = array( - "idgroup" => array("authzgroup", "idgroup", - "ON UPDATE CASCADE ON DELETE CASCADE"), - "idobject" => array("authzobject", "idobject", - "ON UPDATE CASCADE ON DELETE CASCADE"), - ); - $this->dbRight->titles = array( + $this->dbRight->unique = ["idright", ["idgroup", "idobject"]]; + $this->dbRight->foreign = [ + "idgroup" => ["authzgroup", "idgroup", + "ON UPDATE CASCADE ON DELETE CASCADE"], + "idobject" => ["authzobject", "idobject", + "ON UPDATE CASCADE ON DELETE CASCADE"], + ]; + $this->dbRight->titles = [ "idright" => dgettext("domframework", "idright"), "idgroup" => dgettext("domframework", "idgroup"), "idobject" => dgettext("domframework", "idobject"), "right" => dgettext("domframework", "Right"), - "comment" => dgettext("domframework", "Comment")); + "comment" => dgettext("domframework", "Comment")]; return true; } - /** Disconnect from the database. Should be only used in the unit tests - */ + /** + * Disconnect from the database. Should be only used in the unit tests + */ public function disconnect() { $this->dbObject->disconnect(); } - /** Create the tables in the database to store the data - */ + /** + * Create the tables in the database to store the data + */ public function createTables() { if ($this->dbObject == null) { @@ -459,7 +465,7 @@ class Authzgroups "DB for Right is not connected" ), 500); } - $tables = array("Object", "Group", "GroupMember", "Right"); + $tables = ["Object", "Group", "GroupMember", "Right"]; foreach ($tables as $table) { try { $class = "db$table"; @@ -474,12 +480,13 @@ class Authzgroups ///////////////// // OBJECTS // ///////////////// - /** Add a new object to object list - * Return the idobject created - * @param string $module The module to use - * @param string $object The object to create - * @param string|null $comment The comment to save - */ + /** + * Add a new object to object list + * Return the idobject created + * @param string $module The module to use + * @param string $object The object to create + * @param string|null $comment The comment to save + */ public function objectAdd($module, $object, $comment = "") { if ($this->dbObject == null) { @@ -490,15 +497,16 @@ class Authzgroups } // TODO : Check parameters before saving them $this->rightCache = null; - return $this->dbObject->insert(array("module" => $module, + return $this->dbObject->insert(["module" => $module, "object" => $object, - "comment" => $comment)); + "comment" => $comment]); } - /** Remove an object from database and all the rights using it - * @param string $module The module to use - * @param string $object The object to delete - */ + /** + * Remove an object from database and all the rights using it + * @param string $module The module to use + * @param string $object The object to delete + */ public function objectDel($module, $object) { if ($this->dbObject == null) { @@ -518,10 +526,11 @@ class Authzgroups return $this->dbObject->delete($idobjects[0]["idobject"]); } - /** Remove an object from database and all the rights using it - * @param string $module The module to use - * @param integer $idobject The object to delete - */ + /** + * Remove an object from database and all the rights using it + * @param string $module The module to use + * @param integer $idobject The object to delete + */ public function objectDelByID($module, $idobject) { if ($this->dbObject == null) { @@ -541,12 +550,13 @@ class Authzgroups return $this->dbObject->delete($idobjects[0]["idobject"]); } - /** Update an object in the database - * @param string $module The module to use - * @param string $object The object to update - * @param string $newobject The new name of the object - * @param string|null $newcomment The new comment of the object - */ + /** + * Update an object in the database + * @param string $module The module to use + * @param string $object The object to update + * @param string $newobject The new name of the object + * @param string|null $newcomment The new comment of the object + */ public function objectUpdate($module, $object, $newobject, $newcomment = "") { if ($this->dbObject == null) { @@ -565,17 +575,18 @@ class Authzgroups $this->rightCache = null; return $this->dbObject->update( $idobjects[0]["idobject"], - array("object" => $newobject, - "comment" => $newcomment) + ["object" => $newobject, + "comment" => $newcomment] ); } - /** Update an object in the database - * @param string $module The module to use - * @param integer $idobject The object to update - * @param string $newobject The new name of the object - * @param string|null $newcomment The new comment of the object - */ + /** + * Update an object in the database + * @param string $module The module to use + * @param integer $idobject The object to update + * @param string $newobject The new name of the object + * @param string|null $newcomment The new comment of the object + */ public function objectUpdateByID( $module, $idobject, @@ -598,16 +609,17 @@ class Authzgroups $this->rightCache = null; return $this->dbObject->update( $idobjects[0]["idobject"], - array("object" => $newobject, - "comment" => $newcomment) + ["object" => $newobject, + "comment" => $newcomment] ); } - /** Return an array with all the available objects in the module, or only - * one object if $object is provided - * @param string $module The module to use - * @param string $object The name of the object to get - */ + /** + * Return an array with all the available objects in the module, or only + * one object if $object is provided + * @param string $module The module to use + * @param string $object The name of the object to get + */ public function objectRead($module, $object = null) { if ($this->dbObject == null) { @@ -616,22 +628,23 @@ class Authzgroups "DB for Object is not connected" ), 500); } - $select[] = array("module", $module); + $select[] = ["module", $module]; if ($object !== null) { - $select[] = array("object", $object); + $select[] = ["object", $object]; } return $this->dbObject->read( $select, null, - array(array("object", "ASC")) + [["object", "ASC"]] ); } - /** Return an array with all the available objects in the module, or only - * one object if $object is provided - * @param string $module The module to use - * @param integer $idobject The name of the object to get - */ + /** + * Return an array with all the available objects in the module, or only + * one object if $object is provided + * @param string $module The module to use + * @param integer $idobject The name of the object to get + */ public function objectReadByID($module, $idobject = null) { if ($this->dbObject == null) { @@ -640,26 +653,28 @@ class Authzgroups "DB for Object is not connected" ), 500); } - $select[] = array("module", $module); + $select[] = ["module", $module]; if ($idobject !== null) { - $select[] = array("idobject", $idobject); + $select[] = ["idobject", $idobject]; } return $this->dbObject->read($select); } - /** Return an array containing the titles of the table translating in the user - * language - */ + /** + * Return an array containing the titles of the table translating in the user + * language + */ public function objectTitles() { return $this->dbObject->titles; } - /** Check if the provided data are compliant with the object specification - * @param array $data The name of the object to get - * @param integer|null $idobject The object to check - * @return array The errors found in the data - */ + /** + * Check if the provided data are compliant with the object specification + * @param array $data The name of the object to get + * @param integer|null $idobject The object to check + * @return array The errors found in the data + */ public function objectVerify($data, $idobject = false) { return $this->dbObject->verify($data, $idobject); @@ -668,12 +683,13 @@ class Authzgroups //////////////// // GROUPS // //////////////// - /** Add a new group to group list - * Return the idgroup created - * @param string $module The module to use - * @param string $group The group to create - * @param string|null $comment The comment to add with the group - */ + /** + * Add a new group to group list + * Return the idgroup created + * @param string $module The module to use + * @param string $group The group to create + * @param string|null $comment The comment to add with the group + */ public function groupAdd($module, $group, $comment = "") { if ($this->dbGroup == null) { @@ -683,15 +699,16 @@ class Authzgroups ), 500); } // TODO : Check parameters before saving them - return $this->dbGroup->insert(array("module" => $module, + return $this->dbGroup->insert(["module" => $module, "group" => $group, - "comment" => $comment)); + "comment" => $comment]); } - /** Remove an group from database and all the rights using it - * @param string $module The module to use - * @param string $group The group to delete - */ + /** + * Remove an group from database and all the rights using it + * @param string $module The module to use + * @param string $group The group to delete + */ public function groupDel($module, $group) { if ($this->dbGroup == null) { @@ -710,10 +727,11 @@ class Authzgroups return $this->dbGroup->delete($idgroups[0]["idgroup"]); } - /** Remove an group from database and all the rights using it - * @param string $module The module to use - * @param integer $idgroup The group to delete - */ + /** + * Remove an group from database and all the rights using it + * @param string $module The module to use + * @param integer $idgroup The group to delete + */ public function groupDelByID($module, $idgroup) { if ($this->dbGroup == null) { @@ -732,12 +750,13 @@ class Authzgroups return $this->dbGroup->delete($idgroups[0]["idgroup"]); } - /** Update an group in the database - * @param string $module The module to use - * @param string $group The group to update - * @param string $newgroup The new group name - * @param string|null $comment The comment for the group - */ + /** + * Update an group in the database + * @param string $module The module to use + * @param string $group The group to update + * @param string $newgroup The new group name + * @param string|null $comment The comment for the group + */ public function groupUpdate($module, $group, $newgroup, $comment = "") { if ($this->dbGroup == null) { @@ -755,17 +774,18 @@ class Authzgroups } return $this->dbGroup->update( $idgroups[0]["idgroup"], - array("group" => $newgroup, - "comment" => $comment) + ["group" => $newgroup, + "comment" => $comment] ); } - /** Update an group in the database - * @param string $module The module to use - * @param integer $idgroup The group to update - * @param string $newgroup The new group name - * @param string|null $comment The comment for the group - */ + /** + * Update an group in the database + * @param string $module The module to use + * @param integer $idgroup The group to update + * @param string $newgroup The new group name + * @param string|null $comment The comment for the group + */ public function groupUpdateByID($module, $idgroup, $newgroup, $comment = "") { if ($this->dbGroup == null) { @@ -783,15 +803,16 @@ class Authzgroups } return $this->dbGroup->update( $idgroups[0]["idgroup"], - array("group" => $newgroup, - "comment" => $comment) + ["group" => $newgroup, + "comment" => $comment] ); } - /** Return an array with all the available groups in the module - * @param string $module The module to use - * @param string|null $group The group to check if exists - */ + /** + * Return an array with all the available groups in the module + * @param string $module The module to use + * @param string|null $group The group to check if exists + */ public function groupRead($module, $group = null) { if ($this->dbGroup == null) { @@ -800,18 +821,19 @@ class Authzgroups "DB for Group is not connected" ), 500); } - $select[] = array("module", $module); + $select[] = ["module", $module]; if ($group !== null) { - $select[] = array("group", $group); + $select[] = ["group", $group]; } - return $this->dbGroup->read($select, null, array(array("group", "ASC"))); + return $this->dbGroup->read($select, null, [["group", "ASC"]]); } - /** Return an array with all the available groups in the module - * @param string $module The module to use - * @param integer $idgroup The group to check if exists - */ + /** + * Return an array with all the available groups in the module + * @param string $module The module to use + * @param integer $idgroup The group to check if exists + */ public function groupReadByID($module, $idgroup) { if ($this->dbGroup == null) { @@ -820,24 +842,26 @@ class Authzgroups "DB for Group is not connected" ), 500); } - $select[] = array("module", $module); - $select[] = array("idgroup", $idgroup); + $select[] = ["module", $module]; + $select[] = ["idgroup", $idgroup]; return $this->dbGroup->read($select); } - /** Return an array containing the titles of the table translating in the user - * language - */ + /** + * Return an array containing the titles of the table translating in the user + * language + */ public function groupTitles() { return $this->dbGroup->titles; } - /** Check if the provided data are compilant with the group specification - * @param array $data The data to check - * @param integer|null $idgroup The idgroup to check - * @return array The errors found in the data - */ + /** + * Check if the provided data are compilant with the group specification + * @param array $data The data to check + * @param integer|null $idgroup The idgroup to check + * @return array The errors found in the data + */ public function groupVerify($data, $idgroup = false) { return $this->dbGroup->verify($data, $idgroup); @@ -846,13 +870,14 @@ class Authzgroups ////////////////////// // GROUP MEMBER // ////////////////////// - /** Add a new groupmember to groupmember list - * Return the idgroupmember created - * @param string $module The module to use - * @param string $group The group to use - * @param string $user The user to add in group - * @param string|null $comment The comment to save - */ + /** + * Add a new groupmember to groupmember list + * Return the idgroupmember created + * @param string $module The module to use + * @param string $group The group to use + * @param string $user The user to add in group + * @param string|null $comment The comment to save + */ public function groupmemberAdd($module, $group, $user, $comment = "") { if ($this->dbGroupMember == null) { @@ -872,17 +897,18 @@ class Authzgroups ), 404); } $this->rightCache = null; - return $this->dbGroupMember->insert(array( + return $this->dbGroupMember->insert([ "user" => $user, "idgroup" => $groups[0]["idgroup"], - "comment" => $comment)); + "comment" => $comment]); } - /** Remove an groupmember from database and all the rights using it - * @param string $module The module to use - * @param string $group The group to use - * @param string $user The user to remove - */ + /** + * Remove an groupmember from database and all the rights using it + * @param string $module The module to use + * @param string $group The group to use + * @param string $user The user to remove + */ public function groupmemberDel($module, $group, $user) { if ($this->dbGroupMember == null) { @@ -901,9 +927,9 @@ class Authzgroups "Wanted group not found" ), 404); } - $groupsMembers = $this->dbGroupMember->read(array( - array("user", $user), - array("idgroup", $groups[0]["idgroup"]))); + $groupsMembers = $this->dbGroupMember->read([ + ["user", $user], + ["idgroup", $groups[0]["idgroup"]]]); if (! isset($groupsMembers[0]["idgroupmember"])) { throw new \Exception(dgettext( "domframework", @@ -914,11 +940,12 @@ class Authzgroups return $this->dbGroupMember->delete($groupsMembers[0]["idgroupmember"]); } - /** Remove an groupmember from database and all the rights using it - * @param string $module The module to use - * @param integer $idgroup The group to use - * @param integer $idgroupmember The user to remove - */ + /** + * Remove an groupmember from database and all the rights using it + * @param string $module The module to use + * @param integer $idgroup The group to use + * @param integer $idgroupmember The user to remove + */ public function groupmemberDelByID($module, $idgroup, $idgroupmember) { if ($this->dbGroupMember == null) { @@ -934,9 +961,9 @@ class Authzgroups "Wanted group not found" ), 404); } - $groupsMembers = $this->dbGroupMember->read(array( - array("idgroupmember", $idgroupmember), - array("idgroup", $idgroup))); + $groupsMembers = $this->dbGroupMember->read([ + ["idgroupmember", $idgroupmember], + ["idgroup", $idgroup]]); if (! isset($groupsMembers[0]["idgroupmember"])) { throw new \Exception(dgettext( "domframework", @@ -947,25 +974,27 @@ class Authzgroups return $this->dbGroupMember->delete($groupsMembers[0]["idgroupmember"]); } - /** Update an groupmember in the database - * @param string $module The module to use - * @param string $group The group to use - * @param string $user The user to update - * @param string|null $comment The comment to update - */ + /** + * Update an groupmember in the database + * @param string $module The module to use + * @param string $group The group to use + * @param string $user The user to update + * @param string|null $comment The comment to update + */ public function groupmemberUpdate($module, $group, $user, $comment = "") { $this->rightCache = null; die("This function is not available : contact us if you need it\n"); } - /** Update an groupmember in the database - * @param string $module The module to use - * @param integer $idgroup The group to use - * @param integer $iduser The user to update - * @param string $user The new user name - * @param string|null $comment The comment to update - */ + /** + * Update an groupmember in the database + * @param string $module The module to use + * @param integer $idgroup The group to use + * @param integer $iduser The user to update + * @param string $user The new user name + * @param string|null $comment The comment to update + */ public function groupmemberUpdateByID( $module, $idgroup, @@ -983,16 +1012,17 @@ class Authzgroups $this->rightCache = null; return $this->dbGroupMember->update( $iduser, - array("user" => $user, - "comment" => $comment) + ["user" => $user, + "comment" => $comment] ); } - /** Return an array with all the groups where the user is in and in the module - * @param string $module The module to use - * @param string $user The user to search - */ + /** + * Return an array with all the groups where the user is in and in the module + * @param string $module The module to use + * @param string $user The user to search + */ public function groupmemberReadUser($module, $user) { if ($this->dbGroupMember == null) { @@ -1006,24 +1036,25 @@ class Authzgroups } $idgrouptmps = $this->groupRead($module); // Create an array with idgroup=>group - $idgroups = array(); + $idgroups = []; foreach ($idgrouptmps as $val) { $idgroups[$val["idgroup"]] = $val["group"]; } - $select = array(); - $select[] = array("user", $user); + $select = []; + $select[] = ["user", $user]; $idgroupmembers = $this->dbGroupMember->read($select); - $res = array(); + $res = []; foreach ($idgroupmembers as $idmembers) { $res[$idmembers["idgroup"]] = $idgroups[$idmembers["idgroup"]]; } return $res; } - /** Return an array with all the groups where the user is in and in the module - * @param string $module The module to use - * @param integer $idgroupmember The user to search - */ + /** + * Return an array with all the groups where the user is in and in the module + * @param string $module The module to use + * @param integer $idgroupmember The user to search + */ public function groupmemberReadUserByID($module, $idgroupmember) { if ($this->dbGroupMember == null) { @@ -1037,25 +1068,26 @@ class Authzgroups } $idgrouptmps = $this->groupRead($module); // Create an array with idgroup=>group - $idgroups = array(); + $idgroups = []; foreach ($idgrouptmps as $val) { $idgroups[$val["idgroup"]] = $val["group"]; } - $select = array(); - $select[] = array("idgroupmember", $idgroupmember); + $select = []; + $select[] = ["idgroupmember", $idgroupmember]; $idgroupmembers = $this->dbGroupMember->read($select); - $res = array(); + $res = []; foreach ($idgroupmembers as $idmembers) { $res[$idmembers["idgroup"]] = $idgroups[$idmembers["idgroup"]]; } return $res; } - /** Return an array with all the available users in the group and in the - * module - * @param string $module The module to use - * @param string $group The group to search - */ + /** + * Return an array with all the available users in the group and in the + * module + * @param string $module The module to use + * @param string $group The group to search + */ public function groupmemberReadGroup($module, $group) { if ($this->dbGroupMember == null) { @@ -1074,15 +1106,16 @@ class Authzgroups "Wanted group not found" ), 404); } - $select[] = array("idgroup", $groups[0]["idgroup"]); - return $this->dbGroupMember->read($select, array("user")); + $select[] = ["idgroup", $groups[0]["idgroup"]]; + return $this->dbGroupMember->read($select, ["user"]); } - /** Return an array with all the available users in the group and in the - * module - * @param string $module The module to use - * @param integer $idgroup The group to search - */ + /** + * Return an array with all the available users in the group and in the + * module + * @param string $module The module to use + * @param integer $idgroup The group to search + */ public function groupmemberReadGroupByID($module, $idgroup) { if ($this->dbGroupMember == null) { @@ -1101,15 +1134,16 @@ class Authzgroups "Wanted group not found" ), 404); } - $select[] = array("idgroup", $groups[0]["idgroup"]); + $select[] = ["idgroup", $groups[0]["idgroup"]]; return $this->dbGroupMember->read($select); } - /** Return an array containing the information of a user in a specific group - * @param string $module The module to use - * @param integer $idgroup The group to search - * @param integer $iduser The user to search - */ + /** + * Return an array containing the information of a user in a specific group + * @param string $module The module to use + * @param integer $idgroup The group to search + * @param integer $iduser The user to search + */ public function groupmemberReadUserDataByID($module, $idgroup, $iduser) { if ($this->dbGroupMember == null) { @@ -1128,24 +1162,26 @@ class Authzgroups "Wanted group not found" ), 404); } - $select[] = array("idgroup", $groups[0]["idgroup"]); - $select[] = array("idgroupmember", $iduser); + $select[] = ["idgroup", $groups[0]["idgroup"]]; + $select[] = ["idgroupmember", $iduser]; return $this->dbGroupMember->read($select); } - /** Return an array containing the titles of the table translating in the user - * language - */ + /** + * Return an array containing the titles of the table translating in the user + * language + */ public function groupmembersTitles() { return $this->dbGroupMember->titles; } - /** Check if the provided data are compilant with the group specification - * @param array $data The data to check - * @param integer|null $idgroupmember The group member associated to verify - * @return array The errors found in the data - */ + /** + * Check if the provided data are compilant with the group specification + * @param array $data The data to check + * @param integer|null $idgroupmember The group member associated to verify + * @return array The errors found in the data + */ public function groupmembersVerify($data, $idgroupmember = false) { return $this->dbGroupMember->verify($data, $idgroupmember); @@ -1154,14 +1190,15 @@ class Authzgroups //////////////// // RIGHTS // //////////////// - /** Add a new right to right list - * Return the idright created - * @param string $module The module to use - * @param string $group The group to use - * @param string $object The object to use - * @param string $right The right to add - * @param string|null $comment The comment to add - */ + /** + * Add a new right to right list + * Return the idright created + * @param string $module The module to use + * @param string $group The group to use + * @param string $object The object to use + * @param string $right The right to add + * @param string|null $comment The comment to add + */ public function rightAdd($module, $group, $object, $right, $comment = "") { if ($this->dbRight == null) { @@ -1201,20 +1238,21 @@ class Authzgroups ), 404); } $this->rightCache = null; - return $this->dbRight->insert(array("idgroup" => $groups[0]["idgroup"], + return $this->dbRight->insert(["idgroup" => $groups[0]["idgroup"], "idobject" => $objects[0]["idobject"], "right" => $right, - "comment" => $comment)); + "comment" => $comment]); } - /** Add a new right to right list by ID - * Return the idright created - * @param string $module The module to use - * @param integer $idgroup The group to use - * @param integer $idobject The object to use - * @param integer $idright The right to add - * @param string|null $comment The comment to add - */ + /** + * Add a new right to right list by ID + * Return the idright created + * @param string $module The module to use + * @param integer $idgroup The group to use + * @param integer $idobject The object to use + * @param integer $idright The right to add + * @param string|null $comment The comment to add + */ public function rightAddByID( $module, $idgroup, @@ -1259,17 +1297,18 @@ class Authzgroups ), 404); } $this->rightCache = null; - return $this->dbRight->insert(array("idgroup" => $groups[0]["idgroup"], + return $this->dbRight->insert(["idgroup" => $groups[0]["idgroup"], "idobject" => $objects[0]["idobject"], "right" => $right, - "comment" => $comment)); + "comment" => $comment]); } - /** Remove an right from database and all the rights using it - * @param string $module The module to use - * @param string $group The group to use - * @param string $object The object to remove the rights - */ + /** + * Remove an right from database and all the rights using it + * @param string $module The module to use + * @param string $group The group to use + * @param string $object The object to remove the rights + */ public function rightDel($module, $group, $object) { if ($this->dbRight == null) { @@ -1289,10 +1328,11 @@ class Authzgroups return $this->dbRight->delete($idrights[0]["idright"]); } - /** Remove an right from database by ID and all the rights using it - * @param string $module The module to use - * @param integer $idright The idright to be deleted - */ + /** + * Remove an right from database by ID and all the rights using it + * @param string $module The module to use + * @param integer $idright The idright to be deleted + */ public function rightDelByID($module, $idright) { if ($this->dbRight == null) { @@ -1312,13 +1352,14 @@ class Authzgroups return $this->dbRight->delete($idrights[0]["idright"]); } - /** Update a right in the database - * @param string $module The module to use - * @param string $group The group to update the right - * @param string $object The object ot update the right - * @param string $newright The new right to save - * @param string|null $newcomment The new comment to save - */ + /** + * Update a right in the database + * @param string $module The module to use + * @param string $group The group to update the right + * @param string $object The object ot update the right + * @param string $newright The new right to save + * @param string|null $newcomment The new comment to save + */ public function rightUpdate( $module, $group, @@ -1358,18 +1399,19 @@ class Authzgroups $this->rightCache = null; return $this->dbRight->update( $idrights[0]["idright"], - array("right" => $newright, - "comment" => $newcomment) + ["right" => $newright, + "comment" => $newcomment] ); } - /** Update a right by ID in the database - * @param string $module The module to use - * @param integer $idright The idright to update the right - * @param integer $newidobject The object ot update the right - * @param integer $newright The new right to save - * @param string|null $newcomment The new comment to save - */ + /** + * Update a right by ID in the database + * @param string $module The module to use + * @param integer $idright The idright to update the right + * @param integer $newidobject The object ot update the right + * @param integer $newright The new right to save + * @param string|null $newcomment The new comment to save + */ public function rightUpdateByID( $module, $idright, @@ -1409,19 +1451,20 @@ class Authzgroups $this->rightCache = null; return $this->dbRight->update( $idrights[0]["idright"], - array("idobject" => $newidobject, + ["idobject" => $newidobject, "right" => $newright, - "comment" => $newcomment) + "comment" => $newcomment] ); } - /** Return an array with all the available rights in the module, for a group, - * and concerning an object - * @param string $module The module to use - * @param string $group The group to get the rights - * @param string $object The object to get the rights - */ + /** + * Return an array with all the available rights in the module, for a group, + * and concerning an object + * @param string $module The module to use + * @param string $group The group to get the rights + * @param string $object The object to get the rights + */ public function rightRead($module, $group, $object) { if ($this->dbRight == null) { @@ -1444,15 +1487,16 @@ class Authzgroups "Wanted object not found" ), 404); } - $select[] = array("idgroup", $groups[0]["idgroup"]); - $select[] = array("idobject", $objects[0]["idobject"]); + $select[] = ["idgroup", $groups[0]["idgroup"]]; + $select[] = ["idobject", $objects[0]["idobject"]]; return $this->dbRight->read($select); } - /** Return an array with all the available rights for a module and a group - * @param string $module The module to use - * @param string $group The group to get the rights - */ + /** + * Return an array with all the available rights for a module and a group + * @param string $module The module to use + * @param string $group The group to get the rights + */ public function rightReadByGroup($module, $group) { if ($this->dbRight == null) { @@ -1471,10 +1515,11 @@ class Authzgroups return $this->rightReadByGroupByID($module, $groups[0]["idgroup"]); } - /** Return an array with all the available rights for a module and a group - * @param string $module The module to use - * @param integer $idgroup The group to get the rights - */ + /** + * Return an array with all the available rights for a module and a group + * @param string $module The module to use + * @param integer $idgroup The group to get the rights + */ public function rightReadByGroupByID($module, $idgroup) { if ($this->dbRight == null) { @@ -1483,15 +1528,16 @@ class Authzgroups "DB for Right is not connected" ), 500); } - $select[] = array("idgroup", $idgroup); + $select[] = ["idgroup", $idgroup]; return $this->dbRight->read($select); } - /** Return an array with all the information concerning a right selected by - * @param string $module The module to use - * @param integer $idright The right to search - * ID - */ + /** + * Return an array with all the information concerning a right selected by + * @param string $module The module to use + * @param integer $idright The right to search + * ID + */ public function rightReadByID($module, $idright) { if ($this->dbRight == null) { @@ -1500,14 +1546,15 @@ class Authzgroups "DB for Right is not connected" ), 500); } - $select[] = array("idright", $idright); + $select[] = ["idright", $idright]; return $this->dbRight->read($select); } - /** Return an array with all the available rights for a module and an object - * @param string $module The module to use - * @param string $object The object to search - */ + /** + * Return an array with all the available rights for a module and an object + * @param string $module The module to use + * @param string $object The object to search + */ public function rightReadByObject($module, $object) { if ($this->dbRight == null) { @@ -1523,14 +1570,15 @@ class Authzgroups "Wanted object not found" ), 404); } - $select[] = array("idobject", $objects[0]["idobject"]); + $select[] = ["idobject", $objects[0]["idobject"]]; return $this->dbRight->read($select); } - /** Return an array with all the available rights for a module and an idobject - * @param string $module The module to use - * @param integer $idobject The object to search - */ + /** + * Return an array with all the available rights for a module and an idobject + * @param string $module The module to use + * @param integer $idobject The object to search + */ public function rightReadByObjectByID($module, $idobject) { if ($this->dbRight == null) { @@ -1540,31 +1588,34 @@ class Authzgroups ), 500); } // FIXME : Do not use $module ? - $select[] = array("idobject", $idobject); + $select[] = ["idobject", $idobject]; return $this->dbRight->read($select); } - /** Return an array containing the titles of the table translating in the user - * language - */ + /** + * Return an array containing the titles of the table translating in the user + * language + */ public function rightTitles() { return $this->dbRight->titles; } - /** Return all the types of rights available (RO and RW) - */ + /** + * Return all the types of rights available (RO and RW) + */ public function rightTypes() { - return array("1" => "RO", "2" => "RW"); + return ["1" => "RO", "2" => "RW"]; } - /** Check if the provided data are compilant with the group specification - * @param array $data The data of the right to check - * @param integer $idright The right to search - * @return array The errors found in the data - */ + /** + * Check if the provided data are compilant with the group specification + * @param array $data The data of the right to check + * @param integer $idright The right to search + * @return array The errors found in the data + */ public function rightVerify($data, $idright = false) { return $this->dbRight->verify($data, $idright); diff --git a/src/Authzgroupsoo.php b/src/Authzgroupsoo.php index cc58c75..39314b4 100644 --- a/src/Authzgroupsoo.php +++ b/src/Authzgroupsoo.php @@ -1,57 +1,77 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** All the needed functions to authorize or deny access to an authenticated - * user by its groups membership - * Based on Dblayeroo - */ +/** + * All the needed functions to authorize or deny access to an authenticated + * user by its groups membership + * Based on Dblayeroo + */ class Authzgroupsoo { - /** The table prefix to use */ + /** + * The table prefix to use + */ public $tableprefix = ""; - /** The dblayeroo object use to manage the Object table */ + /** + * The dblayeroo object use to manage the Object table + */ private $dbObject = null; - /** The dblayeroo object use to manage the Group table */ + /** + * The dblayeroo object use to manage the Group table + */ private $dbGroup = null; - /** The dblayeroo object use to manage the GroupMember table */ + /** + * The dblayeroo object use to manage the GroupMember table + */ private $dbGroupMember = null; - /** The dblayeroo object use to manage the Right table */ + /** + * The dblayeroo object use to manage the Right table + */ private $dbRight = null; - /** Set the debug level */ + /** + * Set the debug level + */ public $debug = 0; - /** A local cache of the rights if multiple tests are needed */ + /** + * A local cache of the rights if multiple tests are needed + */ private $rightCache = null; - /** Get the dbObject - */ + /** + * Get the dbObject + */ public function dbObject() { return $this->dbObject; } - /** Get the dbGroup - */ + /** + * Get the dbGroup + */ public function dbGroup() { return $this->dbGroup; } - /** Get the dbGroupMember - */ + /** + * Get the dbGroupMember + */ public function dbGroupMember() { return $this->dbGroupMember; } - /** Get the dbRight - */ + /** + * Get the dbRight + */ public function dbRight() { return $this->dbRight; @@ -60,12 +80,13 @@ class Authzgroupsoo ///////////////////// // USER RIGHTS // ///////////////////// - /** Return an array with all the rights of the user in the module. - * Cache this information to be quicker with next requests - * Remove the entries where path is not at least readable - * @param string $module The module to use - * @param string $user The user to get the rights - */ + /** + * Return an array with all the rights of the user in the module. + * Cache this information to be quicker with next requests + * Remove the entries where path is not at least readable + * @param string $module The module to use + * @param string $user The user to get the rights + */ public function userrightsget($module, $user) { // if (isset ($_SESSION["domframework"]["authzgroups"][$module][$user])) @@ -94,25 +115,25 @@ class Authzgroupsoo $this->dbGroupMember->whereAdd("user", "=", $user); $this->dbGroup->joinInner( $this->dbGroupMember, - array("idgroup" => "idgroup") + ["idgroup" => "idgroup"] ) ->whereAdd("module", "=", $module); $this->dbRight->displayAdd("MAX(right)", "right") ->joinInner( $this->dbGroup, - array("idgroup" => "idgroup") + ["idgroup" => "idgroup"] ); $resTmp = $this->dbObject->select() ->displayAdd("object", "object") ->orderAdd("object", "ASC") ->joinInner( $this->dbRight, - array("idobject" => "idobject") + ["idobject" => "idobject"] ) ->execute(); } - $res = array(); + $res = []; foreach ($resTmp as $row) { $res[$row["object"]] = $row["right"]; } @@ -142,47 +163,32 @@ class Authzgroupsoo return $res; } - /** Return the right defined for this user in the module for one object - * @param string $module The module to use - * @param string $user The user to get the rights - * @param string $object The object to return the rights for the user - */ + /** + * Return the right defined for this user in the module for one object + * @param string $module The module to use + * @param string $user The user to get the rights + * @param string $object The object to return the rights for the user + */ public function allow($module, $user, $object) { $ressource = $this->userrightsget($module, $user); // The complete tree should not be readable for the user : it can have // access to a card, but not to all the cards (group -> reject, // group/XXX->allow) - /*// Limit to allowed trees : if a member of the path is not recorded (is - // unreadable), return NO. - // Can be the last entry (the complete object) too - $path = explode ("/", $object); - $completePath = "/"; - foreach ($path as $k => $p) - { - if ($k>1) - $completePath .= "/"; - $completePath .= "$p"; - if (! isset ($ressource[$completePath])) - { - if ($this->debug) - echo "DEBUG allow : REJECT because $completePath is not found\n"; - return "NO"; - } - }*/ if (! isset($ressource[$object])) { return "NO"; } return $ressource[$object]; } - /** Return TRUE if the user right allow to see the object (RO or RW) - * Return a 403 Exception if the user don't have the right - * Return a 401 Exception if the user is not connected - * @param string $module The module to use - * @param string $user The user to get the rights - * @param string $object The object to check the rights for the user - */ + /** + * Return TRUE if the user right allow to see the object (RO or RW) + * Return a 403 Exception if the user don't have the right + * Return a 401 Exception if the user is not connected + * @param string $module The module to use + * @param string $user The user to get the rights + * @param string $object The object to check the rights for the user + */ public function accessRight($module, $user, $object) { if ($this->dbObject === null) { @@ -227,13 +233,14 @@ class Authzgroupsoo throw new \Exception(dgettext("domframework", "Access forbidden"), 403); } - /** Return TRUE if the user right allow to edit the object (RW only) - * Return a 403 Exception if the user don't have the right - * Return a 401 Exception if the user is not connected - * @param string $module The module to use - * @param string $user The user to get the rights - * @param string $object The object to check the rights for the user - */ + /** + * Return TRUE if the user right allow to edit the object (RW only) + * Return a 403 Exception if the user don't have the right + * Return a 401 Exception if the user is not connected + * @param string $module The module to use + * @param string $user The user to get the rights + * @param string $object The object to check the rights for the user + */ public function accessWrite($module, $user, $object) { if ($this->dbObject === null) { @@ -281,14 +288,15 @@ class Authzgroupsoo ); } - /** Return TRUE if the user right allow to see but without modification - * the object (RO only) - * Return a 403 Exception if the user don't have the right - * Return a 401 Exception if the user is not connected - * @param string $module The module to use - * @param string $user The user to get the rights - * @param string $object The object to check the rights for the user - */ + /** + * Return TRUE if the user right allow to see but without modification + * the object (RO only) + * Return a 403 Exception if the user don't have the right + * Return a 401 Exception if the user is not connected + * @param string $module The module to use + * @param string $user The user to get the rights + * @param string $object The object to check the rights for the user + */ public function accessReadOnly($module, $user, $object) { if ($this->dbObject === null) { @@ -336,14 +344,15 @@ class Authzgroupsoo ///////////////////////// // DATABASE STORAGE // ///////////////////////// - /** Connect to the database before using it - * @param string $dsn The DSN to use to connect to the database - * @param string|null $username The username to use to connect to the - * database - * @param string|null $password The password to use to connect to the - * database - * @param array|null $driver_options The options to pass to PDO driver - */ + /** + * Connect to the database before using it + * @param string $dsn The DSN to use to connect to the database + * @param string|null $username The username to use to connect to the + * database + * @param string|null $password The password to use to connect to the + * database + * @param array|null $driver_options The options to pass to PDO driver + */ public function connect( $dsn, $username = null, @@ -359,18 +368,18 @@ class Authzgroupsoo $this->dbObject->debug($this->debug); $this->dbObject->table("authzobject"); $this->dbObject->tableprefix($this->tableprefix); - $this->dbObject->fields(array( - "idobject" => array("integer", "not null", "autoincrement"), - "module" => array("varchar(255)", "not null"), - "object" => array("varchar(255)", "not null"), - "comment" => array("varchar(255)"))); + $this->dbObject->fields([ + "idobject" => ["integer", "not null", "autoincrement"], + "module" => ["varchar(255)", "not null"], + "object" => ["varchar(255)", "not null"], + "comment" => ["varchar(255)"]]); $this->dbObject->primary("idobject"); - $this->dbObject->unique(array("idobject", array("object", "module"))); - $this->dbObject->titles(array( + $this->dbObject->unique(["idobject", ["object", "module"]]); + $this->dbObject->titles([ "idobject" => dgettext("domframework", "idobject"), "module" => dgettext("domframework", "Module"), "object" => dgettext("domframework", "Object"), - "comment" => dgettext("domframework", "Comment"))); + "comment" => dgettext("domframework", "Comment")]); $this->dbGroup = new Dblayeroo( $dsn, @@ -381,18 +390,18 @@ class Authzgroupsoo $this->dbGroup->debug($this->debug); $this->dbGroup->table("authzgroup"); $this->dbGroup->tableprefix($this->tableprefix); - $this->dbGroup->fields(array( - "idgroup" => array("integer", "not null", "autoincrement"), - "module" => array("varchar(255)", "not null"), - "group" => array("varchar(255)", "not null"), - "comment" => array("varchar(255)"))); + $this->dbGroup->fields([ + "idgroup" => ["integer", "not null", "autoincrement"], + "module" => ["varchar(255)", "not null"], + "group" => ["varchar(255)", "not null"], + "comment" => ["varchar(255)"]]); $this->dbGroup->primary("idgroup"); - $this->dbGroup->unique(array("idgroup", array("module", "group"))); - $this->dbGroup->titles(array( + $this->dbGroup->unique(["idgroup", ["module", "group"]]); + $this->dbGroup->titles([ "idgroup" => dgettext("domframework", "idgroup"), "module" => dgettext("domframework", "Module"), "group" => dgettext("domframework", "Group"), - "comment" => dgettext("domframework", "Comment"))); + "comment" => dgettext("domframework", "Comment")]); $this->dbGroupMember = new Dblayeroo( $dsn, @@ -403,23 +412,23 @@ class Authzgroupsoo $this->dbGroupMember->debug($this->debug); $this->dbGroupMember->table("authzgroupmember"); $this->dbGroupMember->tableprefix($this->tableprefix); - $this->dbGroupMember->fields(array( - "idgroupmember" => array("integer", "not null", "autoincrement"), - "user" => array("varchar(255)", "not null"), - "idgroup" => array("integer", "not null"), - "comment" => array("varchar(255)"))); + $this->dbGroupMember->fields([ + "idgroupmember" => ["integer", "not null", "autoincrement"], + "user" => ["varchar(255)", "not null"], + "idgroup" => ["integer", "not null"], + "comment" => ["varchar(255)"]]); $this->dbGroupMember->primary("idgroupmember"); - $this->dbGroupMember->unique(array("idgroupmember", - array("user", "idgroup"))); - $this->dbGroupMember->foreign(array( - "idgroup" => array($this->tableprefix . "authzgroup", "idgroup", - "ON UPDATE CASCADE ON DELETE CASCADE"))); + $this->dbGroupMember->unique(["idgroupmember", + ["user", "idgroup"]]); + $this->dbGroupMember->foreign([ + "idgroup" => [$this->tableprefix . "authzgroup", "idgroup", + "ON UPDATE CASCADE ON DELETE CASCADE"]]); $this->dbGroupMember->setForeignObj($this->dbGroup); - $this->dbGroupMember->titles(array( + $this->dbGroupMember->titles([ "idgroupmember" => dgettext("domframework", "idgroupmember"), "user" => dgettext("domframework", "User"), "idgroup" => dgettext("domframework", "idgroup"), - "comment" => dgettext("domframework", "Comment"))); + "comment" => dgettext("domframework", "Comment")]); $this->dbRight = new Dblayeroo( $dsn, @@ -430,40 +439,42 @@ class Authzgroupsoo $this->dbRight->debug($this->debug); $this->dbRight->table("authzright"); $this->dbRight->tableprefix($this->tableprefix); - $this->dbRight->fields(array( - "idright" => array("integer", "not null", "autoincrement"), - "idgroup" => array("integer", "not null"), - "idobject" => array("integer", "not null"), - "right" => array("varchar(2)", "not null"), // NO, RO, RW - "comment" => array("varchar(255)"))); + $this->dbRight->fields([ + "idright" => ["integer", "not null", "autoincrement"], + "idgroup" => ["integer", "not null"], + "idobject" => ["integer", "not null"], + "right" => ["varchar(2)", "not null"], // NO, RO, RW + "comment" => ["varchar(255)"]]); $this->dbRight->primary("idright"); - $this->dbRight->unique(array("idright", array("idgroup", "idobject"))); - $this->dbRight->foreign(array( - "idgroup" => array($this->tableprefix . "authzgroup", "idgroup", - "ON UPDATE CASCADE ON DELETE CASCADE"), - "idobject" => array($this->tableprefix . "authzobject", "idobject", - "ON UPDATE CASCADE ON DELETE CASCADE"), - )); + $this->dbRight->unique(["idright", ["idgroup", "idobject"]]); + $this->dbRight->foreign([ + "idgroup" => [$this->tableprefix . "authzgroup", "idgroup", + "ON UPDATE CASCADE ON DELETE CASCADE"], + "idobject" => [$this->tableprefix . "authzobject", "idobject", + "ON UPDATE CASCADE ON DELETE CASCADE"], + ]); $this->dbRight->setForeignObj($this->dbGroup); $this->dbRight->setForeignObj($this->dbObject); - $this->dbRight->titles(array( + $this->dbRight->titles([ "idright" => dgettext("domframework", "idright"), "idgroup" => dgettext("domframework", "idgroup"), "idobject" => dgettext("domframework", "idobject"), "right" => dgettext("domframework", "Right"), - "comment" => dgettext("domframework", "Comment"))); + "comment" => dgettext("domframework", "Comment")]); return true; } - /** Disconnect from the database. Should be only used in the unit tests - */ + /** + * Disconnect from the database. Should be only used in the unit tests + */ public function disconnect() { $this->dbObject->disconnect(); } - /** Create the tables in the database to store the data - */ + /** + * Create the tables in the database to store the data + */ public function createTables() { if ($this->dbObject == null) { @@ -493,7 +504,7 @@ class Authzgroupsoo "DB for Right is not connected" ), 500); } - $tables = array("Object", "Group", "GroupMember", "Right"); + $tables = ["Object", "Group", "GroupMember", "Right"]; foreach ($tables as $table) { try { $class = "db$table"; @@ -505,8 +516,9 @@ class Authzgroupsoo return true; } - /** Return true if all the tables are created, false otherwise - */ + /** + * Return true if all the tables are created, false otherwise + */ public function stateTables() { if ($this->dbObject == null) { @@ -516,18 +528,19 @@ class Authzgroupsoo ), 500); } $tables = $this->dbObject->listTables(); - $needed = array("authzobject", "authzgroup", "authzgroupmember", - "authzright"); + $needed = ["authzobject", "authzgroup", "authzgroupmember", + "authzright"]; foreach ($needed as $table) { - if (! in_array($this->tableprefix . $table, $tables)) { + if (! in_array($this->tableprefix . $table, $tables, true)) { return false; } } return true; } - /** Return true if all the tables are deleted, false otherwise - */ + /** + * Return true if all the tables are deleted, false otherwise + */ public function deleteTables() { if ($this->dbObject == null) { @@ -537,7 +550,7 @@ class Authzgroupsoo ), 500); } $tables = $this->dbObject->listTables(); - $needed = array("Object", "Group", "GroupMember", "Right"); + $needed = ["Object", "Group", "GroupMember", "Right"]; $needed = array_reverse($needed); foreach ($needed as $table) { $class = "db$table"; @@ -549,12 +562,13 @@ class Authzgroupsoo ///////////////// // OBJECTS // ///////////////// - /** Add a new object to object list - * Return the idobject created - * @param string $module The module to use - * @param string $object The object to create - * @param string|null $comment The comment to save - */ + /** + * Add a new object to object list + * Return the idobject created + * @param string $module The module to use + * @param string $object The object to create + * @param string|null $comment The comment to save + */ public function objectAdd($module, $object, $comment = "") { if ($this->dbObject == null) { @@ -567,16 +581,17 @@ class Authzgroupsoo $this->rightCache = null; $this->dbObject->clearRequest(); return $this->dbObject->insert() - ->setValues(array("module" => $module, + ->setValues(["module" => $module, "object" => $object, - "comment" => $comment)) + "comment" => $comment]) ->execute(); } - /** Remove an object from database and all the rights using it - * @param string $module The module to use - * @param string $object The object to delete - */ + /** + * Remove an object from database and all the rights using it + * @param string $module The module to use + * @param string $object The object to delete + */ public function objectDel($module, $object) { if ($this->dbObject == null) { @@ -603,10 +618,11 @@ class Authzgroupsoo ->execute(); } - /** Remove an object from database and all the rights using it - * @param string $module The module to use - * @param integer $idobject The object to delete - */ + /** + * Remove an object from database and all the rights using it + * @param string $module The module to use + * @param integer $idobject The object to delete + */ public function objectDelByID($module, $idobject) { if ($this->dbObject == null) { @@ -633,12 +649,13 @@ class Authzgroupsoo ->execute(); } - /** Update an object in the database - * @param string $module The module to use - * @param string $object The object to update - * @param string $newobject The new name of the object - * @param string|null $newcomment The new comment of the object - */ + /** + * Update an object in the database + * @param string $module The module to use + * @param string $object The object to update + * @param string $newobject The new name of the object + * @param string|null $newcomment The new comment of the object + */ public function objectUpdate($module, $object, $newobject, $newcomment = "") { if ($this->dbObject == null) { @@ -662,17 +679,18 @@ class Authzgroupsoo "=", $idobjects[0]["idobject"] ) - ->setValues(array("object" => $newobject, - "comment" => $newcomment)) + ->setValues(["object" => $newobject, + "comment" => $newcomment]) ->execute(); } - /** Update an object in the database - * @param string $module The module to use - * @param integer $idobject The object to update - * @param string $newobject The new name of the object - * @param string|null $newcomment The new comment of the object - */ + /** + * Update an object in the database + * @param string $module The module to use + * @param integer $idobject The object to update + * @param string $newobject The new name of the object + * @param string|null $newcomment The new comment of the object + */ public function objectUpdateByID( $module, $idobject, @@ -700,16 +718,17 @@ class Authzgroupsoo "=", $idobjects[0]["idobject"] ) - ->setValues(array("object" => $newobject, - "comment" => $newcomment)) + ->setValues(["object" => $newobject, + "comment" => $newcomment]) ->execute(); } - /** Return an array with all the available objects in the module, or only - * one object if $object is provided - * @param string $module The module to use - * @param string $object The name of the object to get - */ + /** + * Return an array with all the available objects in the module, or only + * one object if $object is provided + * @param string $module The module to use + * @param string $object The name of the object to get + */ public function objectRead($module, $object = null) { if ($this->dbObject == null) { @@ -728,11 +747,12 @@ class Authzgroupsoo ->execute(); } - /** Return an array with all the available objects in the module, or only - * one object if $object is provided - * @param string $module The module to use - * @param integer $idobject The name of the object to get - */ + /** + * Return an array with all the available objects in the module, or only + * one object if $object is provided + * @param string $module The module to use + * @param integer $idobject The name of the object to get + */ public function objectReadByID($module, $idobject = null) { if ($this->dbObject == null) { @@ -750,19 +770,21 @@ class Authzgroupsoo ->execute(); } - /** Return an array containing the titles of the table translating in the user - * language - */ + /** + * Return an array containing the titles of the table translating in the user + * language + */ public function objectTitles() { return $this->dbObject->titles(); } - /** Check if the provided data are compliant with the object specification - * @param array $data The name of the object to get - * @param integer|null $idobject The object to check - * @return array The errors found in the data - */ + /** + * Check if the provided data are compliant with the object specification + * @param array $data The name of the object to get + * @param integer|null $idobject The object to check + * @return array The errors found in the data + */ public function objectVerify($data, $idobject = false) { return $this->dbObject->verify($data, $idobject); @@ -771,12 +793,13 @@ class Authzgroupsoo //////////////// // GROUPS // //////////////// - /** Add a new group to group list - * Return the idgroup created - * @param string $module The module to use - * @param string $group The group to create - * @param string|null $comment The comment to add with the group - */ + /** + * Add a new group to group list + * Return the idgroup created + * @param string $module The module to use + * @param string $group The group to create + * @param string|null $comment The comment to add with the group + */ public function groupAdd($module, $group, $comment = "") { if ($this->dbGroup == null) { @@ -788,16 +811,17 @@ class Authzgroupsoo $this->dbGroup->clearRequest(); // TODO : Check parameters before saving them return $this->dbGroup->insert() - ->setValues(array("module" => $module, + ->setValues(["module" => $module, "group" => $group, - "comment" => $comment)) + "comment" => $comment]) ->execute(); } - /** Remove an group from database and all the rights using it - * @param string $module The module to use - * @param string $group The group to delete - */ + /** + * Remove an group from database and all the rights using it + * @param string $module The module to use + * @param string $group The group to delete + */ public function groupDel($module, $group) { if ($this->dbGroup == null) { @@ -819,10 +843,11 @@ class Authzgroupsoo ->execute(); } - /** Remove an group from database and all the rights using it - * @param string $module The module to use - * @param integer $idgroup The group to delete - */ + /** + * Remove an group from database and all the rights using it + * @param string $module The module to use + * @param integer $idgroup The group to delete + */ public function groupDelByID($module, $idgroup) { if ($this->dbGroup == null) { @@ -844,12 +869,13 @@ class Authzgroupsoo ->execute(); } - /** Update an group in the database - * @param string $module The module to use - * @param string $group The group to update - * @param string $newgroup The new group name - * @param string|null $comment The comment for the group - */ + /** + * Update an group in the database + * @param string $module The module to use + * @param string $group The group to update + * @param string $newgroup The new group name + * @param string|null $comment The comment for the group + */ public function groupUpdate($module, $group, $newgroup, $comment = "") { if ($this->dbGroup == null) { @@ -868,17 +894,18 @@ class Authzgroupsoo $this->dbGroup->clearRequest(); return $this->dbGroup->update() ->whereAdd("idgroup", "=", $idgroups[0]["idgroup"]) - ->setValues(array("group" => $newgroup, - "comment" => $comment)) + ->setValues(["group" => $newgroup, + "comment" => $comment]) ->execute(); } - /** Update an group in the database - * @param string $module The module to use - * @param integer $idgroup The group to update - * @param string $newgroup The new group name - * @param string|null $comment The comment for the group - */ + /** + * Update an group in the database + * @param string $module The module to use + * @param integer $idgroup The group to update + * @param string $newgroup The new group name + * @param string|null $comment The comment for the group + */ public function groupUpdateByID($module, $idgroup, $newgroup, $comment = "") { if ($this->dbGroup == null) { @@ -897,15 +924,16 @@ class Authzgroupsoo $this->dbGroup->clearRequest(); return $this->dbGroup->update() ->whereAdd("idgroup", "=", $idgroups[0]["idgroup"]) - ->setValues(array("group" => $newgroup, - "comment" => $comment)) + ->setValues(["group" => $newgroup, + "comment" => $comment]) ->execute(); } - /** Return an array with all the available groups in the module - * @param string $module The module to use - * @param string|null $group The group to check if exists - */ + /** + * Return an array with all the available groups in the module + * @param string $module The module to use + * @param string|null $group The group to check if exists + */ public function groupRead($module, $group = null) { if ($this->dbGroup == null) { @@ -925,10 +953,11 @@ class Authzgroupsoo } - /** Return an array with all the available groups in the module - * @param string $module The module to use - * @param integer $idgroup The group to check if exists - */ + /** + * Return an array with all the available groups in the module + * @param string $module The module to use + * @param integer $idgroup The group to check if exists + */ public function groupReadByID($module, $idgroup) { if ($this->dbGroup == null) { @@ -944,19 +973,21 @@ class Authzgroupsoo ->execute(); } - /** Return an array containing the titles of the table translating in the user - * language - */ + /** + * Return an array containing the titles of the table translating in the user + * language + */ public function groupTitles() { return $this->dbGroup->titles(); } - /** Check if the provided data are compilant with the group specification - * @param array $data The data to check - * @param integer|null $idgroup The idgroup to check - * @return array The errors found in the data - */ + /** + * Check if the provided data are compilant with the group specification + * @param array $data The data to check + * @param integer|null $idgroup The idgroup to check + * @return array The errors found in the data + */ public function groupVerify($data, $idgroup = false) { return $this->dbGroup->verify($data, $idgroup); @@ -965,13 +996,14 @@ class Authzgroupsoo ////////////////////// // GROUP MEMBER // ////////////////////// - /** Add a new groupmember to groupmember list - * Return the idgroupmember created - * @param string $module The module to use - * @param string $group The group to use - * @param string $user The user to add in group - * @param string|null $comment The comment to save - */ + /** + * Add a new groupmember to groupmember list + * Return the idgroupmember created + * @param string $module The module to use + * @param string $group The group to use + * @param string $user The user to add in group + * @param string|null $comment The comment to save + */ public function groupmemberAdd($module, $group, $user, $comment = "") { if ($this->dbGroupMember == null) { @@ -993,18 +1025,19 @@ class Authzgroupsoo $this->rightCache = null; $this->dbGroupMember->clearRequest(); return $this->dbGroupMember->insert() - ->setValues(array( + ->setValues([ "user" => $user, "idgroup" => $groups[0]["idgroup"], - "comment" => $comment)) + "comment" => $comment]) ->execute(); } - /** Remove an groupmember from database and all the rights using it - * @param string $module The module to use - * @param string $group The group to use - * @param string $user The user to remove - */ + /** + * Remove an groupmember from database and all the rights using it + * @param string $module The module to use + * @param string $group The group to use + * @param string $user The user to remove + */ public function groupmemberDel($module, $group, $user) { if ($this->dbGroupMember == null) { @@ -1049,11 +1082,12 @@ class Authzgroupsoo ->execute(); } - /** Remove an groupmember from database and all the rights using it - * @param string $module The module to use - * @param integer $idgroup The group to use - * @param integer $idgroupmember The user to remove - */ + /** + * Remove an groupmember from database and all the rights using it + * @param string $module The module to use + * @param integer $idgroup The group to use + * @param integer $idgroupmember The user to remove + */ public function groupmemberDelByID($module, $idgroup, $idgroupmember) { if ($this->dbGroupMember == null) { @@ -1098,25 +1132,27 @@ class Authzgroupsoo ->execute(); } - /** Update an groupmember in the database - * @param string $module The module to use - * @param string $group The group to use - * @param string $user The user to update - * @param string|null $comment The comment to update - */ + /** + * Update an groupmember in the database + * @param string $module The module to use + * @param string $group The group to use + * @param string $user The user to update + * @param string|null $comment The comment to update + */ public function groupmemberUpdate($module, $group, $user, $comment = "") { $this->rightCache = null; die("This function is not available : contact us if you need it\n"); } - /** Update an groupmember in the database - * @param string $module The module to use - * @param integer $idgroup The group to use - * @param integer $iduser The user to update - * @param string $user The new user name - * @param string|null $comment The comment to update - */ + /** + * Update an groupmember in the database + * @param string $module The module to use + * @param integer $idgroup The group to use + * @param integer $iduser The user to update + * @param string $user The new user name + * @param string|null $comment The comment to update + */ public function groupmemberUpdateByID( $module, $idgroup, @@ -1139,16 +1175,17 @@ class Authzgroupsoo "=", $data[0]["idgroupmember"] ) - ->setValues(array("user" => $user, - "comment" => $comment)) + ->setValues(["user" => $user, + "comment" => $comment]) ->execute(); } - /** Return an array with all the groups where the user is in and in the module - * @param string $module The module to use - * @param string $user The user to search - */ + /** + * Return an array with all the groups where the user is in and in the module + * @param string $module The module to use + * @param string $user The user to search + */ public function groupmemberReadUser($module, $user) { if ($this->dbGroupMember == null) { @@ -1162,7 +1199,7 @@ class Authzgroupsoo } $idgrouptmps = $this->groupRead($module); // Create an array with idgroup=>group - $idgroups = array(); + $idgroups = []; foreach ($idgrouptmps as $val) { $idgroups[$val["idgroup"]] = $val["group"]; } @@ -1170,17 +1207,18 @@ class Authzgroupsoo $idgroupmembers = $this->dbGroupMember->select() ->whereAdd("user", "=", $user) ->execute(); - $res = array(); + $res = []; foreach ($idgroupmembers as $idmembers) { $res[$idmembers["idgroup"]] = $idgroups[$idmembers["idgroup"]]; } return $res; } - /** Return an array with all the groups where the user is in and in the module - * @param string $module The module to use - * @param integer $idgroupmember The user to search - */ + /** + * Return an array with all the groups where the user is in and in the module + * @param string $module The module to use + * @param integer $idgroupmember The user to search + */ public function groupmemberReadUserByID($module, $idgroupmember) { if ($this->dbGroupMember == null) { @@ -1194,25 +1232,26 @@ class Authzgroupsoo } $idgrouptmps = $this->groupRead($module); // Create an array with idgroup=>group - $idgroups = array(); + $idgroups = []; foreach ($idgrouptmps as $val) { $idgroups[$val["idgroup"]] = $val["group"]; } $this->dbGroupMember->clearRequest(); $this->dbGroupMember->whereAdd("idgroupmember", "=", $idgroupmember); $idgroupmembers = $this->dbGroupMember->select()->execute(); - $res = array(); + $res = []; foreach ($idgroupmembers as $idmembers) { $res[$idmembers["idgroup"]] = $idgroups[$idmembers["idgroup"]]; } return $res; } - /** Return an array with all the available users in the group and in the - * module - * @param string $module The module to use - * @param string $group The group to search - */ + /** + * Return an array with all the available users in the group and in the + * module + * @param string $module The module to use + * @param string $group The group to search + */ public function groupmemberReadGroup($module, $group) { if ($this->dbGroupMember == null) { @@ -1242,11 +1281,12 @@ class Authzgroupsoo ->execute(); } - /** Return an array with all the available users in the group and in the - * module - * @param string $module The module to use - * @param integer $idgroup The group to search - */ + /** + * Return an array with all the available users in the group and in the + * module + * @param string $module The module to use + * @param integer $idgroup The group to search + */ public function groupmemberReadGroupByID($module, $idgroup) { if ($this->dbGroupMember == null) { @@ -1275,11 +1315,12 @@ class Authzgroupsoo ->execute(); } - /** Return an array containing the information of a user in a specific group - * @param string $module The module to use - * @param integer $idgroup The group to search - * @param integer $iduser The user to search - */ + /** + * Return an array containing the information of a user in a specific group + * @param string $module The module to use + * @param integer $idgroup The group to search + * @param integer $iduser The user to search + */ public function groupmemberReadUserDataByID($module, $idgroup, $iduser) { if ($this->dbGroupMember == null) { @@ -1309,19 +1350,21 @@ class Authzgroupsoo ->execute(); } - /** Return an array containing the titles of the table translating in the user - * language - */ + /** + * Return an array containing the titles of the table translating in the user + * language + */ public function groupmembersTitles() { return $this->dbGroupMember->titles(); } - /** Check if the provided data are compilant with the group specification - * @param array $data The data to check - * @param integer|null $idgroupmember The group member associated to verify - * @return array The errors found in the data - */ + /** + * Check if the provided data are compilant with the group specification + * @param array $data The data to check + * @param integer|null $idgroupmember The group member associated to verify + * @return array The errors found in the data + */ public function groupmembersVerify($data, $idgroupmember = false) { return $this->dbGroupMember->verify($data, $idgroupmember); @@ -1330,14 +1373,15 @@ class Authzgroupsoo //////////////// // RIGHTS // //////////////// - /** Add a new right to right list - * Return the idright created - * @param string $module The module to use - * @param string $group The group to use - * @param string $object The object to use - * @param string $right The right to add - * @param string|null $comment The comment to add - */ + /** + * Add a new right to right list + * Return the idright created + * @param string $module The module to use + * @param string $group The group to use + * @param string $object The object to use + * @param string $right The right to add + * @param string|null $comment The comment to add + */ public function rightAdd($module, $group, $object, $right, $comment = "") { if ($this->dbRight == null) { @@ -1384,22 +1428,23 @@ class Authzgroupsoo $this->rightCache = null; $this->dbRight->clearRequest(); return $this->dbRight->insert() - ->setValues(array( + ->setValues([ "idgroup" => $groups[0]["idgroup"], "idobject" => $objects[0]["idobject"], "right" => $right, - "comment" => $comment)) + "comment" => $comment]) ->execute(); } - /** Add a new right to right list by ID - * Return the idright created - * @param string $module The module to use - * @param integer $idgroup The group to use - * @param integer $idobject The object to use - * @param integer $idright The right to add - * @param string|null $comment The comment to add - */ + /** + * Add a new right to right list by ID + * Return the idright created + * @param string $module The module to use + * @param integer $idgroup The group to use + * @param integer $idobject The object to use + * @param integer $idright The right to add + * @param string|null $comment The comment to add + */ public function rightAddByID( $module, $idgroup, @@ -1449,19 +1494,20 @@ class Authzgroupsoo $this->rightCache = null; $this->dbRight->clearRequest(); return $this->dbRight->insert() - ->setValues(array( + ->setValues([ "idgroup" => $groups[0]["idgroup"], "idobject" => $objects[0]["idobject"], "right" => $right, - "comment" => $comment)) + "comment" => $comment]) ->execute(); } - /** Remove an right from database and all the rights using it - * @param string $module The module to use - * @param string $group The group to use - * @param string $object The object to remove the rights - */ + /** + * Remove an right from database and all the rights using it + * @param string $module The module to use + * @param string $group The group to use + * @param string $object The object to remove the rights + */ public function rightDel($module, $group, $object) { if ($this->dbRight == null) { @@ -1484,10 +1530,11 @@ class Authzgroupsoo ->execute(); } - /** Remove an right from database by ID and all the rights using it - * @param string $module The module to use - * @param integer $idright The idright to be deleted - */ + /** + * Remove an right from database by ID and all the rights using it + * @param string $module The module to use + * @param integer $idright The idright to be deleted + */ public function rightDelByID($module, $idright) { if ($this->dbRight == null) { @@ -1510,13 +1557,14 @@ class Authzgroupsoo ->execute(); } - /** Update a right in the database - * @param string $module The module to use - * @param string $group The group to update the right - * @param string $object The object ot update the right - * @param string $newright The new right to save - * @param string|null $newcomment The new comment to save - */ + /** + * Update a right in the database + * @param string $module The module to use + * @param string $group The group to update the right + * @param string $object The object ot update the right + * @param string $newright The new right to save + * @param string|null $newcomment The new comment to save + */ public function rightUpdate( $module, $group, @@ -1560,18 +1608,19 @@ class Authzgroupsoo $this->dbRight->clearRequest(); return $this->dbRight->update() ->whereAdd("idright", "=", $idrights[0]["idright"]) - ->setValues(array("right" => $newright, - "comment" => $newcomment)) + ->setValues(["right" => $newright, + "comment" => $newcomment]) ->execute(); } - /** Update a right by ID in the database - * @param string $module The module to use - * @param integer $idright The idright to update the right - * @param integer $newidobject The object ot update the right - * @param integer $newright The new right to save - * @param string|null $newcomment The new comment to save - */ + /** + * Update a right by ID in the database + * @param string $module The module to use + * @param integer $idright The idright to update the right + * @param integer $newidobject The object ot update the right + * @param integer $newright The new right to save + * @param string|null $newcomment The new comment to save + */ public function rightUpdateByID( $module, $idright, @@ -1615,19 +1664,20 @@ class Authzgroupsoo $this->dbRight->clearRequest(); return $this->dbRight->update() ->whereAdd("idright", "=", $idrights[0]["idright"]) - ->setValues(array("idobject" => $newidobject, + ->setValues(["idobject" => $newidobject, "right" => $newright, - "comment" => $newcomment)) + "comment" => $newcomment]) ->execute(); } - /** Return an array with all the available rights in the module, for a group, - * and concerning an object - * @param string $module The module to use - * @param string $group The group to get the rights - * @param string $object The object to get the rights - */ + /** + * Return an array with all the available rights in the module, for a group, + * and concerning an object + * @param string $module The module to use + * @param string $group The group to get the rights + * @param string $object The object to get the rights + */ public function rightRead($module, $group, $object) { if ($this->dbRight == null) { @@ -1657,10 +1707,11 @@ class Authzgroupsoo ->execute(); } - /** Return an array with all the available rights for a module and a group - * @param string $module The module to use - * @param string $group The group to get the rights - */ + /** + * Return an array with all the available rights for a module and a group + * @param string $module The module to use + * @param string $group The group to get the rights + */ public function rightReadByGroup($module, $group) { if ($this->dbRight == null) { @@ -1679,10 +1730,11 @@ class Authzgroupsoo return $this->rightReadByGroupByID($module, $groups[0]["idgroup"]); } - /** Return an array with all the available rights for a module and a group - * @param string $module The module to use - * @param integer $idgroup The group to get the rights - */ + /** + * Return an array with all the available rights for a module and a group + * @param string $module The module to use + * @param integer $idgroup The group to get the rights + */ public function rightReadByGroupByID($module, $idgroup) { if ($this->dbRight == null) { @@ -1697,11 +1749,12 @@ class Authzgroupsoo ->execute(); } - /** Return an array with all the information concerning a right selected by - * @param string $module The module to use - * @param integer $idright The right to search - * ID - */ + /** + * Return an array with all the information concerning a right selected by + * @param string $module The module to use + * @param integer $idright The right to search + * ID + */ public function rightReadByID($module, $idright) { if ($this->dbRight == null) { @@ -1716,10 +1769,11 @@ class Authzgroupsoo ->execute(); } - /** Return an array with all the available rights for a module and an object - * @param string $module The module to use - * @param string $object The object to search - */ + /** + * Return an array with all the available rights for a module and an object + * @param string $module The module to use + * @param string $object The object to search + */ public function rightReadByObject($module, $object) { if ($this->dbRight == null) { @@ -1741,10 +1795,11 @@ class Authzgroupsoo ->execute(); } - /** Return an array with all the available rights for a module and an idobject - * @param string $module The module to use - * @param integer $idobject The object to search - */ + /** + * Return an array with all the available rights for a module and an idobject + * @param string $module The module to use + * @param integer $idobject The object to search + */ public function rightReadByObjectByID($module, $idobject) { if ($this->dbRight == null) { @@ -1760,26 +1815,29 @@ class Authzgroupsoo } - /** Return an array containing the titles of the table translating in the user - * language - */ + /** + * Return an array containing the titles of the table translating in the user + * language + */ public function rightTitles() { return $this->dbRight->titles(); } - /** Return all the types of rights available (RO and RW) - */ + /** + * Return all the types of rights available (RO and RW) + */ public function rightTypes() { - return array("0" => "NO", "1" => "RO", "2" => "RW"); + return ["0" => "NO", "1" => "RO", "2" => "RW"]; } - /** Check if the provided data are compilant with the group specification - * @param array $data The data of the right to check - * @param integer $idright The right to search - * @return array The errors found in the data - */ + /** + * Check if the provided data are compilant with the group specification + * @param array $data The data of the right to check + * @param integer $idright The right to search + * @return array The errors found in the data + */ public function rightVerify($data, $idright = false) { return $this->dbRight->verify($data, $idright); diff --git a/src/Backtrace.php b/src/Backtrace.php index ead4f42..d4d6c5c 100644 --- a/src/Backtrace.php +++ b/src/Backtrace.php @@ -1,21 +1,24 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** Display the backtrace in HTML with clicks to display the content - */ +/** + * Display the backtrace in HTML with clicks to display the content + */ class Backtrace { - /** Display the backtrace in the browser - * use: \backtrace::show (debug_backtrace ()); - * @param array $backtrace The backtrace to display - */ + /** + * Display the backtrace in the browser + * use: \backtrace::show (debug_backtrace ()); + * @param array $backtrace The backtrace to display + */ public static function show($backtrace) { if (! is_array($backtrace)) { diff --git a/src/Cachefile.php b/src/Cachefile.php index e67d9c2..0b54751 100644 --- a/src/Cachefile.php +++ b/src/Cachefile.php @@ -1,29 +1,34 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** A cache manager in file - */ +/** + * A cache manager in file + */ class Cachefile { - /** Where to store the cached information - */ + /** + * Where to store the cached information + */ public $directory = "./cache"; - /** If TRUE : no information is cached - */ + /** + * If TRUE : no information is cached + */ public $nocache = false; - /** Getter/setter for $directory cache - * @param string|null $val The directory to use - * @return $this or $this->directory value - */ + /** + * Getter/setter for $directory cache + * @param string|null $val The directory to use + * @return $this or $this->directory value + */ public function directory($val = null) { if ($val === null) { @@ -36,8 +41,9 @@ class Cachefile return $this; } - /** Check if there is some garbage to clean - */ + /** + * Check if there is some garbage to clean + */ public function garbage() { try { @@ -57,9 +63,9 @@ class Cachefile } if ($res === false) { - $data = array("ttl" => 24 * 60 * 60, + $data = ["ttl" => 24 * 60 * 60, "createTime" => time(), - "data" => "CACHE-Garbage"); + "data" => "CACHE-Garbage"]; file_put_contents($fileCache, serialize($data)); chmod($fileCache, 0666); $files = glob($this->directory . "/*", GLOB_NOSORT); @@ -86,12 +92,13 @@ class Cachefile } } - /** This function check if the cachedir exists and create it if it is not the - * case. - * Check if the cache dir is writable and readable - * @return true if OK - * @throw Exception if an error occured - */ + /** + * This function check if the cachedir exists and create it if it is not the + * case. + * Check if the cache dir is writable and readable + * @return true if OK + * @throw Exception if an error occured + */ public function cachedir() { if (! isset($this->directory) || $this->directory === "") { @@ -147,14 +154,15 @@ class Cachefile return true; } - /** This function write data in cache - * @param string $id Cache identifier (add the authentication, the METHOD...) - * @param mixed $data The data to save - * @param integer|null $ttl The cache Time to Leave in seconds (3600s by - * default) - * @return true - * @throw if an error occured - */ + /** + * This function write data in cache + * @param string $id Cache identifier (add the authentication, the METHOD...) + * @param mixed $data The data to save + * @param integer|null $ttl The cache Time to Leave in seconds (3600s by + * default) + * @return true + * @throw if an error occured + */ public function write($id, $data, $ttl = 3600) { if ($this->nocache !== false) { @@ -182,21 +190,22 @@ class Cachefile $this->garbage(); $fileCache = $this->directory . "/" . sha1($id); touch($fileCache . ".lock"); - $data = array("ttl" => $ttl, + $data = ["ttl" => $ttl, "createTime" => time(), - "data" => $data); + "data" => $data]; file_put_contents($fileCache, serialize($data)); unlink($fileCache . ".lock"); chmod($fileCache, 0666); return true; } - /** This function read data from cache. Return FALSE in case of empty or too - * older cache - * @param string $id Cache identifier (add the authentication, the METHOD) - * @return false if the cache is empty or too old - * @return mixed The data stored in cache - */ + /** + * This function read data from cache. Return FALSE in case of empty or too + * older cache + * @param string $id Cache identifier (add the authentication, the METHOD) + * @return false if the cache is empty or too old + * @return mixed The data stored in cache + */ public function read($id) { if ($this->nocache !== false) { @@ -275,10 +284,11 @@ class Cachefile return false; } - /** This function delete an id in cache - * @param string $id Cache identifier (add the authentication, the METHOD...) - * @return boolean The cache is well deleted - */ + /** + * This function delete an id in cache + * @param string $id Cache identifier (add the authentication, the METHOD...) + * @return boolean The cache is well deleted + */ public function delete($id) { $fileCache = $this->directory . "/" . sha1($id); diff --git a/src/Cacheoutput.php b/src/Cacheoutput.php index 43e9c50..5781db6 100644 --- a/src/Cacheoutput.php +++ b/src/Cacheoutput.php @@ -1,38 +1,51 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** This class permit to cache the ouptut of a code. If the cache is already - * available, use it. - * It resend the headers as the ouptut send them - * Use it by : - * $c = new Cacheoutput ("URL"); - * Don't forget to define a variable or the cache saved is always empty - */ +/** + * This class permit to cache the ouptut of a code. If the cache is already + * available, use it. + * It resend the headers as the ouptut send them + * Use it by : + * $c = new Cacheoutput ("URL"); + * Don't forget to define a variable or the cache saved is always empty + */ class Cacheoutput { - /** Record if the saving of pages is on going */ + /** + * Record if the saving of pages is on going + */ private $saving = false; - /** The called id */ + /** + * The called id + */ private $id = null; - /** The called ttl */ + /** + * The called ttl + */ private $ttl = null; - /** The cache object */ + /** + * The cache object + */ private $cache = null; - /** Current path at start due to lack of information in __destruct*/ + /** + * Current path at start due to lack of information in __destruct + */ private $cacheCWD = null; /** - @param string $id The cache identifier - @param integer|null $ttl The cache Time to Leave in seconds (60s by - default) - @param string|null $method The cache method to use */ + * @param string $id The cache identifier + * @param integer|null $ttl The cache Time to Leave in seconds (60s by + * default) + * @param string|null $method The cache method to use + */ public function __construct($id, $ttl = 60, $method = "file") { $res = @include("domframework/cache$method.php"); @@ -68,15 +81,17 @@ class Cacheoutput // The data are sent automatically } - /** End of saving the data in cache */ + /** + * End of saving the data in cache + */ public function __destruct() { // Force the path because it return to / in the destructor chdir($this->cacheCWD); if ($this->saving === true) { // Do the saving of the data - $data = array("content" => ob_get_contents(), - "headers" => headers_list()); + $data = ["content" => ob_get_contents(), + "headers" => headers_list()]; $this->cache->write($this->id, $data, $this->ttl); } } diff --git a/src/Certificationauthority.php b/src/Certificationauthority.php index 83d1bd3..c0284e5 100644 --- a/src/Certificationauthority.php +++ b/src/Certificationauthority.php @@ -1,39 +1,47 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** An certificate authority - */ +/** + * An certificate authority + */ class Certificationauthority { // PROPERTIES - /** The opensslCnfPath file - */ + /** + * The opensslCnfPath file + */ private $opensslCnfPath; - /** The CA public cert - */ + /** + * The CA public cert + */ private $caCert = ""; - /** The CA private key - */ + /** + * The CA private key + */ private $caKey = ""; - /** The user private key resource - */ + /** + * The user private key resource + */ private $privateKey; - /** The configuration arguments - */ - private $configargs = array(); + /** + * The configuration arguments + */ + private $configargs = []; - /** The basic openssl.cnf configuration - */ + /** + * The basic openssl.cnf configuration + */ private $opensslConf = 'HOME = . RANDFILE = $ENV::HOME/.rnd @@ -54,8 +62,9 @@ keyUsage = nonRepudiation, digitalSignature, keyEncipherment extendedKeyUsage = serverAuth, clientAuth '; - /** Check if openssl support is available in PHP - */ + /** + * Check if openssl support is available in PHP + */ public function __construct() { if (! function_exists("openssl_csr_new")) { @@ -66,15 +75,16 @@ extendedKeyUsage = serverAuth, clientAuth } $this->opensslCnfPath = tempnam("/tmp", "openssl-"); file_put_contents($this->opensslCnfPath, $this->opensslConf); - $this->configargs = array( + $this->configargs = [ "config" => $this->opensslCnfPath, "digest_alg" => "sha256WithRSAEncryption", "private_key_bits" => 4096, - ); + ]; } - /** Remove the temporary files when destroying the object - */ + /** + * Remove the temporary files when destroying the object + */ public function __destruct() { if (file_exists($this->opensslCnfPath)) { @@ -82,30 +92,31 @@ extendedKeyUsage = serverAuth, clientAuth } } - /** Create the pair key/cert for authority - * @param string $countryName Country name (like FR) - * @param string $organizationName Name of organization - * @param string $commonName Common name of authority - * @param integer|null $days The number of days of validity of the CA (3650 - * by default) - * @return $this - */ + /** + * Create the pair key/cert for authority + * @param string $countryName Country name (like FR) + * @param string $organizationName Name of organization + * @param string $commonName Common name of authority + * @param integer|null $days The number of days of validity of the CA (3650 + * by default) + * @return $this + */ public function createCA( $countryName, $organizationName, $commonName, $days = 3650 ) { - $req_key = openssl_pkey_new(array( + $req_key = openssl_pkey_new([ "config" => $this->opensslCnfPath, "private_key_bits" => 4096, "private_key_type" => OPENSSL_KEYTYPE_RSA, - )); - $dn = array( + ]); + $dn = [ "countryName" => $countryName, "organizationName" => $organizationName, "commonName" => $commonName, - ); + ]; $this->configargs["x509_extensions"] = "v3_ca"; // x509_extensions must be defined in /etc/ssl/openssl.cnf $req_csr = openssl_csr_new($dn, $req_key, $this->configargs); @@ -125,10 +136,11 @@ extendedKeyUsage = serverAuth, clientAuth return $this; } - /** Get/Set the ca cert - * @param string|null $caCert The CA cert to get/set - * @return ($caCert is null ? string : $this) the CA if get in PEM, $this if set - */ + /** + * Get/Set the ca cert + * @param string|null $caCert The CA cert to get/set + * @return ($caCert is null ? string : $this) the CA if get in PEM, $this if set + */ public function caCert($caCert = null) { if ($caCert === null) { @@ -141,10 +153,11 @@ extendedKeyUsage = serverAuth, clientAuth return $this; } - /** Get/Set the ca key - * @param string|null $caKey The CA key to get/set - * @return ($caKey is null ? string : $this) the CA if get, $this if set - */ + /** + * Get/Set the ca key + * @param string|null $caKey The CA key to get/set + * @return ($caKey is null ? string : $this) the CA if get, $this if set + */ public function caKey($caKey = null) { if ($caKey === null) { @@ -157,23 +170,25 @@ extendedKeyUsage = serverAuth, clientAuth return $this; } - /** Create a private key - * @return $this; - */ + /** + * Create a private key + * @return $this; + */ public function createPrivateKey() { - $this->privateKey = openssl_pkey_new(array( + $this->privateKey = openssl_pkey_new([ "config" => $this->opensslCnfPath, "private_key_bits" => 4096, "private_key_type" => OPENSSL_KEYTYPE_RSA, - )); + ]); return $this; } - /** Get in PEM/Set the private key - * @param string|null $privateKey The private key to use - * @return ($privateKey is null ? string : $this) the privatekey if get in PEM, $this if set - */ + /** + * Get in PEM/Set the private key + * @param string|null $privateKey The private key to use + * @return ($privateKey is null ? string : $this) the privatekey if get in PEM, $this if set + */ public function privateKey($privateKey = null) { if ($privateKey === null) { @@ -190,23 +205,24 @@ extendedKeyUsage = serverAuth, clientAuth return $this; } - /** Create a CSR. - * Will create a private key if none is already exists - * @param string $countryName Country name (like FR) - * @param string $organizationName Name of organization - * @param string $commonName Common name of authority - * @return string the CSR created in PEM - */ + /** + * Create a CSR. + * Will create a private key if none is already exists + * @param string $countryName Country name (like FR) + * @param string $organizationName Name of organization + * @param string $commonName Common name of authority + * @return string the CSR created in PEM + */ public function createCSR($countryName, $organizationName, $commonName) { if ($this->privateKey === null) { $this->createPrivateKey(); } - $dn = array( + $dn = [ "countryName" => $countryName, "organizationName" => $organizationName, "commonName" => $commonName, - ); + ]; $this->configargs["x509_extensions"] = "v3_req"; $req_csr = openssl_csr_new($dn, $this->privateKey, $this->configargs); if ($req_csr === false) { @@ -217,22 +233,23 @@ extendedKeyUsage = serverAuth, clientAuth return $out; } - /** Sign a CSR with an CA cert/key pair and return the signed certificate in - * PEM mode - * The caCert and caKey must be defined - * @param string $csr The CSR to sign - * @param string $caCert The CA Certificate - * @param string $caKey The CA private key - * @param integer|null $days The number of days of validity (365 by default) - * @param array|null $altNames The alternative names allowed in cert - * @return string the signed certificate in PEM - */ + /** + * Sign a CSR with an CA cert/key pair and return the signed certificate in + * PEM mode + * The caCert and caKey must be defined + * @param string $csr The CSR to sign + * @param string $caCert The CA Certificate + * @param string $caKey The CA private key + * @param integer|null $days The number of days of validity (365 by default) + * @param array|null $altNames The alternative names allowed in cert + * @return string the signed certificate in PEM + */ public function signCSR( $csr, $caCert, $caKey, $days = 365, - $altNames = array() + $altNames = [] ) { if ($days === null) { $days = 365; diff --git a/src/Cli.php b/src/Cli.php index 16de14e..f5fb583 100644 --- a/src/Cli.php +++ b/src/Cli.php @@ -1,75 +1,90 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** Allow to interract with controllers and models from the CLI */ +/** + * Allow to interract with controllers and models from the CLI + */ class Cli { - /** Run in CLI mode with parameters - * Example of cli code : - * #!/usr/bin/php - * run(); - */ - /** The expert mode allow to see/execute the models */ + /** + * Run in CLI mode with parameters + * Example of cli code : + * #!/usr/bin/php + * run(); + */ + /** + * The expert mode allow to see/execute the models + */ private $EXPERT = false; - /** Quiet mode don't display empty results */ + /** + * Quiet mode don't display empty results + */ private $QUIET; - /** Store the controllers pathes to test - */ - private $controllersPath = array("controllers/*.php"); + /** + * Store the controllers pathes to test + */ + private $controllersPath = ["controllers/*.php"]; - /** Store the models pathes to test - */ - private $modelsPath = array("models/*.php"); + /** + * Store the models pathes to test + */ + private $modelsPath = ["models/*.php"]; - /** The construtor define the catching of the errors */ + /** + * The construtor define the catching of the errors + */ public function __construct() { global $argv; $launcher = $argv[0]; chdir(dirname($argv[0]) . "/.."); // Catch the trigger_errors and display them politely - set_error_handler(array(&$this, "cliErrorHandler")); + set_error_handler([&$this, "cliErrorHandler"]); } - /** Define the controllers path - * @param string|array $path The controllers pathes to use - */ + /** + * Define the controllers path + * @param string|array $path The controllers pathes to use + */ public function controllersDir($path) { if (! is_array($path)) { - $path = array($path); + $path = [$path]; } $this->controllersPath = $path; } - /** Define the models path - * @param string|array $path The models pathes to use - */ + /** + * Define the models path + * @param string|array $path The models pathes to use + */ public function modelsDir($path) { if (! is_array($path)) { - $path = array($path); + $path = [$path]; } $this->modelsPath = $path; } - /** The error handler for CLI : display error in STDERR - * @param integer $errno The error type - * @param string $errstr The string to send in error - * @param string $errfile The error file which generate the error - * @param integer $errline The line with an error - */ + /** + * The error handler for CLI : display error in STDERR + * @param integer $errno The error type + * @param string $errstr The string to send in error + * @param string $errfile The error file which generate the error + * @param integer $errline The line with an error + */ public function cliErrorHandler($errno, $errstr, $errfile, $errline) { if (!(error_reporting() & $errno)) { @@ -135,8 +150,9 @@ class Cli } } - /** The real application launcher and helpers - */ + /** + * The real application launcher and helpers + */ public function run() { global $argv; @@ -180,7 +196,7 @@ class Cli } // List the controllers and the models if the expert mode is activated - $files = array(); + $files = []; foreach ($this->controllersPath as $path) { $files = array_merge($files, glob($path)); } @@ -210,7 +226,7 @@ class Cli } // Check if there is some classes which can be shorted (classes only in // controllers or only in models - $shortClasses = array(); + $shortClasses = []; foreach ($classes as $class => $file) { $short = substr(strstr($class, "\\"), 1); if ($short === false) { @@ -379,7 +395,7 @@ class Cli } $min = 0; $max = 0; - $paramsConst = array(); + $paramsConst = []; try { $r1 = new \ReflectionMethod($class, "__construct"); $paramsConst = $r1->getParameters(); @@ -397,7 +413,7 @@ class Cli $max++; } - if (in_array("-?", $argv)) { + if (in_array("-?", $argv, true)) { // Question mark display the PHPDoc of the method $comment = trim(substr($r1->getDocComment(), 3, -2)); if ($comment !== "") { @@ -422,8 +438,8 @@ class Cli if (count($argv) < $min) { die("Not enough parameters provided to method\n"); } - if (in_array("-", $argv)) { - $tab = array_keys($argv, "-"); + if (in_array("-", $argv, true)) { + $tab = array_keys($argv, "-", true); $keyStdIn = reset($tab); $dataStdIn = file_get_contents("php://stdin"); $argv[$keyStdIn] = $dataStdIn; @@ -444,7 +460,7 @@ class Cli $argv[$key] = $name; } else { if (! is_array($argv[$key])) { - $argv[$key] = array(); + $argv[$key] = []; } $argv[$key][$name] = $value; } @@ -452,7 +468,7 @@ class Cli } // Manage a parameter in the constructor of the class - $paramConst = array(); + $paramConst = []; if (count($paramsConst) > 0) { $paramConst = array_slice($argv, 0, count($paramsConst)); $argv = array_slice($argv, count($paramsConst)); @@ -461,8 +477,8 @@ class Cli try { $classReflection = new \ReflectionClass($class); $r = $classReflection->newInstanceArgs($paramConst); - $s = call_user_func_array(array($r, $method), $argv); - if ($this->QUIET === false || $s !== "" && $s !== array() && $s !== null) { + $s = call_user_func_array([$r, $method], $argv); + if ($this->QUIET === false || $s !== "" && $s !== [] && $s !== null) { if (is_string($s)) { echo $s; } elseif (is_array($s)) { diff --git a/src/Color.php b/src/Color.php index 37996b8..971a6a0 100644 --- a/src/Color.php +++ b/src/Color.php @@ -19,195 +19,195 @@ class Color * From http://www.rapidtables.com/web/color/index.htm * @var array> */ - public $colorList = array( + public $colorList = [ // Black - "black" => array(0, 0, 0), - "dimgrey" => array(105, 105, 105), - "grey" => array(128, 128, 128), - "darkgrey" => array(169, 169, 169), - "silver" => array(192, 192, 192), + "black" => [0, 0, 0], + "dimgrey" => [105, 105, 105], + "grey" => [128, 128, 128], + "darkgrey" => [169, 169, 169], + "silver" => [192, 192, 192], // Blue - "aliceblue" => array(240, 248, 255), - "lavender" => array(230, 230, 250), - "powderblue" => array(176, 224, 230), - "lightblue" => array(173, 216, 230), - "lightskyblue" => array(135, 206, 250), - "skyblue" => array(135, 206, 235), - "deepskyblue" => array(0, 191, 255), - "lightsteelblue" => array(176, 196, 222), - "dodgerblue" => array(30, 144, 255), - "cornflowerblue" => array(100, 149, 237), - "steelblue" => array(70, 130, 180), - "cadetblue" => array(95, 158, 160), - "mediumslateblue" => array(123, 104, 238), - "slateblue" => array(106, 90, 205), - "darkslateblue" => array(72, 61, 139), - "royalblue" => array(65, 105, 225), - "blue" => array(0, 0, 255), - "mediumblue" => array(0, 0, 205), - "darkblue" => array(0, 0, 139), - "navy" => array(0, 0, 128), - "midnightblue" => array(25, 25, 112), - "blueviolet" => array(138, 43, 226), - "indigo" => array(75, 0, 130), + "aliceblue" => [240, 248, 255], + "lavender" => [230, 230, 250], + "powderblue" => [176, 224, 230], + "lightblue" => [173, 216, 230], + "lightskyblue" => [135, 206, 250], + "skyblue" => [135, 206, 235], + "deepskyblue" => [0, 191, 255], + "lightsteelblue" => [176, 196, 222], + "dodgerblue" => [30, 144, 255], + "cornflowerblue" => [100, 149, 237], + "steelblue" => [70, 130, 180], + "cadetblue" => [95, 158, 160], + "mediumslateblue" => [123, 104, 238], + "slateblue" => [106, 90, 205], + "darkslateblue" => [72, 61, 139], + "royalblue" => [65, 105, 225], + "blue" => [0, 0, 255], + "mediumblue" => [0, 0, 205], + "darkblue" => [0, 0, 139], + "navy" => [0, 0, 128], + "midnightblue" => [25, 25, 112], + "blueviolet" => [138, 43, 226], + "indigo" => [75, 0, 130], // Brown - "cornsilk" => array(255, 248, 220), - "blanchedalmond" => array(255, 235, 205), - "bisque" => array(255, 228, 196), - "wheat" => array(245, 222, 179), - "burlywood" => array(222, 184, 135), - "tan" => array(210, 180, 140), - "rosybrown" => array(188, 143, 143), - "sandybrown" => array(244, 164, 96), - "goldenrod" => array(218, 165, 32), - "peru" => array(205, 133, 63), - "chocolate" => array(210, 105, 30), - "saddlebrown" => array(139, 69, 19), - "sienna" => array(160, 82, 45), - "brown" => array(165, 42, 42), + "cornsilk" => [255, 248, 220], + "blanchedalmond" => [255, 235, 205], + "bisque" => [255, 228, 196], + "wheat" => [245, 222, 179], + "burlywood" => [222, 184, 135], + "tan" => [210, 180, 140], + "rosybrown" => [188, 143, 143], + "sandybrown" => [244, 164, 96], + "goldenrod" => [218, 165, 32], + "peru" => [205, 133, 63], + "chocolate" => [210, 105, 30], + "saddlebrown" => [139, 69, 19], + "sienna" => [160, 82, 45], + "brown" => [165, 42, 42], // Cyan - "lightcyan" => array(224, 255, 255), - "cyan" => array(0, 255, 255), - "aqua" => array(0, 255, 255), - "aquamarine" => array(127, 255, 212), - "mediumaquamarine" => array(102, 205, 170), - "paleturquoise" => array(175, 238, 238), - "turquoise" => array(64, 224, 208), - "mediumturquoise" => array(72, 209, 204), - "darkturquoise" => array(0, 206, 209), - "lightseagreen" => array(32, 178, 170), - "darkcyan" => array(0, 139, 139), - "teal" => array(0, 128, 128), + "lightcyan" => [224, 255, 255], + "cyan" => [0, 255, 255], + "aqua" => [0, 255, 255], + "aquamarine" => [127, 255, 212], + "mediumaquamarine" => [102, 205, 170], + "paleturquoise" => [175, 238, 238], + "turquoise" => [64, 224, 208], + "mediumturquoise" => [72, 209, 204], + "darkturquoise" => [0, 206, 209], + "lightseagreen" => [32, 178, 170], + "darkcyan" => [0, 139, 139], + "teal" => [0, 128, 128], // Gold - "palegoldenrod" => array(238, 232, 170), - "khaki" => array(240, 230, 140), - "gold" => array(255, 215, 0), - "orange" => array(255, 165, 0), - "darkorange" => array(255, 140, 0), - "goldenyellow" => array(255, 223, 0), - "metallicgold" => array(212, 175, 55), - "oldgold" => array(207, 181, 59), - "vegasgold" => array(197, 179, 88), - "palegold" => array(230, 190, 138), - "goldenbrown" => array(153, 101, 21), + "palegoldenrod" => [238, 232, 170], + "khaki" => [240, 230, 140], + "gold" => [255, 215, 0], + "orange" => [255, 165, 0], + "darkorange" => [255, 140, 0], + "goldenyellow" => [255, 223, 0], + "metallicgold" => [212, 175, 55], + "oldgold" => [207, 181, 59], + "vegasgold" => [197, 179, 88], + "palegold" => [230, 190, 138], + "goldenbrown" => [153, 101, 21], // Green - "lawngreen" => array(124, 252, 0), - "chartreuse" => array(127, 255, 0), - "limegreen" => array(50, 205, 50), - "lime" => array(0, 255, 0), - "forestgreen" => array(34, 139, 34), - "green" => array(0, 128, 0), - "darkgreen" => array(0, 100, 0), - "greenyellow" => array(173, 255, 47), - "yellowgreen" => array(154, 205, 50), - "springgreen" => array(0, 255, 127), - "mediumspringgreen" => array(0, 250, 154), - "lightgreen" => array(144, 238, 144), - "palegreen" => array(152, 251, 152), - "darkseagreen" => array(143, 188, 143), - "mediumseagreen" => array(60, 179, 113), - "seagreen" => array(46, 139, 87), - "olive" => array(128, 128, 0), - "darkolivegreen" => array(85, 107, 47), - "olivedrab" => array(107, 142, 35), + "lawngreen" => [124, 252, 0], + "chartreuse" => [127, 255, 0], + "limegreen" => [50, 205, 50], + "lime" => [0, 255, 0], + "forestgreen" => [34, 139, 34], + "green" => [0, 128, 0], + "darkgreen" => [0, 100, 0], + "greenyellow" => [173, 255, 47], + "yellowgreen" => [154, 205, 50], + "springgreen" => [0, 255, 127], + "mediumspringgreen" => [0, 250, 154], + "lightgreen" => [144, 238, 144], + "palegreen" => [152, 251, 152], + "darkseagreen" => [143, 188, 143], + "mediumseagreen" => [60, 179, 113], + "seagreen" => [46, 139, 87], + "olive" => [128, 128, 0], + "darkolivegreen" => [85, 107, 47], + "olivedrab" => [107, 142, 35], // Grey - "gainsboro" => array(220, 220, 220), - "lightgray" => array(211, 211, 211), - "lightgrey" => array(211, 211, 211), - "darkgray" => array(169, 169, 169), - "gray" => array(128, 128, 128), - "dimgray" => array(105, 105, 105), - "lightslategray" => array(119, 136, 153), - "lightslategrey" => array(119, 136, 153), - "slategray" => array(112, 128, 144), - "slategrey" => array(112, 128, 144), - "darkslategray" => array(47, 79, 79), - "darkslategrey" => array(47, 79, 79), + "gainsboro" => [220, 220, 220], + "lightgray" => [211, 211, 211], + "lightgrey" => [211, 211, 211], + "darkgray" => [169, 169, 169], + "gray" => [128, 128, 128], + "dimgray" => [105, 105, 105], + "lightslategray" => [119, 136, 153], + "lightslategrey" => [119, 136, 153], + "slategray" => [112, 128, 144], + "slategrey" => [112, 128, 144], + "darkslategray" => [47, 79, 79], + "darkslategrey" => [47, 79, 79], // Maroon - "maroon" => array(128, 0, 0), + "maroon" => [128, 0, 0], // Orange - "coral" => array(255, 127, 80), - "tomato" => array(255, 99, 71), - "orangered" => array(255, 69, 0), + "coral" => [255, 127, 80], + "tomato" => [255, 99, 71], + "orangered" => [255, 69, 0], // Pink - "pink" => array(255, 192, 203), - "lightpink" => array(255, 182, 193), - "hotpink" => array(255, 105, 180), - "deeppink" => array(255, 20, 147), - "palevioletred" => array(219, 112, 147), - "mediumvioletred" => array(199, 21, 133), + "pink" => [255, 192, 203], + "lightpink" => [255, 182, 193], + "hotpink" => [255, 105, 180], + "deeppink" => [255, 20, 147], + "palevioletred" => [219, 112, 147], + "mediumvioletred" => [199, 21, 133], // Purple - "thistle" => array(216, 191, 216), - "plum" => array(221, 160, 221), - "violet" => array(238, 130, 238), - "orchid" => array(218, 112, 214), - "fuchsia" => array(255, 0, 255), - "magenta" => array(255, 0, 255), - "mediumorchid" => array(186, 85, 211), - "mediumpurple" => array(147, 112, 219), - "darkviolet" => array(148, 0, 211), - "darkorchid" => array(153, 50, 204), - "darkmagenta" => array(139, 0, 139), - "purple" => array(128, 0, 128), + "thistle" => [216, 191, 216], + "plum" => [221, 160, 221], + "violet" => [238, 130, 238], + "orchid" => [218, 112, 214], + "fuchsia" => [255, 0, 255], + "magenta" => [255, 0, 255], + "mediumorchid" => [186, 85, 211], + "mediumpurple" => [147, 112, 219], + "darkviolet" => [148, 0, 211], + "darkorchid" => [153, 50, 204], + "darkmagenta" => [139, 0, 139], + "purple" => [128, 0, 128], // Red - "lightsalmon" => array(255, 160, 122), - "salmon" => array(250, 128, 114), - "darksalmon" => array(233, 150, 122), - "lightcoral" => array(240, 128, 128), - "indianred" => array(205, 92, 92), - "crimson" => array(220, 20, 60), - "firebrick" => array(178, 34, 34), - "red" => array(255, 0, 0), - "darkred" => array(139, 0, 0), + "lightsalmon" => [255, 160, 122], + "salmon" => [250, 128, 114], + "darksalmon" => [233, 150, 122], + "lightcoral" => [240, 128, 128], + "indianred" => [205, 92, 92], + "crimson" => [220, 20, 60], + "firebrick" => [178, 34, 34], + "red" => [255, 0, 0], + "darkred" => [139, 0, 0], // White - "white" => array(255, 255, 255), - "snow" => array(255, 250, 250), - "honeydew" => array(240, 255, 240), - "mintcream" => array(245, 255, 250), - "azure" => array(240, 255, 255), - "ghostwhite" => array(248, 248, 255), - "whitesmoke" => array(245, 245, 245), - "seashell" => array(255, 245, 238), - "beige" => array(245, 245, 220), - "oldlace" => array(253, 245, 230), - "floralwhite" => array(255, 250, 240), - "ivory" => array(255, 255, 240), - "antiquewhite" => array(250, 235, 215), - "linen" => array(250, 240, 230), - "lavenderblush" => array(255, 240, 245), - "mistyrose" => array(255, 228, 225), - "navajowhite" => array(255, 222, 173), + "white" => [255, 255, 255], + "snow" => [255, 250, 250], + "honeydew" => [240, 255, 240], + "mintcream" => [245, 255, 250], + "azure" => [240, 255, 255], + "ghostwhite" => [248, 248, 255], + "whitesmoke" => [245, 245, 245], + "seashell" => [255, 245, 238], + "beige" => [245, 245, 220], + "oldlace" => [253, 245, 230], + "floralwhite" => [255, 250, 240], + "ivory" => [255, 255, 240], + "antiquewhite" => [250, 235, 215], + "linen" => [250, 240, 230], + "lavenderblush" => [255, 240, 245], + "mistyrose" => [255, 228, 225], + "navajowhite" => [255, 222, 173], // Yellow - "lightyellow" => array(255, 255, 224), - "lemonchiffon" => array(255, 250, 205), - "lightgoldenrodyellow" => array(250, 250, 210), - "papayawhip" => array(255, 239, 213), - "moccasin" => array(255, 228, 181), - "peachpuff" => array(255, 218, 185), - "darkkhaki" => array(189, 183, 107), - "lightyellow1" => array(255, 255, 204), - "lightyellow2" => array(255, 255, 153), - "lightyellow3" => array(255, 255, 102), - "lightyellow4" => array(255, 255, 51), - "yellow" => array(255, 255, 0), - "darkyellow1" => array(204, 204, 0), - "darkyellow2" => array(153, 153, 0), - "darkyellow3" => array(102, 102, 0), - "darkyellow4" => array(51, 51, 0), - ); + "lightyellow" => [255, 255, 224], + "lemonchiffon" => [255, 250, 205], + "lightgoldenrodyellow" => [250, 250, 210], + "papayawhip" => [255, 239, 213], + "moccasin" => [255, 228, 181], + "peachpuff" => [255, 218, 185], + "darkkhaki" => [189, 183, 107], + "lightyellow1" => [255, 255, 204], + "lightyellow2" => [255, 255, 153], + "lightyellow3" => [255, 255, 102], + "lightyellow4" => [255, 255, 51], + "yellow" => [255, 255, 0], + "darkyellow1" => [204, 204, 0], + "darkyellow2" => [153, 153, 0], + "darkyellow3" => [102, 102, 0], + "darkyellow4" => [51, 51, 0], + ]; /** * Return the list of the known colors list diff --git a/src/Config.php b/src/Config.php index d77b125..1a9b55c 100644 --- a/src/Config.php +++ b/src/Config.php @@ -1,40 +1,47 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** Manage the configurations of the module done by administrator in a config - * file - * It is based on the module configuration defaults - * The DocType allow to define the configuration HTML page. It must contains - * @param : the name of the parameter - * @description : the textual description of the parameter - * @type : the type of the parameter (string, integer, array) - * @values : an array containing the allowed values to the parameter. Can be - * a function like timezone_identifiers_list - * @default : the default value (can be an array or a string or a number) - * @group : Group all the parameters in a group - * POC : - * $config = new Config(); - * $config->default = array ("param"=>"default", - * "param2"=>array (1,2,3), - * "param3"=>null); - * $var = $config->get ("param"); - */ +/** + * Manage the configurations of the module done by administrator in a config + * file + * It is based on the module configuration defaults + * The DocType allow to define the configuration HTML page. It must contains + * @param : the name of the parameter + * @description : the textual description of the parameter + * @type : the type of the parameter (string, integer, array) + * @values : an array containing the allowed values to the parameter. Can be + * a function like timezone_identifiers_list + * @default : the default value (can be an array or a string or a number) + * @group : Group all the parameters in a group + * POC : + * $config = new Config(); + * $config->default = array ("param"=>"default", + * "param2"=>array (1,2,3), + * "param3"=>null); + * $var = $config->get ("param"); + */ class Config { - /** All the parameters allowed with their default value */ - public $default = array(); - /** Use the .php to protect the information */ + /** + * All the parameters allowed with their default value + */ + public $default = []; + /** + * Use the .php to protect the information + */ public $confFile = null; - /** Select the configuration file - */ + /** + * Select the configuration file + */ public function selectConfFile() { if ($this->confFile !== null) { @@ -50,20 +57,22 @@ class Config } } - /** List all the parameters configurable in the software - */ + /** + * List all the parameters configurable in the software + */ public function params() { $this->selectConfFile(); return $this->default; } - /** Return the defined values in array format - */ + /** + * Return the defined values in array format + */ public function getAll() { $this->selectConfFile(); - $conf = array(); + $conf = []; $rc = include($this->confFile); if ($rc !== 1) { throw new \Exception("Error in configuration file", 500); @@ -71,12 +80,13 @@ class Config return $conf; } - /** Return the defined values in Slash format - */ + /** + * Return the defined values in Slash format + */ public function getAllInSlash() { $conf = $this->getAll(); - $vals = array(); + $vals = []; foreach ($this->docComment() as $key) { if (! key_exists("param", $key)) { continue; @@ -105,10 +115,11 @@ class Config return $vals; } - /** Get the value of the provided parameter recorded in .php file - * If it is not set in .php file, use the default value - * @param string $param The option name to be returned - */ + /** + * Get the value of the provided parameter recorded in .php file + * If it is not set in .php file, use the default value + * @param string $param The option name to be returned + */ public function get($param) { $this->selectConfFile(); @@ -140,7 +151,7 @@ class Config $this->confFile )); } - $conf = array(); + $conf = []; $rc = include($this->confFile); if ($rc !== 1) { throw new \Exception("Error in configuration file", 500); @@ -188,12 +199,13 @@ class Config return $conf[$param]; } - /** Define a value for the parameter in the config file. Add all the default - * values if they are not defined - * @param string $param The option name - * @param mixed $value The option value - * @return TRUE if the parameter is saved or an exception - */ + /** + * Define a value for the parameter in the config file. Add all the default + * values if they are not defined + * @param string $param The option name + * @param mixed $value The option value + * @return TRUE if the parameter is saved or an exception + */ public function set($param, $value) { $this->selectConfFile(); @@ -231,7 +243,7 @@ class Config $this->confFile ), 500); } - $conf = array(); + $conf = []; $rc = include($this->confFile); if ($rc !== 1) { throw new \Exception(dgettext( @@ -239,7 +251,7 @@ class Config "Error in configuration file" ), 500); } - $newconf = array_merge($this->default, $conf, array($param => $value)); + $newconf = array_merge($this->default, $conf, [$param => $value]); $txt = "writePHP($newconf, $txt, 4); @@ -257,11 +269,12 @@ class Config return true; } - /** Display the $values in PHP format to be "require" easily - * @param mixed $values Values to be recorded - * @param string $phpcode Actual value of the php code - * @param integer $indent Number of spaces in the indentation of config - */ + /** + * Display the $values in PHP format to be "require" easily + * @param mixed $values Values to be recorded + * @param string $phpcode Actual value of the php code + * @param integer $indent Number of spaces in the indentation of config + */ private function writePHP($values, $phpcode, $indent) { foreach ($values as $key => $val) { @@ -296,16 +309,17 @@ class Config return $phpcode; } - /** Convert a string to the right PHP type, without using the eval function - * @param string $values The string to convert - */ + /** + * Convert a string to the right PHP type, without using the eval function + * @param string $values The string to convert + */ private function strToType($values) { $values = str_replace("array (", "array(", $values); if (stripos($values, "array(") !== false) { $values = substr($values, 6, -1); $values = explode(",", $values); - $new = array(); + $new = []; foreach ($values as $key => $val) { $val = trim($val); if (strpos($val, "=>") !== false) { @@ -352,12 +366,13 @@ class Config return $new; } - /** Update the configuration file with the provided parameters - * @param array $paramsSlash The parameters to analyze for updating the file - * The params are in an array like array ("/authentication/html" => "value") - * All the parameters are not needed - * To remove a parameter, set it to default value - */ + /** + * Update the configuration file with the provided parameters + * @param array $paramsSlash The parameters to analyze for updating the file + * The params are in an array like array ("/authentication/html" => "value") + * All the parameters are not needed + * To remove a parameter, set it to default value + */ public function updateParamsSlash($paramsSlash) { $debug = 0; @@ -383,7 +398,7 @@ class Config if ($debug) { var_dump($stored); } - $new = array(); + $new = []; // Update the stored values with the provided ones foreach ($definitions as $key => $unused) { if ($debug) { @@ -478,9 +493,10 @@ class Config return true; } - /** Cast the provided string into the associated value - * @param string $val The val to cast - */ + /** + * Cast the provided string into the associated value + * @param string $val The val to cast + */ private function cast($val) { if (isset($val[0]) && ($val[0] === "\"" || $val[0] === "'")) { @@ -505,10 +521,11 @@ class Config return $new; } - /** Return an array containing the definitions read from the default config - * file - * The definition of param are in Slash format - */ + /** + * Return an array containing the definitions read from the default config + * file + * The definition of param are in Slash format + */ public function docComment() { $debug = 0; @@ -533,7 +550,7 @@ class Config $tokens = token_get_all($filecontent); $foundDefault = ""; $parenthesis = 0; - $params = array(); + $params = []; $path = ""; $group = dgettext("domframework", "Default parameters"); foreach ($tokens as $token) { @@ -552,7 +569,8 @@ class Config } // Append the not completed lines $text = trim(substr($text, 3, -2)); - $text = preg_replace("/\n\s+\*?\s*/", " ", $text); + $text = preg_replace("/\n\s+\*?\s + */", " ", $text); $text = preg_replace( "/(@(param|description|type|values|default|group|prefix))/", "\n\${1}", @@ -560,7 +578,7 @@ class Config ); $text = ltrim($text); // Look at each parameter and save them in a data array - $data = array(); + $data = []; foreach (explode("\n", $text) as $line) { $tmp = explode(" ", $line); $key = reset($tmp); diff --git a/src/Console.php b/src/Console.php index db8aa6f..4968c0a 100644 --- a/src/Console.php +++ b/src/Console.php @@ -1,88 +1,103 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** Allow to manage a linux Console to have a minimal but working text interface - * When using this class, you must use the $console::echo method and not - * display directely on screen - * Like readline, but all in PHP - * Manage the historical of the provided commands - * Allow the user to use arrow keys and the shortcuts Ctrl+arrow, Ctrl+L, - * Ctrl+U, Ctrl+W - * To not allow the stop of the program by Ctrl+C, you can add - * exec ("stty intr ^J"); - * To update the window size when the terminal is resized, use after console - * instanciation : - * declare(ticks = 1); - * pcntl_signal (SIGWINCH, function () use ($console) { - * $console->updateTerminalSize (); - * }); - */ +/** + * Allow to manage a linux Console to have a minimal but working text interface + * When using this class, you must use the $console::echo method and not + * display directely on screen + * Like readline, but all in PHP + * Manage the historical of the provided commands + * Allow the user to use arrow keys and the shortcuts Ctrl+arrow, Ctrl+L, + * Ctrl+U, Ctrl+W + * To not allow the stop of the program by Ctrl+C, you can add + * exec ("stty intr ^J"); + * To update the window size when the terminal is resized, use after console + * instanciation : + * declare(ticks = 1); + * pcntl_signal (SIGWINCH, function () use ($console) { + * $console->updateTerminalSize (); + * }); + */ class Console { // PROPERTIES - /** Set the debug on if a filename is provided, or do not debug if false is - * provided - */ + /** + * Set the debug on if a filename is provided, or do not debug if false is + * provided + */ //private $debug = "/tmp/debug"; private $debug = false; - /** Save the initial stty value - */ + /** + * Save the initial stty value + */ private $initSttyState; - /** Line Content - */ + /** + * Line Content + */ private $lineContent = ""; - /** If true, display each char the user has pressed (echo mode) - */ + /** + * If true, display each char the user has pressed (echo mode) + */ private $echoMode = true; - /** List of non printable chars in decimal. The non printable chars are not - * displayed but are correctely captured - */ - private $nonWriteableChar = array(1, 2, 3, 4, 6, 8, 9, 16, 18, + /** + * List of non printable chars in decimal. The non printable chars are not + * displayed but are correctely captured + */ + private $nonWriteableChar = [1, 2, 3, 4, 6, 8, 9, 16, 18, 20, 21, 22, 23, 24, 25, 27, - 127); + 127]; - /** The history list in an array - */ - private $history = array(); + /** + * The history list in an array + */ + private $history = []; - /** The history max size in entries - */ + /** + * The history max size in entries + */ private $historyMaxSize = 1000; - /** Set the completion keys. Not set by default - */ + /** + * Set the completion keys. Not set by default + */ private $completionKeys = false; - /** Set the function called when the completion char is called - */ - private $completionFunction = array(); + /** + * Set the function called when the completion char is called + */ + private $completionFunction = []; - /** Set the width of the terminal in chars - */ + /** + * Set the width of the terminal in chars + */ private $termWidth; - /** Set the height of the terminal in chars - */ + /** + * Set the height of the terminal in chars + */ private $termHeight; - /** Store the last cursor position in the last readline - */ + /** + * Store the last cursor position in the last readline + */ private $cursorPos = 1; - /** The constructor init the console. - * Check if we have the rights to execute, if wa have in cli... - */ + /** + * The constructor init the console. + * Check if we have the rights to execute, if wa have in cli... + */ public function __construct() { if (! function_exists("exec")) { @@ -98,8 +113,9 @@ class Console $this->updateTerminalSize(); } - /** Update the terminal size - */ + /** + * Update the terminal size + */ public function updateTerminalSize() { $this->termWidth = 80; @@ -120,8 +136,9 @@ class Console } } - /** The destructor return the terminal to initial state - */ + /** + * The destructor return the terminal to initial state + */ public function __destruct() { if ($this->initSttyState !== "") { @@ -132,51 +149,56 @@ class Console $this->textBold(false); } - /** Each time a key is pressed by the user, display the value on screen (echo) - */ + /** + * Each time a key is pressed by the user, display the value on screen (echo) + */ public function setEcho() { $this->echoMode = true; } - /** Each time a key is pressed by the user, DO NOT display the value on screen - * (echo disabled) - */ + /** + * Each time a key is pressed by the user, DO NOT display the value on screen + * (echo disabled) + */ public function unsetEcho() { $this->echoMode = false; } - /** Display a text on screen. Must be used before "readline" method because - * the provided message will not be deleted by readline process. - * @param string $message The message to display - */ + /** + * Display a text on screen. Must be used before "readline" method because + * the provided message will not be deleted by readline process. + * @param string $message The message to display + */ public function echo($message) { echo $message; $this->lineContent .= $message; } - /** Wait one valid character from the user. - * The non printable chars are not displayed, nor returned - * The ESC Sequences are skipped - * @return the pressed char - */ + /** + * Wait one valid character from the user. + * The non printable chars are not displayed, nor returned + * The ESC Sequences are skipped + * @return the pressed char + */ public function getc() { $char = $this->getKey(); - while (in_array(ord($char), $this->nonWriteableChar)) { + while (in_array(ord($char), $this->nonWriteableChar, true)) { $char = $this->getKey(); } return $char; } - /** Wait one key pressed by the user. If the key pressed is an ESC sequence, - * return this sequence - * The non printable chars are not displayed, but are correctely returned - * The UTF8 chars are return as multiple length chars - * @return the pressed char - */ + /** + * Wait one key pressed by the user. If the key pressed is an ESC sequence, + * return this sequence + * The non printable chars are not displayed, but are correctely returned + * The UTF8 chars are return as multiple length chars + * @return the pressed char + */ public function getKey() { $char = fgetc(STDIN); @@ -230,20 +252,21 @@ class Console // Four chars $char .= fgetc(STDIN) . fgetc(STDIN) . fgetc(STDIN); } - if ($this->echoMode && ! in_array(ord($char), $this->nonWriteableChar)) { + if ($this->echoMode && ! in_array(ord($char), $this->nonWriteableChar, true)) { echo $char; } return $char; } - /** Get the line of characters pressed by the user and return the result. - * Stop when the user valid by \n. - * Manage correctely the backspace, the Ctrl+W to remove word... - * @param string $propo Preset the text for the user - * @param boolean|string $stopperChar The chars to stop the analysis and - * return the result - * @return string The typed string - */ + /** + * Get the line of characters pressed by the user and return the result. + * Stop when the user valid by \n. + * Manage correctely the backspace, the Ctrl+W to remove word... + * @param string $propo Preset the text for the user + * @param boolean|string $stopperChar The chars to stop the analysis and + * return the result + * @return string The typed string + */ public function readline($propo = "", $stopperChar = false) { // Gets can not delete chars before the call. Keep the prompt (if exists) @@ -269,7 +292,7 @@ class Console } if ( $stopperChar !== false && - in_array($char, $this->mb_str_split($stopperChar)) + in_array($char, $this->mb_str_split($stopperChar), true) ) { // End of process with stopperChars $this->lineContent = ""; @@ -277,7 +300,7 @@ class Console } if ( $this->completionKeys !== false && - in_array($char, $this->mb_str_split($this->completionKeys)) + in_array($char, $this->mb_str_split($this->completionKeys), true) ) { // Manage autocompletion $this->debug("Autocompletion starting"); @@ -535,7 +558,7 @@ class Console $this->rewriteLine($prompt . $string); $this->moveCursor($cursorPos); } - } elseif (in_array(ord($char), $this->nonWriteableChar)) { + } elseif (in_array(ord($char), $this->nonWriteableChar, true)) { // Non writeable char : skip it $this->debug("Non writeable char : " . ord($char)); } else { @@ -544,7 +567,7 @@ class Console $strArr = $this->mb_str_split($string); $firstArr = array_slice($strArr, 0, $cursorPos - $minLength); $lastArr = array_slice($strArr, $cursorPos - $minLength); - $insertArr = array($char); + $insertArr = [$char]; $strArr = array_merge($firstArr, $insertArr, $lastArr); $string = implode($strArr); $cursorPos++; @@ -556,10 +579,11 @@ class Console return $string; } - /** Rewrite the line with the provided $text. - * Delete all the old data - * @param string $text The new text to use on line - */ + /** + * Rewrite the line with the provided $text. + * Delete all the old data + * @param string $text The new text to use on line + */ private function rewriteLine($text) { $this->debug("Call rewriteLine ($text)"); @@ -571,9 +595,10 @@ class Console } } - /** Move the cursor on position $position. The first column is $cursorPos=1 - * @param integer $cursorPos The new position on line - */ + /** + * Move the cursor on position $position. The first column is $cursorPos=1 + * @param integer $cursorPos The new position on line + */ private function moveCursor($cursorPos) { $this->debug("Call moveCursor ($cursorPos)"); @@ -602,8 +627,9 @@ class Console } } - /** Clear the existing line. - */ + /** + * Clear the existing line. + */ public function clearLine() { $this->debug("Call clearLine"); @@ -631,37 +657,41 @@ class Console $this->cursorPos = 1; } - /** Clear all the screen and remove the scroll of the screen - */ + /** + * Clear all the screen and remove the scroll of the screen + */ public function clearScreen() { echo "\033[2J\033[;H\033c"; } - /** Get the terminal Height - */ + /** + * Get the terminal Height + */ public function getTermHeight() { return $this->termHeight; } - /** Get the terminal Width - */ + /** + * Get the terminal Width + */ public function getTermWidth() { return $this->termWidth; } - /** Call a specific function when a completion key is pressed - * The function must get the partial text as first parameter, and must return - * an array with the possibilities - * If only one possibility is returned, the console will be immediately - * updated. - * @param string|bool $completionKeys The list of the completion keys. False - * unset the method - * @param callable $completionFunction The function called when one of the - * completion keys is pressed. - */ + /** + * Call a specific function when a completion key is pressed + * The function must get the partial text as first parameter, and must return + * an array with the possibilities + * If only one possibility is returned, the console will be immediately + * updated. + * @param string|bool $completionKeys The list of the completion keys. False + * unset the method + * @param callable $completionFunction The function called when one of the + * completion keys is pressed. + */ public function completeFunction($completionKeys, $completionFunction) { if (! is_string($completionKeys) && ! is_boolean($completionKeys)) { @@ -678,25 +708,28 @@ class Console $this->completionFunction = $completionFunction; } - /** Get the actual history in memory - */ + /** + * Get the actual history in memory + */ public function getHistory() { return $this->history; } - /** Clear the history - * This method do NOT write the empty history on disk - */ + /** + * Clear the history + * This method do NOT write the empty history on disk + */ public function clearHistory() { - $this->history = array(); + $this->history = []; return $this; } - /** Write the history to disk. - * @param string $historyFile The history file where the history is stored - */ + /** + * Write the history to disk. + * @param string $historyFile The history file where the history is stored + */ public function writeHistory($historyFile) { if (file_exists($historyFile)) { @@ -729,16 +762,17 @@ class Console return $this; } - /** Read the history from the disk - * If the file doesn't exists, return an empty array - * @param string $historyFile The history file where the history is stored - * @return the read history with timestamp as key and command as value - */ + /** + * Read the history from the disk + * If the file doesn't exists, return an empty array + * @param string $historyFile The history file where the history is stored + * @return the read history with timestamp as key and command as value + */ public function readHistory($historyFile) { if (! file_exists($historyFile)) { - $this->history = array(); - return array(); + $this->history = []; + return []; } if (! is_readable($historyFile)) { $this->consoleException("History file '$historyFile' can not be read"); @@ -765,11 +799,12 @@ class Console return $this->history; } - /** Add a new entry in history. - * The new line can not be empty : it is not stored, but without error - * This method do NOT write the history on disk : you must use writeHistory - * @param string The new entry to add in history - */ + /** + * Add a new entry in history. + * The new line can not be empty : it is not stored, but without error + * This method do NOT write the history on disk : you must use writeHistory + * @param string The new entry to add in history + */ public function addHistory($line) { if (! is_string($line)) { @@ -789,10 +824,11 @@ class Console return $this; } - /** Get/Set the maximum number of entries in the history - * If null, get the defined maximum number - * @param integer|null $historyMaxSize The maximum number of entries - */ + /** + * Get/Set the maximum number of entries in the history + * If null, get the defined maximum number + * @param integer|null $historyMaxSize The maximum number of entries + */ public function historyMaxSize($historyMaxSize = null) { if ($historyMaxSize === null) { @@ -805,17 +841,19 @@ class Console $this->historyMaxSize = intval($historyMaxSize); } - /** Error management - * @param string $message The message to throw in the exception - */ + /** + * Error management + * @param string $message The message to throw in the exception + */ public function consoleException($message) { throw new \Exception($message, 500); } - /** Set the text color - * @param integer $colorNum The color number to use - */ + /** + * Set the text color + * @param integer $colorNum The color number to use + */ public function colorText($colorNum) { if (! is_int($colorNum)) { @@ -825,9 +863,10 @@ class Console echo "\033[38;5;{$colorNum}m"; } - /** Set the background text color - * @param integer $colorNum The color number to use - */ + /** + * Set the background text color + * @param integer $colorNum The color number to use + */ public function colorBackgroundText($colorNum) { if (! is_int($colorNum)) { @@ -837,16 +876,18 @@ class Console echo "\033[48;5;{$colorNum}m"; } - /** Reset the colors - */ + /** + * Reset the colors + */ public function colorReset() { echo "\033[0m"; } - /** Underline the text - * @param boolean $underline True to underline, false to remove the underline - */ + /** + * Underline the text + * @param boolean $underline True to underline, false to remove the underline + */ public function textUnderline($underline) { if ($underline === false) { @@ -857,9 +898,10 @@ class Console echo "\033[{$underline}4m"; } - /** Bold the text - * @param boolean $bold True to bold, false to remove the bold - */ + /** + * Bold the text + * @param boolean $bold True to bold, false to remove the bold + */ public function textBold($bold) { if ($bold === false) { @@ -870,22 +912,24 @@ class Console echo "\033[{$bold}m"; } - /** Return true if the TTY is enabled, or false if the program is called from pipe - */ + /** + * Return true if the TTY is enabled, or false if the program is called from pipe + */ public function isTTY() { return !! $this->initSttyState; } - /** Tokenize the provided line and aggragate if there is single or double - * quotes. - * Trim the spaces - * @param string $line The line to tokenize - * @return array The tokens - */ + /** + * Tokenize the provided line and aggragate if there is single or double + * quotes. + * Trim the spaces + * @param string $line The line to tokenize + * @return array The tokens + */ public static function tokenize($line) { - $tokens = array(); + $tokens = []; $token = strtok(trim($line), ' '); while ($token) { // find double quoted tokens @@ -902,23 +946,25 @@ class Console return $tokens; } - /** This function return an array with each char, but supports UTF-8 - * @param string $string The string to explode - * @param integer $split_length The number of chars in each split - * @return array - */ + /** + * This function return an array with each char, but supports UTF-8 + * @param string $string The string to explode + * @param integer $split_length The number of chars in each split + * @return array + */ private function mb_str_split($string, $split_length = 1) { - $res = array(); + $res = []; for ($i = 0; $i < mb_strlen($string); $i += $split_length) { $res[] = mb_substr($string, $i, $split_length); } return $res; } - /** This function debug the data - * @param mixed $data The data to store - */ + /** + * This function debug the data + * @param mixed $data The data to store + */ private function debug($data) { if ($this->debug === false) { @@ -930,10 +976,11 @@ class Console file_put_contents($this->debug, date("H:i:s") . " $data\n", FILE_APPEND); } - /** Look in the array which first chars of each possibilites are identical. - * @param array $completeArr The values to examine - * @return string the identical chars - */ + /** + * Look in the array which first chars of each possibilites are identical. + * @param array $completeArr The values to examine + * @return string the identical chars + */ private function shortestIdenticalValues($completeArr) { if (! is_array($completeArr)) { diff --git a/src/Convert.php b/src/Convert.php index 68b9371..c9fb9e5 100644 --- a/src/Convert.php +++ b/src/Convert.php @@ -1,33 +1,36 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** Convert a format to another one - */ +/** + * Convert a format to another one + */ class Convert { - /** Convert Date received in one format to another. - * If the provided string is not corresponding to the format, generate an - * exception or return the original string - * Format used http://php.net/manual/en/datetime.createfromformat.php - * Do not accept the locale ! The language of the dates is always in english - * @param string $inputDate The date to modify - * @param string $inputFormat The input format of the date - * @param string $outputFormat The output format of the date - * @param boolean|null $exception If set, generate an exception if the - * provided date is invalid - * @param string|null $inputTimezone The timezone used to read the input - * By default, Europe/Paris - * @param string|null $outputTimezone The timezone used to write the output - * By default, Europe/Paris - * @return string - */ + /** + * Convert Date received in one format to another. + * If the provided string is not corresponding to the format, generate an + * exception or return the original string + * Format used http://php.net/manual/en/datetime.createfromformat.php + * Do not accept the locale ! The language of the dates is always in english + * @param string $inputDate The date to modify + * @param string $inputFormat The input format of the date + * @param string $outputFormat The output format of the date + * @param boolean|null $exception If set, generate an exception if the + * provided date is invalid + * @param string|null $inputTimezone The timezone used to read the input + * By default, Europe/Paris + * @param string|null $outputTimezone The timezone used to write the output + * By default, Europe/Paris + * @return string + */ public static function convertDate( $inputDate, $inputFormat, @@ -79,10 +82,11 @@ class Convert return $date->format($outputFormat); } - /** Convert the first char to capital and the rest of the sentence in - * lowercase (like ucfirst, but UTF8 compliant) - * @param string $str The string to convert - */ + /** + * Convert the first char to capital and the rest of the sentence in + * lowercase (like ucfirst, but UTF8 compliant) + * @param string $str The string to convert + */ public static function ucfirst($str) { if (! function_exists("mb_strtoupper")) { @@ -95,15 +99,16 @@ class Convert return $a . mb_substr($str, 1, null, 'UTF-8'); } - /** Convert the first char of each word of a sentence to capital. The word - * delimiter can be provided. - * The sentence is in UTF-8. - * The sentence is converted to lowercase before doing the action (in - * contrary of the original PHP function) - * @param string $str The string to convert - * @param string $delimiters The delimiters (by default " \t\r\n\f\v") - * @return string - */ + /** + * Convert the first char of each word of a sentence to capital. The word + * delimiter can be provided. + * The sentence is in UTF-8. + * The sentence is converted to lowercase before doing the action (in + * contrary of the original PHP function) + * @param string $str The string to convert + * @param string $delimiters The delimiters (by default " \t\r\n\f\v") + * @return string + */ public static function ucwords($str, $delimiters = " \t\r\n\f\v") { if (! function_exists("mb_strtolower")) { @@ -127,14 +132,15 @@ class Convert return $res; } - /** Convert the provided float to human readable format - * Example : 1440000 => 1.44MB - * @param float|integer $value The number to convert - * @param integer|null $decimals The number of decimal (2 by default) - * @param integer|null $power (1000 by default or 1024) - * @param string|null $unit The Unit displayed after the multiplier (B for - * Bytes by default) - */ + /** + * Convert the provided float to human readable format + * Example : 1440000 => 1.44MB + * @param float|integer $value The number to convert + * @param integer|null $decimals The number of decimal (2 by default) + * @param integer|null $power (1000 by default or 1024) + * @param string|null $unit The Unit displayed after the multiplier (B for + * Bytes by default) + */ public static function humanSize( $value, $decimals = 2, @@ -156,7 +162,7 @@ class Convert throw new \Exception("convert::humanSize power value !== 1000 and 1024" . " : " . var_export($power, true), 500); } - $size = array( + $size = [ -8 => 'y', // yocto -7 => 'z', // zepto -6 => 'a', // atto @@ -173,7 +179,7 @@ class Convert 5 => 'P', // peta 6 => 'E', // exa 7 => 'Z', // zetta - 8 => 'Y');// yotta + 8 => 'Y'];// yotta for ($factor = 8; $factor > -8; $factor--) { if (abs($value) >= pow($power, $factor)) { break; diff --git a/src/Csrf.php b/src/Csrf.php index f6d0f7b..c400a11 100644 --- a/src/Csrf.php +++ b/src/Csrf.php @@ -1,35 +1,43 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** CSRF protection - * By default, the CSRF protection is active if a SESSION is active too. - * It can be disabled if needed. An Exception is raised if the form is send - * back without the token - */ +/** + * CSRF protection + * By default, the CSRF protection is active if a SESSION is active too. + * It can be disabled if needed. An Exception is raised if the form is send + * back without the token + */ class Csrf { - /** Allow to disable the csrf protection - */ + /** + * Allow to disable the csrf protection + */ public $csrf = true; - /** This hidden field name in HTML - */ + /** + * This hidden field name in HTML + */ public $field = "CSRF_TOKEN"; - /** The created token - */ + /** + * The created token + */ private $csrfToken = ""; - /** Timeout of the CSRF token : 3600s by default (maximum time allowed to - * enter information in form and submit) */ + /** + * Timeout of the CSRF token : 3600s by default (maximum time allowed to + * enter information in form and submit) + */ private $csrfTimeout = 3600; - /** Manage the singleton - */ + /** + * Manage the singleton + */ public function __construct() { if (isset($GLOBALS["domframework"]["csrf"])) { @@ -41,9 +49,10 @@ class Csrf } } - /** Get / Set the status of the CSRF protection - * @param boolean|null $val The value to set/get if null - */ + /** + * Get / Set the status of the CSRF protection + * @param boolean|null $val The value to set/get if null + */ public function csrfState($val = null) { if ($val === null) { @@ -54,9 +63,10 @@ class Csrf return $this; } - /** Get / Set the name of the field in HTML - * @param string|null $val The value to set/get if null - */ + /** + * Get / Set the name of the field in HTML + * @param string|null $val The value to set/get if null + */ public function field($val = null) { if ($val === null) { @@ -67,8 +77,9 @@ class Csrf return $this; } - /** This function return the token - */ + /** + * This function return the token + */ public function createToken() { $l = 30; // Number of chars in token @@ -84,10 +95,11 @@ class Csrf return $this->csrfToken; } - /** Check if the provided token is the right token, defined last displayed - * page - * @param string $tokenFromUser The value csrf the user's token - */ + /** + * Check if the provided token is the right token, defined last displayed + * page + * @param string $tokenFromUser The value csrf the user's token + */ public function checkToken($tokenFromUser) { if ($this->csrf === false) { @@ -99,10 +111,10 @@ class Csrf isset($_SESSION["domframework"]["csrf"]["csrf"]) && isset($_SESSION["domframework"]["csrf"]["csrfStart"]) ) { - $_SESSION["domframework"]["csrf"] = array( + $_SESSION["domframework"]["csrf"] = [ $_SESSION["domframework"]["csrf"]["csrf"] => $_SESSION["domframework"]["csrf"]["csrfStart"] - ); + ]; unset($_SESSION["domframework"]["csrf"]["csrfStart"]); } if (! isset($_SESSION["domframework"]["csrf"])) { @@ -136,8 +148,9 @@ class Csrf return true; } - /** Return the CSRF token in a hidden field - */ + /** + * Return the CSRF token in a hidden field + */ public function displayFormCSRF() { if ($this->csrfToken == "") { @@ -148,8 +161,9 @@ class Csrf return $res; } - /** Return the token if exists or create a new one if needed - */ + /** + * Return the token if exists or create a new one if needed + */ public function getToken() { if ($this->csrfToken === "") { @@ -158,9 +172,10 @@ class Csrf return $this->csrfToken; } - /** Add more time to existing CSRF token - * @param string $tokenFromUser The existing token - */ + /** + * Add more time to existing CSRF token + * @param string $tokenFromUser The existing token + */ public function extendToken($tokenFromUser) { $this->checkToken($tokenFromUser); @@ -168,9 +183,10 @@ class Csrf return true; } - /** Check an existing token, then delete it - * @param string $tokenFromUser The existing token - */ + /** + * Check an existing token, then delete it + * @param string $tokenFromUser The existing token + */ public function checkThenDeleteToken($tokenFromUser) { $this->checkToken($tokenFromUser); diff --git a/src/Daemon.php b/src/Daemon.php index 90afa38..9b8ef55 100644 --- a/src/Daemon.php +++ b/src/Daemon.php @@ -1,24 +1,28 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** Manage a daemon. - * Allow to start, stop, get status of a callable method - */ +/** + * Manage a daemon. + * Allow to start, stop, get status of a callable method + */ class Daemon { - /** Set the directory to store the PID of the daemon - */ + /** + * Set the directory to store the PID of the daemon + */ private $runDir = "/var/run"; - /** The constructor check if /proc is mounted - */ + /** + * The constructor check if /proc is mounted + */ public function __construct() { if (! file_exists("/proc")) { @@ -26,9 +30,10 @@ class Daemon } } - /** Get/set the directory to store the PID of the daemon - * @param string|null $val The directory - */ + /** + * Get/set the directory to store the PID of the daemon + * @param string|null $val The directory + */ public function runDir($val = null) { if ($val === null) { @@ -40,16 +45,17 @@ class Daemon $this->runDir = "$val"; } - /** Start the callable method. The terminal is closed. All the displayed - * messages from the child are silently dropped. - * If some parameters are provided, the called child method will receive them - * This function fork and return the child PID - * @param string $name The name of daemon to start. - * @param callable $callable The callback method to use in child - * @param mixed|null $params The params to provide to child method - * @return The child PID - */ - public function start($name, $callable, $params = array()) + /** + * Start the callable method. The terminal is closed. All the displayed + * messages from the child are silently dropped. + * If some parameters are provided, the called child method will receive them + * This function fork and return the child PID + * @param string $name The name of daemon to start. + * @param callable $callable The callback method to use in child + * @param mixed|null $params The params to provide to child method + * @return The child PID + */ + public function start($name, $callable, $params = []) { $file = new File(); if (! $file->is_writeable($this->runDir)) { @@ -79,14 +85,15 @@ class Daemon return $pid; } - /** Stop a $name daemon - * @param string $name The name of daemon to stop. The name must be the same - * as the name used in the start method - * @param integer $maxWaitStop The waiting maximum time after SIGTERM before - * sending SIGKILL - * @param integer $maxWaitKill The waiting maximum time after SIGKILL before - * raising an error - */ + /** + * Stop a $name daemon + * @param string $name The name of daemon to stop. The name must be the same + * as the name used in the start method + * @param integer $maxWaitStop The waiting maximum time after SIGTERM before + * sending SIGKILL + * @param integer $maxWaitKill The waiting maximum time after SIGKILL before + * raising an error + */ public function stop($name, $maxWaitStop = 3, $maxWaitKill = 3) { $file = new File(); @@ -143,10 +150,11 @@ class Daemon throw new \Exception("Can't stop and can't kill the process $pid", 500); } - /** Status of a daemon - * @param string $name The name of daemon to have status. The name must be - * the same as the name used in the start method - */ + /** + * Status of a daemon + * @param string $name The name of daemon to have status. The name must be + * the same as the name used in the start method + */ public function status($name) { $file = new File(); @@ -173,10 +181,11 @@ class Daemon return "The daemon is running on PID $pid\n"; } - /** Send a HUP Signal to the daemon - * @param string $name The name of daemon to HUP. The name must be - * the same as the name used in the start method - */ + /** + * Send a HUP Signal to the daemon + * @param string $name The name of daemon to HUP. The name must be + * the same as the name used in the start method + */ public function reload($name) { $file = new File(); diff --git a/src/Dbjson.php b/src/Dbjson.php index 03a1f69..12eb7ca 100644 --- a/src/Dbjson.php +++ b/src/Dbjson.php @@ -1,43 +1,56 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** DBJSON : a NoSQL DB in JSON - * Documentation - * - A filter is an array containing the fields and the values to found - * array ("key"=>"val") <== Look for the key equal val - * array ("key=>array ("val", "<=")) <== Look for the key lighter or equal - * than val - * array () <== Look for all the documents (no - * filter) - * array ("key"=>"val", "key2"=>"val2") <== Look for two parameters - * - A document is an array containing the fields and the values to store - * array ("key"=>"val) - * - * - The field named _id is the document key - */ +/** + * DBJSON : a NoSQL DB in JSON + * Documentation + * - A filter is an array containing the fields and the values to found + * array ("key"=>"val") <== Look for the key equal val + * array ("key=>array ("val", "<=")) <== Look for the key lighter or equal + * than val + * array () <== Look for all the documents (no + * filter) + * array ("key"=>"val", "key2"=>"val2") <== Look for two parameters + * - A document is an array containing the fields and the values to store + * array ("key"=>"val) + * + * - The field named _id is the document key + */ class Dbjson { - /** The DSN of the connection */ + /** + * The DSN of the connection + */ private $dsn = ""; - /** The database file */ + /** + * The database file + */ private $dbfile = ""; - /** The lock file */ + /** + * The lock file + */ private $dbfileLock = ""; - /** The last Insert Id */ + /** + * The last Insert Id + */ private $lastInsertId = 0; - /** The database content */ + /** + * The database content + */ private $db; - /** The constructor - * @param string $dsn The DSN of the connection - */ + /** + * The constructor + * @param string $dsn The DSN of the connection + */ public function __construct($dsn) { if (! function_exists("openssl_random_pseudo_bytes")) { @@ -99,18 +112,19 @@ class Dbjson $this->dbfile = $this->dbfile; } - /** Store one document in database - * @param string $collection The collection name - * @param array $document The document to insert - * @return integer return The number of document inserted in the database - */ + /** + * Store one document in database + * @param string $collection The collection name + * @param array $document The document to insert + * @return integer return The number of document inserted in the database + */ public function insertOne($collection, $document) { $uniqueKey = $this->uniqueKey(); $this->lockEX(); $this->db = $this->readDB(); $this->db[$collection]["content"][$uniqueKey] = array_merge( - array("_id" => $uniqueKey), + ["_id" => $uniqueKey], $document ); $this->writeDB(); @@ -118,11 +132,12 @@ class Dbjson return 1; } - /** Store multiple documents in database - * @param string $collection The collection name - * @param array $documents array(array ()) - * @return integer The number of documents inserted in the database - */ + /** + * Store multiple documents in database + * @param string $collection The collection name + * @param array $documents array(array ()) + * @return integer The number of documents inserted in the database + */ public function insertMany($collection, $documents) { foreach ($documents as $document) { @@ -135,7 +150,7 @@ class Dbjson foreach ($documents as $document) { $uniqueKey = $this->uniqueKey(); $this->db[$collection]["content"][$uniqueKey] = array_merge( - array("_id" => $uniqueKey), + ["_id" => $uniqueKey], $document ); } @@ -145,20 +160,21 @@ class Dbjson return count($documents); } - /** Look at the documents matching $filter (all by default). - * Then return only the $fields (all by default). - * The field _id is always returned - * Return $limit maximum documents (no limit by default) - * @param string $collection The collection name - * @param array $filter The filter to apply to found the documents - * @param array|string $fields The fields to display (* for all, empty array - * for none) - * @param integer $limit The number of documents to display - * @return array The documents matching the parameters - */ + /** + * Look at the documents matching $filter (all by default). + * Then return only the $fields (all by default). + * The field _id is always returned + * Return $limit maximum documents (no limit by default) + * @param string $collection The collection name + * @param array $filter The filter to apply to found the documents + * @param array|string $fields The fields to display (* for all, empty array + * for none) + * @param integer $limit The number of documents to display + * @return array The documents matching the parameters + */ public function find( $collection, - $filter = array(), + $filter = [], $fields = "*", $limit = null ) { @@ -166,14 +182,14 @@ class Dbjson $this->db = $this->readDB(); // Get the keys of the documents based on the filter $keys = $this->filter($collection, $filter); - $res = array(); + $res = []; foreach ($keys as $key) { // Limit the fields - $tmp = array(); + $tmp = []; if ($fields === "*") { $tmp = $this->db[$collection]["content"][$key]; } elseif (is_array($fields)) { - if (! in_array("_id", $fields)) { + if (! in_array("_id", $fields, true)) { array_unshift($fields, "_id"); } foreach ($fields as $field) { @@ -200,20 +216,21 @@ class Dbjson return $res; } - /** Update some existing documents. Do not change the _id keys - * @param string $collection The collection name - * @param array $filter The filter to apply to found the documents - * @param array $document The data to update - * @return integer The number of modified documents - * To unset a field, add in the document array a "_unset"=>array("field)" - */ + /** + * Update some existing documents. Do not change the _id keys + * @param string $collection The collection name + * @param array $filter The filter to apply to found the documents + * @param array $document The data to update + * @return integer The number of modified documents + * To unset a field, add in the document array a "_unset"=>array("field)" + */ public function update($collection, $filter, $document) { $this->lockEX(); $this->db = $this->readDB(); // Get the keys of the documents based on the filter $keys = $this->filter($collection, $filter); - $unset = array(); + $unset = []; if (array_key_exists("_unset", $document)) { $unset = $document["_unset"]; unset($document["_unset"]); @@ -253,12 +270,13 @@ class Dbjson return count($keys); } - /** Replace some existing documents. Do not change the _id keys - * @param string $collection The collection name - * @param array $filter The filter to apply to found the documents - * @param array $document The data to update - * @return integer The number of modified documents - */ + /** + * Replace some existing documents. Do not change the _id keys + * @param string $collection The collection name + * @param array $filter The filter to apply to found the documents + * @param array $document The data to update + * @return integer The number of modified documents + */ public function replace($collection, $filter, $document) { $this->lockEX(); @@ -267,7 +285,7 @@ class Dbjson $keys = $this->filter($collection, $filter); foreach ($keys as $key) { $tmp = $this->db[$collection]["content"][$key]; - $replace = array(); + $replace = []; $replace["_id"] = $tmp["_id"]; $replace = array_merge($replace, $document); $this->db[$collection]["content"][$key] = $replace; @@ -278,11 +296,12 @@ class Dbjson return count($keys); } - /** Delete the first document matching the filter - * @param string $collection The collection name - * @param array $filter The filter to found the documents - * @return integer The number of deleted documents - */ + /** + * Delete the first document matching the filter + * @param string $collection The collection name + * @param array $filter The filter to found the documents + * @return integer The number of deleted documents + */ public function deleteOne($collection, $filter) { $this->lockEX(); @@ -301,11 +320,12 @@ class Dbjson return 1; } - /** Delete all the documents matching the filter - * @param string $collection The collection name - * @param array $filter The filter to apply to found the documents - * @return integer The number of deleted documents - */ + /** + * Delete all the documents matching the filter + * @param string $collection The collection name + * @param array $filter The filter to apply to found the documents + * @return integer The number of deleted documents + */ public function deleteMany($collection, $filter) { $this->lockEX(); @@ -321,33 +341,34 @@ class Dbjson return count($keys); } - /** Look for the keys corresponding to the filter in the collection - * Don't manage the locks ! - * @param string $collection The collection name - * @param array $filter The filter to apply to found the documents - * - A filter is an array containing the fields and the values to found - * array () <== Look for all the documents (no - * filter) - * array ("key"=>"val") <== Look for the key equal val - * array ("key=>array ("val", "<=")) <== Look for the key lighter or - * equal than val - * array ("key"=>"val", "key2"=>"val2") <== Look for two parameters - * array ("key"=>array ("val", "=="), - * "key2"=>array ("val2", "==")) <== Look for two complex parameters - * Here is the comparison types available : ==, - * @return array the keys matching the filter - */ + /** + * Look for the keys corresponding to the filter in the collection + * Don't manage the locks ! + * @param string $collection The collection name + * @param array $filter The filter to apply to found the documents + * - A filter is an array containing the fields and the values to found + * array () <== Look for all the documents (no + * filter) + * array ("key"=>"val") <== Look for the key equal val + * array ("key=>array ("val", "<=")) <== Look for the key lighter or + * equal than val + * array ("key"=>"val", "key2"=>"val2") <== Look for two parameters + * array ("key"=>array ("val", "=="), + * "key2"=>array ("val2", "==")) <== Look for two complex parameters + * Here is the comparison types available : ==, + * @return array the keys matching the filter + */ public function filter($collection, $filter) { if ($this->db === null) { $this->db = $this->readDB(); } - $keys = array(); + $keys = []; if (! array_key_exists($collection, $this->db)) { - $this->db[$collection]["content"] = array(); + $this->db[$collection]["content"] = []; } foreach ($this->db[$collection]["content"] as $key => $document) { - if ($filter === array()) { + if ($filter === []) { $keys[] = $key; continue; } @@ -390,7 +411,7 @@ class Dbjson $matchFilter = true; } elseif ( strtolower($fvals[1]) === "in_array" && - in_array($fvals[0], $document[$fkey]) + in_array($fvals[0], $document[$fkey], true) ) { $matchFilter = true; } else { @@ -418,9 +439,10 @@ class Dbjson return $keys; } - /** Generate a unique key - * @return string the Unique key generated - */ + /** + * Generate a unique key + * @return string the Unique key generated + */ private function uniqueKey() { $data = openssl_random_pseudo_bytes(16); @@ -429,7 +451,9 @@ class Dbjson return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } - /** Exclusive lock the database file */ + /** + * Exclusive lock the database file + */ private function lockEX() { $this->dbfileLock = fopen($this->dbfile, "rt"); @@ -438,7 +462,9 @@ class Dbjson } } - /** Shared lock the database file */ + /** + * Shared lock the database file + */ private function lockSH() { $this->dbfileLock = fopen($this->dbfile, "rt"); @@ -447,7 +473,9 @@ class Dbjson } } - /** Unlock the database file */ + /** + * Unlock the database file + */ private function lockUN() { if ($this->dbfileLock !== null) { @@ -457,22 +485,24 @@ class Dbjson } } - /** Read the dbfile and return an array containing the data. This function - * don't do locks ! - * @return array The database content from the dbfile - */ + /** + * Read the dbfile and return an array containing the data. This function + * don't do locks ! + * @return array The database content from the dbfile + */ private function readDB() { $res = json_decode(file_get_contents($this->dbfile), true); if ($res === null) { - $res = array(); + $res = []; } return $res; } - /** Write the dbfile with the provided data. This function don't do locks ! - * @return bool True if the recording is OK, false if there is a problem - */ + /** + * Write the dbfile with the provided data. This function don't do locks ! + * @return bool True if the recording is OK, false if there is a problem + */ private function writeDB() { return !! file_put_contents($this->dbfile, json_encode($this->db)); diff --git a/src/Dblayer.php b/src/Dblayer.php index 03dd8f7..76e9438 100644 --- a/src/Dblayer.php +++ b/src/Dblayer.php @@ -1,10 +1,11 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; @@ -36,86 +37,140 @@ To use it, extends in your code this class, and define the attributes : Optionnaly, you can add the - public $debug = TRUE : enable the debug on screen (NOT FOR PROD !!) -*/ + */ -/** Permit abstraction on the differents SQL databases available */ +/** + * Permit abstraction on the differents SQL databases available + */ class Dblayer { - /** The table name to use */ + /** + * The table name to use + */ public $table = null; - /** The tableprefix text to prepend to table name (Should finish by _) - Just allow chars ! */ + /** + * The tableprefix text to prepend to table name (Should finish by _) + * Just allow chars ! + */ public $tableprefix = ""; - /** The fields with the definition of type, and special parameters */ - public $fields = array(); - /** The primary field */ + /** + * The fields with the definition of type, and special parameters + */ + public $fields = []; + /** + * The primary field + */ public $primary = null; - /** An array to define the unique fields (or array of unique fields) */ + /** + * An array to define the unique fields (or array of unique fields) + */ public $unique = null; - /** An array to define the foreign keys of the field */ - public $foreign = array(); - /** Debug of the SQL */ + /** + * An array to define the foreign keys of the field + */ + public $foreign = []; + /** + * Debug of the SQL + */ public $debug = false; - /** The connecting DSN */ + /** + * The connecting DSN + */ private $dsn = null; - /** The field group delimiter */ + /** + * The field group delimiter + */ private $sep = ""; - /** Titles */ - public $titles = array(); + /** + * Titles + */ + public $titles = []; - /** Define the name of the method to use to verify each entry */ + /** + * Define the name of the method to use to verify each entry + */ public $verifyOneFunc; - /** Define the name of the method to use to verify all entries */ + /** + * Define the name of the method to use to verify all entries + */ public $verifyAllFunc; - /** Define the name of the method of hook before read */ + /** + * Define the name of the method of hook before read + */ public $hookprereadFunc; - /** Define the name of the method of hook after read */ + /** + * Define the name of the method of hook after read + */ public $hookpostreadFunc; - /** Define the name of the method of hook before insert */ + /** + * Define the name of the method of hook before insert + */ public $hookpreinsertFunc; - /** Define the name of the method of hook after insert */ + /** + * Define the name of the method of hook after insert + */ public $hookpostinsertFunc; - /** Define the name of the method of hook before update */ + /** + * Define the name of the method of hook before update + */ public $hookpreupdateFunc; - /** Define the name of the method of hook after update */ + /** + * Define the name of the method of hook after update + */ public $hookpostupdateFunc; - /** Define the name of the method of hook before delete */ + /** + * Define the name of the method of hook before delete + */ public $hookpredeleteFunc; - /** Define the name of the method of hook after delete */ + /** + * Define the name of the method of hook after delete + */ public $hookpostdeleteFunc; - /** The verify unitary stack - @param string $field The name of the field to test - @param string $val The value of the field to test */ + /** + * The verify unitary stack + * @param string $field The name of the field to test + * @param string $val The value of the field to test + */ public function verifyOne($field, $val) { } - /** The verify global stack - @param array $data The associative array of contents */ + /** + * The verify global stack + * @param array $data The associative array of contents + */ public function verifyAll($data) { } // TODO !! - /** Create Table creation from $this->fields with engine abstraction - Example in sqlite3 id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - in MySQL id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, */ + /** + * Create Table creation from $this->fields with engine abstraction + * Example in sqlite3 id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + * in MySQL id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, + */ // TODO !! - /** Create automatic creation of $fields from .schema of sqlite3/ - show create table `NomTable`; for MySQL - SQLite3 : PRAGMA TABLE_INFO('yourtable'); - MYSQL : SHOW COLUMNS FROM yourtable;*/ + /** + * Create automatic creation of $fields from .schema of sqlite3/ + * show create table `NomTable`; for MySQL + * SQLite3 : PRAGMA TABLE_INFO('yourtable'); + * MYSQL : SHOW COLUMNS FROM yourtable; + */ // TODO !! - /** Allow to modify tables if the definition is changed - Attention : SQLite don't supports adding Foreign keys without deleting all - the table, and re-import the data (http://www.sqlite.org/omitted.html) */ + /** + * Allow to modify tables if the definition is changed + * Attention : SQLite don't supports adding Foreign keys without deleting all + * the table, and re-import the data (http://www.sqlite.org/omitted.html) + */ - /** Limit to one instance of the connection to the same database */ + /** + * Limit to one instance of the connection to the same database + */ // Based on an idea of http://tonylandis.com/php/php5-pdo-singleton-class/ - private static $instance = array(); + private static $instance = []; /** * Connection to the database engine @@ -131,16 +186,16 @@ class Dblayer $password = null, $driver_options = null ) { - $this->verifyOneFunc = array($this, "verifyOne"); - $this->verifyAllFunc = array($this, "verifyAll"); - $this->hookprereadFunc = array($this, "hookpreread"); - $this->hookpostreadFunc = array($this, "hookpostread"); - $this->hookpreinsertFunc = array($this, "hookpreinsert"); - $this->hookpostinsertFunc = array($this, "hookpostinsert"); - $this->hookpreupdateFunc = array($this, "hookpreupdate"); - $this->hookpostupdateFunc = array($this, "hookpostupdate"); - $this->hookpredeleteFunc = array($this, "hookpredelete"); - $this->hookpostdeleteFunc = array($this, "hookpostdelete"); + $this->verifyOneFunc = [$this, "verifyOne"]; + $this->verifyAllFunc = [$this, "verifyAll"]; + $this->hookprereadFunc = [$this, "hookpreread"]; + $this->hookpostreadFunc = [$this, "hookpostread"]; + $this->hookpreinsertFunc = [$this, "hookpreinsert"]; + $this->hookpostinsertFunc = [$this, "hookpostinsert"]; + $this->hookpreupdateFunc = [$this, "hookpreupdate"]; + $this->hookpostupdateFunc = [$this, "hookpostupdate"]; + $this->hookpredeleteFunc = [$this, "hookpredelete"]; + $this->hookpostdeleteFunc = [$this, "hookpostdelete"]; $driver = @explode(":", $dsn); if (! isset($driver[0])) { @@ -149,7 +204,7 @@ class Dblayer 500 ); } - if (! in_array($driver[0], pdo_drivers())) { + if (! in_array($driver[0], pdo_drivers(), true)) { throw new \Exception(sprintf( dgettext( "domframework", @@ -287,7 +342,7 @@ class Dblayer ); } $vals = explode(";", substr(strstr($this->dsn, ":"), 1)); - $dsnExplode = array(); + $dsnExplode = []; foreach ($vals as $val) { @list($k, $v) = explode("=", $val); $dsnExplode[$k] = $v; @@ -314,7 +369,7 @@ class Dblayer $req = "SELECT name FROM sqlite_master WHERE type='table'"; $st = self::$instance[$this->dsn]->prepare($req); $st->execute(); - $res = array(); + $res = []; while ($d = $st->fetch(\PDO::FETCH_ASSOC)) { $res[] = $d["name"]; } @@ -325,7 +380,7 @@ class Dblayer WHERE TABLE_SCHEMA='" . $this->databasename() . "'"; $st = self::$instance[$this->dsn]->prepare($req); $st->execute(); - $res = array(); + $res = []; while ($d = $st->fetch(\PDO::FETCH_ASSOC)) { $res[] = $d["TABLE_NAME"]; } @@ -336,7 +391,7 @@ class Dblayer WHERE schemaname = 'public'"; $st = self::$instance[$this->dsn]->prepare($req); $st->execute(); - $res = array(); + $res = []; while ($d = $st->fetch(\PDO::FETCH_ASSOC)) { $res[] = $d["tablename"]; } @@ -361,7 +416,7 @@ class Dblayer if ($this->debug) { echo "== Entering verify\n"; } - $errors = array(); + $errors = []; foreach ($this->fields as $key => $params) { if ($this->debug) { echo " verify ($key)\n"; @@ -369,27 +424,27 @@ class Dblayer if ($updatekey === false) { // Don't check if there is an update : the database is already filled // For autoincrement, in INSERT mode, force the value to null - if (in_array("autoincrement", $params)) { + if (in_array("autoincrement", $params, true)) { $data[$key] = null; } - if (in_array("not null", $params) && !array_key_exists($key, $data)) { - $errors[$key] = array("error", sprintf( + if (in_array("not null", $params, true) && !array_key_exists($key, $data)) { + $errors[$key] = ["error", sprintf( dgettext( "domframework", "Mandatory field '%s' not provided" ), $key - )); + )]; continue; } - if (in_array("not null", $params) && $data[$key] === "") { - $errors[$key] = array("error", sprintf( + if (in_array("not null", $params, true) && $data[$key] === "") { + $errors[$key] = ["error", sprintf( dgettext( "domframework", "Mandatory field '%s' is empty" ), $key - )); + )]; continue; } } @@ -402,7 +457,7 @@ class Dblayer // Verify the fields, if $verify is defined, before doing insertion $verify = call_user_func($this->verifyOneFunc, $key, $data[$key]); if (is_array($verify) && count($verify)) { - $errors[$key] = array($verify[0], $verify[1]); + $errors[$key] = [$verify[0], $verify[1]]; //." ". dgettext ("domframework","in")." ".$key); continue; } @@ -412,78 +467,78 @@ class Dblayer // Skipped the removed autoincrement keys continue; } elseif (! is_string($data[$key]) && ! is_integer($data[$key])) { - $errors[$key] = array("error", sprintf( + $errors[$key] = ["error", sprintf( dgettext( "domframework", "Errors in consistency : '%s' is not an integer or a string [is %s]" ), $key, gettype($data[$key]) - )); + )]; continue; } elseif ($data[$key] !== "" && $params[0] === "integer") { if (strspn($data[$key], "0123456789") !== strlen($data[$key])) { - $errors[$key] = array("error", sprintf( + $errors[$key] = ["error", sprintf( dgettext( "domframework", "Errors in consistency : '%s' is not an integer" ), $key - )); + )]; continue; } } elseif ($data[$key] !== "" && $params[0] === "varchar") { if (! isset($params[1])) { - $errors[$key] = array("error", sprintf( + $errors[$key] = ["error", sprintf( dgettext( "domframework", "The length of varchar field '%s' is not provided" ), $key - )); + )]; continue; } if (mb_strlen($data[$key]) > $params[1]) { - $errors[$key] = array("error", sprintf( + $errors[$key] = ["error", sprintf( dgettext( "domframework", "Errors in consistency : '%s' data is too long" ), $key - )); + )]; continue; } } elseif ($data[$key] !== "" && $params[0] === "datetime") { // The date format must be in ANSI SQL : YYYY-MM-DD HH:MM:SS $d = \DateTime::createFromFormat("Y-m-d H:i:s", $data[$key]); if (!$d || $d->format("Y-m-d H:i:s") !== $data[$key]) { - $errors[$key] = array("error", sprintf( + $errors[$key] = ["error", sprintf( dgettext( "domframework", "Incorrect datetime provided for field '%s'" ), $key - )); + )]; continue; } } elseif ($data[$key] !== "" && $params[0] === "date") { // The date format must be in ANSI SQL : YYYY-MM-DD $d = \DateTime::createFromFormat("Y-m-d", $data[$key]); if (!$d || $d->format("Y-m-d") !== $data[$key]) { - $errors[$key] = array("error", sprintf( + $errors[$key] = ["error", sprintf( dgettext( "domframework", "Incorrect date provided for field '%s'" ), $key - )); + )]; continue; } } elseif ($data[$key] !== "") { - $errors[$key] = array("error", sprintf(dgettext( + $errors[$key] = ["error", sprintf(dgettext( "domframework", "Unknown field type for '%s'" - ), $key)); + ), $key)]; continue; } else { // Nothing to do if the value is empty : just save it @@ -496,14 +551,14 @@ class Dblayer // Check for inconsistency $verify = call_user_func($this->verifyAllFunc, $data); if (is_null($verify)) { - $verify = array(); + $verify = []; } $allErrors = array_merge($errors, $verify); if (count($allErrors)) { return $allErrors; } - $dataOK = array(); + $dataOK = []; foreach ($this->fields as $field => $desc) { if (array_key_exists($field, $data)) { $dataOK[$field] = $data[$field]; @@ -516,12 +571,12 @@ class Dblayer } // Check if the unique constrain is valid before doing the insertion // 1. Read the actual state - $before = $this->read(array(array($this->primary, $updatekey))); + $before = $this->read([[$this->primary, $updatekey]]); if (count($before) === 0) { - return array("error", dgettext( + return ["error", dgettext( "domframework", "Entry to modify unavailable" - )); + )]; } $before = reset($before); // 2. Map the proposal entries into the before state @@ -537,17 +592,17 @@ class Dblayer } // Check if the unique constrain is valid before doing the insertion if ($this->unique === null && $this->primary !== null) { - $this->unique = array($this->primary); + $this->unique = [$this->primary]; } // TODO : If Unique is not defined nor primary // FIXME : If unique is defined, could I test if the primary key is defined // in a parameter of the unique and if it is not add it automatically foreach ($this->unique as $k => $columns) { if ($this->primary === null) { - return array(dgettext( + return [dgettext( "domframework", "No field primary defined for tests in primary" - )); + )]; } if (is_array($columns)) { @@ -555,25 +610,25 @@ class Dblayer if ($this->debug) { echo " verify unique multiple $k\n"; } - $select = array(); + $select = []; if ($updatekey !== false) { - $select[] = array($this->primary, $updatekey, "!="); + $select[] = [$this->primary, $updatekey, "!="]; } foreach ($columns as $col) { if (!array_key_exists($col, $after)) { continue; } - $select[] = array($col, $after[$col]); + $select[] = [$col, $after[$col]]; } // If there is only the primary key, there is no chance to have a // conflict // Before updating, check if the new values are not creating an error - $rc = $this->read($select, array($this->primary)); + $rc = $this->read($select, [$this->primary]); if (count($rc) > 0) { - $errors[] = array("error", dgettext( + $errors[] = ["error", dgettext( "domframework", "An entry with these values already exists" - )); + )]; continue; } } else { @@ -584,22 +639,22 @@ class Dblayer if (!array_key_exists($columns, $after)) { continue; } - $select = array(); + $select = []; if ($updatekey !== false) { // This line have a problem to update a tuple with the same values // if ($columns === $this->primary) - $select[] = array($this->primary, $updatekey, "!="); + $select[] = [$this->primary, $updatekey, "!="]; } - $select[] = array($columns, $after[$columns]); + $select[] = [$columns, $after[$columns]]; $rc = $this->read( $select, - array($this->primary) + [$this->primary] ); if (count($rc) > 0) { - $errors[] = array("error", dgettext( + $errors[] = ["error", dgettext( "domframework", "An entry with this value already exists" - )); + )]; continue; } } @@ -614,13 +669,13 @@ class Dblayer echo " verify foreign $foreign\n"; } if (! isset($data[$foreign])) { - $errors[] = array("error", sprintf( + $errors[] = ["error", sprintf( dgettext( "domframework", "The foreign column '%s' is not provided" ), $foreign - )); + )]; return $errors; } /* if (! isset($data[$foreign][0])) { @@ -633,7 +688,8 @@ class Dblayer )); return $errors; continue; - }*/ + } + */ } else { if (! array_key_exists($foreign, $d)) { continue; @@ -674,27 +730,28 @@ class Dblayer ); } $st->execute(); - $res = array(); + $res = []; while ($d = $st->fetch(\PDO::FETCH_ASSOC)) { $res[] = $d; } if (count($res) === 0) { - $errors[] = array("error", sprintf( + $errors[] = ["error", sprintf( dgettext( "domframework", "The foreign key '%s' doesn't exists" ), $column - )); + )]; continue; } } return $errors; } - /** Insert a new line of data in the table. Datas must be an indexed array - * @param array $data Datas to be recorded (column=>value) - */ + /** + * Insert a new line of data in the table. Datas must be an indexed array + * @param array $data Datas to be recorded (column=>value) + */ public function insert($data) { if ($this->debug) { @@ -737,19 +794,19 @@ class Dblayer ); } foreach ($this->fields as $key => $params) { - if (in_array("autoincrement", $params)) { + if (in_array("autoincrement", $params, true)) { $data[$key] = null; } } - if (!in_array($this->primary, $this->unique)) { + if (!in_array($this->primary, $this->unique, true)) { $this->unique[] = $this->primary; } - $dataOK = array(); + $dataOK = []; $errors = $this->verify($data); if (count($errors) !== 0) { $errors = reset($errors); if (! is_array($errors)) { - $errors = array(0 => "error", 1 => $errors); + $errors = [0 => "error", 1 => $errors]; } throw new \Exception($errors[1], 405); } @@ -804,13 +861,13 @@ class Dblayer } if ( key_exists($this->primary, $data) && - ! in_array("autoincrement", $this->fields[$this->primary]) && + ! in_array("autoincrement", $this->fields[$this->primary], true) && $data[$this->primary] !== null ) { $lastID = $data[$this->primary]; } elseif ( key_exists($this->primary, $data) && - in_array("autoincrement", $this->fields[$this->primary]) && + in_array("autoincrement", $this->fields[$this->primary], true) && $data[$this->primary] !== null ) { $lastID = $data[$this->primary]; @@ -888,7 +945,7 @@ class Dblayer } if ($display !== null) { foreach ($display as $f) { - if (!in_array($f, array_keys($this->fields))) { + if (!in_array($f, array_keys($this->fields), true)) { throw new \Exception(sprintf(dgettext( "domframework", "Field '%s' not allowed" @@ -899,7 +956,7 @@ class Dblayer $display = array_keys($this->fields); } - $foreignSelectCols = array(); + $foreignSelectCols = []; if ($foreignSelect !== null) { foreach ($foreignSelect as $s) { $foreignSelectCols[] = $s[0]; @@ -907,8 +964,8 @@ class Dblayer } call_user_func_array( $this->hookprereadFunc, - array(&$select, &$display, &$order, - &$whereOr, &$foreignSelect) + [&$select, &$display, &$order, + &$whereOr, &$foreignSelect] ); $req = "SELECT $this->sep"; $req .= implode("$this->sep,$this->sep", $display); @@ -924,7 +981,7 @@ class Dblayer throw new \Exception("Select not an array for element $n", 500); } // The foreign keys can not be in the select too (conflict) - if (in_array($s[0], $foreignSelectCols)) { + if (in_array($s[0], $foreignSelectCols, true)) { continue; } if (! array_key_exists(0, $s)) { @@ -1041,7 +1098,7 @@ class Dblayer echo "DEBUG : EXECUTE ERROR ! Return FALSE\n"; } } - $res = array(); + $res = []; while ($d = $st->fetch(\PDO::FETCH_ASSOC)) { $res[] = $d; } @@ -1092,7 +1149,7 @@ class Dblayer "No data to update provided" ), 500); } - $dataOK = array(); + $dataOK = []; $errors = $this->verify($data, $updatekey); if (count($errors) !== 0) { if (is_array($errors)) { @@ -1181,10 +1238,11 @@ class Dblayer return $nbLinesUpdated; } - /** Delete a tuple identified by its primary key - * Return the number of deleted rows (can be 0 !) - * @param string|integer $deletekey The key of primary key to be deleted - */ + /** + * Delete a tuple identified by its primary key + * Return the number of deleted rows (can be 0 !) + * @param string|integer $deletekey The key of primary key to be deleted + */ public function delete($deletekey) { if ($this->debug) { @@ -1231,8 +1289,9 @@ class Dblayer return $nbLinesDeleted; } - /** Translation of fieldsi - */ + /** + * Translation of fieldsi + */ public function titles() { if ($this->debug) { @@ -1241,7 +1300,7 @@ class Dblayer if (count($this->fields) === 0) { throw new \Exception(dgettext("domframework", "No Field defined"), 500); } - $arr = array(); + $arr = []; if (count($this->titles) !== 0) { foreach ($this->titles as $field => $v) { $arr[$field] = $field; @@ -1254,8 +1313,9 @@ class Dblayer return $arr; } - /** Drop the table - */ + /** + * Drop the table + */ public function dropTable() { if ($this->debug) { @@ -1280,22 +1340,23 @@ class Dblayer return self::$instance[$this->dsn]->exec($sql); } - /** Create the table defined by the differents fields. - * Define the SQL syntax based on SQL engines - * $table = "dns zones"; - * $fields = array ( - * "id"=>array ("integer", "not null", "autoincrement"), - * "zo ne"=>array ("varchar", "255", "not null"), - * "vie wname"=>array ("varchar", "255"), - * "view clients"=>array ("varchar", "255"), - * "comme nt"=>array ("varchar", "1024"), - * "opendate"=>array ("datetime", "not null"), - * "closedate"=>array ("datetime"), - * ); - * $primary = "id"; - * $unique = array ("id", array ("zo ne", "vie wname")); - * $foreign = array ("zone"=>"table.field",...); - */ + /** + * Create the table defined by the differents fields. + * Define the SQL syntax based on SQL engines + * $table = "dns zones"; + * $fields = array ( + * "id"=>array ("integer", "not null", "autoincrement"), + * "zo ne"=>array ("varchar", "255", "not null"), + * "vie wname"=>array ("varchar", "255"), + * "view clients"=>array ("varchar", "255"), + * "comme nt"=>array ("varchar", "1024"), + * "opendate"=>array ("datetime", "not null"), + * "closedate"=>array ("datetime"), + * ); + * $primary = "id"; + * $unique = array ("id", array ("zo ne", "vie wname")); + * $foreign = array ("zone"=>"table.field",...); + */ public function createTable() { if ($this->debug) { @@ -1553,7 +1614,7 @@ class Dblayer } // Name of field $sql .= "\"$field\" "; - if (in_array("autoincrement", $params)) { + if (in_array("autoincrement", $params, true)) { $sql .= "SERIAL"; } else { // Type of field : in $params[0] @@ -1667,10 +1728,11 @@ class Dblayer return self::$instance[$this->dsn]->exec($sql); } - /** This function permit to send a SQL request to the database to do a SELECT - * Return the an array with the data - * @param string $sql A valid SQL request to be execute - */ + /** + * This function permit to send a SQL request to the database to do a SELECT + * Return the an array with the data + * @param string $sql A valid SQL request to be execute + */ public function directRead($sql) { if ($this->debug) { @@ -1681,66 +1743,72 @@ class Dblayer } $st = self::$instance[$this->dsn]->prepare($sql); $st->execute(); - $res = array(); + $res = []; while ($d = $st->fetch(\PDO::FETCH_ASSOC)) { $res[] = $d; } return $res; } - /** This function disconnect the database. It is normally only used in phpunit - * unit tests - */ + /** + * This function disconnect the database. It is normally only used in phpunit + * unit tests + */ public function disconnect() { unset(self::$instance[$this->dsn]); } - /** The prepare method - * @param string $statement The valid template to be replaced - * @param array|null $driver_options The replacement to be done - */ - public function prepare($statement, $driver_options = array()) + /** + * The prepare method + * @param string $statement The valid template to be replaced + * @param array|null $driver_options The replacement to be done + */ + public function prepare($statement, $driver_options = []) { return self::$instance[$this->dsn]->prepare($statement, $driver_options); } - /** Start a new Transaction - */ + /** + * Start a new Transaction + */ public function beginTransaction() { return self::$instance[$this->dsn]->beginTransaction(); } - /** Commit (validate) a transaction - */ + /** + * Commit (validate) a transaction + */ public function commit() { return self::$instance[$this->dsn]->commit(); } - /** RollBack a transaction - */ + /** + * RollBack a transaction + */ public function rollback() { return self::$instance[$this->dsn]->rollback(); } - /** Hook preread - * This hook is run before selecting the data in the database, after the - * verification - * @param array|null &$select Rows to select with - * $select = array (array ($key, $val, $operator), ...) - * $key=>column, $val=>value to found, $operator=>'LIKE', =... - * @param array|null &$display Columns displayed - * $display = array ($col1, $col2...); - * @param array|null &$order Sort the columns by orientation - * $order = array (array ($key, $orientation), ...) - * $key=>column, $orientation=ASC/DESC - * @param boolean|null &$whereOr The WHERE parameters are separated by OR - * instead of AND - * @param array|null &$foreignSelect Add a filter on foreign keys - */ + /** + * Hook preread + * This hook is run before selecting the data in the database, after the + * verification + * @param array|null &$select Rows to select with + * $select = array (array ($key, $val, $operator), ...) + * $key=>column, $val=>value to found, $operator=>'LIKE', =... + * @param array|null &$display Columns displayed + * $display = array ($col1, $col2...); + * @param array|null &$order Sort the columns by orientation + * $order = array (array ($key, $orientation), ...) + * $key=>column, $orientation=ASC/DESC + * @param boolean|null &$whereOr The WHERE parameters are separated by OR + * instead of AND + * @param array|null &$foreignSelect Add a filter on foreign keys + */ public function hookpreread( &$select, &$display, @@ -1837,81 +1905,90 @@ class Dblayer /////////////////// /// SETTERS /// /////////////////// - /** Set the table property - * @param string $table The table name to use - */ + /** + * Set the table property + * @param string $table The table name to use + */ public function tableSet($table) { $this->table = $table; return $this; } - /** Set the tableprefix property - * @param string $tableprefix The prefix to add in table names - */ + /** + * Set the tableprefix property + * @param string $tableprefix The prefix to add in table names + */ public function tableprefixSet($tableprefix) { $this->tableprefix = $tableprefix; return $this; } - /** Set the fields property - * @param array $fields Set the definition of the fields - */ + /** + * Set the fields property + * @param array $fields Set the definition of the fields + */ public function fieldsSet($fields) { $this->fields = $fields; return $this; } - /** Set the primary property - * @param string $primary The primary field - */ + /** + * Set the primary property + * @param string $primary The primary field + */ public function primarySet($primary) { $this->primary = $primary; return $this; } - /** Set the unique property - * @param array $unique The array of the unique contraints - */ + /** + * Set the unique property + * @param array $unique The array of the unique contraints + */ public function uniqueSet($unique) { $this->unique = $unique; return $this; } - /** Set the foreign property - * @param array $foreign The foreign array - */ + /** + * Set the foreign property + * @param array $foreign The foreign array + */ public function foreignSet($foreign) { $this->foreign = $foreign; return $this; } - /** Set the debug property - * @param integer $debug The debug value - */ + /** + * Set the debug property + * @param integer $debug The debug value + */ public function debugSet($debug) { $this->debug = $debug; return $this; } - /** Set the dsn property - * @param string $dsn The DSN to use - */ + /** + * Set the dsn property + * @param string $dsn The DSN to use + */ public function dsnSet($dsn) { $this->dsn = $dsn; return $this; } - /** Set the titles property - * @param array $titles The titles of the fields - */ + /** + * Set the titles property + * @param array $titles The titles of the fields + */ public function titlesSet($titles) { $this->titles = $titles; @@ -1919,38 +1996,39 @@ class Dblayer } } -/** POC : -error_reporting (E_ALL); -class Zone extends DbLayer -{ - // The database must be initialized with - // CREATE TABLE `dns_zones` (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, - // zone VARCHAR(255) NOT NULL, - // viewname VARCHAR(255), - // viewclients VARCHAR(255), - // comment VARCHAR(1024), - // opendate DATETIME NOT NULL, - // closedate DATETIME, - // UNIQUE (zone,viewname)); - protected $table = "dns_zones"; - protected $fields = array ( - "id"=>array ("integer", "not null", "autoincrement"), - "zone"=>array ("varchar", "255", "not null"), - "viewname"=>array ("varchar", "255"), - "viewclients"=>array ("varchar", "255"), - "comment"=>array ("varchar", "1024"), - "opendate"=>array ("datetime", "not null"), - "closedate"=>array ("datetime"), - ); - protected $primary = "id"; - protected $unique = array ("id", array ("zone", "viewname")); -} - -ini_set ("date.timezone", "Europe/Paris"); -$zone = new zone ("sqlite:data/database.db"); -$last = $zone->create (array ("zone"=>"testZone", - "opendate"=>date("Y-m-d H:i:s"))); -//print_r ($zone->read ()); -$zone->update (2040, array ("zone"=>"testZone2")); -print_r ($zone->delete ($last)); -*/ +/** + * POC : + * error_reporting (E_ALL); + * class Zone extends DbLayer + * { + * // The database must be initialized with + * // CREATE TABLE `dns_zones` (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + * // zone VARCHAR(255) NOT NULL, + * // viewname VARCHAR(255), + * // viewclients VARCHAR(255), + * // comment VARCHAR(1024), + * // opendate DATETIME NOT NULL, + * // closedate DATETIME, + * // UNIQUE (zone,viewname)); + * protected $table = "dns_zones"; + * protected $fields = array ( + * "id"=>array ("integer", "not null", "autoincrement"), + * "zone"=>array ("varchar", "255", "not null"), + * "viewname"=>array ("varchar", "255"), + * "viewclients"=>array ("varchar", "255"), + * "comment"=>array ("varchar", "1024"), + * "opendate"=>array ("datetime", "not null"), + * "closedate"=>array ("datetime"), + * ); + * protected $primary = "id"; + * protected $unique = array ("id", array ("zone", "viewname")); + * } + * + * ini_set ("date.timezone", "Europe/Paris"); + * $zone = new zone ("sqlite:data/database.db"); + * $last = $zone->create (array ("zone"=>"testZone", + * "opendate"=>date("Y-m-d H:i:s"))); + * //print_r ($zone->read ()); + * $zone->update (2040, array ("zone"=>"testZone2")); + * print_r ($zone->delete ($last)); + */ diff --git a/src/Dblayerauthzgroups.php b/src/Dblayerauthzgroups.php index 659896e..dad6c2b 100644 --- a/src/Dblayerauthzgroups.php +++ b/src/Dblayerauthzgroups.php @@ -1,54 +1,73 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** DBLayer with authorization - * All the actions in database are conditionned to the rights in authzgroups - */ +/** + * DBLayer with authorization + * All the actions in database are conditionned to the rights in authzgroups + */ class Dblayerauthzgroups extends Dblayer { - /** The authzgroups object, connected to the database */ + /** + * The authzgroups object, connected to the database + */ public $authzgroups = null; - /** The module name for authzgroups */ + /** + * The module name for authzgroups + */ public $module = null; - /** The user name for authzgroups */ + /** + * The user name for authzgroups + */ public $user = null; - /** The auth information (email, lastname, firstname) */ + /** + * The auth information (email, lastname, firstname) + */ public $auth = null; - /** The default group(s) when creating a new object. Can be a string or an - array with multiple groups */ + /** + * The default group(s) when creating a new object. Can be a string or an + * array with multiple groups + */ public $createGroup = null; - /** The default right when creating a new object */ + /** + * The default right when creating a new object + */ public $createRight = "RW"; - /** Pre-Path in object authzgroups */ + /** + * Pre-Path in object authzgroups + */ public $path = ""; - /** Flag when primary key is added before search */ + /** + * Flag when primary key is added before search + */ private $primaryKeyAdded = false; //////////////////////// /// MAIN METHODS /// //////////////////////// - /** Hook preread - * This hook is run before selecting the data in the database, after the - * verification - * @param array|null &$select Rows to select with - * $select = array (array ($key, $val, $operator), ...) - * $key=>column, $val=>value to found, $operator=>'LIKE', =... - * @param array|null &$display Columns displayed - * $display = array ($col1, $col2...); - * @param array|null &$order Sort the columns by orientation - * $order = array (array ($key, $orientation), ...) - * $key=>column, $orientation=ASC/DESC - * @param boolean|null &$whereOr The WHERE parameters are separated by OR - * instead of AND - * @param array|null &$foreignSelect Add a filter on foreign keys - */ + /** + * Hook preread + * This hook is run before selecting the data in the database, after the + * verification + * @param array|null &$select Rows to select with + * $select = array (array ($key, $val, $operator), ...) + * $key=>column, $val=>value to found, $operator=>'LIKE', =... + * @param array|null &$display Columns displayed + * $display = array ($col1, $col2...); + * @param array|null &$order Sort the columns by orientation + * $order = array (array ($key, $orientation), ...) + * $key=>column, $orientation=ASC/DESC + * @param boolean|null &$whereOr The WHERE parameters are separated by OR + * instead of AND + * @param array|null &$foreignSelect Add a filter on foreign keys + */ public function hookpreread( &$select, &$display, @@ -74,7 +93,7 @@ class Dblayerauthzgroups extends Dblayer 500 ); } - if ($display === null || ! in_array($this->primary, $display)) { + if ($display === null || ! in_array($this->primary, $display, true)) { // Need the primary key to allow/deny access. Add it and remove the data // after the access verification $display[] = $this->primary; @@ -82,12 +101,13 @@ class Dblayerauthzgroups extends Dblayer } } - /** Hook postread - * This hook is run after selecting the data. Return only the allowed data to - * the user. It must have at least the RO flag. - * @param array $data the data selected by the select - * @return array The data modified by the hook - */ + /** + * Hook postread + * This hook is run after selecting the data. Return only the allowed data to + * the user. It must have at least the RO flag. + * @param array $data the data selected by the select + * @return array The data modified by the hook + */ public function hookpostread($data) { // TODO : If foreign keys, do we check if the access is allowed too ? @@ -127,12 +147,13 @@ class Dblayerauthzgroups extends Dblayer return $data; } - /** Hook preinsert - * This hook is run before inserting a new data in the database, after the - * verification - * @param array $data the data to insert in the database - * @return the modified data - */ + /** + * Hook preinsert + * This hook is run before inserting a new data in the database, after the + * verification + * @param array $data the data to insert in the database + * @return the modified data + */ public function hookpreinsert($data) { if ($this->module === null) { @@ -164,12 +185,13 @@ class Dblayerauthzgroups extends Dblayer return $data; } - /** Hook postinsert - * This hook is run after successfuly insert a new data in the database - * @param array $data The data stored in the database - * @param integer $lastID The lastID stored - * @return the modified lastID - */ + /** + * Hook postinsert + * This hook is run after successfuly insert a new data in the database + * @param array $data The data stored in the database + * @param integer $lastID The lastID stored + * @return the modified lastID + */ public function hookpostinsert($data, $lastID) { if ($this->module === null) { @@ -220,13 +242,14 @@ class Dblayerauthzgroups extends Dblayer return $lastID; } - /** Hook preupdate - * This hook is run before updating a data in the database, after the - * verification - * @param integer $updatekey The key which will be updated - * @param array $data The data to store in the provided key - * @return the modified data - */ + /** + * Hook preupdate + * This hook is run before updating a data in the database, after the + * verification + * @param integer $updatekey The key which will be updated + * @param array $data The data to store in the provided key + * @return the modified data + */ public function hookpreupdate($updatekey, $data) { if ($this->module === null) { @@ -257,11 +280,12 @@ class Dblayerauthzgroups extends Dblayer return $data; } - /** Hook predelete - * This hook is run before deleting a data in the database - * @param string $deletekey The key to delete - * @return the modified $deletekey - */ + /** + * Hook predelete + * This hook is run before deleting a data in the database + * @param string $deletekey The key to delete + * @return the modified $deletekey + */ public function hookpredelete($deletekey) { if ($this->module === null) { @@ -292,12 +316,13 @@ class Dblayerauthzgroups extends Dblayer return $deletekey; } - /** Hook postdelete - * This hook is run after successfuly deleting a data in the database - * @param string $deletekey The key to delete - * @param integer $nbLinesDeleted The number of deleted lines - * @return $nbLinesUpdated - */ + /** + * Hook postdelete + * This hook is run after successfuly deleting a data in the database + * @param string $deletekey The key to delete + * @param integer $nbLinesDeleted The number of deleted lines + * @return $nbLinesUpdated + */ public function hookpostdelete($deletekey, $nbLinesDeleted) { if ($this->module === null) { @@ -322,8 +347,9 @@ class Dblayerauthzgroups extends Dblayer return $nbLinesDeleted; } - /** Return true if all the paths are allowed. Throw an exception elsewhere - */ + /** + * Return true if all the paths are allowed. Throw an exception elsewhere + */ private function allowPath() { if ($this->module === null) { @@ -360,63 +386,70 @@ class Dblayerauthzgroups extends Dblayer /////////////////// /// SETTERS /// /////////////////// - /** Set the authzgroups property - * @param object $authzgroups The object of the authzgroups - */ + /** + * Set the authzgroups property + * @param object $authzgroups The object of the authzgroups + */ public function authzgroupsSet($authzgroups) { $this->authzgroups = $authzgroups; return $this; } - /** Set the module property - * @param string $module The module name to use - */ + /** + * Set the module property + * @param string $module The module name to use + */ public function moduleSet($module) { $this->module = $module; return $this; } - /** Set the auth property - * @param array $auth The auth array - */ + /** + * Set the auth property + * @param array $auth The auth array + */ public function authSet($auth) { $this->auth = $auth; return $this; } - /** Set the user property - * @param string $user The user to authorize - */ + /** + * Set the user property + * @param string $user The user to authorize + */ public function userSet($user) { $this->user = $user; return $this; } - /** Set the createGroup property - * @param array|string $createGroup The createGroup to set - */ + /** + * Set the createGroup property + * @param array|string $createGroup The createGroup to set + */ public function createGroupSet($createGroup) { $this->createGroup = $createGroup; return $this; } - /** Set the createRight property - * @param string $createRight The right to create - */ + /** + * Set the createRight property + * @param string $createRight The right to create + */ public function createRightSet($createRight) { $this->createRight = $createRight; return $this; } - /** Set the path property - * @param string $path The pre-path to use - */ + /** + * Set the path property + * @param string $path The pre-path to use + */ public function pathSet($path) { $this->path = $path; diff --git a/src/Dblayeroo.php b/src/Dblayeroo.php index fe4d277..be428da 100644 --- a/src/Dblayeroo.php +++ b/src/Dblayeroo.php @@ -1,75 +1,92 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** Permit abstraction on the differents SQL databases available - */ +/** + * Permit abstraction on the differents SQL databases available + */ class Dblayeroo { - /** The table name to use - */ + /** + * The table name to use + */ private $table = null; - /** The tableprefix text to prepend to table name (Should finish by _) - * Just allow chars ! - */ + /** + * The tableprefix text to prepend to table name (Should finish by _) + * Just allow chars ! + */ private $tableprefix = ""; - /** The fields with the definition of type, and special parameters - */ - private $fields = array(); - /** The primary field - */ + /** + * The fields with the definition of type, and special parameters + */ + private $fields = []; + /** + * The primary field + */ private $primary = null; - /** An array to define the unique fields (or array of unique fields) - */ + /** + * An array to define the unique fields (or array of unique fields) + */ private $unique = null; - /** An array to define the foreign keys of the field - */ - private $foreign = array(); - /** Debug of the SQL - */ + /** + * An array to define the foreign keys of the field + */ + private $foreign = []; + /** + * Debug of the SQL + */ protected $debug = false; - /** The connecting DSN - */ + /** + * The connecting DSN + */ private $dsn = null; - /** The driver to use - */ + /** + * The driver to use + */ private $driver = null; - /** The field group delimiter - */ + /** + * The field group delimiter + */ private $sep = ""; - /** Titles - */ - private $titles = array(); - /** The real types of each fields. The real types are different of the SQL - * types : a "mail" type is stored in a "VARCHAR(255)" in SQL. - * The real types are optional : if not set, there is no check. - * They are more strict than the SQL types - */ - private $realTypes = array(); + /** + * Titles + */ + private $titles = []; + /** + * The real types of each fields. The real types are different of the SQL + * types : a "mail" type is stored in a "VARCHAR(255)" in SQL. + * The real types are optional : if not set, there is no check. + * They are more strict than the SQL types + */ + private $realTypes = []; - /** Limit to one instance of the connection to the same database - */ + /** + * Limit to one instance of the connection to the same database + */ // Based on an idea of http://tonylandis.com/php/php5-pdo-singleton-class/ - private static $instance = array(); + private static $instance = []; - /** Store each executed requests meta data to analyze the times, number of - * requests, debugging - */ - private static $meta = array(); + /** + * Store each executed requests meta data to analyze the times, number of + * requests, debugging + */ + private static $meta = []; - /** Connection to the database engine - * See http://fr2.php.net/manual/en/pdo.construct.php for the $dsn format - * @param string $dsn PDO Data Source Name - * @param string|null $username Username to connect - * @param string|null $password Password to connect - * @param string|null $driver_options Driver options to the database - */ + /** + * Connection to the database engine + * See http://fr2.php.net/manual/en/pdo.construct.php for the $dsn format + * @param string $dsn PDO Data Source Name + * @param string|null $username Username to connect + * @param string|null $password Password to connect + * @param string|null $driver_options Driver options to the database + */ public function __construct( $dsn, $username = null, @@ -79,13 +96,14 @@ class Dblayeroo $this->connect($dsn, $username, $password, $driver_options); } - /** Connection to the database engine - * See http://fr2.php.net/manual/en/pdo.construct.php for the $dsn format - * @param string $dsn PDO Data Source Name - * @param string|null $username Username to connect - * @param string|null $password Password to connect - * @param string|null $driver_options Driver options to the database - */ + /** + * Connection to the database engine + * See http://fr2.php.net/manual/en/pdo.construct.php for the $dsn format + * @param string $dsn PDO Data Source Name + * @param string|null $username Username to connect + * @param string|null $password Password to connect + * @param string|null $driver_options Driver options to the database + */ public function connect( $dsn, $username = null, @@ -103,7 +121,7 @@ class Dblayeroo $this->DBException(dgettext("domframework", "No valid DSN provided")); } $driver[0] = strtolower($driver[0]); - if (! in_array($driver[0], pdo_drivers())) { + if (! in_array($driver[0], pdo_drivers(), true)) { $this->DBException(sprintf( dgettext( "domframework", @@ -243,59 +261,64 @@ class Dblayeroo return self::$instance[$this->dsn]; } - /** This function disconnect the database. It is normally only used in phpunit - * unit tests - */ + /** + * This function disconnect the database. It is normally only used in phpunit + * unit tests + */ public function disconnect() { unset(self::$instance[$this->dsn]); self::$sortOrder = 0; } - /** Start a new Transaction - */ + /** + * Start a new Transaction + */ public function beginTransaction() { - self::$meta[] = array( + self::$meta[] = [ "command" => "BEGIN", "sql" => "BEGIN TRANSACTION", "sqltime" => 0, "displayQuery" => "BEGIN TRANSACTION", "nbrows" => 0, - ); + ]; return self::$instance[$this->dsn]->beginTransaction(); } - /** Commit (validate) a transaction - */ + /** + * Commit (validate) a transaction + */ public function commit() { - self::$meta[] = array( + self::$meta[] = [ "command" => "COMMIT", "sql" => "COMMIT TRANSACTION", "sqltime" => 0, "displayQuery" => "COMMIT TRANSACTION", "nbrows" => 0, - ); + ]; return self::$instance[$this->dsn]->commit(); } - /** RollBack a transaction - */ + /** + * RollBack a transaction + */ public function rollback() { - self::$meta[] = array( + self::$meta[] = [ "command" => "ROLLBACK", "sql" => "ROLLBACK TRANSACTION", "sqltime" => 0, "displayQuery" => "ROLLBACK TRANSACTION", "nbrows" => 0, - ); + ]; return self::$instance[$this->dsn]->rollback(); } - /** Return the connected database name from DSN used to connect - */ + /** + * Return the connected database name from DSN used to connect + */ public function databasename() { if ($this->sep === "") { @@ -309,7 +332,7 @@ class Dblayeroo return null; } $vals = explode(";", substr(strstr($this->dsn, ":"), 1)); - $dsnExplode = array(); + $dsnExplode = []; foreach ($vals as $val) { @list($k, $v) = explode("=", $val); $dsnExplode[$k] = $v; @@ -320,8 +343,9 @@ class Dblayeroo return null; } - /** Return all the tables available in the database - */ + /** + * Return all the tables available in the database + */ public function listTables() { if ($this->sep === "") { @@ -332,7 +356,7 @@ class Dblayeroo $req = "SELECT name FROM sqlite_master WHERE type='table'"; $st = self::$instance[$this->dsn]->prepare($req); $st->execute(); - $res = array(); + $res = []; while ($d = $st->fetch(\PDO::FETCH_ASSOC)) { if ($d["name"] !== "sqlite_sequence") { $res[] = $d["name"]; @@ -345,7 +369,7 @@ class Dblayeroo WHERE TABLE_SCHEMA='" . $this->databasename() . "'"; $st = self::$instance[$this->dsn]->prepare($req); $st->execute(); - $res = array(); + $res = []; while ($d = $st->fetch(\PDO::FETCH_ASSOC)) { $res[] = $d["TABLE_NAME"]; } @@ -356,7 +380,7 @@ class Dblayeroo WHERE schemaname = 'public'"; $st = self::$instance[$this->dsn]->prepare($req); $st->execute(); - $res = array(); + $res = []; while ($d = $st->fetch(\PDO::FETCH_ASSOC)) { $res[] = $d["tablename"]; } @@ -371,22 +395,23 @@ class Dblayeroo return array_values($res); } - /** Create the table defined by the differents fields. - * Define the SQL syntax based on SQL engines - * $table = "dns zones"; - * $fields = array ( - * "id"=>array ("integer", "not null", "autoincrement"), - * "zo ne"=>array ("varchar(255)", "not null"), - * "vie wname"=>array ("varchar(255)"), - * "view clients"=>array ("varchar(255)"), - * "comme nt"=>array ("varchar(1024)"), - * "opendate"=>array ("datetime", "not null"), - * "closedate"=>array ("datetime"), - * ); - * $primary = "id"; - * $unique = array ("id", array ("zo ne", "vie wname")); - * $foreign = array ("zone"=>"table.field", ...); - */ + /** + * Create the table defined by the differents fields. + * Define the SQL syntax based on SQL engines + * $table = "dns zones"; + * $fields = array ( + * "id"=>array ("integer", "not null", "autoincrement"), + * "zo ne"=>array ("varchar(255)", "not null"), + * "vie wname"=>array ("varchar(255)"), + * "view clients"=>array ("varchar(255)"), + * "comme nt"=>array ("varchar(1024)"), + * "opendate"=>array ("datetime", "not null"), + * "closedate"=>array ("datetime"), + * ); + * $primary = "id"; + * $unique = array ("id", array ("zo ne", "vie wname")); + * $foreign = array ("zone"=>"table.field", ...); + */ public function createTable() { $this->debugLog("Entering createTable", 2); @@ -658,7 +683,7 @@ class Dblayeroo } // Name of field $sql .= "\"$field\" "; - if (in_array("autoincrement", $params)) { + if (in_array("autoincrement", $params, true)) { if ($this->primary !== $field) { throw new \Exception(sprintf( dgettext( @@ -774,8 +799,9 @@ class Dblayeroo return self::$instance[$this->dsn]->exec($sql); } - /** Drop the table - */ + /** + * Drop the table + */ public function dropTable() { $this->debugLog("Entering dropTable ()", 2); @@ -793,9 +819,10 @@ class Dblayeroo return self::$instance[$this->dsn]->exec($sql); } - /** Get the informations about a table - * @param string $tableName The table to examine - */ + /** + * Get the informations about a table + * @param string $tableName The table to examine + */ public function getTableSchema($tableName) { $this->debugLog("Entering getTableSchema (", $tableName, ")", 2); @@ -806,9 +833,9 @@ class Dblayeroo ); $st->execute(); $content = $st->fetchAll(\PDO::FETCH_ASSOC); - $fields = array(); - $unique = array(); - $foreign = array(); + $fields = []; + $unique = []; + $foreign = []; $primary = ""; foreach ($content as $row) { $type = str_replace(" ", "", strtolower($row["type"])); @@ -833,7 +860,7 @@ class Dblayeroo $st->execute(); $content2 = $st->fetchAll(\PDO::FETCH_ASSOC); if (count($content2) > 1) { - $index = array(); + $index = []; foreach ($content2 as $c2) { $index[] = $c2["name"]; } @@ -844,7 +871,7 @@ class Dblayeroo } } ksort($unique); - if (! in_array($primary, $unique)) { + if (! in_array($primary, $unique, true)) { $unique[] = $primary; } @@ -867,7 +894,7 @@ class Dblayeroo $st->execute(); $content = $st->fetchAll(\PDO::FETCH_ASSOC); foreach ($content as $for) { - $tmp = array($for["table"], $for["to"]); + $tmp = [$for["table"], $for["to"]]; $cascade = ""; if ($for["on_update"] !== "NO ACTION") { $cascade .= "ON UPDATE " . $for["on_update"]; @@ -881,7 +908,7 @@ class Dblayeroo $foreign[$for["from"]] = $tmp; } - $foreignUsed = array(); + $foreignUsed = []; foreach ($this->listTables() as $tbl) { $st = self::$instance[$this->dsn]->prepare( "PRAGMA foreign_key_list($tbl)" @@ -892,17 +919,17 @@ class Dblayeroo if ($row["table"] !== $tableName) { continue; } - $foreignUsed[$row["to"]][] = array( + $foreignUsed[$row["to"]][] = [ $tbl, $row["from"] - ); + ]; } } - return array("table" => $tableName, + return ["table" => $tableName, "fields" => $fields, "primary" => $primary, "unique" => $unique, "foreign" => $foreign, - "foreignUsed" => $foreignUsed); + "foreignUsed" => $foreignUsed]; break; case "mysql": $st = self::$instance[$this->dsn]->prepare( @@ -910,12 +937,12 @@ class Dblayeroo ); $st->execute(); $content = $st->fetchAll(\PDO::FETCH_ASSOC); - $fields = array(); - $unique = array(); - $foreign = array("TBD"); + $fields = []; + $unique = []; + $foreign = ["TBD"]; $primary = ""; foreach ($content as $col) { - $tmp = array(); + $tmp = []; if ($col["Type"] === "int(11)") { $tmp[] = "integer"; } else { @@ -943,7 +970,7 @@ class Dblayeroo } if (array_key_exists($col["Key_name"], $unique)) { if (!is_array($unique[$col["Key_name"]])) { - $unique[$col["Key_name"]] = array($unique[$col["Key_name"]]); + $unique[$col["Key_name"]] = [$unique[$col["Key_name"]]]; } $unique[$col["Key_name"]][] = $col["Column_name"]; } else { @@ -952,7 +979,7 @@ class Dblayeroo } } $unique = array_values($unique); - if (! in_array($primary, $unique)) { + if (! in_array($primary, $unique, true)) { $unique[] = $primary; } $st = self::$instance[$this->dsn]->prepare(" @@ -963,12 +990,12 @@ class Dblayeroo WHERE rCons.CONSTRAINT_SCHEMA=:dbname AND rCons.TABLE_NAME=:table AND rCons.CONSTRAINT_NAME=kColUsage.CONSTRAINT_NAME AND rCons.CONSTRAINT_SCHEMA=kColUsage.CONSTRAINT_SCHEMA"); - $st->execute(array(':dbname' => $this->databasename(), - ':table' => $tableName)); + $st->execute([':dbname' => $this->databasename(), + ':table' => $tableName]); $foreignTmp = $st->fetchAll(\PDO::FETCH_ASSOC); - $foreign = array(); + $foreign = []; foreach ($foreignTmp as $f) { - $tmp = array(); + $tmp = []; $tmp[] = $f["REFERENCED_TABLE_NAME"]; $tmp[] = $f["REFERENCED_COLUMN_NAME"]; $tmp[2] = ""; @@ -1000,26 +1027,26 @@ class Dblayeroo TABLE_SCHEMA=:dbname ORDER BY TABLE_NAME ASC "); - $st->execute(array(':dbname' => $this->databasename(), - ':table' => $tableName)); + $st->execute([':dbname' => $this->databasename(), + ':table' => $tableName]); $foreignUsedTmp = $st->fetchAll(\PDO::FETCH_ASSOC); - $foreignUsed = array(); + $foreignUsed = []; foreach ($foreignUsedTmp as $f) { - $foreignUsed[$f["REFERENCED_COLUMN_NAME"]][] = array( + $foreignUsed[$f["REFERENCED_COLUMN_NAME"]][] = [ $f["TABLE_NAME"], - $f["COLUMN_NAME"]); + $f["COLUMN_NAME"]]; } - return array("table" => $tableName, + return ["table" => $tableName, "fields" => $fields, "primary" => $primary, "unique" => $unique, "foreign" => $foreign, - "foreignUsed" => $foreignUsed); + "foreignUsed" => $foreignUsed]; break; case "pgsql": - $fields = array(); - $unique = array(); - $foreign = array(); + $fields = []; + $unique = []; + $foreign = []; $primary = ""; // Get the defined primary key if not autoincrement $st = self::$instance[$this->dsn]->prepare(" @@ -1030,7 +1057,7 @@ class Dblayeroo WHERE i.indrelid = :table::regclass AND i.indisprimary; "); - $st->execute(array(':table' => $tableName)); + $st->execute([':table' => $tableName]); $content = $st->fetchAll(\PDO::FETCH_ASSOC); if (key_exists(0, $content)) { $primary = $content[0]["attname"]; @@ -1044,7 +1071,7 @@ class Dblayeroo $st->execute(); $content = $st->fetchAll(\PDO::FETCH_ASSOC); foreach ($content as $col) { - $tmp = array(); + $tmp = []; if ($col["data_type"] === "character varying") { $tmp[] = "varchar(" . $col["character_maximum_length"] . ")"; } else { @@ -1071,15 +1098,15 @@ class Dblayeroo if (array_key_exists($col["constraint_name"], $unique)) { if (! is_array($unique[$col["constraint_name"]])) { $unique[$col["constraint_name"]] = - array($unique[$col["constraint_name"]]); + [$unique[$col["constraint_name"]]]; } $unique[$col["constraint_name"]][] = $col["column_name"]; - } elseif (! in_array($col["column_name"], $unique)) { + } elseif (! in_array($col["column_name"], $unique, true)) { $unique[$col["constraint_name"]] = $col["column_name"]; } } $unique = array_values($unique); - if (! in_array($primary, $unique)) { + if (! in_array($primary, $unique, true)) { $unique[] = $primary; } $st = self::$instance[$this->dsn]->prepare(" @@ -1094,12 +1121,12 @@ class Dblayeroo AND rCons.constraint_name=kColUsage1.constraint_name AND rCons.unique_constraint_name=kColUsage2.constraint_name "); - $st->execute(array(':dbname' => $this->databasename(), - ':table' => $tableName)); + $st->execute([':dbname' => $this->databasename(), + ':table' => $tableName]); $foreignTmp = $st->fetchAll(\PDO::FETCH_ASSOC); - $foreign = array(); + $foreign = []; foreach ($foreignTmp as $f) { - $tmp = array(); + $tmp = []; $tmp[] = $f["referenced_table_name"]; $tmp[] = $f["referenced_column_name"]; $tmp[2] = ""; @@ -1140,24 +1167,24 @@ class Dblayeroo ORDER BY kColUsage1.table_name "); $st->execute( - array(':dbname' => $this->databasename(), - ':table' => $tableName) + [':dbname' => $this->databasename(), + ':table' => $tableName] ); $foreignUsedTmp = $st->fetchAll(\PDO::FETCH_ASSOC); - $foreignUsed = array(); + $foreignUsed = []; foreach ($foreignUsedTmp as $f) { - $foreignUsed[$f["referenced_column_name"]][] = array( + $foreignUsed[$f["referenced_column_name"]][] = [ $f["table_name"], - $f["column_name"]); + $f["column_name"]]; } - return array("table" => $tableName, + return ["table" => $tableName, "fields" => $fields, "primary" => $primary, "unique" => $unique, "foreign" => $foreign, - "foreignUsed" => $foreignUsed); + "foreignUsed" => $foreignUsed]; break; default: $this->DBException(dgettext( @@ -1167,9 +1194,10 @@ class Dblayeroo } } - /** Return the type of the provided field - * @param string $field The field to get the type - */ + /** + * Return the type of the provided field + * @param string $field The field to get the type + */ private function fieldTypeComplete($field) { // $this->debugLog ("Entering fieldTypeComplete (",$field,")", 2); @@ -1196,10 +1224,11 @@ class Dblayeroo return $type; } - /** Return the type of the provided field. For varchar(255), return only - * varchar - * @param string $field The field to get the type - */ + /** + * Return the type of the provided field. For varchar(255), return only + * varchar + * @param string $field The field to get the type + */ private function fieldTypeLight($field) { $type = $this->fieldTypeComplete($field); @@ -1207,9 +1236,10 @@ class Dblayeroo return $type; } - /** Return the length of a field (generally a varchar) - * @param string $field The field to get the type - */ + /** + * Return the length of a field (generally a varchar) + * @param string $field The field to get the type + */ private function fieldLength($field) { $type = $this->fieldTypeComplete($field); @@ -1233,9 +1263,10 @@ class Dblayeroo ///////////////////////////// /// GETTERS / SETTERS /// ///////////////////////////// - /** Get/Set the table property - * @param string|null $table The table to use - */ + /** + * Get/Set the table property + * @param string|null $table The table to use + */ public function table($table = null) { $this->debugLog("Entering table (", $table, ")", 2); @@ -1252,9 +1283,10 @@ class Dblayeroo return $this; } - /** Get/Set the tableprefix property - * @param string|null $tableprefix The prefix to append - */ + /** + * Get/Set the tableprefix property + * @param string|null $tableprefix The prefix to append + */ public function tableprefix($tableprefix = null) { $this->debugLog("Entering tableprefix (", $tableprefix, ")", 2); @@ -1272,11 +1304,12 @@ class Dblayeroo return $this; } - /** Get/Set the fields property - * The fields to define are in the format: - * array ("fieldName"=>array ("type"[, "not null"[, "autoincrement"]])) - * @param array|null $fields The fields to define - */ + /** + * Get/Set the fields property + * The fields to define are in the format: + * array ("fieldName"=>array ("type"[, "not null"[, "autoincrement"]])) + * @param array|null $fields The fields to define + */ public function fields($fields = null) { $this->debugLog("Entering fields (VALUE)", 2); @@ -1356,13 +1389,14 @@ class Dblayeroo return $this; } - /** Get all the fields with the table name if needed. - * If the objectJoin is set, return the fields name too - * @param boolean|null $full Add the table name if the $full is set - */ + /** + * Get all the fields with the table name if needed. + * If the objectJoin is set, return the fields name too + * @param boolean|null $full Add the table name if the $full is set + */ public function fieldsAll($full = false) { - $fields = array(); + $fields = []; if ($this->joinObject) { foreach ($this->joinObject as $obj) { $fields = array_merge($fields, $obj->fieldsAll(true)); @@ -1380,9 +1414,10 @@ class Dblayeroo return $fields; } - /** Get/Set the primary property - * @param string|null $primary The primary key to use - */ + /** + * Get/Set the primary property + * @param string|null $primary The primary key to use + */ public function primary($primary = null) { $this->debugLog("Entering primary (", $primary, ")", 2); @@ -1402,9 +1437,10 @@ class Dblayeroo return $this; } - /** Get/Set the unique property - * @param array|null $unique The unique fields constraint to add - */ + /** + * Get/Set the unique property + * @param array|null $unique The unique fields constraint to add + */ public function unique($unique = null) { $this->debugLog("Entering unique (VALUE)", 2); @@ -1439,14 +1475,15 @@ class Dblayeroo return $this; } - /** Get/Set the foreign property - * @param array|null $foreign The definition of the foreign constraint - * The format is : - * array ( - * "field" => array ("parentTable", "parentField", "options if needed"), - * ) - * Multiple field and parnentField can be provided, separated by comma - */ + /** + * Get/Set the foreign property + * @param array|null $foreign The definition of the foreign constraint + * The format is : + * array ( + * "field" => array ("parentTable", "parentField", "options if needed"), + * ) + * Multiple field and parnentField can be provided, separated by comma + */ public function foreign($foreign = null) { $this->debugLog("Entering foreign (VALUE)", 2); @@ -1516,9 +1553,10 @@ class Dblayeroo return $this; } - /** Get/Set the debug property - * @param integer|null $debug Set the debug value - */ + /** + * Get/Set the debug property + * @param integer|null $debug Set the debug value + */ public function debug($debug = null) { $this->debugLog("Entering debug (", $debug, ")", 2); @@ -1532,16 +1570,18 @@ class Dblayeroo return $this; } - /** Get the sep property - */ + /** + * Get the sep property + */ public function sep() { return $this->sep; } - /** Get/Set the dsn property - * @param string|null $dsn Set the DSN property of PDO - */ + /** + * Get/Set the dsn property + * @param string|null $dsn Set the DSN property of PDO + */ public function dsn($dsn = null) { $this->debugLog("Entering dsn (", $dsn, ")", 2); @@ -1555,10 +1595,11 @@ class Dblayeroo return $this; } - /** Get/Set the titles property - * @param array|null $titles The titles of the fields - * @param boolean|null $full Add the table name if the $full is set - */ + /** + * Get/Set the titles property + * @param array|null $titles The titles of the fields + * @param boolean|null $full Add the table name if the $full is set + */ public function titles($titles = null, $full = false) { $this->debugLog("Entering titles (VALUE)", 2); @@ -1566,7 +1607,7 @@ class Dblayeroo if ($full === false && $this->joinObject === null) { return $this->titles; } - $titles = array(); + $titles = []; foreach ($this->titles as $key => $val) { $titles[$this->tableprefix . $this->table . "." . $key] = $val; } @@ -1600,32 +1641,34 @@ class Dblayeroo return $this; } - /** Dump the configuration of the table in an array - */ + /** + * Dump the configuration of the table in an array + */ public function exportConf() { - return array("table" => $this->table, + return ["table" => $this->table, "tableprefix" => $this->tableprefix, "fields" => $this->fields, "primary" => $this->primary, "unique" => $this->unique, "foreign" => $this->foreign, "titles" => $this->titles, - ); + ]; } - /** Define a real type array - * Must be array ("field" => "realtype") - * @param array $realTypes The realTypes to set - * The allowed real types are defined in test method : - * checkRealType_TYPE ($val, $definition) - * The allowed real types are : mail, date, datetime, allowedchars(a23d), - * uuid, time, array('val1','val2','val3'), regex(/^[a-zA-Z]{3,}$/i) - * integer, integerPositive, - * To be done : - * integerNegative, - * php_function(), function($val) { if ($val > 0) return "MESSAGE";} - */ + /** + * Define a real type array + * Must be array ("field" => "realtype") + * @param array $realTypes The realTypes to set + * The allowed real types are defined in test method : + * checkRealType_TYPE ($val, $definition) + * The allowed real types are : mail, date, datetime, allowedchars(a23d), + * uuid, time, array('val1','val2','val3'), regex(/^[a-zA-Z]{3,}$/i) + * integer, integerPositive, + * To be done : + * integerNegative, + * php_function(), function($val) { if ($val > 0) return "MESSAGE";} + */ public function realTypes($realTypes = null) { if ($realTypes === null) { @@ -1651,91 +1694,110 @@ class Dblayeroo return $this; } - /** Get the meta data or clear them. - * The meta data are all the requests done by the dblayeroo, the time needed - * for each, the number of rows returned by the SQL server. - * They allow to debug the app - * @param boolean|null $meta If meta is set, clear the meta-data. If not set, - * return the actual value of the meta-data - * @return array or $this - */ + /** + * Get the meta data or clear them. + * The meta data are all the requests done by the dblayeroo, the time needed + * for each, the number of rows returned by the SQL server. + * They allow to debug the app + * @param boolean|null $meta If meta is set, clear the meta-data. If not set, + * return the actual value of the meta-data + * @return array or $this + */ public function meta($meta = null) { if ($meta === null) { return self::$meta; } - self::$meta = array(); + self::$meta = []; return $this; } ///////////////////////////////////// /// MANAGE THE REQUEST BY OOP /// ///////////////////////////////////// - /** The command to use - */ + /** + * The command to use + */ private $command = ""; - /** The DISTINCT option - */ + /** + * The DISTINCT option + */ private $distinct = ""; - /** The columns to display in SELECT, with the tables names and the separators - * correctely defined - */ + /** + * The columns to display in SELECT, with the tables names and the separators + * correctely defined + */ private $displayColumn = null; - /** The alias associated to each displayColumn - */ - private $displayAlias = array(); - /** Manage the joins - */ - private $joins = array(); - /** The WHERE expression - */ - private $whereExpression = array(); - /** The values for each parameter for the WHERE condition - */ - private $whereValues = array(); - /** The columns in GROUP BY condition - */ + /** + * The alias associated to each displayColumn + */ + private $displayAlias = []; + /** + * Manage the joins + */ + private $joins = []; + /** + * The WHERE expression + */ + private $whereExpression = []; + /** + * The values for each parameter for the WHERE condition + */ + private $whereValues = []; + /** + * The columns in GROUP BY condition + */ private $groupByExpression = null; - /** The ORDER expression - */ - private $orderExpression = array(); - /** The LIMIT expression - */ + /** + * The ORDER expression + */ + private $orderExpression = []; + /** + * The LIMIT expression + */ private $limitExpression = ""; - /** The values to SET in INSERT/UPDATE - */ - private $setValues = array(); - /** The types to SET in INSERT/UPDATE - */ - private $setType = array(); - /** The dblayeroo object of the foreign keys tables to check - */ - private $setForeignObj = array(); + /** + * The values to SET in INSERT/UPDATE + */ + private $setValues = []; + /** + * The types to SET in INSERT/UPDATE + */ + private $setType = []; + /** + * The dblayeroo object of the foreign keys tables to check + */ + private $setForeignObj = []; - /** If we need to join this object with another one, save the second one in - * this property - */ + /** + * If we need to join this object with another one, save the second one in + * this property + */ private $joinObject; - /** The debug depth (as we clone object, the depth is increased to debug - * easily the functions - */ + /** + * The debug depth (as we clone object, the depth is increased to debug + * easily the functions + */ protected $debugDepth = 1; - /** The sort order of select/order entries crossed the differents objects - */ + /** + * The sort order of select/order entries crossed the differents objects + */ private static $sortOrder = 0; - /** The method to get a new sort order acrossed the differents objects - */ + /** + * The method to get a new sort order acrossed the differents objects + */ public function getSortOrder() { ++self::$sortOrder; return "order" . self::$sortOrder; } - /** Reinit the SQL request - */ + /** + * Reinit the SQL request + */ public function clearRequest() { $this->debugLog("Entering clearRequest ()", 2); @@ -1748,25 +1810,26 @@ class Dblayeroo $this->command = ""; $this->distinct = ""; $this->displayColumn = null; - $this->displayAlias = array(); - $this->joins = array(); - $this->whereExpression = array(); - $this->whereValues = array(); + $this->displayAlias = []; + $this->joins = []; + $this->whereExpression = []; + $this->whereValues = []; $this->groupByExpression = null; - $this->orderExpression = array(); + $this->orderExpression = []; $this->limitExpression = ""; - $this->setValues = array(); - $this->setType = array(); + $this->setValues = []; + $this->setType = []; // The foreign keys can be defined in the constructor for all the // modifications checks. No need to remove them //$this->setForeignObj = array (); return $this; } - /** Define a new foreign object - * @param object $object The dblayeroo object to use for foreign constraint - * checks - */ + /** + * Define a new foreign object + * @param object $object The dblayeroo object to use for foreign constraint + * checks + */ public function setForeignObj($object) { $this->debugLog("Entering setForeignObj (OBJECT)", 2); @@ -1791,84 +1854,92 @@ class Dblayeroo return $this; } - /** Define the command to execute. Can be - * "SELECT", "INSERT", "DELETE", "UPDATE". - * @param string $command The command to execute - */ + /** + * Define the command to execute. Can be + * "SELECT", "INSERT", "DELETE", "UPDATE". + * @param string $command The command to execute + */ public function command($command) { $this->debugLog("Entering command (", $command, ")", 2); - $allowed = array("SELECT", "INSERT", "DELETE", "UPDATE"); + $allowed = ["SELECT", "INSERT", "DELETE", "UPDATE"]; if (! is_string($command)) { $this->DBException("Invalid command provided (not string)"); } $command = strtoupper($command); - if (! in_array($command, $allowed)) { + if (! in_array($command, $allowed, true)) { $this->DBException("Invalid command provided (unknown command)"); } $this->command = $command; return $this; } - /** Alias of command ("SELECT") - */ + /** + * Alias of command ("SELECT") + */ public function select() { $this->command = "SELECT"; return $this; } - /** Alias of command ("INSERT") - */ + /** + * Alias of command ("INSERT") + */ public function insert() { $this->command = "INSERT"; return $this; } - /** Alias of command ("DELETE") - */ + /** + * Alias of command ("DELETE") + */ public function delete() { $this->command = "DELETE"; return $this; } - /** Alias of command ("UPDATE") - */ + /** + * Alias of command ("UPDATE") + */ public function update() { $this->command = "UPDATE"; return $this; } - /** Set the DISTINCT option - */ + /** + * Set the DISTINCT option + */ public function setDistinct() { $this->distinct = "DISTINCT"; return $this; } - /** Changing the name displayColumns to displayAdd - * @param array|string|null $columnNames The columns name, separated by comma - * @deprecated 0.36 - */ - public function displayColumn($columnNames = array()) + /** + * Changing the name displayColumns to displayAdd + * @param array|string|null $columnNames The columns name, separated by comma + * @deprecated 0.36 + */ + public function displayColumn($columnNames = []) { return $this->displayAdd($columnNames); } - /** Set the columns to display for the next SELECT request. - * The columns are ordered by the first added to the last added - * @param array|string|null $columnNames The columns name, separated by comma - * By default, display all the columns if this method is not called - * If the value is null or not provided or an empty array, do not display - * any field - * @param array|string|null $aliasNames Add the Aliases to the displayed - * columns - */ - public function displayAdd($columnNames = array(), $aliasNames = array()) + /** + * Set the columns to display for the next SELECT request. + * The columns are ordered by the first added to the last added + * @param array|string|null $columnNames The columns name, separated by comma + * By default, display all the columns if this method is not called + * If the value is null or not provided or an empty array, do not display + * any field + * @param array|string|null $aliasNames Add the Aliases to the displayed + * columns + */ + public function displayAdd($columnNames = [], $aliasNames = []) { $this->debugLog( "Entering displayAdd (", @@ -1892,7 +1963,7 @@ class Dblayeroo // A string must be separated by comma. But comma can be also in function // parameter like GROUP_CONCAT(group,','),field1,field2 // This block will explode on comma but only if not in a parenthesis block - $tmpArr = array(); + $tmpArr = []; $parenthesis = false; $tmp = ""; for ($i = 0; $i < strlen($columnNames); $i++) { @@ -1927,7 +1998,7 @@ class Dblayeroo } // If there is no provided names, reset all the defined ones if (count($columnNames) === 0) { - $this->displayColumn = array(); + $this->displayColumn = []; } foreach ($columnNames as $nb => $display) { if (! is_string($display)) { @@ -1942,8 +2013,8 @@ class Dblayeroo $name = trim(substr($name, $pos + 1, -1)); $separator = ""; if ( - in_array($func, array("AVG", "COUNT", "GROUP_CONCAT", "MAX", - "MIN","SUM")) + in_array($func, ["AVG", "COUNT", "GROUP_CONCAT", "MAX", + "MIN","SUM"], true) ) { $aggregateFunction = true; // Aggregate function. Add the non aggregate fields to the GROUP BY @@ -1953,7 +2024,7 @@ class Dblayeroo // there is no already defined displayed Columns. // Used if the group by is called from join object if ($this->displayColumn === null) { - $this->groupByExpression = array(); + $this->groupByExpression = []; } else { $this->groupByExpression = $this->displayColumn; } @@ -2017,24 +2088,25 @@ class Dblayeroo return $this; } - /** Return the name of the display field, with $this->sep - * Add the table prefix/name if full is set - * Allow : - * name, - * DISTINCT name, - * $this->sep.$name.$this->sep, - * DISTINCT $this->sep.$name.$this->sep, - * func(name), - * func(DISTINCT name), - * func($this->sep.$name.$this->sep), - * func(DISTINCT $this->sep.$name.$this->sep), - * func($this->sep.$this->tableprefix.$this->table.$this->sep.".". - * $this->sep.$name.$this->sep) - * func(DISTINCT $this->sep.$this->tableprefix.$this->table.$this->sep.".". - * $this->sep.$name.$this->sep) - * @param string $name The name of the field - * @param boolean|null $full Add the table prefix/name if set - */ + /** + * Return the name of the display field, with $this->sep + * Add the table prefix/name if full is set + * Allow : + * name, + * DISTINCT name, + * $this->sep.$name.$this->sep, + * DISTINCT $this->sep.$name.$this->sep, + * func(name), + * func(DISTINCT name), + * func($this->sep.$name.$this->sep), + * func(DISTINCT $this->sep.$name.$this->sep), + * func($this->sep.$this->tableprefix.$this->table.$this->sep.".". + * $this->sep.$name.$this->sep) + * func(DISTINCT $this->sep.$this->tableprefix.$this->table.$this->sep.".". + * $this->sep.$name.$this->sep) + * @param string $name The name of the field + * @param boolean|null $full Add the table prefix/name if set + */ private function displayConvert($name, $full = false) { $pos = strpos($name, "("); @@ -2064,15 +2136,16 @@ class Dblayeroo return $name; } - /** Get the columns set in the query by displayAdd. If the $full parameter - * is set, add the table prefix/name to the result. - * If the join object is set, ask to it the columns too - * @param boolean $full Add the table prefix/name if set - */ + /** + * Get the columns set in the query by displayAdd. If the $full parameter + * is set, add the table prefix/name to the result. + * If the join object is set, ask to it the columns too + * @param boolean $full Add the table prefix/name if set + */ public function displayGet($full = false) { - $columns = array(); - $displayColumn = array(); + $columns = []; + $displayColumn = []; if ($this->joinObject) { // The join object will be added at the end $full = true; @@ -2116,51 +2189,55 @@ class Dblayeroo return $columns; } - /** Do a inner join between two dblayer objects - * The join array is a associated array with local field as key and distant - * field as value - * @param object $object The dblayeroo object to use for searching the join - * data - * @param array $joinArray The values to search for join - */ + /** + * Do a inner join between two dblayer objects + * The join array is a associated array with local field as key and distant + * field as value + * @param object $object The dblayeroo object to use for searching the join + * data + * @param array $joinArray The values to search for join + */ public function joinInner($object, $joinArray) { $this->debugLog("Entering joinInner (OBJECT, JOINARRAY)", 2); return $this->joinReal("INNER", $object, $joinArray); } - /** Do a left join between two dblayer objects - * The join array is a associated array with local field as key and distant - * field as value - * @param object $object The dblayeroo object to use for searching the join - * data - * @param array $joinArray The values to search for join - */ + /** + * Do a left join between two dblayer objects + * The join array is a associated array with local field as key and distant + * field as value + * @param object $object The dblayeroo object to use for searching the join + * data + * @param array $joinArray The values to search for join + */ public function joinLeft($object, $joinArray) { $this->debugLog("Entering joinLeft (OBJECT, JOINARRAY)", 2); return $this->joinReal("LEFT", $object, $joinArray); } - /** Do a right join between two dblayer objects - * The join array is a associated array with local field as key and distant - * field as value - * @param object $object The dblayeroo object to use for searching the join - * data - * @param array $joinArray The values to search for join - */ + /** + * Do a right join between two dblayer objects + * The join array is a associated array with local field as key and distant + * field as value + * @param object $object The dblayeroo object to use for searching the join + * data + * @param array $joinArray The values to search for join + */ public function joinRight($object, $joinArray) { $this->debugLog("Entering joinRight (OBJECT, JOINARRAY)", 2); return $this->joinReal("RIGHT", $object, $joinArray); } - /** Convert a CONCAT('text',field) to CONCAT('text',`table`.`field`) or - * generate an exception if the field is not available in table - * If the provided string is not a concat, return the original one - * @param string $concat The string to examine - * @param object $object The dblayer object to use - */ + /** + * Convert a CONCAT('text',field) to CONCAT('text',`table`.`field`) or + * generate an exception if the field is not available in table + * If the provided string is not a concat, return the original one + * @param string $concat The string to examine + * @param object $object The dblayer object to use + */ private function concat($concat, $object) { if (substr($concat, 0, 7) !== "CONCAT(") { @@ -2196,19 +2273,20 @@ class Dblayeroo return $new; } - /** Do the real join - * @param string $joinType The join type to use ("INNER", "LEFT", "RIGHT") - * @param object $object The dblayeroo object to use for searching the join - * data - * @param array $joinArray The values to search for join - */ + /** + * Do the real join + * @param string $joinType The join type to use ("INNER", "LEFT", "RIGHT") + * @param object $object The dblayeroo object to use for searching the join + * data + * @param array $joinArray The values to search for join + */ private function joinReal($joinType, $object, $joinArray) { $this->debugLog("Entering joinReal (", $joinType, ", OBJECT, JOINARRAY)", 2); if (! is_string($joinType)) { $this->DBException("Invalid joinType provided to join (not string)"); } - if (! in_array($joinType, array("INNER", "LEFT", "RIGHT"))) { + if (! in_array($joinType, ["INNER", "LEFT", "RIGHT"], true)) { $this->DBException("Invalid joinType provided to join (not known)"); } if (! is_object($object)) { @@ -2235,7 +2313,7 @@ class Dblayeroo if (empty($joinArray)) { $this->DBException("Invalid joinArray provided (empty array)"); } - $newJoinArray = array(); + $newJoinArray = []; foreach ($joinArray as $fieldLocal => $fieldToJoin) { if (substr($fieldLocal, 0, 7) === "CONCAT(") { $fieldLocal = $this->concat($fieldLocal, $this); @@ -2294,16 +2372,17 @@ class Dblayeroo return $this; } - /** Get the join SQL part with recursive call of the child joins - * @param object|null $joinObject The joinObject to examine too - */ + /** + * Get the join SQL part with recursive call of the child joins + * @param object|null $joinObject The joinObject to examine too + */ public function joinsGet($joinObject = null) { $joins = ""; if ($joinObject === null) { $joinObject = $this; } - if ($joinObject->joins !== array()) { + if ($joinObject->joins !== []) { $joins = implode("\n ", $joinObject->joins); } if ($joinObject->joinObject !== null) { @@ -2314,12 +2393,13 @@ class Dblayeroo return trim($joins); } - /** Set a new WHERE expression value - * @param string $field The field to check - * @param string $operator The operator ("=", "<=", ">=", "!=", "NOT LIKE", - * "LIKE", "IS NULL", "REGEXP", "NOT REGEXP") - * @param string|null $value The value to search ("" if not provided) - */ + /** + * Set a new WHERE expression value + * @param string $field The field to check + * @param string $operator The operator ("=", "<=", ">=", "!=", "NOT LIKE", + * "LIKE", "IS NULL", "REGEXP", "NOT REGEXP") + * @param string|null $value The value to search ("" if not provided) + */ public function whereAdd($field, $operator, $value = "") { $this->debugLog( @@ -2352,10 +2432,10 @@ class Dblayeroo )); } $operator = strtoupper($operator); - $allowed = array("=", "<", "<=", ">", ">=", "!=", + $allowed = ["=", "<", "<=", ">", ">=", "!=", "LIKE", "NOT LIKE", "IS NULL", "IS NOT NULL", - "REGEXP", "NOT REGEXP"); - if (! in_array($operator, $allowed)) { + "REGEXP", "NOT REGEXP"]; + if (! in_array($operator, $allowed, true)) { $this->DBException("Invalid operator provided (unknown operator)"); } // TODO : Check if the value is corresponding to the type of the column @@ -2384,19 +2464,20 @@ class Dblayeroo $this->whereExpression[] = $this->sep . $this->tableprefix . $this->table . $this->sep . "." . $this->sep . $field . $this->sep . " " . $operator . " :$hash"; - $this->whereValues[$hash] = array( + $this->whereValues[$hash] = [ "field" => $field, "fieldfull" => $this->tableprefix . $this->table . "." . $field, "operator" => $operator, "value" => $value, "hash" => $hash, - "type" => $this->fieldTypeLight($field)); + "type" => $this->fieldTypeLight($field)]; } return $this; } - /** Add a new AND to the WHERE expression - */ + /** + * Add a new AND to the WHERE expression + */ public function whereAddAND() { $this->debugLog("Entering whereAddAND ()", 2); @@ -2407,8 +2488,9 @@ class Dblayeroo return $this; } - /** Add a new OR to the WHERE expression - */ + /** + * Add a new OR to the WHERE expression + */ public function whereAddOR() { $this->debugLog("Entering whereAddOR ()", 2); @@ -2419,8 +2501,9 @@ class Dblayeroo return $this; } - /** Add a new Open Parenthesis to the WHERE expression - */ + /** + * Add a new Open Parenthesis to the WHERE expression + */ public function whereAddParenthesisOpen() { $this->debugLog("Entering whereAddParenthesisOpen ()", 2); @@ -2436,8 +2519,9 @@ class Dblayeroo return $this; } - /** Add a new Close Parenthesis to the WHERE expression - */ + /** + * Add a new Close Parenthesis to the WHERE expression + */ public function whereAddParenthesisClose() { $this->debugLog("Entering whereAddParenthesisClose ()", 2); @@ -2445,14 +2529,15 @@ class Dblayeroo return $this; } - /** Get the WHERE clause of the object. - * If the joinObject is set, return all the WHERE clauses - */ + /** + * Get the WHERE clause of the object. + * If the joinObject is set, return all the WHERE clauses + */ public function whereGetExpression() { $whereExpression = $this->whereExpression; if ($whereExpression === null) { - $whereExpression = array(); + $whereExpression = []; } if ($this->joinObject !== null) { foreach ($this->joinObject as $obj) { @@ -2475,15 +2560,16 @@ class Dblayeroo return $whereExpression; } - /** Get the WHERE values of the object. - * If the joinObject is set, return all the WHERE clauses with AND and - * parenthesis - */ + /** + * Get the WHERE values of the object. + * If the joinObject is set, return all the WHERE clauses with AND and + * parenthesis + */ public function whereGetValues() { $whereValues = $this->whereValues; if ($whereValues === null) { - $whereValues = array(); + $whereValues = []; } if ($this->joinObject !== null) { foreach ($this->joinObject as $obj) { @@ -2496,12 +2582,13 @@ class Dblayeroo return $whereValues; } - /** Add a new ORDER sort. The multiple ORDERS are used from the first added to - * the last added - * @param string $field The field to sort - * @param string|null $sort The sort order ("ASC", "DESC", "NATASC", - * "NATDESC"); - */ + /** + * Add a new ORDER sort. The multiple ORDERS are used from the first added to + * the last added + * @param string $field The field to sort + * @param string|null $sort The sort order ("ASC", "DESC", "NATASC", + * "NATDESC"); + */ public function orderAdd($field, $sort = "ASC") { $this->debugLog("Entering orderAdd (", $field, ", ", $sort, ")", 2); @@ -2512,14 +2599,14 @@ class Dblayeroo $this->DBException("Invalid sort provided (not string)"); } $sort = strtoupper($sort); - if (! in_array($sort, array("ASC", "DESC", "NATASC", "NATDESC"))) { + if (! in_array($sort, ["ASC", "DESC", "NATASC", "NATDESC"], true)) { $this->DBException( "Invalid sort provided (not ASC nor DESC nor NATASC nor NATDESC)" ); } if ( ! array_key_exists($field, $this->fields) && - ! in_array($field, $this->displayAlias) + ! in_array($field, $this->displayAlias, true) ) { $this->DBException(sprintf( "Invalid field to orderAdd '%s' : not defined in table nor in alias", @@ -2540,15 +2627,16 @@ class Dblayeroo return $this; } - /** Get the ORDER fields defined. If a joinObject is set with ORDER statement, - * return the joinObject order with its tableprefix/name in addition of - * the ones of this object - * If the parameter $full is set, add the table prefix/name to the result - * @param boolean|null $full Add the table prefix/name if set - */ + /** + * Get the ORDER fields defined. If a joinObject is set with ORDER statement, + * return the joinObject order with its tableprefix/name in addition of + * the ones of this object + * If the parameter $full is set, add the table prefix/name to the result + * @param boolean|null $full Add the table prefix/name if set + */ public function orderGet($full = false) { - $order = array(); + $order = []; if ($this->joinObject) { $full = true; } @@ -2569,9 +2657,10 @@ class Dblayeroo return $order; } - /** Return true if this object or one of the join objects need GROUP BY SQL - * part - */ + /** + * Return true if this object or one of the join objects need GROUP BY SQL + * part + */ public function groupByNeeded() { $needGroupBy = false; @@ -2588,26 +2677,27 @@ class Dblayeroo return $needGroupBy; } - /** Get the GROUP BY fields defined. If a joinObject is set with GROUP BY - * statement, return the joinObject order with its tableprefix/name in - * addition of the ones of this object - * If the parameter $full is set, add the table prefix/name to the result - * @param boolean|null $full Add the table prefix/name if set - */ + /** + * Get the GROUP BY fields defined. If a joinObject is set with GROUP BY + * statement, return the joinObject order with its tableprefix/name in + * addition of the ones of this object + * If the parameter $full is set, add the table prefix/name to the result + * @param boolean|null $full Add the table prefix/name if set + */ public function groupByGet($full = false) { if ($this->joinObject) { $full = true; } - $localGroupBy = array(); + $localGroupBy = []; // Manage the local object group by entries. In full mode, return the // groupByExpression if it is set, or the list of the displayed fields. if ($full) { if ($this->groupByExpression !== null) { foreach ($this->groupByExpression as $pos => $o) { if ($localGroupBy === null) { - $localGroupBy = array(); + $localGroupBy = []; } $localGroupBy[$pos] = $this->sep . $this->tableprefix . $this->table . $this->sep . "." . $o; @@ -2623,12 +2713,12 @@ class Dblayeroo if ($this->groupByExpression !== null) { $localGroupBy = $this->groupByExpression; } else { - $localGroupBy = array(); + $localGroupBy = []; } } // Add the distant entries - $distantGroupBy = array(); + $distantGroupBy = []; if ($this->joinObject) { foreach ($this->joinObject as $obj) { $ext = $obj->groupByGet(true); @@ -2641,11 +2731,12 @@ class Dblayeroo return $groupBy; } - /** Define a LIMIT for the request. - * To use only the nbLines, put a 0 on startLine - * @param integer $startLine The starting line in the result list - * @param integer $nbLines The number of lines to return - */ + /** + * Define a LIMIT for the request. + * To use only the nbLines, put a 0 on startLine + * @param integer $startLine The starting line in the result list + * @param integer $nbLines The number of lines to return + */ public function limit($startLine, $nbLines) { $this->debugLog("Entering limit (", $startLine, ", ", $nbLines, ")", 2); @@ -2671,9 +2762,10 @@ class Dblayeroo return $this; } - /** Define a LIMIT for the request. - * @param integer $nbLines The number of lines to return - */ + /** + * Define a LIMIT for the request. + * @param integer $nbLines The number of lines to return + */ public function limitLines($nbLines) { $this->debugLog("Entering limitLines (", $nbLines, ")", 2); @@ -2688,11 +2780,12 @@ class Dblayeroo return $this; } - /** Set INSERT/UPDATE values - * - The provided array must be an associative array, the field name must be - * provided as key and the value as value. Each field=>val will be updated - * @param array $values The values to INSERT or UPDATE - */ + /** + * Set INSERT/UPDATE values + * - The provided array must be an associative array, the field name must be + * provided as key and the value as value. Each field=>val will be updated + * @param array $values The values to INSERT or UPDATE + */ public function setValues($values) { $this->debugLog("Entering setValues (", $values, ")", 2); @@ -2701,8 +2794,8 @@ class Dblayeroo } $values = $this->normalize($values); $associative = null; - $tmpValues = array(); - $tmpType = array(); + $tmpValues = []; + $tmpType = []; foreach ($values as $key => $val) { if (! array_key_exists($key, $this->fields)) { $this->DBException(sprintf( @@ -2729,8 +2822,9 @@ class Dblayeroo return $this; } - /** Create the SQL request - */ + /** + * Create the SQL request + */ private function createRequest() { if ($this->sep === "") { @@ -2795,7 +2889,7 @@ class Dblayeroo $sql .= "\n LIMIT $this->limitExpression"; } // No set Values for SELECT - $this->setValues = array(); + $this->setValues = []; break; case "INSERT": $sql = "INSERT INTO $this->sep$this->tableprefix$this->table$this->sep ("; @@ -2821,8 +2915,8 @@ class Dblayeroo } $sql .= ")"; // No WHERE in INSERT : remove the WHERE parameters - $this->whereExpression = array(); - $this->whereValues = array(); + $this->whereExpression = []; + $this->whereValues = []; break; case "DELETE": $sql = "DELETE FROM $this->sep$this->tableprefix$this->table$this->sep"; @@ -2837,7 +2931,7 @@ class Dblayeroo $sql .= " LIMIT $this->limitExpression"; } // No set Values for DELETE - $this->setValues = array(); + $this->setValues = []; break; case "UPDATE": $sql = "UPDATE $this->sep$this->tableprefix$this->table$this->sep"; @@ -2871,13 +2965,14 @@ class Dblayeroo return $sql; } - /** Prepare the request with the associated entries. - * If textForm is true, return a string to display what will be done - * If textForm is false, return a statement - * @param string $sql The SQL request to prepare - * @param boolean $textForm If true, return the result. If false prepare - * really the request - */ + /** + * Prepare the request with the associated entries. + * If textForm is true, return a string to display what will be done + * If textForm is false, return a statement + * @param string $sql The SQL request to prepare + * @param boolean $textForm If true, return the result. If false prepare + * really the request + */ private function prepareRequest($sql, $textForm) { $text = ""; @@ -2988,8 +3083,9 @@ class Dblayeroo } } - /** Return the query that will be executed - */ + /** + * Return the query that will be executed + */ public function getDisplayQuery() { $text = ""; @@ -3002,13 +3098,14 @@ class Dblayeroo return $text; } - /** Normalize the values before using them. - * The normalize is called by methods : verify, checkRealTypes and setValues - * By default, remove the spaces (trim) at begin and end. - * This method can be overloaded by extending the class - * @param array $values The values to test or INSERT or UPDATE - * @return array the updated values - */ + /** + * Normalize the values before using them. + * The normalize is called by methods : verify, checkRealTypes and setValues + * By default, remove the spaces (trim) at begin and end. + * This method can be overloaded by extending the class + * @param array $values The values to test or INSERT or UPDATE + * @return array the updated values + */ public function normalize($values) { if (! is_array($values)) { @@ -3022,17 +3119,18 @@ class Dblayeroo return $values; } - /** Check the provided values which will be inserted or updated against the - * database structure. - * In update, do not forget to define the whereAdd parameters ! - * @param array $values The values to test - * @param boolean|null $update if true UPDATE request, else INSERT request - * @return array The errors found by field - */ + /** + * Check the provided values which will be inserted or updated against the + * database structure. + * In update, do not forget to define the whereAdd parameters ! + * @param array $values The values to test + * @param boolean|null $update if true UPDATE request, else INSERT request + * @return array The errors found by field + */ public function verify($values, $update = false) { $update = !! $update; - $errors = array(); + $errors = []; if ($this->table === null) { throw new \Exception("No table name defined", 500); } @@ -3051,7 +3149,7 @@ class Dblayeroo // - Look if all the NOT NULL fields are filled foreach ($this->fields as $field => $params) { if ( - in_array("not null", $params) && + in_array("not null", $params, true) && ! array_key_exists($field, $values) ) { $errors[$field] = sprintf( @@ -3062,7 +3160,7 @@ class Dblayeroo $field ); } elseif ( - ! in_array("not null", $params) && + ! in_array("not null", $params, true) && ! array_key_exists($field, $values) ) { continue; @@ -3084,13 +3182,13 @@ class Dblayeroo continue; } if ( - ! in_array("not null", $params) && + ! in_array("not null", $params, true) && ! array_key_exists($field, $values) ) { continue; } if ( - in_array("not null", $params) && + in_array("not null", $params, true) && ! array_key_exists($field, $values) ) { $errors[$field] = dgettext( @@ -3100,8 +3198,8 @@ class Dblayeroo continue; } if ( - in_array("not null", $params) && - ! in_array("autoincrement", $params) && + in_array("not null", $params, true) && + ! in_array("autoincrement", $params, true) && $values[$field] === null ) { $errors[$field] = dgettext( @@ -3201,10 +3299,10 @@ class Dblayeroo $this->debugLog(" verify the unique constraint", 2); $uniques = $this->unique; if (! is_array($uniques)) { - $uniques = array(); + $uniques = []; } - if (! in_array($this->primary, $uniques)) { - $uniques = array_merge(array($this->primary), $uniques); + if (! in_array($this->primary, $uniques, true)) { + $uniques = array_merge([$this->primary], $uniques); } $setValues = $values; $foundImpactedLines = 0; @@ -3349,7 +3447,7 @@ class Dblayeroo } if ( ! array_key_exists($field, $values) && - in_array("not null", $this->fields[$field]) + in_array("not null", $this->fields[$field], true) ) { $errors[$field] = sprintf( dgettext( @@ -3372,7 +3470,7 @@ class Dblayeroo } if ( ! array_key_exists($field, $values) && - ! in_array("not null", $this->fields[$field]) + ! in_array("not null", $this->fields[$field], true) ) { $values[$field] = null; } @@ -3410,10 +3508,11 @@ class Dblayeroo return $errors; } - /** Check the values before doing really the modification of the database - * @param array $values The values to test - * @param boolean|null $update if true UPDATE request, else INSERT request - */ + /** + * Check the values before doing really the modification of the database + * @param array $values The values to test + * @param boolean|null $update if true UPDATE request, else INSERT request + */ public function checkValues($values, $update = false) { $this->debugLog("Entering checkValues (", $update, ")", 2); @@ -3441,15 +3540,16 @@ class Dblayeroo return $errors; } - /** Check the types of the data against the realTypes - * Return an array with the field name in error and a message - * If allowEmpty is set, do not test the "NOT NULL" feature - * In UPDATE, the values don't need be not set : they are already in database - * so $allowEmpty is true - * @param array $values The values to test - * @param boolean|null $allowEmpty Allow the "not null" to not be set - * @return array empty array if no error - */ + /** + * Check the types of the data against the realTypes + * Return an array with the field name in error and a message + * If allowEmpty is set, do not test the "NOT NULL" feature + * In UPDATE, the values don't need be not set : they are already in database + * so $allowEmpty is true + * @param array $values The values to test + * @param boolean|null $allowEmpty Allow the "not null" to not be set + * @return array empty array if no error + */ public function checkRealTypes($values, $allowEmpty = false) { $this->debugLog( @@ -3467,12 +3567,12 @@ class Dblayeroo ); } $values = $this->normalize($values); - $errors = array(); + $errors = []; foreach ($this->fields as $field => $params) { if (! key_exists($field, $values) || trim($values[$field]) === "") { if ( - in_array("not null", $params) && - ! in_array("autoincrement", $params) + in_array("not null", $params, true) && + ! in_array("autoincrement", $params, true) ) { if ($allowEmpty === false) { $errors[$field] = dgettext( @@ -3511,11 +3611,12 @@ class Dblayeroo return $errors; } - /** Execute the pre-defined query - * Return the content array if SELECT command is choosed - * Return the Last ID if INSERT command is choosed - * Return the number of modified lines for UPDATE/DELETE command - */ + /** + * Execute the pre-defined query + * Return the content array if SELECT command is choosed + * Return the Last ID if INSERT command is choosed + * Return the number of modified lines for UPDATE/DELETE command + */ public function execute() { $this->debugLog("Entering execute ()", 2); @@ -3618,7 +3719,7 @@ class Dblayeroo // Function. The function that return an int must be added in this // list, to cast correctely the value $func = strtoupper(trim(substr($columns[$colNb], 0, $pos))); - if (in_array($func, array("AVG", "COUNT", "MAX", "MIN", "SUM"))) { + if (in_array($func, ["AVG", "COUNT", "MAX", "MIN", "SUM"], true)) { $val = intval($val); } } else { @@ -3630,7 +3731,8 @@ class Dblayeroo $name = str_replace("DISTINCT ", "", $name); /*if ($cleanable) $name = str_replace ($this->sep.$this->tableprefix.$this->table. - $this->sep.".", "", $name);*/ + $this->sep.".", "", $name); + */ if ( strtolower($fieldsAll[$name][0]) === "integer" && $val !== null @@ -3648,26 +3750,26 @@ class Dblayeroo unset($result[$rownb][$colNb]); } } - self::$meta[] = array( + self::$meta[] = [ "command" => $this->command, "sql" => $sql, "sqltime" => microtime(true) - $startTime, "displayQuery" => $this->getDisplayQuery(), "nbrows" => count($result), - ); + ]; return $result; case "INSERT": - self::$meta[] = array( + self::$meta[] = [ "command" => $this->command, "sql" => $sql, "sqltime" => microtime(true) - $startTime, "displayQuery" => $this->getDisplayQuery(), "nbrows" => $st->rowCount(), - ); + ]; // If the primary key is not autoincrement, return the provided value if // exists if ( - ! in_array("autoincrement", $this->fields[$this->primary]) && + ! in_array("autoincrement", $this->fields[$this->primary], true) && key_exists($this->primary, $this->setValues) ) { return $this->setValues[$this->primary]; @@ -3676,7 +3778,7 @@ class Dblayeroo // If the primary key is autoincrement and the provided value is not null // Return it if ( - in_array("autoincrement", $this->fields[$this->primary]) && + in_array("autoincrement", $this->fields[$this->primary], true) && key_exists($this->primary, $this->setValues) && $this->setValues[$this->primary] !== null ) { @@ -3689,7 +3791,7 @@ class Dblayeroo $autoInc = null; if ($this->driver === "pgsql") { foreach ($this->fields as $col => $params) { - if (in_array("autoincrement", $params)) { + if (in_array("autoincrement", $params, true)) { $autoInc = $col; break; } @@ -3706,25 +3808,26 @@ class Dblayeroo return self::$instance[$this->dsn]->lastInsertId($autoInc); case "UPDATE": case "DELETE": - self::$meta[] = array( + self::$meta[] = [ "command" => $this->command, "sql" => $sql, "sqltime" => microtime(true) - $startTime, "displayQuery" => $this->getDisplayQuery(), "nbrows" => $st->rowCount(), - ); + ]; return $st->rowCount(); default: $this->DBException("execute : command not defined : no RC"); } } - /** Execute a non prepared query in the database context. - * As there is no verification, this method is DANGEROUS and should not be - * used ! - * @param string $sql The SQL request to directely send to the database - * @return PDOStatement The PDO Statement to traverse - */ + /** + * Execute a non prepared query in the database context. + * As there is no verification, this method is DANGEROUS and should not be + * used ! + * @param string $sql The SQL request to directely send to the database + * @return PDOStatement The PDO Statement to traverse + */ public function directQuery($sql) { if (! key_exists($this->dsn, self::$instance)) { @@ -3733,19 +3836,21 @@ class Dblayeroo return self::$instance[$this->dsn]->query($sql, \PDO::FETCH_ASSOC); } - /** Error management - * @param string $message The message to throw in the exception - * @param integer|null $code The error code to return to the user - */ + /** + * Error management + * @param string $message The message to throw in the exception + * @param integer|null $code The error code to return to the user + */ public function DBException($message, $code = 500) { $message = $this->DBExceptionMsg($message); throw new \Exception($message, $code); } - /** Return the $message adapted with the debug trace if needed - * @param string $message The message to throw in the exception - */ + /** + * Return the $message adapted with the debug trace if needed + * @param string $message The message to throw in the exception + */ public function DBExceptionMsg($message) { $backtrace = debug_backtrace(); @@ -3764,10 +3869,11 @@ class Dblayeroo return $message; } - /** Debug function - * @param mixed ...$message The message to display in debug - * @param integer priority The display message if $priority <= $this->debug - */ + /** + * Debug function + * @param mixed ...$message The message to display in debug + * @param integer priority The display message if $priority <= $this->debug + */ public function debugLog($message, $priority) { if ((!!$this->debug) === false) { @@ -3800,11 +3906,12 @@ class Dblayeroo ////////////////////////////////////////////// //// ALL THE CHECK REALTYPES METHODS //// ////////////////////////////////////////////// - /** Check the type "integerPositive" - * @param string $val The value to check - * @param string $definition The definition of the type - * @return string or null - */ + /** + * Check the type "integerPositive" + * @param string $val The value to check + * @param string $definition The definition of the type + * @return string or null + */ private function checkRealType_integerPositive($val, $definition) { if (substr($val, 0, 1) === "-") { @@ -3822,11 +3929,12 @@ class Dblayeroo return; } - /** Check the type "integer" - * @param string $val The value to check - * @param string $definition The definition of the type - * @return string or null - */ + /** + * Check the type "integer" + * @param string $val The value to check + * @param string $definition The definition of the type + * @return string or null + */ private function checkRealType_integer($val, $definition) { if (strspn($val, "0123456789-") !== strlen($val)) { @@ -3844,12 +3952,13 @@ class Dblayeroo return; } - /** Check the type "allowedchars" - * the chars must be in UTF-8 - * @param string $val The value to check - * @param string $definition The definition of the type - * @return string or null - */ + /** + * Check the type "allowedchars" + * the chars must be in UTF-8 + * @param string $val The value to check + * @param string $definition The definition of the type + * @return string or null + */ private function checkRealType_allowedchars($val, $definition) { list($func, $param) = explode("(", $definition); @@ -3873,11 +3982,12 @@ class Dblayeroo return dgettext("domframework", "Invalid char provided"); } - /** Check the type "array" - * @param string $val The value to check - * @param string $definition The definition of the type - * @return string or null - */ + /** + * Check the type "array" + * @param string $val The value to check + * @param string $definition The definition of the type + * @return string or null + */ private function checkRealType_array($val, $definition) { list($func, $param) = explode("(", $definition); @@ -3894,19 +4004,20 @@ class Dblayeroo foreach ($array as $key => $tmp) { $array[$key] = mb_substr($tmp, 1, -1); } - if (in_array($val, $array)) { + if (in_array($val, $array, true)) { return; } return dgettext("domframework", "Invalid value provided : " . "not in allowed list"); } - /** Check the type "regex" - * Do not forget to add the separators, the ^ and $ - * @param string $val The value to check - * @param string $definition The definition of the type - * @return string or null - */ + /** + * Check the type "regex" + * Do not forget to add the separators, the ^ and $ + * @param string $val The value to check + * @param string $definition The definition of the type + * @return string or null + */ private function checkRealType_regex($val, $definition) { list($func, $param) = explode("(", $definition); @@ -3930,11 +4041,12 @@ class Dblayeroo "do not match the regex"); } - /** Check the type "mail" - * @param string $val The value to check - * @param string $definition The definition of the type - * @return string or null - */ + /** + * Check the type "mail" + * @param string $val The value to check + * @param string $definition The definition of the type + * @return string or null + */ private function checkRealType_mail($val, $definition) { if (!! filter_var($val, FILTER_VALIDATE_EMAIL)) { @@ -3943,11 +4055,12 @@ class Dblayeroo return dgettext("domframework", "Invalid mail provided"); } - /** Check the type "uuid" - * @param string $val The value to check - * @param string $definition The definition of the type - * @return string or null - */ + /** + * Check the type "uuid" + * @param string $val The value to check + * @param string $definition The definition of the type + * @return string or null + */ private function checkRealType_uuid($val, $definition) { if (strlen($val) !== 36) { @@ -3965,11 +4078,12 @@ class Dblayeroo } } - /** Check the type "sqldate" - * @param string $val The value to check - * @param string $definition The definition of the type - * @return string or null - */ + /** + * Check the type "sqldate" + * @param string $val The value to check + * @param string $definition The definition of the type + * @return string or null + */ private function checkRealType_sqldate($val, $definition) { if (strlen($val) !== 10) { @@ -3999,11 +4113,12 @@ class Dblayeroo } } - /** Check the type "sqltime" - * @param string $val The value to check - * @param string $definition The definition of the type - * @return string or null - */ + /** + * Check the type "sqltime" + * @param string $val The value to check + * @param string $definition The definition of the type + * @return string or null + */ private function checkRealType_sqltime($val, $definition) { if (strlen($val) !== 8) { @@ -4033,11 +4148,12 @@ class Dblayeroo } } - /** Check the type "sqldatetime" - * @param string $val The value to check - * @param string $definition The definition of the type - * @return string or null - */ + /** + * Check the type "sqldatetime" + * @param string $val The value to check + * @param string $definition The definition of the type + * @return string or null + */ private function checkRealType_sqldatetime($val, $definition) { if (strlen($val) !== 19) { diff --git a/src/Encrypt.php b/src/Encrypt.php index 0bd34d4..40bf3ee 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -1,19 +1,22 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** Allow to encrypt/decrypt data - */ +/** + * Allow to encrypt/decrypt data + */ class Encrypt { - /** Check if openssl library is enabled - */ + /** + * Check if openssl library is enabled + */ public function __construct() { if (! function_exists("openssl_random_pseudo_bytes")) { @@ -24,15 +27,16 @@ class Encrypt } } - /** Encrypt the payload to not be readable by anybody - * @param string $payload The payload to encrypt - * @param string $ckey The 24 chars for the cipher key - * @param string|null $cipherMethod DES-EDE3-CBC by default - * @return encrypted payload - */ + /** + * Encrypt the payload to not be readable by anybody + * @param string $payload The payload to encrypt + * @param string $ckey The 24 chars for the cipher key + * @param string|null $cipherMethod DES-EDE3-CBC by default + * @return encrypted payload + */ public function encrypt($payload, $ckey, $cipherMethod = "des-ede3-cbc") { - if (! in_array($cipherMethod, openssl_get_cipher_methods())) { + if (! in_array($cipherMethod, openssl_get_cipher_methods(), true)) { throw new \Exception(dgettext( "domframework", "Invalid cipher provided to encrypt method : " . @@ -74,12 +78,13 @@ class Encrypt return $ciphertext; } - /** Decrypt the ciphertext - * @param string $ciphertext The payload to decrypt - * @param string $ckey The 24 chars for the cipher key - * @param string|null $cipherMethod DES-EDE3-CBC by default - * @return decrypted text - */ + /** + * Decrypt the ciphertext + * @param string $ciphertext The payload to decrypt + * @param string $ckey The 24 chars for the cipher key + * @param string|null $cipherMethod DES-EDE3-CBC by default + * @return decrypted text + */ public function decrypt($ciphertext, $ckey, $cipherMethod = "des-ede3-cbc") { if (! is_string($ciphertext)) { @@ -106,7 +111,7 @@ class Encrypt "Invalid ciphertext provided to decrypt method : empty string" ), 500); } - if (! in_array($cipherMethod, openssl_get_cipher_methods())) { + if (! in_array($cipherMethod, openssl_get_cipher_methods(), true)) { throw new \Exception(dgettext( "domframework", "Invalid cipherMethod provided to decrypt method : " . diff --git a/src/File.php b/src/File.php index a084281..01fec09 100644 --- a/src/File.php +++ b/src/File.php @@ -1,39 +1,50 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** The file method allow to manage files like PHP with a working chroot on all - * plateforms, and a right management compatible with database - * Don't follow links ! - * - * To allow an external authorization test in plus of the filesystem check, you - * must extends the class and overload checkExternalPathRO and - * checkExternalPathRW. - */ +/** + * The file method allow to manage files like PHP with a working chroot on all + * plateforms, and a right management compatible with database + * Don't follow links ! + * + * To allow an external authorization test in plus of the filesystem check, you + * must extends the class and overload checkExternalPathRO and + * checkExternalPathRW. + */ class File { - /** The virtual current working directory */ + /** + * The virtual current working directory + */ private $cwd = "."; - /** The real directory used as root in virtual chroot */ + /** + * The real directory used as root in virtual chroot + */ private $baseDir = "/"; - /** The lock stack */ - private $locks = array(); + /** + * The lock stack + */ + private $locks = []; - /** Activate the debug and define the minimum priority to save */ + /** + * Activate the debug and define the minimum priority to save + */ public $debug = 0; - /** Change the current working directory - * @param string $directory Go in the provided directory - * @return bool true if the directory is changed - * @throws If directory not exists, or the directory is not executable - */ + /** + * Change the current working directory + * @param string $directory Go in the provided directory + * @return bool true if the directory is changed + * @throws If directory not exists, or the directory is not executable + */ public function chdir($directory) { $this->debug(2, "chdir ($directory)"); @@ -48,11 +59,12 @@ class File return true; } - /** Change the group for a file/dir... - * @param string $filename The file/directory to change - * @param mixed $group The group name or group GID - * @throws If filename not exists, or the directory is not RW - */ + /** + * Change the group for a file/dir... + * @param string $filename The file/directory to change + * @param mixed $group The group name or group GID + * @throws If filename not exists, or the directory is not RW + */ public function chgrp($filename, $group) { $this->debug(2, "chgrp ($filename, $group)"); @@ -81,11 +93,12 @@ class File return $rc; } - /** Change the rights mode for a file/dir... - * @param string $filename The file/directory to change - * @param integer $mode The mode to use for the filename - * @throws If filename not exists, or the directory is not RW - */ + /** + * Change the rights mode for a file/dir... + * @param string $filename The file/directory to change + * @param integer $mode The mode to use for the filename + * @throws If filename not exists, or the directory is not RW + */ public function chmod($filename, $mode) { $this->debug(2, "chmod ($filename, $mode)"); @@ -114,11 +127,12 @@ class File return $rc; } - /** Change the owner for a file/dir... - * @param string $filename The file/directory to change - * @param mixed $user The user name or user UID - * @throws If filename not exists, or the directory is not RW - */ + /** + * Change the owner for a file/dir... + * @param string $filename The file/directory to change + * @param mixed $user The user name or user UID + * @throws If filename not exists, or the directory is not RW + */ public function chown($filename, $user) { $this->debug(2, "chown ($filename, $user)"); @@ -160,11 +174,12 @@ class File return $rc; } - /** Chroot in the provided directory - * @param string $directory The directory to chroot - * @return boolean true if the chroot is done, false if there is a failure - * @throws If directory not exists, or the directory is not executable - */ + /** + * Chroot in the provided directory + * @param string $directory The directory to chroot + * @return boolean true if the chroot is done, false if there is a failure + * @throws If directory not exists, or the directory is not executable + */ public function chroot($directory) { // Use the checkPathRO (using the $this->baseDir) to not allow to go away of @@ -178,13 +193,14 @@ class File return true; } - /** Get the file contents in an array (like 'file' function, but can not - * have the same name as the class...) - * @param string $filename Name of the file to read - * @return string Content of the file - * @throws If parent directory not exists, is not readable, the file is not - * exists or is not readable - */ + /** + * Get the file contents in an array (like 'file' function, but can not + * have the same name as the class...) + * @param string $filename Name of the file to read + * @return string Content of the file + * @throws If parent directory not exists, is not readable, the file is not + * exists or is not readable + */ public function fileArray($filename) { $this->debug(2, "file ($filename)"); @@ -213,11 +229,12 @@ class File return $contents; } - /** Checks whether a file or directory exists - * @param string $filename The file or directory to verify - * @return bool true if the file exists, false otherwise - * @throws If parent directory not exists, or is not executable - */ + /** + * Checks whether a file or directory exists + * @param string $filename The file or directory to verify + * @return bool true if the file exists, false otherwise + * @throws If parent directory not exists, or is not executable + */ public function file_exists($filename) { $this->debug(2, "file_exists ($filename)"); @@ -235,12 +252,13 @@ class File return false; } - /** Get the file contents - * @param string $filename Name of the file to read - * @return string Content of the file - * @throws If parent directory not exists, is not readable, the file is not - * exists or is not readable - */ + /** + * Get the file contents + * @param string $filename Name of the file to read + * @return string Content of the file + * @throws If parent directory not exists, is not readable, the file is not + * exists or is not readable + */ public function file_get_contents($filename) { $this->debug(2, "file_get_contents ($filename)"); @@ -270,14 +288,15 @@ class File return $contents; } - /** Write a string to a file - * @param string $filename Path to the file where to write the data - * @param string|integer $data The data to write - * @param integer|null $flags The optional flags - * @return integer the length of the data stored - * @throws If parent directory not exists, is not writeable, or the file - * exists and is not writeable - */ + /** + * Write a string to a file + * @param string $filename Path to the file where to write the data + * @param string|integer $data The data to write + * @param integer|null $flags The optional flags + * @return integer the length of the data stored + * @throws If parent directory not exists, is not writeable, or the file + * exists and is not writeable + */ public function file_put_contents($filename, $data, $flags = 0) { $this->debug(2, "file_put_contents ($filename)"); @@ -307,13 +326,14 @@ class File return $contents; } - /** Get the file modification time of a file - * @param string $filename Path to the file - * @return integer|boolean the time the file was last modified, or FALSE - * on failure. The time is returned as a Unix timestamp, which is suitable - * for the date() function. - * @throws If parent directory not exists, is not writeable - */ + /** + * Get the file modification time of a file + * @param string $filename Path to the file + * @return integer|boolean the time the file was last modified, or FALSE + * on failure. The time is returned as a Unix timestamp, which is suitable + * for the date() function. + * @throws If parent directory not exists, is not writeable + */ public function filemtime($filename) { $this->debug(2, "filemtime ($filename)"); @@ -322,11 +342,12 @@ class File return filemtime($filename); } - /** Get the file size - * @param string $filename Path to the file - * @return integer|boolean the size of the file or FALSE on failure. - * @throws If parent directory not exists, is not writeable - */ + /** + * Get the file size + * @param string $filename Path to the file + * @return integer|boolean the size of the file or FALSE on failure. + * @throws If parent directory not exists, is not writeable + */ public function filesize($filename) { $this->debug(2, "filesize ($filename)"); @@ -335,11 +356,12 @@ class File return filesize($filename); } - /** Get the file info of the provided filename - * @param string $filename Path to the file - * @return string the mimetype of the file - * @throws If parent directory not exists, is not writeable - */ + /** + * Get the file info of the provided filename + * @param string $filename Path to the file + * @return string the mimetype of the file + * @throws If parent directory not exists, is not writeable + */ public function fileinfoMimeType($filename) { $this->debug(2, "filesize ($filename)"); @@ -349,22 +371,25 @@ class File return $finfo->file($filename); } - /** Return the current working directory - * @return string the current working directory */ + /** + * Return the current working directory + * @return string the current working directory + */ public function getcwd() { $this->debug(1, "getcwd $this->cwd"); return $this->cwd; } - /** Find pathnames matching a pattern - * If there is some unreadable files, skip them quietly - * @param string $pattern The pattern to found - * @param integer|null $flags The additional flags - * @return array Return an array if there is an error - * @throws If parent directory not exists, or is not executable - * or if there is one file unreadable - */ + /** + * Find pathnames matching a pattern + * If there is some unreadable files, skip them quietly + * @param string $pattern The pattern to found + * @param integer|null $flags The additional flags + * @return array Return an array if there is an error + * @throws If parent directory not exists, or is not executable + * or if there is one file unreadable + */ public function glob($pattern, $flags = 0) { $this->debug(2, "glob ($pattern, $flags)"); @@ -396,12 +421,13 @@ class File return $files; } - /** Tells whether the given filename is a directory - * @param string $filename The filename to test - * @return bool true if the $filename is a directory and exists, false - * otherwise - * @throws If parent directory not exists, or is not executable - */ + /** + * Tells whether the given filename is a directory + * @param string $filename The filename to test + * @return bool true if the $filename is a directory and exists, false + * otherwise + * @throws If parent directory not exists, or is not executable + */ public function is_dir($filename) { $this->debug(2, "is_dir ($filename)"); @@ -413,11 +439,12 @@ class File return false; } - /** Tells whether the given filename is a valid file - * @param string $filename The filename to test - * @return bool true if the $filename is a file and exists, false otherwise - * @throws If parent directory not exists, or is not executable - */ + /** + * Tells whether the given filename is a valid file + * @param string $filename The filename to test + * @return bool true if the $filename is a file and exists, false otherwise + * @throws If parent directory not exists, or is not executable + */ public function is_file($filename) { $this->debug(2, "is_file ($filename)"); @@ -429,11 +456,12 @@ class File return false; } - /** Tells whether a file exists and is executable - * @param string $filename The filename to test - * @return bool true if the $filename is a file exists and is writeable - * @throws If parent directory not exists, or is not executable - */ + /** + * Tells whether a file exists and is executable + * @param string $filename The filename to test + * @return bool true if the $filename is a file exists and is writeable + * @throws If parent directory not exists, or is not executable + */ public function is_executable($filename) { $this->debug(2, "is_executable ($filename)"); @@ -445,11 +473,12 @@ class File return false; } - /** Tells whether a file exists and is readable - * @param string $filename The filename to test - * @return bool true if the $filename is a file exists and is readable - * @throws If parent directory not exists, or is not executable - */ + /** + * Tells whether a file exists and is readable + * @param string $filename The filename to test + * @return bool true if the $filename is a file exists and is readable + * @throws If parent directory not exists, or is not executable + */ public function is_readable($filename) { $this->debug(2, "is_readable ($filename)"); @@ -461,11 +490,12 @@ class File return false; } - /** Tells whether a file exists and is writeable - * @param string $filename The filename to test - * @return bool true if the $filename is a file exists and is writeable - * @throws If parent directory not exists, or is not executable - */ + /** + * Tells whether a file exists and is writeable + * @param string $filename The filename to test + * @return bool true if the $filename is a file exists and is writeable + * @throws If parent directory not exists, or is not executable + */ public function is_writeable($filename) { $this->debug(2, "is_writeable ($filename)"); @@ -477,11 +507,12 @@ class File return false; } - /** Lock a file exclusively - * @param string $filename The file to lock - * @return bool true if the lock is acquired, false otherwise - * @throws If parent directory not exists, or is not writeable - */ + /** + * Lock a file exclusively + * @param string $filename The file to lock + * @return bool true if the lock is acquired, false otherwise + * @throws If parent directory not exists, or is not writeable + */ public function lockEX($filename) { $this->debug(2, "lockEX ($filename)"); @@ -509,11 +540,12 @@ class File return flock($this->locks[$filename], LOCK_EX); } - /** Lock a file shared (allow multiple read) - * @param string $filename The file to lock - * @return bool true if the lock is acquired, false otherwise - * @throws If parent directory not exists, or is not writeable - */ + /** + * Lock a file shared (allow multiple read) + * @param string $filename The file to lock + * @return bool true if the lock is acquired, false otherwise + * @throws If parent directory not exists, or is not writeable + */ public function lockSH($filename) { $this->debug(2, "lockSH ($filename)"); @@ -541,11 +573,12 @@ class File return flock($this->locks[$filename], LOCK_SH); } - /** Unlock a file previously locked - * @param string $filename The file to lock - * @return bool true if the lock is acquired, false otherwise - * @throws If parent directory not exists, or is not writeable - */ + /** + * Unlock a file previously locked + * @param string $filename The file to lock + * @return bool true if the lock is acquired, false otherwise + * @throws If parent directory not exists, or is not writeable + */ public function lockUN($filename) { $this->debug(2, "lockUN ($filename)"); @@ -560,11 +593,12 @@ class File return $res; } - /** Calculate the md5 sum of a file - * @param string $filename The file to hash - * @return string the calulated hash - * @throws If the file doesn't exists - */ + /** + * Calculate the md5 sum of a file + * @param string $filename The file to hash + * @return string the calulated hash + * @throws If the file doesn't exists + */ public function md5_file($filename) { $this->debug(2, "md5_file ($filename)"); @@ -591,14 +625,15 @@ class File return md5_file($filename); } - /** Create a new directory - * @param string $pathname The directory to create - * @param integer $mode The mode to create (0777 by default) - * @param boolean $recursive (false by default) - * @return bool true if the directory is correctely created, false if the - * directory already exists - * @throws If parent directory not exists, is not writeable - */ + /** + * Create a new directory + * @param string $pathname The directory to create + * @param integer $mode The mode to create (0777 by default) + * @param boolean $recursive (false by default) + * @return bool true if the directory is correctely created, false if the + * directory already exists + * @throws If parent directory not exists, is not writeable + */ public function mkdir($pathname, $mode = 0777, $recursive = false) { $this->debug(2, "mkdir ($pathname, $mode, $recursive)"); @@ -642,12 +677,13 @@ class File return $rc; } - /** Copy a file or a directory - * @param string $oldname The file to copy - * @param string $newname The new name of the file. It will be - * overwrited if it already exists - * @return bool - */ + /** + * Copy a file or a directory + * @param string $oldname The file to copy + * @param string $newname The new name of the file. It will be + * overwrited if it already exists + * @return bool + */ public function copy($oldname, $newname) { $this->debug(2, "copy ($oldname, $newname)"); @@ -671,12 +707,13 @@ class File return $rc; } - /** Renames a file or directory - * @param string $oldname The file or directory to rename - * @param string $newname The new name of the file or directory. It will be - * overwrited if it already exists - * @return bool - */ + /** + * Renames a file or directory + * @param string $oldname The file or directory to rename + * @param string $newname The new name of the file or directory. It will be + * overwrited if it already exists + * @return bool + */ public function rename($oldname, $newname) { $this->debug(2, "rename ($oldname, $newname)"); @@ -689,11 +726,12 @@ class File return $rc; } - /** Return a ini file converted to an array - * @param string $filename The filename of the ini file being parsed. - * @param boolean $process_sections Process the sections - * @return array - */ + /** + * Return a ini file converted to an array + * @param string $filename The filename of the ini file being parsed. + * @param boolean $process_sections Process the sections + * @return array + */ public function parse_ini_file($filename, $process_sections = false) { $this->debug(2, "parse_ini_file ($filename, $process_sections)"); @@ -720,11 +758,12 @@ class File return parse_ini_file($filename, $process_sections); } - /** Return the canonical absolute path. Do not check if the directory exists, - * if there is links. Just calculate the realpath based on the chroot value - * @param string $path the path to analyze - * @return string the canonical absolute path - */ + /** + * Return the canonical absolute path. Do not check if the directory exists, + * if there is links. Just calculate the realpath based on the chroot value + * @param string $path the path to analyze + * @return string the canonical absolute path + */ public function realpath($path) { $oriPath = $path; @@ -738,7 +777,7 @@ class File $tmp = explode("/", $current); foreach ($parts as $part) { if ($part === "") { - $tmp = array(); + $tmp = []; } elseif ($part === ".") { continue; } elseif ($part === "..") { @@ -765,15 +804,16 @@ class File return $path; } - /** Remove the provided directory - * If the recurse flag is true, remove the content too (files and - * directories) - * @param string $dirname The directory to remove - * @param boolean $recursive Remove recursively - * @return bool true if all is removed, false otherwise - * @throws If parent directory not exists, is not writeable or the current - * dir is not writeable - */ + /** + * Remove the provided directory + * If the recurse flag is true, remove the content too (files and + * directories) + * @param string $dirname The directory to remove + * @param boolean $recursive Remove recursively + * @return bool true if all is removed, false otherwise + * @throws If parent directory not exists, is not writeable or the current + * dir is not writeable + */ public function rmdir($dirname, $recursive = false) { $this->debug(2, "rmdir ($dirname, $recursive)"); @@ -783,7 +823,7 @@ class File if ($recursive === false) { return @rmdir($tmpdirname); } - $files = array_diff(scandir($tmpdirname), array(".", "..")); + $files = array_diff(scandir($tmpdirname), [".", ".."]); foreach ($files as $file) { if (is_dir("$tmpdirname/$file")) { $this->rmdir("$dirname/$file", $recursive); @@ -794,30 +834,32 @@ class File return rmdir($tmpdirname); } - /** Return the list of files and directories in the directory. - * Do not return the . and .. virtual dirs. - * The result is sorted - * @param string $directory The directory to read - * @return array the list of files and dirs - * @throws If directory not exists, or is not executable - */ + /** + * Return the list of files and directories in the directory. + * Do not return the . and .. virtual dirs. + * The result is sorted + * @param string $directory The directory to read + * @return array the list of files and dirs + * @throws If directory not exists, or is not executable + */ public function scandir($directory) { $this->debug(2, "scandir ($directory)"); $directory = $this->realpath($directory); $this->checkPathRO($directory); - $res = array_values(array_diff(scandir($directory), array('..', '.'))); + $res = array_values(array_diff(scandir($directory), ['..', '.'])); natsort($res); return $res; } - /** Return the list of files and directories in the directory. - * Do not return the . and .. virtual dirs. - * The result is NOT sorted - * @param string $directory The directory to read - * @return array the list of files and dirs - * @throws If directory not exists, or is not executable - */ + /** + * Return the list of files and directories in the directory. + * Do not return the . and .. virtual dirs. + * The result is NOT sorted + * @param string $directory The directory to read + * @return array the list of files and dirs + * @throws If directory not exists, or is not executable + */ public function scandirNotSorted($directory) { $this->debug(2, "scandirNotSorted ($directory)"); @@ -825,16 +867,17 @@ class File $this->checkPathRO($directory); $res = array_values(array_diff( scandir($directory, SCANDIR_SORT_NONE), - array('..', '.') + ['..', '.'] )); return $res; } - /** Calculate the sha1 sum of a file - * @param string $filename The file to hash - * @return string the calulated hash - * @throws If the file doesn't exists - */ + /** + * Calculate the sha1 sum of a file + * @param string $filename The file to hash + * @return string the calulated hash + * @throws If the file doesn't exists + */ public function sha1_file($filename) { $this->debug(2, "sha1_file ($filename)"); @@ -861,15 +904,16 @@ class File return sha1_file($filename); } - /** Create a new file or update the timestamp if the file exists - * @param string $filename the filename - * @param integer|null $time the timestamp to use (actual timestamp if not - * defined) - * @param integer|null $atime the access timestamp to use (actual timestamp - * if not defined) - * @return bool true or false on failure - * @throws If parent directory not exists, is not writeable - */ + /** + * Create a new file or update the timestamp if the file exists + * @param string $filename the filename + * @param integer|null $time the timestamp to use (actual timestamp if not + * defined) + * @param integer|null $atime the access timestamp to use (actual timestamp + * if not defined) + * @return bool true or false on failure + * @throws If parent directory not exists, is not writeable + */ public function touch($filename, $time = null, $atime = null) { $this->debug(2, "touch ($filename, $time, $atime)"); @@ -886,11 +930,12 @@ class File return $rc; } - /** Delete an existing file. - * @param string $filename The filename to remove - * @return bool true if the file si removed, false otherwise - * @throws If parent directory not exists, or is not executable - */ + /** + * Delete an existing file. + * @param string $filename The filename to remove + * @return bool true if the file si removed, false otherwise + * @throws If parent directory not exists, or is not executable + */ public function unlink($filename) { $this->debug(2, "unlink ($filename)"); @@ -902,15 +947,16 @@ class File return unlink($filename); } - /** Check all the parents of the $directory if they are available, and - * executable. The path must exists. - * Must use the filesystem path (complete) and not the version in chroot. - * The last directoy must be executable and readable (no test for writeable) - * @param string $path The directory path to check - * @return boolean true if the path is executable for all the parents and - * for the last directory - * @throws if there is a missing part, or a parent is not executable - */ + /** + * Check all the parents of the $directory if they are available, and + * executable. The path must exists. + * Must use the filesystem path (complete) and not the version in chroot. + * The last directoy must be executable and readable (no test for writeable) + * @param string $path The directory path to check + * @return boolean true if the path is executable for all the parents and + * for the last directory + * @throws if there is a missing part, or a parent is not executable + */ private function checkPathRO($path) { $this->debug(2, "checkPathRO ($path)"); @@ -1007,15 +1053,16 @@ class File return $this->checkExternalPathRO($path); } - /** Check all the parents of the $directory if they are available, and - * executable. The path must exists. - * Must use the filesystem path (complete) and not the version in chroot. - * The last directoy must be executable and readable and writeable - * @param string $path The directory path to check - * @return true if the path is executable for all the parents and for the - * last directory - * @throws if there is a missing part, or a parent is not executable - */ + /** + * Check all the parents of the $directory if they are available, and + * executable. The path must exists. + * Must use the filesystem path (complete) and not the version in chroot. + * The last directoy must be executable and readable and writeable + * @param string $path The directory path to check + * @return true if the path is executable for all the parents and for the + * last directory + * @throws if there is a missing part, or a parent is not executable + */ private function checkPathRW($path) { $this->debug(2, "checkPathRW ($path)"); @@ -1047,12 +1094,13 @@ class File return true; } - /** Save a debug log - * @param integer $prio The message priority. Should be higher than - * $this->debug to save the message - * @param string $message The message to save - * @return null - */ + /** + * Save a debug log + * @param integer $prio The message priority. Should be higher than + * $this->debug to save the message + * @param string $message The message to save + * @return null + */ private function debug($prio, $message) { if ($this->debug === false || $this->debug === 0) { @@ -1066,21 +1114,23 @@ class File } } - /** External function allowed to be overloaded to test the RO access to a - * resource - * @param string $path The path to test in the filesystem - * @return boolean true if RO access, false if not - */ + /** + * External function allowed to be overloaded to test the RO access to a + * resource + * @param string $path The path to test in the filesystem + * @return boolean true if RO access, false if not + */ public function checkExternalPathRO($path) { return true; } - /** External function allowed to be overloaded to test the RW access to a - * resource - * @param string $path The path to test in the filesystem - * @return boolean true if RW access, false if not - */ + /** + * External function allowed to be overloaded to test the RW access to a + * resource + * @param string $path The path to test in the filesystem + * @return boolean true if RW access, false if not + */ public function checkExternalPathRW($path) { return true; diff --git a/src/Fork.php b/src/Fork.php index 3d469d4..facd842 100644 --- a/src/Fork.php +++ b/src/Fork.php @@ -1,23 +1,27 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** Manage the fork of children in Posix mode - */ +/** + * Manage the fork of children in Posix mode + */ class Fork { - /** The PID list of childs - */ - private $pidList = array(); + /** + * The PID list of childs + */ + private $pidList = []; - /** The constructor check if the posix functions exists - */ + /** + * The constructor check if the posix functions exists + */ public function __construct() { if (! function_exists("pcntl_fork")) { @@ -33,28 +37,31 @@ class Fork } } - /** Return the number of active PID - */ + /** + * Return the number of active PID + */ public function childCount() { return count($this->pidList); } - /** Return the list of the active PID - */ + /** + * Return the list of the active PID + */ public function childList() { return $this->pidList; } - /** Create a child - * If some parameters are provided, the called child method will receive them - * This function fork and return the child PID - * @param callable $callable The callback method to use in child - * @param mixed|null $params The params to provide to child method - * @return The child PID - */ - public function startChild($callable, $params = array()) + /** + * Create a child + * If some parameters are provided, the called child method will receive them + * This function fork and return the child PID + * @param callable $callable The callback method to use in child + * @param mixed|null $params The params to provide to child method + * @return The child PID + */ + public function startChild($callable, $params = []) { $pid = pcntl_fork(); if ($pid === -1) { @@ -71,16 +78,17 @@ class Fork exit; } - /** Create a detached child. The terminal is closed. All the displayed - * messages from the child are silently dropped. - * If some parameters are provided, the called child method will receive them - * This function fork and return the child PID - * @param string $name The name displayed in the processus list - * @param callable $callable The callback method to use in child - * @param mixed|null $params The params to provide to child method - * @return The child PID - */ - public function startDetachedChild($name, $callable, $params = array()) + /** + * Create a detached child. The terminal is closed. All the displayed + * messages from the child are silently dropped. + * If some parameters are provided, the called child method will receive them + * This function fork and return the child PID + * @param string $name The name displayed in the processus list + * @param callable $callable The callback method to use in child + * @param mixed|null $params The params to provide to child method + * @return The child PID + */ + public function startDetachedChild($name, $callable, $params = []) { $pid = pcntl_fork(); if ($pid === -1) { @@ -116,9 +124,10 @@ class Fork exit; } - /** Wait the end of one child - * Return the PID of the dead child - */ + /** + * Wait the end of one child + * Return the PID of the dead child + */ public function waitEndChild() { while (1) { @@ -131,8 +140,9 @@ class Fork } } - /** Clean the childs which are finished. Do not block the process - */ + /** + * Clean the childs which are finished. Do not block the process + */ public function cleanEndChild() { $stoppedPid = pcntl_wait($status, WNOHANG); @@ -142,15 +152,16 @@ class Fork } } - /** Stop (SIGTERM) a specific child. - * If the $maxWait parameter is set, wait the dead of the child for $maxWait - * seconds. If $maxWait is not set, do not wait the child, only send it the - * signal - * @param integer $pid The PID of the child to stop - * @param integer|null $maxWait The maximum time to wait the child if set - * @return $pid if the child is dead correctely. Return false if the child is - * not dead in the $maxWait time - */ + /** + * Stop (SIGTERM) a specific child. + * If the $maxWait parameter is set, wait the dead of the child for $maxWait + * seconds. If $maxWait is not set, do not wait the child, only send it the + * signal + * @param integer $pid The PID of the child to stop + * @param integer|null $maxWait The maximum time to wait the child if set + * @return $pid if the child is dead correctely. Return false if the child is + * not dead in the $maxWait time + */ public function stopChild($pid, $maxWait = null) { if (! key_exists($pid, $this->pidList)) { @@ -162,15 +173,16 @@ class Fork return $this->sendSignalToChild(SIGTERM, $pid, $maxWait); } - /** Kill (SIGKILL) a specific child. - * If the $maxWait parameter is set, wait the dead of the child for $maxWait - * seconds. If $maxWait is not set, do not wait the child, only send it the - * signal - * @param integer $pid The PID of the child to stop - * @param integer|null $maxWait The maximum time to wait the child if set - * @return $pid if the child is dead correctely. Return false if the child is - * not dead in the $maxWait time - */ + /** + * Kill (SIGKILL) a specific child. + * If the $maxWait parameter is set, wait the dead of the child for $maxWait + * seconds. If $maxWait is not set, do not wait the child, only send it the + * signal + * @param integer $pid The PID of the child to stop + * @param integer|null $maxWait The maximum time to wait the child if set + * @return $pid if the child is dead correctely. Return false if the child is + * not dead in the $maxWait time + */ public function killChild($pid, $maxWait = null) { if (! key_exists($pid, $this->pidList)) { @@ -182,16 +194,17 @@ class Fork return $this->sendSignalToChild(SIGKILL, $pid, $maxWait); } - /** Send a signal to a specific child. - * If the $maxWait parameter is set, wait the dead of the child for $maxWait - * seconds. If $maxWait is not set, do not wait the child, only send it the - * signal - * @param integer $signal The signal to send to child (SIGTERM or SIGKILL) - * @param integer $pid The PID of the child to stop - * @param integer|null $maxWait The maximum time to wait the child if set - * @return $pid if the child is dead correctely. Return false if the child is - * not dead in the $maxWait time - */ + /** + * Send a signal to a specific child. + * If the $maxWait parameter is set, wait the dead of the child for $maxWait + * seconds. If $maxWait is not set, do not wait the child, only send it the + * signal + * @param integer $signal The signal to send to child (SIGTERM or SIGKILL) + * @param integer $pid The PID of the child to stop + * @param integer|null $maxWait The maximum time to wait the child if set + * @return $pid if the child is dead correctely. Return false if the child is + * not dead in the $maxWait time + */ private function sendSignalToChild($signal, $pid, $maxWait = null) { posix_kill($pid, $signal); @@ -209,41 +222,44 @@ class Fork return $pid; } - /** Stop all the existing children. - * If the $maxWait parameter is set, wait the dead of the child for $maxWait - * seconds. If $maxWait is not set, do not wait the child, only send it the - * signal - * @param integer|null $maxWait The maximum time to wait the child if set - * @return true if all the children are dead correctely. Return false if at - * least one child isnot dead in the $maxWait time - */ + /** + * Stop all the existing children. + * If the $maxWait parameter is set, wait the dead of the child for $maxWait + * seconds. If $maxWait is not set, do not wait the child, only send it the + * signal + * @param integer|null $maxWait The maximum time to wait the child if set + * @return true if all the children are dead correctely. Return false if at + * least one child isnot dead in the $maxWait time + */ public function stopAll($maxWait = null) { return $this->sendSigToAll(SIGTERM, $maxWait); } - /** Kill all the existing children. - * If the $maxWait parameter is set, wait the dead of the child for $maxWait - * seconds. If $maxWait is not set, do not wait the child, only send it the - * signal - * @param integer|null $maxWait The maximum time to wait the child if set - * @return true if all the children are dead correctely. Return false if at - * least one child isnot dead in the $maxWait time - */ + /** + * Kill all the existing children. + * If the $maxWait parameter is set, wait the dead of the child for $maxWait + * seconds. If $maxWait is not set, do not wait the child, only send it the + * signal + * @param integer|null $maxWait The maximum time to wait the child if set + * @return true if all the children are dead correctely. Return false if at + * least one child isnot dead in the $maxWait time + */ public function killAll($maxWait = null) { return $this->sendSigToAll(SIGKILL, $maxWait); } - /** Send a stop or kill signal to all the existing children. - * If the $maxWait parameter is set, wait the dead of the child for $maxWait - * seconds. If $maxWait is not set, do not wait the child, only send it the - * signal - * @param integer $signal The signal to send to child (SIGTERM or SIGKILL) - * @param integer|null $maxWait The maximum time to wait the child if set - * @return true if all the children are dead correctely. Return false if at - * least one child isnot dead in the $maxWait time - */ + /** + * Send a stop or kill signal to all the existing children. + * If the $maxWait parameter is set, wait the dead of the child for $maxWait + * seconds. If $maxWait is not set, do not wait the child, only send it the + * signal + * @param integer $signal The signal to send to child (SIGTERM or SIGKILL) + * @param integer|null $maxWait The maximum time to wait the child if set + * @return true if all the children are dead correctely. Return false if at + * least one child isnot dead in the $maxWait time + */ private function sendSigToAll($signal, $maxWait = null) { foreach ($this->pidList as $pid) { diff --git a/src/Form.php b/src/Form.php index d7efa75..498ff61 100644 --- a/src/Form.php +++ b/src/Form.php @@ -1,161 +1,187 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** This class permit to create easily some forms to HTML (or text mode in - * future). - * Each field can be checked in AJAX or HTML. - */ +/** + * This class permit to create easily some forms to HTML (or text mode in + * future). + * Each field can be checked in AJAX or HTML. + */ class Form { - /** All the fields - */ + /** + * All the fields + */ private $fields = null; - /** The name of the form - */ + /** + * The name of the form + */ private $formName; - /** Allow to debug the PHP - */ + /** + * Allow to debug the PHP + */ public $debug = 0; - /** CSRF protection - * By default, the CSRF protection is active if a SESSION is active too. - * It can be disabled if needed. An Exception is raised if the form is send - * back without the token - */ + /** + * CSRF protection + * By default, the CSRF protection is active if a SESSION is active too. + * It can be disabled if needed. An Exception is raised if the form is send + * back without the token + */ public $csrf = true; - /** Name of the CSRF hidden field in HTML page - */ + /** + * Name of the CSRF hidden field in HTML page + */ public $csrfField = "CSRF_TOKEN"; - /** The CSRF token value - */ + /** + * The CSRF token value + */ private $csrfToken = ""; - /** The method used to send the values - */ + /** + * The method used to send the values + */ private $method = "post"; - /** The Bootstrap width of the column of titles - */ + /** + * The Bootstrap width of the column of titles + */ public $titlewidth = 2; - /** The Bootstrap width of the column of fields - */ + /** + * The Bootstrap width of the column of fields + */ public $fieldwidth = 10; - /** Define a class for form object - */ + /** + * Define a class for form object + */ public $formClass = "form-horizontal"; - /** The logging callable method - */ + /** + * The logging callable method + */ private $loggingCallable = null; - /** The logging basemsg - */ + /** + * The logging basemsg + */ private $loggingBasemsg = ""; - /** Form template (Bootstrap3 by default) - */ + /** + * Form template (Bootstrap3 by default) + */ private $formTemplate = "Bootstrap3"; - /** Create a form - * @param string|null $formName The form name - */ + /** + * Create a form + * @param string|null $formName The form name + */ public function __construct($formName = "form") { $this->formName = $formName; } // The setters of the properties - /** Set the debug level - * @param integer $val The debug value - */ + /** + * Set the debug level + * @param integer $val The debug value + */ public function debug($val) { $this->debug = $val; return $this; } - /** Set the csrf enable - * @param integer $val The csrf check - */ + /** + * Set the csrf enable + * @param integer $val The csrf check + */ public function csrf($val) { $this->csrf = !! $val; return $this; } - /** Set the method - * @param string $val The method to use - */ + /** + * Set the method + * @param string $val The method to use + */ public function method($val) { $this->method = strtolower($val); return $this; } - /** Set the csrf token name - * @param integer $val The csrf token name - */ + /** + * Set the csrf token name + * @param integer $val The csrf token name + */ public function csrfField($val) { $this->csrfField = $val; return $this; } - /** Set the titlewidth - * @param integer $val The titlewidth - */ + /** + * Set the titlewidth + * @param integer $val The titlewidth + */ public function titlewidth($val) { $this->titlewidth = $val; return $this; } - /** Set the fieldwidth - * @param integer $val The fieldwidth - */ + /** + * Set the fieldwidth + * @param integer $val The fieldwidth + */ public function fieldwidth($val) { $this->fieldwidth = $val; return $this; } - /** Set the formClass - * @param integer $val The formClass - */ + /** + * Set the formClass + * @param integer $val The formClass + */ public function formClass($val) { $this->formClass = $val; return $this; } - /** Set logging class an method - * @param callable $loggingCallable The callable function. This method will - * receive two params : the LOG level (LOG_ERROR...) and the message - * @param string|null $loggingBasemsg The basemsg added at the beginning of - * the log - */ + /** + * Set logging class an method + * @param callable $loggingCallable The callable function. This method will + * receive two params : the LOG level (LOG_ERROR...) and the message + * @param string|null $loggingBasemsg The basemsg added at the beginning of + * the log + */ public function logging($loggingCallable, $loggingBasemsg = "") { $this->loggingCallable = $loggingCallable; $this->loggingBasemsg = $loggingBasemsg; } - /** Set the Form Templating to use. - * Can be : Bootstrap3, Bootstrap4 (later Bulma) - * @param string $formTemplate The template to use - */ + /** + * Set the Form Templating to use. + * Can be : Bootstrap3, Bootstrap4 (later Bulma) + * @param string $formTemplate The template to use + */ public function formTemplate($formTemplate) { if ( ! in_array( $formTemplate, - array("Bootstrap3", "Bootstrap4") + ["Bootstrap3", "Bootstrap4"], + true ) ) { throw new \Exception("Unknown formTemplate provided", 500); @@ -164,10 +190,11 @@ class Form return $this; } - /** The private method to log if the $this->loggingCallable is defined - * @param integer $prio The priority of the message - * @param string $msg The message to store - */ + /** + * The private method to log if the $this->loggingCallable is defined + * @param integer $prio The priority of the message + * @param string $msg The message to store + */ private function loggingCallable($prio, $msg) { if (! is_callable($this->loggingCallable)) { @@ -180,55 +207,58 @@ class Form call_user_func($this->loggingCallable, $prio, $base . $msg); } - /** Save the array of fields into the structure. - * Available : - * - name : name of the field in the HTML page - * - label : label written to the describe the field - * - [titles] : text written in radio/checkboxes - * - [defaults] : default values. Must be array for checkbox/select, and - * string for others - * - [type] : text, password, hidden, checkbox, select, radio, submit, - * textarea - * text by default - * - [help] : The Help message (written below the field). Overwrited in - * case of error - * - [multiple] : Multiple selection are possible (if the type supports it) - * - [group] : define a fieldset and define the title with groupe name - * Warning : all the elements of the same group must be - * consecutive ! - * - [readonly] : put a read-only flag on the field (the user see it but - * can't interract on it. The value will be sent to next - * page - * - [mandatory] : boolean to add a red star at end of label - * - [hidden] : hide the field (add a style='display:hidden' to the field) - * - [maxlength] : the maximum length of the content of the field in chars - * - [rows] : Number of rows - * - [cols] : Number of columns - * - [placeholder] : The text to be displayed in the placeholder - * - * @param array $fields The fields to be displayed - */ + /** + * Save the array of fields into the structure. + * Available : + * - name : name of the field in the HTML page + * - label : label written to the describe the field + * - [titles] : text written in radio/checkboxes + * - [defaults] : default values. Must be array for checkbox/select, and + * string for others + * - [type] : text, password, hidden, checkbox, select, radio, submit, + * textarea + * text by default + * - [help] : The Help message (written below the field). Overwrited in + * case of error + * - [multiple] : Multiple selection are possible (if the type supports it) + * - [group] : define a fieldset and define the title with groupe name + * Warning : all the elements of the same group must be + * consecutive ! + * - [readonly] : put a read-only flag on the field (the user see it but + * can't interract on it. The value will be sent to next + * page + * - [mandatory] : boolean to add a red star at end of label + * - [hidden] : hide the field (add a style='display:hidden' to the field) + * - [maxlength] : the maximum length of the content of the field in chars + * - [rows] : Number of rows + * - [cols] : Number of columns + * - [placeholder] : The text to be displayed in the placeholder + * + * @param array $fields The fields to be displayed + */ public function fields($fields) { $this->fields = $fields; } - /** Add a field to the form. For the details of a field, see the description - * in fields method - * @param object $field The field to add - */ + /** + * Add a field to the form. For the details of a field, see the description + * in fields method + * @param object $field The field to add + */ public function addfield($field) { $this->fields[] = $field; } - /** Return the values provided by the user. Test the CSRF before continue - * NEVER read the values from $_POST in your codes or CSRF will not be - * checked - */ + /** + * Return the values provided by the user. Test the CSRF before continue + * NEVER read the values from $_POST in your codes or CSRF will not be + * checked + */ public function values() { - $values = array(); + $values = []; if ($this->method === "post") { if (isset($_POST[$this->formName])) { $values = $_POST[$this->formName]; @@ -283,20 +313,21 @@ class Form return $values; } - /** Return the fields in HTML code. If $values is provided, use it in place - * of default values. In case of select boxes, $values are the selected - * elements - * $method is the method written in method field of
- * @param string|null $method The method to use to transmit the form (POST, - * GET) - * @param array|null $values The default values of the fields - * @param array|null $errors The fields to put in error with the associated - * message - */ + /** + * Return the fields in HTML code. If $values is provided, use it in place + * of default values. In case of select boxes, $values are the selected + * elements + * $method is the method written in method field of + * @param string|null $method The method to use to transmit the form (POST, + * GET) + * @param array|null $values The default values of the fields + * @param array|null $errors The fields to put in error with the associated + * message + */ public function printHTML( $method = 'post', $values = null, - $errors = array() + $errors = [] ) { if (count($this->fields) === 0) { $this->loggingCallable( @@ -360,7 +391,7 @@ class Form if (is_array($errors[$field->name])) { $field->errors = $errors[$field->name]; } else { - $field->errors = array("error", $errors[$field->name]); + $field->errors = ["error", $errors[$field->name]]; } if ($field->type === "hidden") { $field->type = "text"; @@ -421,9 +452,10 @@ class Form return $res; } - /** Check the token from the user - * @param string $tokenFromUser The value form the user's token - */ + /** + * Check the token from the user + * @param string $tokenFromUser The value form the user's token + */ public function checkToken($tokenFromUser) { $csrf = new Csrf(); @@ -433,8 +465,9 @@ class Form $csrf->checkThenDeleteToken($tokenFromUser); } - /** Return the token generated in form - */ + /** + * Return the token generated in form + */ public function getToken() { if ($this->csrfToken === "") { @@ -443,22 +476,23 @@ class Form return $this->csrfToken; } - /** Check if the parameters are correct with the defined fields - * Need the session ! - * @param array $values The values to check - * @param array|null $fields The fields definition (or use the session - * stored one if the value is null) - * @return array containing the errors - */ - public function verify($values, $fields = array()) + /** + * Check if the parameters are correct with the defined fields + * Need the session ! + * @param array $values The values to check + * @param array|null $fields The fields definition (or use the session + * stored one if the value is null) + * @return array containing the errors + */ + public function verify($values, $fields = []) { if (count($fields) === 0) { if (! isset($_SESSION["domframework"]["form"]["fields"])) { - return array(); + return []; } $fields = $_SESSION["domframework"]["form"]["fields"]; } - $errors = array(); + $errors = []; foreach ($fields as $field) { if ( $field->mandatory !== null && @@ -474,25 +508,26 @@ class Form return $errors; } - /** If there is at least one error reported in $errors, save the old values - * and the errors in the session, and redirect to the provided url. - * If there is no error, do nothing - * @param array $values The values of the fields filled by the user - * @param array $errors The errors detected by a verify - * @param object $route the route object - * @param string|null $url The URL to redirect. If not provided, use the - * $route->requestURL () method to found the calling page - * - * Example : - $form = new \Domframework\form (); - $form->logging (array ('\apps\general\controllers\logging', 'log'), - $authHTML["email"]); - $values = $form->values (); - $errors = $spaceObj->verify ($values); - $form->redirectIfError ($values, $errors, $route, "/admin/space/"); - $spaceuuid = $spaceObj->spaceCreateConceal ($values["spacename"]); - $route->redirect ("/admin/space/"); - */ + /** + * If there is at least one error reported in $errors, save the old values + * and the errors in the session, and redirect to the provided url. + * If there is no error, do nothing + * @param array $values The values of the fields filled by the user + * @param array $errors The errors detected by a verify + * @param object $route the route object + * @param string|null $url The URL to redirect. If not provided, use the + * $route->requestURL () method to found the calling page + * + * Example : + * $form = new \Domframework\form (); + * $form->logging (array ('\apps\general\controllers\logging', 'log'), + * $authHTML["email"]); + * $values = $form->values (); + * $errors = $spaceObj->verify ($values); + * $form->redirectIfError ($values, $errors, $route, "/admin/space/"); + * $spaceuuid = $spaceObj->spaceCreateConceal ($values["spacename"]); + * $route->redirect ("/admin/space/"); + */ public function redirectIfError($values, $errors, $route, $url = "") { $this->saveValuesErrors($values, $errors); @@ -505,13 +540,14 @@ class Form $this->saveValuesErrorsReset(); } - /** Save the values and errors to be displayed in the next page if the session - * is available - * Need the session to work - * @param array $values The values of the fields filled by the user - * @param array|null $errors The errors detected by a verify - */ - public function saveValuesErrors($values, $errors = array()) + /** + * Save the values and errors to be displayed in the next page if the session + * is available + * Need the session to work + * @param array $values The values of the fields filled by the user + * @param array|null $errors The errors detected by a verify + */ + public function saveValuesErrors($values, $errors = []) { if (isset($_SESSION)) { $_SESSION["domframework"]["form"][$this->formName]["values"] = $values; @@ -519,20 +555,22 @@ class Form } } - /** Reset the saved values to provide a clean form next page - * Need the session to work - */ + /** + * Reset the saved values to provide a clean form next page + * Need the session to work + */ public function saveValuesErrorsReset() { unset($_SESSION["domframework"]["form"][$this->formName]["values"]); unset($_SESSION["domframework"]["form"][$this->formName]["errors"]); } - /** Get the stored values if there is one. If there is no stored values, - * return the values provided as parameter - * @param array $values The values returned if there is no stored values - * @return array The values to use - */ + /** + * Get the stored values if there is one. If there is no stored values, + * return the values provided as parameter + * @param array $values The values returned if there is no stored values + * @return array The values to use + */ public function getOldValues($values) { if (isset($_SESSION["domframework"]["form"][$this->formName]["values"])) { @@ -542,11 +580,12 @@ class Form return $values; } - /** Get the stored errors if there is one. If there is no sorted errors, - * return the errors provided as parameter - * @param array $errors The values returned if there is no stored values - * @return array The errors to use - */ + /** + * Get the stored errors if there is one. If there is no sorted errors, + * return the errors provided as parameter + * @param array $errors The values returned if there is no stored values + * @return array The errors to use + */ public function getOldErrors($errors) { if (isset($_SESSION["domframework"]["form"][$this->formName]["errors"])) { @@ -556,15 +595,16 @@ class Form return $errors; } - /** Convert Date received in one format to another. - * If the provided string is not corresponding to the format, don't change - * anything. - * Format used http://php.net/manual/en/datetime.createfromformat.php - * @param string $inputDate The date to modify - * @param string $inputFormat The input format of the date - * @param string $outputFormat The output format of the date - * @return string - */ + /** + * Convert Date received in one format to another. + * If the provided string is not corresponding to the format, don't change + * anything. + * Format used http://php.net/manual/en/datetime.createfromformat.php + * @param string $inputDate The date to modify + * @param string $inputFormat The input format of the date + * @param string $outputFormat The output format of the date + * @return string + */ public function convertDate($inputDate, $inputFormat, $outputFormat) { $date = \DateTime::CreateFromFormat($inputFormat, $inputDate); diff --git a/src/Formfield.php b/src/Formfield.php index 227c04b..7506d7e 100644 --- a/src/Formfield.php +++ b/src/Formfield.php @@ -1,85 +1,107 @@ - * @license BSD - */ +/** + * DomFramework + * @package domframework + * @author Dominique Fournier + * @license BSD + */ namespace Domframework; -/** The definition of a formfield - */ +/** + * The definition of a formfield + */ class Formfield { - /** The form name - */ + /** + * The form name + */ public $formName; - /** The name of the field - */ + /** + * The name of the field + */ public $name; - /** The label of the field - */ + /** + * The label of the field + */ public $label; - /** The titles of the field - */ + /** + * The titles of the field + */ public $titles; - /** The defaults values of the field - */ + /** + * The defaults values of the field + */ public $defaults; - /** The type of the field (text, password, checkbox, select) - */ + /** + * The type of the field (text, password, checkbox, select) + */ public $type = "text"; - /** The state of the field : hidden or show - */ + /** + * The state of the field : hidden or show + */ public $hidden = false; - /** Allow a help message to be displayed below the field. In case of error, - * it is overrided by the error message - */ + /** + * Allow a help message to be displayed below the field. In case of error, + * it is overrided by the error message + */ public $help; - /** Display the placeholder if needed - */ + /** + * Display the placeholder if needed + */ public $placeholder = false; - /** The multiplicity of selection of the field (available in select only) - */ + /** + * The multiplicity of selection of the field (available in select only) + */ public $multiple; - /** The name of group for the fields - */ + /** + * The name of group for the fields + */ public $group; - /** The read-only feature of the field - */ + /** + * The read-only feature of the field + */ public $readonly; - /** The field is mandatory - */ + /** + * The field is mandatory + */ public $mandatory; - /** The statut of error of the field - */ + /** + * The statut of error of the field + */ public $error; - /** Number of rows - */ + /** + * Number of rows + */ public $rows; - /** Number of columns - */ + /** + * Number of columns + */ public $cols; - /** The Bootstrap width of the column of titles - */ + /** + * The Bootstrap width of the column of titles + */ public $titlewidth = 2; - /** The Bootstrap width of the column of fields - */ + /** + * The Bootstrap width of the column of fields + */ public $fieldwidth = 10; - /** When adding a field, the name and the label are the minimum mandatory - * @param string $name Name of the field - * @param string|null $label Label of the field - */ + /** + * When adding a field, the name and the label are the minimum mandatory + * @param string $name Name of the field + * @param string|null $label Label of the field + */ public function __construct($name, $label = "") { $this->name = $name; $this->label = $label; } - /** Display really the form - */ + /** + * Display really the form + */ public function display() { $func = "field" . $this->formTemplate . $this->type; @@ -87,90 +109,100 @@ class Formfield } // Setters for all the properties of the class - /** Set the type of the field - * @param string $val The value of the type of the field - */ + /** + * Set the type of the field + * @param string $val The value of the type of the field + */ public function type($val) { $this->type = $val; return $this; } - /** Set the hidden of the field - * @param string $val The value of the hidden of the field - */ + /** + * Set the hidden of the field + * @param string $val The value of the hidden of the field + */ public function hidden($val) { $this->hidden = !! $val; return $this; } - /** Set the help of the field - * @param string $val The value of the help of the field - */ + /** + * Set the help of the field + * @param string $val The value of the help of the field + */ public function help($val) { $this->help = $val; return $this; } - /** Set the placeholder - * @param string $val The value of the placeholder - */ + /** + * Set the placeholder + * @param string $val The value of the placeholder + */ public function placeholder($val) { $this->placeholder = $val; return $this; } - /** Set the multiple - * @param string $val The value of the multiple - */ + /** + * Set the multiple + * @param string $val The value of the multiple + */ public function multiple($val) { $this->multiple = $val; return $this; } - /** Set the group - * @param string $val The value of the group - */ + /** + * Set the group + * @param string $val The value of the group + */ public function group($val) { $this->group = $val; return $this; } - /** Set the readonly - * @param string $val The value of the readonly - */ + /** + * Set the readonly + * @param string $val The value of the readonly + */ public function readonly($val) { $this->readonly = !! $val; return $this; } - /** Set the mandatory - * @param string $val The value of the mandatory - */ + /** + * Set the mandatory + * @param string $val The value of the mandatory + */ public function mandatory($val) { $this->mandatory = !! $val; return $this; } - /** Set the rows - * @param string $val The value of the rows - */ + /** + * Set the rows + * @param string $val The value of the rows + */ public function rows($val) { $this->rows = $val; return $this; } - /** Set the cols - * @param string $val The value of the cols - */ + /** + * Set the cols + * @param string $val The value of the cols + */ public function cols($val) { $this->cols = $val; @@ -180,14 +212,15 @@ class Formfield ////////////////////////// //// BOOTSTRAP3 //// ////////////////////////// - /** Return the checkbox defined - */ + /** + * Return the checkbox defined + */ private function fieldBootstrap3checkbox() { // No $this->multiple, $this->rows $this->cols $this->placeholder, // $this->maxlength if (! is_array($this->titles) || count($this->titles) === 0) { - $titles = array(""); + $titles = [""]; } else { $titles = $this->titles; } @@ -326,8 +359,9 @@ class Formfield return $res; } - /** Return the hidden field defined - */ + /** + * Return the hidden field defined + */ private function fieldBootstrap3hidden() { $res = ""; @@ -347,8 +381,9 @@ class Formfield return $res; } - /** Return the password field defined - */ + /** + * Return the password field defined + */ private function fieldBootstrap3password() { $res = ""; @@ -430,8 +465,9 @@ class Formfield return $res; } - /** Return the radio field defined - */ + /** + * Return the radio field defined + */ private function fieldBootstrap3radio() { $res = ""; @@ -469,7 +505,7 @@ class Formfield } $res .= "
\n"; if (is_string($this->defaults)) { - $this->defaults = array($this->defaults); + $this->defaults = [$this->defaults]; } $res .= " placeholder $this->maxlength @@ -627,7 +664,7 @@ class Formfield } elseif ( isset($this->values) && is_array($this->values) && - in_array($key, $this->values) + in_array($key, $this->values, true) ) { $res .= " selected='selected'"; } @@ -660,8 +697,9 @@ class Formfield return $res; } - /** Return the submit defined - */ + /** + * Return the submit defined + */ private function fieldBootstrap3submit() { $res = ""; @@ -704,8 +742,9 @@ class Formfield return $res; } - /** Return the textarea defined - */ + /** + * Return the textarea defined + */ private function fieldBootstrap3textarea() { $res = ""; @@ -789,8 +828,9 @@ class Formfield return $res; } - /** Return the text defined - */ + /** + * Return the text defined + */ private function fieldBootstrap3text() { $res = ""; @@ -872,8 +912,9 @@ class Formfield return $res; } - /** Return the file defined - */ + /** + * Return the file defined + */ private function fieldBootstrap3file() { $res = ""; @@ -973,14 +1014,15 @@ class Formfield ////////////////////////// //// BOOTSTRAP4 //// ////////////////////////// - /** Return the checkbox defined - */ + /** + * Return the checkbox defined + */ private function fieldBootstrap4checkbox() { // No $this->multiple, $this->rows $this->cols $this->placeholder, // $this->maxlength if (! is_array($this->titles) || count($this->titles) === 0) { - $this->titles = array(""); + $this->titles = [""]; } $res = ""; $res .= "