diff --git a/src/Authentication.php b/src/Authentication.php index e1a42d6..6e24deb 100644 --- a/src/Authentication.php +++ b/src/Authentication.php @@ -68,12 +68,10 @@ class Authentication * @param object $route The route object */ public function __construct ($route) - // {{{ { $this->route = $route; $this->loggingFunc = array ($this, "logging"); } - // }}} /* public function email () { @@ -85,21 +83,18 @@ class Authentication * @return integer|self the actual value or this */ public function debug ($debug = null) - // {{{ { if ($debug === null) return $this->debug; $this->debug = intval ($debug); return $this; } - // }}} /** 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 (); if (session_id () === "") @@ -148,14 +143,12 @@ class Authentication else $this->route->redirect ($url); } - // }}} /** 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 if (session_id () === "") @@ -176,14 +169,12 @@ class Authentication echo $auth->pageHTML ($this->route->baseURL(), $message, $url, $alreadyAuth); } - // }}} /** Check the authentication page * @param string|null $url The url to be redirected after a valid * authentication */ public function verifAuthLoginPage ($url = "") - // {{{ { if (session_id () === "") session_start (); @@ -265,7 +256,6 @@ class Authentication else $this->route->redirect ("/$url", ""); } - // }}} /** Check all the REST API * @param boolean|null $savePassword return the user password if the @@ -273,7 +263,6 @@ class Authentication * @return array The details provided by the authentication mecanism */ public function verifAuthREST ($savePassword = false) - // {{{ { if ($this->debug) echo "=== entering verifAuthREST (restMethods=". @@ -298,7 +287,6 @@ class Authentication $res["password"] = $authparams->password; return $res; } - // }}} /** Return the JSON Web Token * @param string|array $auth The user data to store in JSON Web Token cache. @@ -307,7 +295,6 @@ class Authentication * $this->authServers["authjwt"]["serverKey"] can be set */ public function createJwtToken ($auth) - // {{{ { if (isset ($this->authServers["authjwt"]["serverKey"])) { @@ -336,13 +323,11 @@ class Authentication return $authjwt->createJwtToken ($payloadArray); } } - // }}} /** 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 // pages @@ -374,7 +359,6 @@ class Authentication } return $res; } - // }}} /** Do the real authentication process on all the providers defined in the * properties of the class. @@ -385,7 +369,6 @@ class Authentication * an exception if noting is found */ private function verifAuth ($email, $password) - // {{{ { if ($this->debug) echo "Entering in verifAuth ($email, xxxxxxxx)\n"; @@ -469,13 +452,11 @@ 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... */ public function routes () - // {{{ { $authObj = $this; $route=$this->route; @@ -510,7 +491,6 @@ 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 @@ -518,11 +498,9 @@ class Authentication * @param string $message The message to log */ private function logging ($priority, $message) - // {{{ { if ($this->debug === 0 && $priority > 4) return; file_put_contents ("/tmp/auth.log", "$priority : $message\n", FILE_APPEND); } - // }}} } diff --git a/src/Authjwt.php b/src/Authjwt.php index 20d864c..a5f931c 100644 --- a/src/Authjwt.php +++ b/src/Authjwt.php @@ -48,11 +48,9 @@ class Authjwt extends Auth /** 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 @@ -61,7 +59,6 @@ class Authjwt extends Auth * @param string $password Password not used (wait for Bearer) */ public function authentication ($email, $password) - // {{{ { if (! isset ($_SERVER["HTTP_AUTHENTICATION"])) throw new \Exception (dgettext ("domframework", @@ -86,12 +83,10 @@ class Authjwt extends Auth $this->payload = $payload; return $payload; } - // }}} /** Return all the parameters recorded for the authenticate user */ public function getdetails () - // {{{ { if (! is_array ($this->payload) || key_exists ("email", $this->payload) && @@ -101,7 +96,6 @@ class Authjwt extends Auth "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 @@ -109,7 +103,6 @@ class Authjwt extends Auth * @return string JWT token */ public function createJwtToken ($auth) - // {{{ { if ($this->serverKey === null) return ""; @@ -127,7 +120,6 @@ class Authjwt extends Auth return $jwt->encode ($uuid, $this->serverKey, $this->algorithm, $this->cipherKey); } - // }}} /** Method to change the password : unavailable in SESSION auth * @param string $oldpassword The old password (to check if the user have the @@ -135,12 +127,10 @@ class Authjwt extends Auth * @param string $newpassword The new password to be recorded */ public function changepassword ($oldpassword, $newpassword) - // {{{ { throw new \Exception (dgettext ("domframework", "The password can't be change for JWT users"), 405); } - // }}} /** Method to overwrite the password (without oldpassword check) * Must be reserved to the administrators. For the users, use changepassword @@ -149,17 +139,14 @@ class Authjwt extends Auth * @param string $newpassword The new password to be recorded */ public function overwritepassword ($email, $newpassword) - // {{{ { throw new \Exception (dgettext ("domframework", "The password can't be overwrite for JWT users"), 405); } - // }}} /** Remove the information from the session */ public function logout () - // {{{ { if (! isset ($_SERVER["HTTP_AUTHENTICATION"])) throw new \Exception (dgettext ("domframework", @@ -180,5 +167,4 @@ class Authjwt extends Auth $cachefile->delete ($uuid); return true; } - // }}} } diff --git a/src/Authparams.php b/src/Authparams.php index 8c3701c..1fc537f 100644 --- a/src/Authparams.php +++ b/src/Authparams.php @@ -23,7 +23,6 @@ class Authparams * @param array|null $authprocesses The authentication process to use */ public function __construct ($authprocesses = array ("session", "post")) - // {{{ { if (php_sapi_name () === "cli") { @@ -52,24 +51,20 @@ class Authparams } } } - // }}} /** 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"]); } - // }}} /** Get information from previous recorded session */ public function session () - // {{{ { if (!isset ($_SESSION) || session_id () === "") throw new \Exception ("No session previously enabled", 403); @@ -79,12 +74,10 @@ class Authparams return array ("email" => $_SESSION["domframework"]["auth"]["email"], "password" => $_SESSION["domframework"]["auth"]["password"]); } - // }}} /** Get information from a HTTP authentication */ public function http () - // {{{ { $realm = dgettext ("domframework", "Restricted access"); if (!isset ($_SERVER['PHP_AUTH_USER'])) @@ -102,12 +95,10 @@ class Authparams "password" => $_SERVER["PHP_AUTH_PW"]); } } - // }}} /** Get the information from a shibboleth provider */ public function shibboleth () - // {{{ { if (! isset ($_SERVER["Shib-Session-ID"])) throw new \Exception ("No Shibboleth information available", 403); @@ -116,7 +107,6 @@ class Authparams return array ("email" => $_SERVER["mail"], "password" => "NONE IN SHIBBOLETH"); } - // }}} /** Get the information from a Bearer Token * The token MUST be set in HTTP Header : @@ -132,7 +122,6 @@ class Authparams * jwtServerKey defined in property : the execution is done in constructor */ public function bearer () - // {{{ { if (! isset ($_SERVER["HTTP_AUTHENTICATION"])) throw new \Exception ("No Authentication available", 401); @@ -142,5 +131,4 @@ class Authparams return array ("email" => "NOT YET VALID : TOKEN IN JWT", "password" => "NONE IN JWT"); } - // }}} } diff --git a/src/Authzgroupsoo.php b/src/Authzgroupsoo.php index e87ad8d..7e6bd04 100644 --- a/src/Authzgroupsoo.php +++ b/src/Authzgroupsoo.php @@ -31,38 +31,30 @@ class Authzgroupsoo /** Get the dbObject */ public function dbObject () - // {{{ { return $this->dbObject; } - // }}} /** Get the dbGroup */ public function dbGroup () - // {{{ { return $this->dbGroup; } - // }}} /** Get the dbGroupMember */ public function dbGroupMember () - // {{{ { return $this->dbGroupMember; } - // }}} /** Get the dbRight */ public function dbRight () - // {{{ { return $this->dbRight; } - // }}} ///////////////////// // USER RIGHTS // diff --git a/src/Cachefile.php b/src/Cachefile.php index 36d95a4..8fbeb64 100644 --- a/src/Cachefile.php +++ b/src/Cachefile.php @@ -24,7 +24,6 @@ class Cachefile * @return $this or $this->directory value */ public function directory ($val = null) - // {{{ { if ($val === null) return $this->directory; @@ -33,12 +32,10 @@ class Cachefile $this->directory = $val; return $this; } - // }}} /** Check if there is some garbage to clean */ public function garbage () - // {{{ { try { @@ -93,7 +90,6 @@ class Cachefile } } } - // }}} /** This function check if the cachedir exists and create it if it is not the * case. @@ -102,7 +98,6 @@ class Cachefile * @throw Exception if an error occured */ public function cachedir () - // {{{ { if (! isset ($this->directory) || $this->directory === "") throw new \Exception (dgettext ("domframework", @@ -133,7 +128,6 @@ class Cachefile file_put_contents ($this->directory."/.htaccess", "deny from all\n"); return true; } - // }}} /** This function write data in cache * @param string $id Cache identifier (add the authentication, the METHOD...) @@ -144,7 +138,6 @@ class Cachefile * @throw if an error occured */ public function write ($id, $data, $ttl = 3600) - // {{{ { if ($this->nocache !== false) return false; @@ -175,7 +168,6 @@ class Cachefile chmod ($fileCache, 0666); return true; } - // }}} /** This function read data from cache. Return FALSE in case of empty or too * older cache @@ -184,7 +176,6 @@ class Cachefile * @return mixed The data stored in cache */ public function read ($id) - // {{{ { if ($this->nocache !== false) return false; @@ -249,14 +240,12 @@ 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 */ public function delete ($id) - // {{{ { $fileCache = $this->directory."/".sha1 ($id); if (!file_exists ($fileCache)) @@ -264,5 +253,4 @@ class Cachefile unlink ($fileCache); return true; } - // }}} } diff --git a/src/Console.php b/src/Console.php index 3edbee9..19120cb 100644 --- a/src/Console.php +++ b/src/Console.php @@ -26,7 +26,6 @@ namespace Domframework; class Console { // PROPERTIES - // {{{ /** Set the debug on if a filename is provided, or do not debug if false is * provided */ @@ -79,13 +78,11 @@ class Console /** 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... */ public function __construct () - // {{{ { if (! function_exists ("exec")) throw $this->ConsoleException ("No exec support in PHP"); @@ -98,12 +95,10 @@ class Console exec ("stty -echo -icanon min 1 time 0 2>/dev/null"); $this->updateTerminalSize (); } - // }}} /** Update the terminal size */ public function updateTerminalSize () - // {{{ { $this->termWidth = 80; $this->termHeight = 25; @@ -121,12 +116,10 @@ class Console $this->termHeight = intval ($termHeight); } } - // }}} /** The destructor return the terminal to initial state */ public function __destruct () - // {{{ { if ($this->initSttyState !== "") exec ("stty $this->initSttyState"); @@ -134,38 +127,31 @@ class Console $this->textUnderline (false); $this->textBold (false); } - // }}} /** 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) */ 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 */ 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 @@ -173,14 +159,12 @@ class Console * @return the pressed char */ public function getc () - // {{{ { $char = $this->getKey (); while (in_array (ord ($char), $this->nonWriteableChar)) $char = $this->getKey (); return $char; } - // }}} /** Wait one key pressed by the user. If the key pressed is an ESC sequence, * return this sequence @@ -189,7 +173,6 @@ class Console * @return the pressed char */ public function getKey () - // {{{ { $char = fgetc (STDIN); if ($char === chr (27)) @@ -262,7 +245,6 @@ class Console echo $char; return $char; } - // }}} /** Get the line of characters pressed by the user and return the result. * Stop when the user valid by \n. @@ -273,7 +255,6 @@ class Console * @return string The typed string */ public function readline ($propo = "", $stopperChar = false) - // {{{ { // Gets can not delete chars before the call. Keep the prompt (if exists) if (! is_string ($propo)) @@ -307,7 +288,6 @@ class Console if ($this->completionKeys !== false && in_array ($char, $this->mb_str_split ($this->completionKeys))) // Manage autocompletion - // {{{ { $this->debug ("Autocompletion starting"); // Take the last part of the string without space or double quotes @@ -412,7 +392,6 @@ class Console } $this->debug ("Autocompletion : end '$prompt.$string'"); } - // }}} elseif (ord ($char) === 0) // End of file { @@ -422,7 +401,6 @@ class Console } elseif (ord ($char) === 3) // Abort (Ctrl+C) - // {{{ { $this->debug ("Abort Ctrl+C : ".ord ($char)); $this->lineContent = ""; @@ -431,20 +409,16 @@ class Console echo "$prompt\n"; break; } - // }}} elseif (ord ($char) === 4) // Logout (Ctrl+D) - // {{{ { $this->debug ("Logout Ctrl+D : ".ord ($char)); $string = "exit\n"; $this->rewriteLine ($prompt.$string); return $string; } - // }}} elseif (ord($char) === 12) // Refresh page (Ctrl+L) - // {{{ { $this->debug ("Refresh Ctrl+L : ".ord ($char)); echo "\033[2J\033[;H\033c"; @@ -452,10 +426,8 @@ class Console $this->rewriteLine ($prompt.$string); $this->moveCursor ($cursorPos); } - // }}} elseif (ord($char) === 21) // Empty line from prompt to cursor (Ctrl+U) - // {{{ { $this->debug ("Empty line from prompt to cursor Ctrl+U : ".ord ($char)); $string = mb_substr ($string, $cursorPos - $minLength); @@ -463,10 +435,8 @@ class Console $this->rewriteLine ($prompt.$string); $this->moveCursor ($cursorPos); } - // }}} elseif (ord($char) === 23) // Remove the last word (Ctrl+W) - // {{{ { $this->debug ("Remove the last word Ctrl+W : ".ord ($char)); $tmp = mb_substr ($string, 0, $cursorPos - $minLength); @@ -480,10 +450,8 @@ class Console $this->rewriteLine ($prompt.$string); $this->moveCursor ($cursorPos); } - // }}} elseif (ord($char) === 127 || ord($char) === 8) // Remove the previous char (Backspace) - // {{{ { $this->debug ("Remove the previous char (Backspace) : ".ord ($char)); if ($cursorPos <= $minLength) @@ -495,7 +463,6 @@ class Console $this->rewriteLine ($prompt.$string); $this->moveCursor ($cursorPos); } - // }}} elseif (ord ($char[0]) === 27) { // ESC SEQUENCE @@ -505,7 +472,6 @@ class Console $this->debug ("ESC SEQUENCE : $sequence"); if ($char === chr (27).chr (91).chr (49).chr (59).chr (53).chr (67)) // Cursor right + Ctrl : cursor jump by word - // {{{ { $this->debug ("Cursor right + Ctrl"); $tmp = mb_substr ($string, $cursorPos - $minLength); @@ -517,10 +483,8 @@ class Console $cursorPos = mb_strlen ($prompt.$string) + 1; $this->moveCursor ($cursorPos); } - // }}} elseif ($char === chr (27).chr (91).chr (49).chr (59).chr (53).chr (68)) // Cursor left + Ctrl : cursor jump by word - // {{{ { $this->debug ("Cursor left + Ctrl"); $tmp = mb_substr ($string, 0, $cursorPos - $minLength); @@ -530,10 +494,8 @@ class Console $cursorPos = $minLength + $pos; $this->moveCursor ($cursorPos); } - // }}} elseif ($char === chr (27).chr (91).chr (65)) // Cursor up : display the previous history if defined - // {{{ { $this->debug ("Cursor up"); if (! isset ($historyTmp)) @@ -551,10 +513,8 @@ class Console $this->moveCursor ($cursorPos); } } - // }}} elseif ($char === chr (27).chr (91).chr (66)) // Cursor down : display the next history if defined - // {{{ { $this->debug ("Cursor down"); if ($historyPos < count ($this->history) - 1) @@ -573,10 +533,8 @@ class Console $this->rewriteLine ($prompt.$string); $this->moveCursor ($cursorPos); } - // }}} elseif ($char === chr (27).chr (91).chr (67)) // Cursor right - // {{{ { $this->debug ("Cursor right"); if ($cursorPos <= mb_strlen ($this->lineContent)) @@ -585,10 +543,8 @@ class Console $this->moveCursor ($cursorPos); } } - // }}} elseif ($char === chr (27).chr (91).chr (68)) // Cursor left - // {{{ { $this->debug ("Cursor left"); if ($cursorPos > $minLength) @@ -597,28 +553,22 @@ class Console $this->moveCursor ($cursorPos); } } - // }}} elseif ($char === chr (27).chr (91).chr (70)) // End key - // {{{ { $this->debug ("End key"); $cursorPos = $minLength + mb_strlen ($string); $this->moveCursor ($cursorPos); } - // }}} elseif ($char === chr (27).chr (91).chr (72)) // Home key - // {{{ { $this->debug ("Home key"); $cursorPos = $minLength; $this->moveCursor ($cursorPos); } - // }}} elseif ($char === chr (27).chr (91).chr (51).chr (126)) // Remove the char under the cursor (Delete) - // {{{ { $this->debug ("Delete key"); if ($cursorPos > mb_strlen ($prompt.$string)) @@ -629,18 +579,14 @@ class Console $this->rewriteLine ($prompt.$string); $this->moveCursor ($cursorPos); } - // }}} } elseif (in_array (ord ($char), $this->nonWriteableChar)) // Non writeable char : skip it - // {{{ { $this->debug ("Non writeable char : ".ord ($char)); } - // }}} else // Normal char : Add it to the string - // {{{ { $this->debug ("Normal char : ".ord ($char)); $strArr = $this->mb_str_split ($string); @@ -653,19 +599,16 @@ class Console $this->rewriteLine ($prompt.$string); $this->moveCursor ($cursorPos); } - // }}} } $this->debug ("End of readline '$string'"); return $string; } - // }}} /** 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)"); if ($this->echoMode) @@ -676,13 +619,11 @@ class Console $this->cursorPos = mb_strlen ($this->lineContent); } } - // }}} /** 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)"); if ($cursorPos < 1) @@ -708,12 +649,10 @@ class Console $this->cursorPos = $cursorPos; } } - // }}} /** Clear the existing line. */ public function clearLine () - // {{{ { $this->debug ("Call clearLine"); $oldLength = mb_strlen ($this->lineContent); @@ -742,34 +681,27 @@ class Console $this->lineContent = ""; $this->cursorPos = 1; } - // }}} /** Clear all the screen and remove the scroll of the screen */ public function clearScreen () - // {{{ { echo "\033[2J\033[;H\033c"; } - // }}} /** Get the terminal Height */ public function getTermHeight () - // {{{ { return $this->termHeight; } - // }}} /** 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 @@ -782,7 +714,6 @@ class Console * completion keys is pressed. */ public function completeFunction ($completionKeys, $completionFunction) - // {{{ { if (! is_string ($completionKeys) && ! is_boolean ($completionKeys)) $this->consoleException ("Can not set the completionKeys : not a string"); @@ -794,33 +725,27 @@ class Console $this->completionKeys = $completionKeys; $this->completionFunction = $completionFunction; } - // }}} /** 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 */ public function clearHistory () - // {{{ { $this->history = array (); return $this; } - // }}} /** Write the history to disk. * @param string $historyFile The history file where the history is stored */ public function writeHistory ($historyFile) - // {{{ { if (file_exists ($historyFile)) { @@ -848,7 +773,6 @@ class Console file_put_contents ($historyFile, $history, FILE_APPEND|LOCK_EX); return $this; } - // }}} /** Read the history from the disk * If the file doesn't exists, return an empty array @@ -856,7 +780,6 @@ class Console * @return the read history with timestamp as key and command as value */ public function readHistory ($historyFile) - // {{{ { if (! file_exists ($historyFile)) { @@ -882,7 +805,6 @@ 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 @@ -890,7 +812,6 @@ class Console * @param string The new entry to add in history */ public function addHistory ($line) - // {{{ { if (! is_string ($line)) $this->consoleException ("Can not add line to history : ". @@ -902,14 +823,12 @@ class Console true); 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 */ public function historyMaxSize ($historyMaxSize = null) - // {{{ { if ($historyMaxSize === null) return $this->historyMaxSize; @@ -918,58 +837,48 @@ class Console "negative value provided"); $this->historyMaxSize = intval ($historyMaxSize); } - // }}} /** 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 */ public function colorText ($colorNum) - // {{{ { if (! is_int ($colorNum)) $this->consoleException ("ColorNum provided to colorText is not an ". "integer"); echo "\033[38;5;${colorNum}m"; } - // }}} /** Set the background text color * @param integer $colorNum The color number to use */ public function colorBackgroundText ($colorNum) - // {{{ { if (! is_int ($colorNum)) $this->consoleException ("ColorNum provided to colorBackgroundText not ". "an integer"); echo "\033[48;5;${colorNum}m"; } - // }}} /** Reset the colors */ public function colorReset () - // {{{ { echo "\033[0m"; } - // }}} /** Underline the text * @param boolean $underline True to underline, false to remove the underline */ public function textUnderline ($underline) - // {{{ { if ($underline === false) $underline = 2; @@ -977,13 +886,11 @@ class Console $underline = ""; echo "\033[${underline}4m"; } - // }}} /** Bold the text * @param boolean $bold True to bold, false to remove the bold */ public function textBold ($bold) - // {{{ { if ($bold === false) $bold = 0; @@ -991,7 +898,6 @@ class Console $bold = 1; echo "\033[${bold}m"; } - // }}} /** Return true if the TTY is enabled, or false if the program is called from pipe */ @@ -1007,7 +913,6 @@ class Console * @return array The tokens */ static public function tokenize ($line) - // {{{ { $tokens = array (); $token = strtok (trim ($line),' '); @@ -1022,7 +927,6 @@ class Console } return $tokens; } - // }}} /** This function return an array with each char, but supports UTF-8 * @param string $string The string to explode @@ -1030,20 +934,17 @@ class Console * @return array */ private function mb_str_split ($string, $split_length = 1) - // {{{ { $res = array(); 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 */ private function debug ($data) - // {{{ { if ($this->debug === false) return; @@ -1051,14 +952,12 @@ class Console $data = var_export ($data, true); 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 */ private function shortestIdenticalValues ($completeArr) - // {{{ { if (! is_array ($completeArr)) return ""; @@ -1087,5 +986,4 @@ class Console } return $identicalString; } - // }}} } diff --git a/src/Convert.php b/src/Convert.php index 4b1d48a..1de3ef6 100644 --- a/src/Convert.php +++ b/src/Convert.php @@ -31,7 +31,6 @@ class Convert $exception = true, $inputTimezone = "Europe/Paris", $outputTimezone = "Europe/Paris") - // {{{ { if (! is_string ($inputDate)) throw new \Exception ("The date to convert is not a string", 500); @@ -60,14 +59,12 @@ class Convert $date->setTimezone(new \DateTimeZone ($outputTimezone)); 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 */ public static function ucfirst ($str) - // {{{ { if (! function_exists ("mb_strtoupper")) throw new \Exception ("PHP don't have the MB Support. Please add it !", @@ -75,7 +72,6 @@ class Convert $a = mb_strtoupper (mb_substr ($str, 0, 1, 'UTF-8'), 'UTF-8'); 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. @@ -87,7 +83,6 @@ class Convert * @return string */ public static function ucwords ($str, $delimiters = " \t\r\n\f\v") - // {{{ { if (! function_exists ("mb_strtolower")) throw new \Exception ("PHP don't have the MB Support. Please add it !", @@ -101,7 +96,6 @@ class Convert } return $res; } - // }}} /** Convert the provided float to human readable format * Example : 1440000 => 1.44MB @@ -113,7 +107,6 @@ class Convert */ public static function humanSize ($value, $decimals = 2, $power = 1000, $unit = "B") - // {{{ { if (! is_integer ($value) && ! is_float ($value)) throw new \Exception ("convert::humanSize value not numerical : ". @@ -163,5 +156,4 @@ class Convert return sprintf ("%.${decimals}f", $display).$size[$factor].$unit; } - // }}} } diff --git a/src/Csrf.php b/src/Csrf.php index f130ed4..a7e90f9 100644 --- a/src/Csrf.php +++ b/src/Csrf.php @@ -30,7 +30,6 @@ class Csrf /** Manage the singleton */ public function __construct () - // {{{ { if (isset ($GLOBALS["domframework"]["csrf"])) { @@ -43,13 +42,11 @@ class Csrf $GLOBALS["domframework"]["csrf"] = $this; } } - // }}} /** 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) return $this->csrf; @@ -57,13 +54,11 @@ class Csrf $GLOBALS["domframework"]["csrf"] = $this; return $this; } - // }}} /** 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) return $this->field; @@ -71,12 +66,10 @@ class Csrf $GLOBALS["domframework"]["csrf"] = $this; return $this; } - // }}} /** This function return the token */ public function createToken () - // {{{ { $l = 30; // Number of chars in token $c = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"; @@ -88,14 +81,12 @@ class Csrf $GLOBALS["domframework"]["csrf"] = $this; 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 */ public function checkToken ($tokenFromUser) - // {{{ { if ($this->csrf === FALSE ) return TRUE; @@ -135,12 +126,10 @@ class Csrf } return TRUE; } - // }}} /** Return the CSRF token in a hidden field */ public function displayFormCSRF () - // {{{ { if ($this->csrfToken == "") $this->createToken (); @@ -148,40 +137,33 @@ class Csrf $res .= "value='$this->csrfToken'/>\n"; return $res; } - // }}} /** Return the token if exists or create a new one if needed */ public function getToken () - // {{{ { if ($this->csrfToken === "") $this->createToken (); return $this->csrfToken; } - // }}} /** Add more time to existing CSRF token * @param string $tokenFromUser The existing token */ public function extendToken ($tokenFromUser) - // {{{ { $this->checkToken ($tokenFromUser); $_SESSION["domframework"]["csrf"][$tokenFromUser] = microtime (TRUE); return true; } - // }}} /** Check an existing token, then delete it * @param string $tokenFromUser The existing token */ public function checkThenDeleteToken ($tokenFromUser) - // {{{ { $this->checkToken ($tokenFromUser); unset ($_SESSION["domframework"]["csrf"][$tokenFromUser]); return true; } - // }}} } diff --git a/src/Dblayeroo.php b/src/Dblayeroo.php index 0c5d259..ce392af 100644 --- a/src/Dblayeroo.php +++ b/src/Dblayeroo.php @@ -84,7 +84,6 @@ class Dblayeroo */ public function connect ($dsn, $username = null, $password = null, $driver_options = null) - /* {{{ */ { if (! function_exists ("mb_strlen")) throw new \Exception ("PHP don't have the MB Support. Please add it !", @@ -201,23 +200,19 @@ class Dblayeroo } return self::$instance[$this->dsn]; } - /* }}} */ /** 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 */ public function beginTransaction () - /* {{{ */ { self::$meta[] = array ( "command" => "BEGIN", @@ -228,12 +223,10 @@ class Dblayeroo ); return self::$instance[$this->dsn]->beginTransaction (); } - /* }}} */ /** Commit (validate) a transaction */ public function commit () - /* {{{ */ { self::$meta[] = array ( "command" => "COMMIT", @@ -244,12 +237,10 @@ class Dblayeroo ); return self::$instance[$this->dsn]->commit (); } - /* }}} */ /** RollBack a transaction */ public function rollback () - /* {{{ */ { self::$meta[] = array ( "command" => "ROLLBACK", @@ -260,12 +251,10 @@ class Dblayeroo ); return self::$instance[$this->dsn]->rollback (); } - /* }}} */ /** Return the connected database name from DSN used to connect */ public function databasename () - /* {{{ */ { if ($this->sep === "") $this->DBException (dgettext ("domframework", "Database not connected")); @@ -287,12 +276,10 @@ class Dblayeroo return $dsnExplode["dbname"]; return NULL; } - /* }}} */ /** Return all the tables available in the database */ public function listTables () - /* {{{ */ { if ($this->sep === "") $this->DBException (dgettext ("domframework", "Database not connected")); @@ -336,7 +323,6 @@ class Dblayeroo natsort ($res); return array_values ($res); } - /* }}} */ /** Create the table defined by the differents fields. * Define the SQL syntax based on SQL engines @@ -355,7 +341,6 @@ class Dblayeroo * $foreign = array ("zone"=>"table.field", ...); */ public function createTable () - /* {{{ */ { $this->debugLog ("Entering createTable", 2); if ($this->sep === "") @@ -690,12 +675,10 @@ class Dblayeroo $this->debugLog ($sql, 1); return self::$instance[$this->dsn]->exec ($sql); } - /* }}} */ /** Drop the table */ public function dropTable () - /* {{{ */ { $this->debugLog ("Entering dropTable ()", 2); if ($this->sep === "") @@ -707,13 +690,11 @@ class Dblayeroo $this->debugLog ($sql, 1); return self::$instance[$this->dsn]->exec ($sql); } - /* }}} */ /** Get the informations about a table * @param string $tableName The table to examine */ public function getTableSchema ($tableName) - /* {{{ */ { $this->debugLog ("Entering getTableSchema (",$tableName,")", 2); switch (self::$instance[$this->dsn]->getAttribute(\PDO::ATTR_DRIVER_NAME)) @@ -1064,13 +1045,11 @@ class Dblayeroo "PDO Engine not supported in dbLayeroo"), 500); } } - /* }}} */ /** 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); if (! array_key_exists ($field, $this->fields)) @@ -1089,26 +1068,22 @@ class Dblayeroo $type = str_replace (" ", "", $type); return $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); list ($type, ) = explode ("(", $type); return $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); $pos = strpos ($type, "("); @@ -1121,7 +1096,6 @@ class Dblayeroo "fieldLength : Length equal to Zero for field '%s'", $field)); return $length; } - /* }}} */ ///////////////////////////// /// GETTERS / SETTERS /// @@ -1130,7 +1104,6 @@ class Dblayeroo * @param string|null $table The table to use */ public function table ($table = null) - /* {{{ */ { $this->debugLog ("Entering table (",$table,")", 2); if ($table === null) @@ -1142,13 +1115,11 @@ class Dblayeroo $this->table = $table; return $this; } - /* }}} */ /** Get/Set the tableprefix property * @param string|null $tableprefix The prefix to append */ public function tableprefix ($tableprefix = null) - /* {{{ */ { $this->debugLog ("Entering tableprefix (",$tableprefix,")", 2); if ($tableprefix === null) @@ -1161,7 +1132,6 @@ class Dblayeroo $this->tableprefix = $tableprefix; return $this; } - /* }}} */ /** Get/Set the fields property * The fields to define are in the format: @@ -1169,7 +1139,6 @@ class Dblayeroo * @param array|null $fields The fields to define */ public function fields ($fields = null) - /* {{{ */ { $this->debugLog ("Entering fields (VALUE)", 2); if ($fields === null) @@ -1223,14 +1192,12 @@ class Dblayeroo $this->fields = $fields; 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 */ public function fieldsAll ($full = false) - /* {{{ */ { $fields = array (); if ($this->joinObject) @@ -1249,13 +1216,11 @@ class Dblayeroo } return $fields; } - /* }}} */ /** 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); if ($primary === null) @@ -1269,13 +1234,11 @@ class Dblayeroo $this->primary = $primary; return $this; } - /* }}} */ /** 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); if ($unique === null) @@ -1310,7 +1273,6 @@ class Dblayeroo $this->unique = $unique; return $this; } - /* }}} */ /** Get/Set the foreign property * @param array|null $foreign The definition of the foreign constraint @@ -1321,7 +1283,6 @@ class Dblayeroo * Multiple field and parnentField can be provided, separated by comma */ public function foreign ($foreign = null) - /* {{{ */ { $this->debugLog ("Entering foreign (VALUE)", 2); if ($foreign === null) @@ -1376,13 +1337,11 @@ class Dblayeroo $this->foreign = $foreign; return $this; } - /* }}} */ /** Get/Set the debug property * @param integer|null $debug Set the debug value */ public function debug ($debug = null) - /* {{{ */ { $this->debugLog ("Entering debug (",$debug,")", 2); if ($debug === null) @@ -1392,22 +1351,18 @@ class Dblayeroo $this->debug = $debug; return $this; } - /* }}} */ /** 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 */ public function dsn ($dsn=null) - /* {{{ */ { $this->debugLog ("Entering dsn (",$dsn,")", 2); if ($dsn === null) @@ -1417,14 +1372,12 @@ class Dblayeroo $this->dsn = $dsn; 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 */ public function titles ($titles=null, $full = false) - /* {{{ */ { $this->debugLog ("Entering titles (VALUE)", 2); if ($titles === null) @@ -1463,12 +1416,10 @@ class Dblayeroo $this->titles = $titles; return $this; } - /* }}} */ /** Dump the configuration of the table in an array */ public function exportConf () - /* {{{ */ { return array ("table" => $this->table, "tableprefix" => $this->tableprefix, @@ -1479,7 +1430,6 @@ class Dblayeroo "titles" => $this->titles, ); } - /* }}} */ /** Define a real type array * Must be array ("field" => "realtype") @@ -1494,7 +1444,6 @@ class Dblayeroo * php_function(), function($val) { if ($val > 0) return "MESSAGE";} */ public function realTypes ($realTypes = null) - // {{{ { if ($realTypes === null) return $this->realTypes; @@ -1515,7 +1464,6 @@ class Dblayeroo $this->realTypes = $realTypes; return $this; } - // }}} /** Get the meta data or clear them. * The meta data are all the requests done by the dblayeroo, the time needed @@ -1526,14 +1474,12 @@ class Dblayeroo * @return array or $this */ public function meta ($meta = null) - // {{{ { if ($meta === null) return self::$meta; self::$meta = array (); return $this; } - // }}} ///////////////////////////////////// /// MANAGE THE REQUEST BY OOP /// @@ -1596,17 +1542,14 @@ class Dblayeroo /** 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 */ public function clearRequest () - /* {{{ */ { $this->debugLog ("Entering clearRequest ()", 2); if ($this->joinObject !== null) @@ -1634,14 +1577,12 @@ class Dblayeroo //$this->setForeignObj = array (); return $this; } - /* }}} */ /** 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); if (! is_object ($object)) @@ -1657,14 +1598,12 @@ class Dblayeroo $this->setForeignObj[$object->tableprefix.$object->table] = $object; return $this; } - /* }}} */ /** 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"); @@ -1676,68 +1615,55 @@ class Dblayeroo $this->command = $command; return $this; } - /* }}} */ /** Alias of command ("SELECT") */ public function select () - /* {{{ */ { $this->command = "SELECT"; return $this; } - /* }}} */ /** Alias of command ("INSERT") */ public function insert () - /* {{{ */ { $this->command = "INSERT"; return $this; } - /* }}} */ /** Alias of command ("DELETE") */ public function delete () - /* {{{ */ { $this->command = "DELETE"; return $this; } - /* }}} */ /** Alias of command ("UPDATE") */ public function update () - /* {{{ */ { $this->command = "UPDATE"; return $this; } - /* }}} */ /** 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 ()) - /* {{{ */ { 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 @@ -1749,7 +1675,6 @@ class Dblayeroo * columns */ public function displayAdd ($columnNames = array (), $aliasNames = array ()) - /* {{{ */ { $this->debugLog ("Entering displayAdd (", $columnNames, ",", $aliasNames, ")", 2); @@ -1886,7 +1811,6 @@ class Dblayeroo } return $this; } - /* }}} */ /** Return the name of the display field, with $this->sep * Add the table prefix/name if full is set @@ -1907,7 +1831,6 @@ class Dblayeroo * @param boolean|null $full Add the table prefix/name if set */ private function displayConvert ($name, $full = false) - /* {{{ */ { $pos = strpos ($name, "("); if ($pos !== false) @@ -1933,7 +1856,6 @@ class Dblayeroo $name = "$distinct$name"; 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. @@ -1941,7 +1863,6 @@ class Dblayeroo * @param boolean $full Add the table prefix/name if set */ public function displayGet ($full = false) - /* {{{ */ { $columns = array (); $displayColumn = array (); @@ -1998,7 +1919,6 @@ class Dblayeroo ksort ($columns, SORT_NATURAL); return $columns; } - /* }}} */ /** Do a inner join between two dblayer objects * The join array is a associated array with local field as key and distant @@ -2008,12 +1928,10 @@ class Dblayeroo * @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 @@ -2023,12 +1941,10 @@ class Dblayeroo * @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 @@ -2038,12 +1954,10 @@ class Dblayeroo * @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 @@ -2052,7 +1966,6 @@ class Dblayeroo * @param object $object The dblayer object to use */ private function concat ($concat, $object) - // {{{ { if (substr ($concat, 0, 7) !== "CONCAT(") return $concat; @@ -2079,7 +1992,6 @@ class Dblayeroo $new .= ")"; return $new; } - // }}} /** Do the real join * @param string $joinType The join type to use ("INNER", "LEFT", "RIGHT") @@ -2088,7 +2000,6 @@ class Dblayeroo * @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)) @@ -2158,13 +2069,11 @@ class Dblayeroo $this->sep.$object->tableprefix.$object->table.$this->sep." ON $tmp"; return $this; } - /* }}} */ /** 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) @@ -2178,7 +2087,6 @@ class Dblayeroo } return trim ($joins); } - /* }}} */ /** Set a new WHERE expression value * @param string $field The field to check @@ -2187,7 +2095,6 @@ class Dblayeroo * @param string|null $value The value to search ("" if not provided) */ public function whereAdd ($field, $operator, $value = "") - /* {{{ */ { $this->debugLog ("Entering whereAdd (",$field,", ",$operator,", ",$value, ")", 2); @@ -2242,12 +2149,10 @@ class Dblayeroo } return $this; } - /* }}} */ /** Add a new AND to the WHERE expression */ public function whereAddAND () - /* {{{ */ { $this->debugLog ("Entering whereAddAND ()", 2); if (count ($this->whereExpression) === 0) @@ -2255,12 +2160,10 @@ class Dblayeroo $this->whereExpression[] = "AND"; return $this; } - /* }}} */ /** Add a new OR to the WHERE expression */ public function whereAddOR () - /* {{{ */ { $this->debugLog ("Entering whereAddOR ()", 2); if (count ($this->whereExpression) === 0) @@ -2268,12 +2171,10 @@ class Dblayeroo $this->whereExpression[] = "OR"; return $this; } - /* }}} */ /** Add a new Open Parenthesis to the WHERE expression */ public function whereAddParenthesisOpen () - /* {{{ */ { $this->debugLog ("Entering whereAddParenthesisOpen ()", 2); if (count ($this->whereExpression) && @@ -2284,24 +2185,20 @@ class Dblayeroo $this->whereExpression[] = "("; return $this; } - /* }}} */ /** Add a new Close Parenthesis to the WHERE expression */ public function whereAddParenthesisClose () - /* {{{ */ { $this->debugLog ("Entering whereAddParenthesisClose ()", 2); $this->whereExpression[] = ")"; return $this; } - /* }}} */ /** 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) @@ -2323,14 +2220,12 @@ 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 */ public function whereGetValues () - /* {{{ */ { $whereValues = $this->whereValues; if ($whereValues === null) @@ -2345,7 +2240,6 @@ class Dblayeroo } return $whereValues; } - /* }}} */ /** Add a new ORDER sort. The multiple ORDERS are used from the first added to * the last added @@ -2354,7 +2248,6 @@ class Dblayeroo * "NATDESC"); */ public function orderAdd ($field, $sort = "ASC") - /* {{{ */ { $this->debugLog ("Entering orderAdd (",$field,", ",$sort,")", 2); if (! is_string ($field)) @@ -2383,7 +2276,6 @@ class Dblayeroo $this->orderExpression[$this->getSortOrder()] = $exp; 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 @@ -2392,7 +2284,6 @@ class Dblayeroo * @param boolean|null $full Add the table prefix/name if set */ public function orderGet ($full = false) - /* {{{ */ { $order = array (); if ($this->joinObject) @@ -2413,13 +2304,11 @@ class Dblayeroo ksort ($order, SORT_NATURAL); return $order; } - /* }}} */ /** Return true if this object or one of the join objects need GROUP BY SQL * part */ public function groupByNeeded () - /* {{{ */ { $needGroupBy = false; if ($this->groupByExpression !== null) @@ -2434,7 +2323,6 @@ 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 @@ -2443,7 +2331,6 @@ class Dblayeroo * @param boolean|null $full Add the table prefix/name if set */ public function groupByGet ($full = false) - /* {{{ */ { if ($this->joinObject) $full = true; @@ -2498,7 +2385,6 @@ class Dblayeroo ksort ($groupBy, SORT_NATURAL); return $groupBy; } - /* }}} */ /** Define a LIMIT for the request. * To use only the nbLines, put a 0 on startLine @@ -2506,7 +2392,6 @@ class Dblayeroo * @param integer $nbLines The number of lines to return */ public function limit ($startLine, $nbLines) - /* {{{ */ { $this->debugLog ("Entering limit (",$startLine,", ",$nbLines,")", 2); if (! preg_match ("/^\d+$/", $startLine)) @@ -2523,13 +2408,11 @@ class Dblayeroo $this->limitExpression = "$nbLines"; return $this; } - /* }}} */ /** 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); if (! preg_match ("/^\d+$/", $nbLines)) @@ -2539,7 +2422,6 @@ class Dblayeroo $this->limitExpression = "$nbLines"; return $this; } - /* }}} */ /** Set INSERT/UPDATE values * - The provided array must be an associative array, the field name must be @@ -2547,7 +2429,6 @@ class Dblayeroo * @param array $values The values to INSERT or UPDATE */ public function setValues ($values) - /* {{{ */ { $this->debugLog ("Entering setValues (",$values,")", 2); if (! is_array ($values)) @@ -2574,12 +2455,10 @@ class Dblayeroo $this->setType = $tmpType; return $this; } - /* }}} */ /** Create the SQL request */ private function createRequest () - /* {{{ */ { if ($this->sep === "") $this->DBException (dgettext ("domframework", "Database not connected")); @@ -2694,7 +2573,6 @@ class Dblayeroo } return $sql; } - /* }}} */ /** Prepare the request with the associated entries. * If textForm is true, return a string to display what will be done @@ -2704,7 +2582,6 @@ class Dblayeroo * really the request */ private function prepareRequest ($sql, $textForm) - /* {{{ */ { $text = ""; if (!$textForm) @@ -2803,12 +2680,10 @@ class Dblayeroo else return $st; } - /* }}} */ /** Return the query that will be executed */ public function getDisplayQuery () - /* {{{ */ { $text = ""; $sql = $this->createRequest (); @@ -2818,7 +2693,6 @@ class Dblayeroo $text .= "\n$prep"; return $text; } - /* }}} */ /** Normalize the values before using them. * The normalize is called by methods : verify, checkRealTypes and setValues @@ -2828,7 +2702,6 @@ class Dblayeroo * @return array the updated values */ public function normalize ($values) - // {{{ { if (! is_array ($values)) $this->DBException ("Invalid values to normalize : not an array", 406); @@ -2839,7 +2712,6 @@ class Dblayeroo } return $values; } - // }}} /** Check the provided values which will be inserted or updated against the * database structure. @@ -2849,7 +2721,6 @@ class Dblayeroo * @return array The errors found by field */ public function verify ($values, $update = false) - /* {{{ */ { $update = !! $update; $errors = array (); @@ -3147,14 +3018,12 @@ 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 */ public function checkValues ($values, $update = false) - /* {{{ */ { $this->debugLog ("Entering checkValues (",$update,")", 2); if (! is_array ($values)) @@ -3174,7 +3043,6 @@ class Dblayeroo "errors", 2); return $errors; } - /* }}} */ /** Check the types of the data against the realTypes * Return an array with the field name in error and a message @@ -3186,7 +3054,6 @@ class Dblayeroo * @return array empty array if no error */ public function checkRealTypes ($values, $allowEmpty = false) - // {{{ { $this->debugLog ("Entering checkRealTypes (",$values,",",$allowEmpty,")", 2); @@ -3231,7 +3098,6 @@ class Dblayeroo $errors, 2); return $errors; } - // }}} /** Execute the pre-defined query * Return the content array if SELECT command is choosed @@ -3239,7 +3105,6 @@ class Dblayeroo * Return the number of modified lines for UPDATE/DELETE command */ public function execute () - /* {{{ */ { $this->debugLog ("Entering execute ()", 2); switch ($this->command) @@ -3442,7 +3307,6 @@ class Dblayeroo $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 @@ -3451,31 +3315,26 @@ class Dblayeroo * @return PDOStatement The PDO Statement to traverse */ public function directQuery ($sql) - /* {{{ */ { if (! key_exists ($this->dsn, self::$instance)) $this->DBException ("Direct query without established connection"); 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 */ 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 */ public function DBExceptionMsg ($message) - /* {{{ */ { $backtrace = debug_backtrace (); if ($this->debug) @@ -3494,14 +3353,12 @@ 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 */ public function debugLog ($message, $priority) - /* {{{ */ { if ((!!$this->debug) === false) return; @@ -3527,19 +3384,16 @@ class Dblayeroo } echo "\n"; } - /* }}} */ ////////////////////////////////////////////// //// 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 */ private function checkRealType_integerPositive ($val, $definition) - // {{{ { if (substr ($val, 0, 1) === "-") return dgettext ("domframework", "Invalid positive integer : ". @@ -3552,7 +3406,6 @@ class Dblayeroo "can not start by Zero"); return; } - // }}} /** Check the type "integer" * @param string $val The value to check @@ -3560,7 +3413,6 @@ class Dblayeroo * @return string or null */ private function checkRealType_integer ($val, $definition) - // {{{ { if (strspn ($val, "0123456789-") !== strlen ($val)) return dgettext ("domframework", "Invalid integer : ". @@ -3573,7 +3425,6 @@ class Dblayeroo "can not start by Minus Zero"); return; } - // }}} /** Check the type "allowedchars" * the chars must be in UTF-8 @@ -3582,7 +3433,6 @@ class Dblayeroo * @return string or null */ private function checkRealType_allowedchars ($val, $definition) - // {{{ { list ($func, $param) = explode ("(", $definition); if ($param === null) @@ -3599,7 +3449,6 @@ class Dblayeroo return; return dgettext ("domframework", "Invalid char provided"); } - // }}} /** Check the type "array" * @param string $val The value to check @@ -3607,7 +3456,6 @@ class Dblayeroo * @return string or null */ private function checkRealType_array ($val, $definition) - // {{{ { list ($func, $param) = explode ("(", $definition); if ($param === null) @@ -3627,7 +3475,6 @@ class Dblayeroo return dgettext ("domframework", "Invalid value provided : ". "not in allowed list"); } - // }}} /** Check the type "regex" * Do not forget to add the separators, the ^ and $ @@ -3636,7 +3483,6 @@ class Dblayeroo * @return string or null */ private function checkRealType_regex ($val, $definition) - // {{{ { list ($func, $param) = explode ("(", $definition); if ($param === null) @@ -3654,7 +3500,6 @@ class Dblayeroo return dgettext ("domframework", "Invalid value provided : ". "do not match the regex"); } - // }}} /** Check the type "mail" * @param string $val The value to check @@ -3662,13 +3507,11 @@ class Dblayeroo * @return string or null */ private function checkRealType_mail ($val, $definition) - // {{{ { if (!! filter_var ($val, FILTER_VALIDATE_EMAIL)) return; return dgettext ("domframework", "Invalid mail provided"); } - // }}} /** Check the type "uuid" * @param string $val The value to check @@ -3676,7 +3519,6 @@ class Dblayeroo * @return string or null */ private function checkRealType_uuid ($val, $definition) - // {{{ { if (strlen ($val) !== 36) return dgettext ("domframework", "Invalid UUID provided : ". @@ -3687,7 +3529,6 @@ class Dblayeroo $val[23] !== "-") return dgettext ("domframework", "Invalid UUID provided : missing dash"); } - // }}} /** Check the type "sqldate" * @param string $val The value to check @@ -3695,7 +3536,6 @@ class Dblayeroo * @return string or null */ private function checkRealType_sqldate ($val, $definition) - // {{{ { if (strlen ($val) !== 10) return dgettext ("domframework", "Invalid date provided : ". @@ -3717,7 +3557,6 @@ class Dblayeroo return dgettext ("domframework", "Invalid date provided : ". "the date doesn't exists"); } - // }}} /** Check the type "sqltime" * @param string $val The value to check @@ -3725,7 +3564,6 @@ class Dblayeroo * @return string or null */ private function checkRealType_sqltime ($val, $definition) - // {{{ { if (strlen ($val) !== 8) return dgettext ("domframework", "Invalid time provided : ". @@ -3747,7 +3585,6 @@ class Dblayeroo return dgettext ("domframework", "Invalid time provided : ". "the time doesn't exists"); } - // }}} /** Check the type "sqldatetime" * @param string $val The value to check @@ -3755,7 +3592,6 @@ class Dblayeroo * @return string or null */ private function checkRealType_sqldatetime ($val, $definition) - // {{{ { if (strlen ($val) !== 19) return dgettext ("domframework", "Invalid date and time provided : ". @@ -3777,6 +3613,4 @@ class Dblayeroo return dgettext ("domframework", "Invalid date and time provided : ". "the date doesn't exists"); } - // }}} - // }}} } diff --git a/src/Encrypt.php b/src/Encrypt.php index e883bfa..cd0be21 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -14,13 +14,11 @@ class Encrypt /** Check if openssl library is enabled */ public function __construct () - // {{{ { if (! function_exists ("openssl_random_pseudo_bytes")) throw new \Exception ("No OpenSSL support in PHP. Please install it", 500); } - // }}} /** Encrypt the payload to not be readable by anybody * @param string $payload The payload to encrypt @@ -29,7 +27,6 @@ class Encrypt * @return encrypted payload */ public function encrypt ($payload, $ckey, $cipherMethod = "des-ede3-cbc") - // {{{ { if (! in_array ($cipherMethod, openssl_get_cipher_methods())) throw new \Exception (dgettext ("domframework", @@ -55,7 +52,6 @@ class Encrypt $ciphertext = $iv . $ciphertext; return $ciphertext; } - // }}} /** Decrypt the ciphertext * @param string $ciphertext The payload to decrypt @@ -64,7 +60,6 @@ class Encrypt * @return decrypted text */ public function decrypt ($ciphertext, $ckey, $cipherMethod = "des-ede3-cbc") - // {{{ { if (! is_string ($ciphertext)) throw new \Exception (dgettext ("domframework", @@ -96,5 +91,4 @@ class Encrypt $ciphertext = substr ($ciphertext, $ivlen); return openssl_decrypt ($ciphertext, $cipherMethod, $ckey, $options, $iv); } - // }}} } diff --git a/src/File.php b/src/File.php index c866f3e..2afa9a5 100644 --- a/src/File.php +++ b/src/File.php @@ -34,7 +34,6 @@ class File * @throws If directory not exists, or the directory is not executable */ public function chdir ($directory) - // {{{ { $this->debug (2, "chdir ($directory)"); $tmpdirectory = $this->realpath ($directory); @@ -46,7 +45,6 @@ class File $this->debug (1, "chdir $directory -> $this->cwd"); return true; } - // }}} /** Change the group for a file/dir... * @param string $filename The file/directory to change @@ -54,7 +52,6 @@ class File * @throws If filename not exists, or the directory is not RW */ public function chgrp ($filename, $group) - // {{{ { $this->debug (2, "chgrp ($filename, $group)"); $filename = $this->realpath ($filename); @@ -71,7 +68,6 @@ class File $this->debug (1, "chgrp ($filename, $group) => $rc"); return $rc; } - // }}} /** Change the rights mode for a file/dir... * @param string $filename The file/directory to change @@ -79,7 +75,6 @@ class File * @throws If filename not exists, or the directory is not RW */ public function chmod ($filename, $mode) - // {{{ { $this->debug (2, "chmod ($filename, $mode)"); $filename = $this->realpath ($filename); @@ -96,7 +91,6 @@ class File $this->debug (1, "chmod ($filename, $mode) => $rc"); return $rc; } - // }}} /** Change the owner for a file/dir... * @param string $filename The file/directory to change @@ -104,7 +98,6 @@ class File * @throws If filename not exists, or the directory is not RW */ public function chown ($filename, $user) - // {{{ { $this->debug (2, "chown ($filename, $user)"); if (posix_getuid () !== 0 && @@ -127,7 +120,6 @@ class File $this->debug (1, "chown ($filename, $user) => $rc"); return $rc; } - // }}} /** Chroot in the provided directory * @param string $directory The directory to chroot @@ -135,7 +127,6 @@ class File * @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 // the chroot. @@ -147,7 +138,6 @@ class File $this->debug (1, "chroot $directory -> $this->baseDir"); return true; } - // }}} /** Get the file contents in an array (like 'file' function, but can not * have the same name as the class...) @@ -157,7 +147,6 @@ class File * exists or is not readable */ public function fileArray ($filename) - // {{{ { $this->debug (2, "file ($filename)"); $filename = $this->realpath ($filename); @@ -174,7 +163,6 @@ class File $this->debug (1, "file ($filename) => ". count ($contents). " rows"); return $contents; } - // }}} /** Checks whether a file or directory exists * @param string $filename The file or directory to verify @@ -182,7 +170,6 @@ class File * @throws If parent directory not exists, or is not executable */ public function file_exists ($filename) - // {{{ { $this->debug (2, "file_exists ($filename)"); $filename = $this->realpath ($filename); @@ -199,7 +186,6 @@ class File return true; return false; } - // }}} /** Get the file contents * @param string $filename Name of the file to read @@ -208,7 +194,6 @@ class File * exists or is not readable */ public function file_get_contents ($filename) - // {{{ { $this->debug (2, "file_get_contents ($filename)"); $filename = $this->realpath ($filename); @@ -226,7 +211,6 @@ class File " bytes"); return $contents; } - // }}} /** Write a string to a file * @param string $filename Path to the file where to write the data @@ -237,7 +221,6 @@ class File * exists and is not writeable */ public function file_put_contents ($filename, $data, $flags=0) - // {{{ { $this->debug (2, "file_put_contents ($filename)"); $filename = $this->realpath ($filename); @@ -256,7 +239,6 @@ class File return $contents; } - // }}} /** Get the file modification time of a file * @param string $filename Path to the file @@ -266,14 +248,12 @@ class File * @throws If parent directory not exists, is not writeable */ public function filemtime ($filename) - // {{{ { $this->debug (2, "filemtime ($filename)"); $filename = $this->realpath ($filename); $this->checkPathRO (dirname ($filename)); return filemtime ($filename); } - // }}} /** Get the file size * @param string $filename Path to the file @@ -281,14 +261,12 @@ class File * @throws If parent directory not exists, is not writeable */ public function filesize ($filename) - // {{{ { $this->debug (2, "filesize ($filename)"); $filename = $this->realpath ($filename); $this->checkPathRO (dirname ($filename)); return filesize ($filename); } - // }}} /** Get the file info of the provided filename * @param string $filename Path to the file @@ -296,7 +274,6 @@ class File * @throws If parent directory not exists, is not writeable */ public function fileinfoMimeType ($filename) - // {{{ { $this->debug (2, "filesize ($filename)"); $filename = $this->realpath ($filename); @@ -304,17 +281,14 @@ class File $finfo = new \finfo (FILEINFO_MIME_TYPE); return $finfo->file ($filename); } - // }}} /** 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 @@ -325,7 +299,6 @@ class File * or if there is one file unreadable */ public function glob ($pattern, $flags=0) - // {{{ { $this->debug (2, "glob ($pattern, $flags)"); $this->checkPathRO ($this->baseDir); @@ -355,7 +328,6 @@ class File } return $files; } - // }}} /** Tells whether the given filename is a directory * @param string $filename The filename to test @@ -364,7 +336,6 @@ class File * @throws If parent directory not exists, or is not executable */ public function is_dir ($filename) - // {{{ { $this->debug (2, "is_dir ($filename)"); $filename = $this->realpath ($filename); @@ -373,7 +344,6 @@ class File return true; return false; } - // }}} /** Tells whether the given filename is a valid file * @param string $filename The filename to test @@ -381,7 +351,6 @@ class File * @throws If parent directory not exists, or is not executable */ public function is_file ($filename) - // {{{ { $this->debug (2, "is_file ($filename)"); $filename = $this->realpath ($filename); @@ -390,7 +359,6 @@ class File return true; return false; } - // }}} /** Tells whether a file exists and is executable * @param string $filename The filename to test @@ -398,7 +366,6 @@ class File * @throws If parent directory not exists, or is not executable */ public function is_executable ($filename) - // {{{ { $this->debug (2, "is_executable ($filename)"); $filename = $this->realpath ($filename); @@ -407,7 +374,6 @@ class File return true; return false; } - // }}} /** Tells whether a file exists and is readable * @param string $filename The filename to test @@ -415,7 +381,6 @@ class File * @throws If parent directory not exists, or is not executable */ public function is_readable ($filename) - // {{{ { $this->debug (2, "is_readable ($filename)"); $filename = $this->realpath ($filename); @@ -424,7 +389,6 @@ class File return true; return false; } - // }}} /** Tells whether a file exists and is writeable * @param string $filename The filename to test @@ -432,7 +396,6 @@ class File * @throws If parent directory not exists, or is not executable */ public function is_writeable ($filename) - // {{{ { $this->debug (2, "is_writeable ($filename)"); $filename = $this->realpath ($filename); @@ -441,7 +404,6 @@ class File return true; return false; } - // }}} /** Lock a file exclusively * @param string $filename The file to lock @@ -449,7 +411,6 @@ class File * @throws If parent directory not exists, or is not writeable */ public function lockEX ($filename) - // {{{ { $this->debug (2, "lockEX ($filename)"); $filename = $this->realpath ($filename); @@ -465,7 +426,6 @@ class File $this->locks[$filename] = fopen ($filename, "rt"); return flock ($this->locks[$filename], LOCK_EX); } - // }}} /** Lock a file shared (allow multiple read) * @param string $filename The file to lock @@ -473,7 +433,6 @@ class File * @throws If parent directory not exists, or is not writeable */ public function lockSH ($filename) - // {{{ { $this->debug (2, "lockSH ($filename)"); $filename = $this->realpath ($filename); @@ -489,7 +448,6 @@ class File $this->locks[$filename] = fopen ($filename, "rt"); return flock ($this->locks[$filename], LOCK_SH); } - // }}} /** Unlock a file previously locked * @param string $filename The file to lock @@ -497,7 +455,6 @@ class File * @throws If parent directory not exists, or is not writeable */ public function lockUN ($filename) - // {{{ { $this->debug (2, "lockUN ($filename)"); $filename = $this->realpath ($filename); @@ -511,7 +468,6 @@ class File } return $res; } - // }}} /** Calculate the md5 sum of a file * @param string $filename The file to hash @@ -519,7 +475,6 @@ class File * @throws If the file doesn't exists */ public function md5_file ($filename) - // {{{ { $this->debug (2, "md5_file ($filename)"); $filename = $this->realpath ($filename); @@ -534,7 +489,6 @@ class File $filename), 500); return md5_file ($filename); } - // }}} /** Create a new directory * @param string $pathname The directory to create @@ -545,7 +499,6 @@ class File * @throws If parent directory not exists, is not writeable */ public function mkdir ($pathname, $mode = 0777, $recursive = false) - // {{{ { $this->debug (2, "mkdir ($pathname, $mode, $recursive)"); $pathname = $this->realpath ($pathname); @@ -583,7 +536,6 @@ class File $this->debug (1, "mkdir ($pathname, $mode, $recursive) => $rc"); return $rc; } - // }}} /** Copy a file or a directory * @param string $oldname The file to copy @@ -592,7 +544,6 @@ class File * @return bool */ public function copy ($oldname, $newname) - // {{{ { $this->debug (2, "copy ($oldname, $newname)"); $oldname = $this->realpath ($oldname); @@ -615,7 +566,6 @@ class File $this->debug (1, "copy ($oldname, $newname) => $rc"); return $rc; } - // }}} /** Renames a file or directory * @param string $oldname The file or directory to rename @@ -624,7 +574,6 @@ class File * @return bool */ public function rename ($oldname, $newname) - // {{{ { $this->debug (2, "rename ($oldname, $newname)"); $oldname = $this->realpath ($oldname); @@ -635,7 +584,6 @@ class File $this->debug (1, "rename ($oldname, $newname) => $rc"); return $rc; } - // }}} /** Return a ini file converted to an array * @param string $filename The filename of the ini file being parsed. @@ -643,7 +591,6 @@ class File * @return array */ public function parse_ini_file ($filename, $process_sections = false) - // {{{ { $this->debug (2, "parse_ini_file ($filename, $process_sections)"); $filename = $this->realpath ($filename); @@ -658,7 +605,6 @@ class File $filename), 500); 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 @@ -666,7 +612,6 @@ class File * @return string the canonical absolute path */ public function realpath ($path) - // {{{ { $oriPath = $path; $this->debug (2, "realpath ($oriPath)"); @@ -705,7 +650,6 @@ class File $this->debug (1, "realpath ($oriPath) => $path"); return $path; } - // }}} /** Remove the provided directory * If the recurse flag is true, remove the content too (files and @@ -717,7 +661,6 @@ class File * dir is not writeable */ public function rmdir ($dirname, $recursive=false) - // {{{ { $this->debug (2, "rmdir ($dirname, $recursive)"); $tmpdirname = $this->realpath ($dirname); @@ -739,7 +682,6 @@ class File } return rmdir ($tmpdirname); } - // }}} /** Return the list of files and directories in the directory. * Do not return the . and .. virtual dirs. @@ -749,7 +691,6 @@ class File * @throws If directory not exists, or is not executable */ public function scandir ($directory) - // {{{ { $this->debug (2, "scandir ($directory)"); $directory = $this->realpath ($directory); @@ -758,7 +699,6 @@ class File natsort ($res); return $res; } - // }}} /** Return the list of files and directories in the directory. * Do not return the . and .. virtual dirs. @@ -768,7 +708,6 @@ class File * @throws If directory not exists, or is not executable */ public function scandirNotSorted ($directory) - // {{{ { $this->debug (2, "scandirNotSorted ($directory)"); $directory = $this->realpath ($directory); @@ -777,7 +716,6 @@ class File array('..', '.'))); return $res; } - // }}} /** Calculate the sha1 sum of a file * @param string $filename The file to hash @@ -785,7 +723,6 @@ class File * @throws If the file doesn't exists */ public function sha1_file ($filename) - // {{{ { $this->debug (2, "sha1_file ($filename)"); $filename = $this->realpath ($filename); @@ -800,7 +737,6 @@ class File $filename), 500); return sha1_file ($filename); } - // }}} /** Create a new file or update the timestamp if the file exists * @param string $filename the filename @@ -812,7 +748,6 @@ class File * @throws If parent directory not exists, is not writeable */ public function touch ($filename, $time = null, $atime = null) - // {{{ { $this->debug (2, "touch ($filename, $time, $atime)"); $filename = $this->realpath ($filename); @@ -825,7 +760,6 @@ class File $this->debug (1, "touch ($filename, $time, $atime) => $rc"); return $rc; } - // }}} /** Delete an existing file. * @param string $filename The filename to remove @@ -833,7 +767,6 @@ class File * @throws If parent directory not exists, or is not executable */ public function unlink ($filename) - // {{{ { $this->debug (2, "unlink ($filename)"); $filename = $this->realpath ($filename); @@ -842,7 +775,6 @@ class File return false; return unlink ($filename); } - // }}} /** Check all the parents of the $directory if they are available, and * executable. The path must exists. @@ -854,7 +786,6 @@ class File * @throws if there is a missing part, or a parent is not executable */ private function checkPathRO ($path) - // {{{ { $this->debug (2, "checkPathRO ($path)"); $path = preg_replace ("#//+#", "/", $path); @@ -925,7 +856,6 @@ class File } return $this->checkExternalPathRO ($path); } - // }}} /** Check all the parents of the $directory if they are available, and * executable. The path must exists. @@ -937,7 +867,6 @@ class File * @throws if there is a missing part, or a parent is not executable */ private function checkPathRW ($path) - // {{{ { $this->debug (2, "checkPathRW ($path)"); $this->checkPathRO ($path); @@ -961,7 +890,6 @@ class File } return true; } - // }}} /** Save a debug log * @param integer $prio The message priority. Should be higher than @@ -970,7 +898,6 @@ class File * @return null */ private function debug ($prio, $message) - // {{{ { if ($this->debug === false || $this->debug === 0) return; @@ -982,7 +909,6 @@ class File // FILE_APPEND); } } - // }}} /** External function allowed to be overloaded to test the RO access to a * resource @@ -990,11 +916,9 @@ class File * @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 @@ -1002,9 +926,7 @@ class File * @return boolean true if RW access, false if not */ public function checkExternalPathRW ($path) - // {{{ { return true; } - // }}} } diff --git a/src/Form.php b/src/Form.php index 928137a..a0d3855 100644 --- a/src/Form.php +++ b/src/Form.php @@ -66,14 +66,11 @@ class 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 */ @@ -161,14 +158,12 @@ class Form $this->formTemplate = $formTemplate; 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 */ private function loggingCallable ($prio, $msg) - // {{{ { if (! is_callable ($this->loggingCallable)) return; @@ -177,7 +172,6 @@ class Form $base = $this->loggingBasemsg. " "; call_user_func ($this->loggingCallable, $prio, $base.$msg); } - // }}} /** Save the array of fields into the structure. * Available : @@ -208,29 +202,24 @@ class Form * @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 */ 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 */ public function values () - // {{{ { $values = array (); if ($this->method === "post") @@ -286,7 +275,6 @@ 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 @@ -300,7 +288,6 @@ class Form */ public function printHTML ($method = 'post', $values = NULL, $errors = array()) - // {{{ { if (count ($this->fields) === 0) { @@ -425,13 +412,11 @@ class Form $res .= "\n"; return $res; } - // }}} /** Check the token from the user * @param string $tokenFromUser The value form the user's token */ public function checkToken ($tokenFromUser) - // {{{ { $csrf = new Csrf (); $csrf->field = $this->csrfField; @@ -439,18 +424,15 @@ class Form // problem. If there is no problem, it delete the token $csrf->checkThenDeleteToken ($tokenFromUser); } - // }}} /** Return the token generated in form */ public function getToken () - // {{{ { if ($this->csrfToken === "") $this->createToken (); return $this->csrfToken; } - // }}} /** Check if the parameters are correct with the defined fields * Need the session ! @@ -460,7 +442,6 @@ class Form * @return array containing the errors */ public function verify ($values, $fields=array ()) - // {{{ { if (count ($fields) === 0) { @@ -479,7 +460,6 @@ 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. @@ -501,7 +481,6 @@ class Form $route->redirect ("/admin/space/"); */ public function redirectIfError ($values, $errors, $route, $url = "") - // {{{ { $this->saveValuesErrors ($values, $errors); if ($url === "") @@ -509,7 +488,6 @@ class Form if (count ($errors)) $route->redirect ($url); $this->saveValuesErrorsReset (); } - // }}} /** Save the values and errors to be displayed in the next page if the session * is available @@ -518,7 +496,6 @@ class Form * @param array|null $errors The errors detected by a verify */ public function saveValuesErrors ($values, $errors=array ()) - // {{{ { if (isset ($_SESSION)) { @@ -526,18 +503,15 @@ class Form $_SESSION["domframework"]["form"][$this->formName]["errors"] = $errors; } } - // }}} /** 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 @@ -545,7 +519,6 @@ class Form * @return array The values to use */ public function getOldValues ($values) - // {{{ { if (isset ($_SESSION["domframework"]["form"][$this->formName]["values"])) { @@ -554,7 +527,6 @@ class Form } return $values; } - // }}} /** Get the stored errors if there is one. If there is no sorted errors, * return the errors provided as parameter @@ -562,7 +534,6 @@ class Form * @return array The errors to use */ public function getOldErrors ($errors) - // {{{ { if (isset ($_SESSION["domframework"]["form"][$this->formName]["errors"])) { @@ -571,7 +542,6 @@ 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 @@ -583,7 +553,6 @@ class Form * @return string */ public function convertDate ($inputDate, $inputFormat, $outputFormat) - // {{{ { $date = \DateTime::CreateFromFormat ($inputFormat, $inputDate); if ($date === false) @@ -593,5 +562,4 @@ class Form return $inputDate; return $date->format ($outputFormat); } - // }}} } diff --git a/src/Formfield.php b/src/Formfield.php index dcfcd1d..a0359b8 100644 --- a/src/Formfield.php +++ b/src/Formfield.php @@ -72,25 +72,20 @@ class Formfield * @param string|null $label Label of the field */ public function __construct ($name, $label = "") - // {{{ { $this->name = $name; $this->label = $label; } - // }}} /** Display really the form */ public function display () - // {{{ { $func = "field".$this->formTemplate.$this->type; return $this->$func (); } - // }}} // 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 */ @@ -180,16 +175,13 @@ class Formfield $this->cols = $val; return $this; } - // }}} ////////////////////////// //// BOOTSTRAP3 //// ////////////////////////// - // {{{ /** Return the checkbox defined */ private function fieldBootstrap3checkbox () - // {{{ { // No $this->multiple, $this->rows $this->cols $this->placeholder, // $this->maxlength @@ -317,12 +309,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the hidden field defined */ private function fieldBootstrap3hidden () - // {{{ { $res = ""; // No $this->label, $this->multiple, $this->readonly, $this->hidden, @@ -339,12 +329,10 @@ class Formfield $res .= "/>\n"; return $res; } - // }}} /** Return the password field defined */ private function fieldBootstrap3password () - // {{{ { $res = ""; // No $this->multiple, $this->rows $this->cols @@ -413,12 +401,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the radio field defined */ private function fieldBootstrap3radio () - // {{{ { $res = ""; // No $this->multiple, $this->rows $this->cols $this->placeholder @@ -505,12 +491,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the checkbox defined */ private function fieldBootstrap3select () - // {{{ { // No $this->placeholder $this->maxlength $res = ""; @@ -631,12 +615,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the submit defined */ private function fieldBootstrap3submit () - // {{{ { $res = ""; // No $this->label, $this->multiple, $this->error, $this->rows, @@ -674,12 +656,10 @@ class Formfield $res .= " \n"; return $res; } - // }}} /** Return the textarea defined */ private function fieldBootstrap3textarea () - // {{{ { $res = ""; // No $this->multiple, $this->titles @@ -751,12 +731,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the text defined */ private function fieldBootstrap3text () - // {{{ { $res = ""; // No $this->multiple, $this->titles, $this->rows, $this->cols @@ -825,12 +803,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the file defined */ private function fieldBootstrap3file () - // {{{ { $res = ""; // No $this->multiple, $this->titles, $this->rows, $this->cols @@ -912,17 +888,13 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} - // }}} ////////////////////////// //// BOOTSTRAP4 //// ////////////////////////// - // {{{ /** Return the checkbox defined */ private function fieldBootstrap4checkbox () - // {{{ { // No $this->multiple, $this->rows $this->cols $this->placeholder, // $this->maxlength @@ -1061,12 +1033,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the hidden field defined */ private function fieldBootstrap4hidden () - // {{{ { $res = ""; // No $this->label, $this->multiple, $this->readonly, $this->hidden, @@ -1083,12 +1053,10 @@ class Formfield $res .= "/>\n"; return $res; } - // }}} /** Return the password field defined */ private function fieldBootstrap4password () - // {{{ { $res = ""; // No $this->multiple, $this->rows $this->cols @@ -1166,12 +1134,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the radio field defined */ private function fieldBootstrap4radio () - // {{{ { $res = ""; // No $this->multiple, $this->rows $this->cols $this->placeholder @@ -1267,12 +1233,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the checkbox defined */ private function fieldBootstrap4select () - // {{{ { // No $this->placeholder $this->maxlength $res = ""; @@ -1402,12 +1366,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the submit defined */ private function fieldBootstrap4submit () - // {{{ { $res = ""; // No $this->label, $this->multiple, $this->error, $this->rows, @@ -1445,12 +1407,10 @@ class Formfield $res .= " \n"; return $res; } - // }}} /** Return the textarea defined */ private function fieldBootstrap4textarea () - // {{{ { $res = ""; // No $this->multiple, $this->titles @@ -1531,12 +1491,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the text defined */ private function fieldBootstrap4text () - // {{{ { $res = ""; // No $this->multiple, $this->titles, $this->rows, $this->cols @@ -1614,12 +1572,10 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} /** Return the file defined */ private function fieldBootstrap4file () - // {{{ { $res = ""; // No $this->multiple, $this->titles, $this->rows, $this->cols @@ -1709,7 +1665,5 @@ class Formfield $res .= " \n"; // End form-group return $res; } - // }}} - // }}} } diff --git a/src/Fts.php b/src/Fts.php index 661ecb7..6203f3f 100644 --- a/src/Fts.php +++ b/src/Fts.php @@ -21,7 +21,6 @@ class Fts /////////////////////////// //// PROPERTIES //// /////////////////////////// - // {{{ /** The minimum length of a token to search */ public $minLength = 3; @@ -46,7 +45,6 @@ class Fts /** The callable method to run on each sentence of the query */ private $callTokenSentence = null; - // }}} //////////////////////////// //// CONSTRUCTOR //// @@ -54,13 +52,11 @@ class Fts /** The constructor check the availability of the MB module */ public function __construct () - // {{{ { if (! function_exists ("mb_strlen")) throw new \Exception ("PHP don't have the MB Support. Please add it !", 500); } - // }}} //////////////////////// //// GETTERS //// @@ -68,29 +64,23 @@ class Fts /** Get the tokens store after the search */ public function getTokens () - // {{{ { return $this->tokens; } - // }}} /** Get the tokens store after the search, without the too small ones */ public function getTokensMin () - // {{{ { return $this->tokensMin; } - // }}} /** Get the regexes defined after the analyzer */ public function getRegexes () - // {{{ { return $this->regexes; } - // }}} /** Set the method to call on tokens word only * The method must return the token updated @@ -98,7 +88,6 @@ class Fts * @return $this */ public function callTokenWord ($callable) - // {{{ { if (! is_callable ($callable)) throw new \Exception (dgettext ("domframework", @@ -106,7 +95,6 @@ class Fts $this->callTokenWord = $callable; return $this; } - // }}} /** Set the method to call on tokens sentence only * The method must return the token updated @@ -114,7 +102,6 @@ class Fts * @return $this */ public function callTokenSentence ($callable) - // {{{ { if (! is_callable ($callable)) throw new \Exception (dgettext ("domframework", @@ -122,7 +109,6 @@ class Fts $this->callTokenSentence = $callable; return $this; } - // }}} ////////////////////////////// //// PUBLIC METHODS //// @@ -133,7 +119,6 @@ class Fts * @return array The operator and the associated regex value to search */ public function search ($query) - // {{{ { $query = trim ($query); $this->tokens = $this->tokenizer ($query); @@ -151,7 +136,6 @@ class Fts $this->tokensMin["minuses"]); return $this->regexes; } - // }}} /** Construct the query based on the tokens. * The tokens can be updated by methods so the query may be modified by the @@ -159,7 +143,6 @@ class Fts * @return string */ public function getQuery () - // {{{ { $res = ""; foreach ($this->tokens["tokens"] as $key => $token) @@ -173,7 +156,6 @@ class Fts } return $res; } - // }}} /** Return $line if the $query match against $line, or false if not * @param string $line The line to examine @@ -181,7 +163,6 @@ class Fts * @return string|false The $line if match, false */ public function searchString ($line, $query) - // {{{ { $regexes = $this->search ($query); if (empty ($this->tokens)) @@ -198,7 +179,6 @@ class Fts } return $line; } - // }}} /** Search in SQL * @param string $query The text to found in the database @@ -208,7 +188,6 @@ class Fts * @return array The result of the query */ public function searchSQL ($query, $dblayeroo, $fields) - // {{{ { $regexes = $this->search ($query); if (empty ($regexes["operator"])) @@ -251,7 +230,6 @@ class Fts } return $dbl->execute (); } - // }}} /////////////////////////////// //// PRIVATE METHODS //// @@ -262,7 +240,6 @@ class Fts * @return array The operator and the associated regex value to search */ private function regex ($tokens, $minuses) - // {{{ { if (! is_array ($tokens)) throw new \Exception ("Invalid tokens provided to fts:tokenMinLength", @@ -284,7 +261,6 @@ class Fts } return array ("operator"=>$operator, "value"=>$value); } - // }}} /** Remove the tokens with too small length. Remove the not desired minuses * too. @@ -293,7 +269,6 @@ class Fts * @return array tokens and minuses */ private function tokenMinLength ($tokens, $minuses) - // {{{ { if (! is_array ($tokens)) throw new \Exception ("Invalid tokens provided to fts:tokenMinLength", @@ -313,14 +288,12 @@ class Fts } return array ("tokens"=>$newTokens, "minuses"=>$newMinuses); } - // }}} /** Return an array with the $query tokenized * @param string $query The text to tokenize * @return array tokens and minuses */ private function tokenizer ($query) - // {{{ { if (! is_string ($query)) throw new \Exception ("Invalid query provided to fts:tokenizer", 500); @@ -382,5 +355,4 @@ class Fts "sentences" => $sentences, "minuses" => $minuses); } - // }}} } diff --git a/src/Getopts.php b/src/Getopts.php index 5a61633..61e148b 100644 --- a/src/Getopts.php +++ b/src/Getopts.php @@ -41,19 +41,16 @@ class Getopts /** The constructor check the availability of the MB module */ public function __construct () - // {{{ { if (! function_exists ("mb_strlen")) throw new \Exception ("PHP don't have the MB Support. Please add it !", 500); } - // }}} /** Set/Get the simulate value * @param string|null $simulate The simulate to get/set */ public function simulate ($simulate = null) - // {{{ { if ($simulate === null) return $this->simulate; @@ -65,7 +62,6 @@ class Getopts $this->simulate = $simulate; return $this; } - // }}} /** Add a new option to check * @param string $identifier The identifier of the options @@ -81,7 +77,6 @@ class Getopts */ public function add ($identifier, $short, $long, $description, $paramName = "", $multiple = 0) - // {{{ { if (! is_string ($identifier)) throw new \Exception ("Identifier provided to getopts is not a string", @@ -210,7 +205,6 @@ class Getopts "multiple" => $multiple); return $this; } - // }}} /** Scan the command line and fill the parameters. * Use the simulate line if provided or use the $argv if not @@ -218,7 +212,6 @@ class Getopts * @return $this; */ public function scan () - // {{{ { global $argv; if ($argv === null) @@ -450,7 +443,6 @@ class Getopts $this->parameters = array (); return $this; } - // }}} /** Get the value of the option if set in the command line. If simulate is * defined, use it. @@ -462,7 +454,6 @@ class Getopts * @param string $identifier The identifier option to get */ public function get ($identifier) - // {{{ { $exists = false; foreach ($this->options as $opt) @@ -484,34 +475,28 @@ class Getopts return array (); return false; } - // }}} /** Get the value found in the rest of line (after the double dashes) */ public function restOfLine () - // {{{ { if ($this->restOfLine === null) $this->scan (); return $this->restOfLine; } - // }}} /** Get the name of the program found in the command line */ public function programName () - // {{{ { if ($this->programName === null) $this->scan (); return $this->programName; } - // }}} /** Get the Help message with all the descriptions and options */ public function help () - // {{{ { if (count ($this->options) === 0) return dgettext ("domframework", "No option defined")."\n"; @@ -549,5 +534,4 @@ class Getopts } return $d; } - // }}} } diff --git a/src/Graph.php b/src/Graph.php index 5734725..c8c2a05 100644 --- a/src/Graph.php +++ b/src/Graph.php @@ -13,7 +13,6 @@ namespace Domframework; * ->height ($height) or ->width ($width) The heigh/width of the graph */ class Graph -/* {{{ */ { /** The X axis object */ @@ -388,11 +387,9 @@ class Graph return base64_encode (ob_get_clean()); } } -/* }}} */ /** The series objects */ class GraphSeries -/* {{{ */ { /** The series stored */ private $series = array (); @@ -441,11 +438,9 @@ class GraphSeries unset ($this->series[$name]); } } -/* }}} */ /** The serie object */ class GraphSerie -/* {{{ */ { /** The name of the serie */ @@ -695,11 +690,9 @@ class GraphSerie $this->style->draw ($gd, $free, $this->data, $axisX, $axisY); } } -/* }}} */ /** Read the data */ class GraphData -/* {{{ */ { /** Store the data when the user provided them. Store them in array form */ @@ -964,11 +957,9 @@ class GraphData return $series; } } -/* }}} */ /** The graphTitle object */ class GraphTitle -/* {{{ */ { /** The title text */ @@ -1092,11 +1083,9 @@ class GraphTitle intval ($free[2]), intval ($free[3])); } } -/* }}} */ /** The graphLegend object */ class GraphLegend -/* {{{ */ { /** Show the legend (no legend by default) */ @@ -1298,11 +1287,9 @@ class GraphLegend return $free; } } -/* }}} */ /** The general axis management */ class GraphAxisGeneral -/* {{{ */ { /** The min value of the axis. Do not use it if the axis is composed of labels */ @@ -1692,11 +1679,9 @@ class GraphAxisGeneral } } } -/* }}} */ /** The graph Axis Horizontal class */ class GraphAxisHorizontal extends GraphAxisGeneral -/* {{{ */ { /** Calculate the position in pixels for a value * If the value is out of range, return null to not draw the point @@ -1776,11 +1761,9 @@ class GraphAxisHorizontal extends GraphAxisGeneral return intval ($this->left + $width * $pos + $width); } } -/* }}} */ /** The X axis management */ class GraphAxisX extends GraphAxisHorizontal -/* {{{ */ { /** The angle choosed to draw the graph */ @@ -1948,11 +1931,9 @@ class GraphAxisX extends GraphAxisHorizontal imageline ($gd, $position, $y, $position, $this->top, $gridColor); } } -/* }}} */ /** Manage the vertical axis */ class GraphAxisVertical extends GraphAxisGeneral -/* {{{ */ { /** The angle choosed to draw the graph */ @@ -2128,11 +2109,9 @@ class GraphAxisVertical extends GraphAxisGeneral } } } -/* }}} */ /** The Y1 axis management */ class GraphAxisY1 extends GraphAxisVertical -/* {{{ */ { /** Draw one value on the axis * @param resource $gd The resource to modify @@ -2206,11 +2185,9 @@ die ("graphAxisY1:: drawGrid NOT numerical line ".__LINE__."\n"); } } } -/* }}} */ /** The Y2 axis management */ class GraphAxisY2 extends GraphAxisVertical -/* {{{ */ { /** Draw one value on the axis * @param resource $gd The resource to modify @@ -2273,11 +2250,9 @@ die ("graphAxisY2:: drawOne NOT numerical line ".__LINE__."\n"); return; } } -/* }}} */ /** The graphStyleLine : draw a graph with lines */ class GraphStyleLinePoints -/* {{{ */ { /** The line color. To hide the lines, choose "transparent" */ @@ -2567,11 +2542,9 @@ class GraphStyleLinePoints $this->drawPoint ($gd, $x, $y); } } -/* }}} */ /** The graphStylePoints : draw a graph with points */ class GraphStylePoints extends GraphStyleLinePoints -/* {{{ */ { /** The line color : transparent */ @@ -2583,11 +2556,9 @@ class GraphStylePoints extends GraphStyleLinePoints return "points"; } } -/* }}} */ /** The graphStyleLine : draw a graph with line */ class GraphStyleLine extends GraphStyleLinePoints -/* {{{ */ { /** The point color background. To hide the points, choose "transparent" */ @@ -2603,11 +2574,9 @@ class GraphStyleLine extends GraphStyleLinePoints return "line"; } } -/* }}} */ /** The graphPalette class */ class GraphPalette -/* {{{ */ { /** Get the complete palette * @param string $name The palette name to get @@ -2633,4 +2602,3 @@ class GraphPalette return $palette[$name]; } } -/* }}} */ diff --git a/src/Http.php b/src/Http.php index b0f8afe..6f4bf33 100644 --- a/src/Http.php +++ b/src/Http.php @@ -27,7 +27,6 @@ class Http * @return string The prefered choice */ function bestChoice ($uservar, $available=array(), $default=FALSE) - // {{{ { $uservar = str_replace (" ", "", $uservar); $userchoices = explode (",", $uservar); @@ -85,13 +84,11 @@ class Http // No best solution found. Use the default available solution return $default; } - // }}} /** Return the associated text for a HTTP code * @param integer $code The HTTP code to translate in text */ function codetext ($code) - // {{{ { switch ($code) { @@ -138,5 +135,4 @@ class Http } return $text; } - // }}} } diff --git a/src/Httpclient.php b/src/Httpclient.php index 5898d2a..6a76cf1 100644 --- a/src/Httpclient.php +++ b/src/Httpclient.php @@ -16,7 +16,6 @@ class Httpclient ////////////////////////// //// PROPERTIES //// ////////////////////////// - // {{{ /** The debug depth. 0: Nothing is displayed, 1: Only URL are displayed, * 2: headers only, 3: all the content */ @@ -121,12 +120,10 @@ class Httpclient */ private $acceptEncoding = "gzip, deflate"; - // }}} /** The constructor */ public function __construct () - // {{{ { $maxsize = str_replace (array ('G', 'M', 'K'), array ('000000000', '000000', '000'), @@ -138,7 +135,6 @@ class Httpclient $this->maxsize = $maxsize; $this->headersReset (); } - // }}} ///////////////////////////////// //// GETTERS / SETTERS //// @@ -147,7 +143,6 @@ class Httpclient * @param string|null $url Set / Get the url */ public function url ($url = null) - // {{{ { if ($url === null) return $this->url; @@ -156,13 +151,11 @@ class Httpclient $this->url = $url; return $this; } - // }}} /** Set / Get the cookies stored * @param array|null $cookies Set / Get the cookies */ public function cookies ($cookies = null) - // {{{ { if ($cookies === null) return $this->cookies; @@ -171,13 +164,11 @@ class Httpclient $this->cookies = $cookies; return $this; } - // }}} /** Set / Get the method * @param string|null $method Set / Get the method */ public function method ($method = null) - // {{{ { if ($method === null) return $this->method; @@ -189,78 +180,63 @@ class Httpclient $this->method = $method; return $this; } - // }}} /** Get the headersReceived after the page was get */ public function headersReceived () - // {{{ { return $this->headersReceived; } - // }}} /** Get the headers sent to the server after the page was get */ public function headersSent () - // {{{ { return $this->headersSent; } - // }}} /** Set the headers to initial value */ public function headersReset () - // {{{ { $this->headersSent = array (); return $this; } - // }}} /** Add a new header to be sent to the server * @param string $header The header to add/update * @param string $value The value to save */ public function headerAdd ($header, $value) - // {{{ { $this->headersSent[$header] = $value; return $this; } - // }}} /** Get the port used for connection */ public function port () - // {{{ { return $this->port; } - // }}} /** Set / Get the maximum maxsize allowed * @param integer|null $maxsize The maxsize in bytes */ public function maxsize ($maxsize = null) - // {{{ { if ($maxsize === null) return $this->maxsize; $this->maxsize = intval ($maxsize); return $this; } - // }}} /** Get the HTTP Return code from connection */ public function httpCode () - // {{{ { return $this->httpCode; } - // }}} /** Set / Get the debug mode * 0: Nothing is displayed, 1: Only URL are displayed, @@ -269,14 +245,12 @@ class Httpclient * @param boolean|null $debug The debug value to set or get */ public function debug ($debug = null) - // {{{ { if ($debug === null) return $this->debug; $this->debug = intval ($debug); return $this; } - // }}} /** Set / Get the form Data * Will be of type array ("field" => "value") @@ -284,7 +258,6 @@ class Httpclient * @param array|null $formData The data to send to the server */ public function formData ($formData = null) - // {{{ { if ($formData === null) return $this->formData; @@ -294,7 +267,6 @@ class Httpclient $this->rawData = ""; return $this; } - // }}} /** Set / Get the content Data * The data is in raw format and will not be modified. @@ -302,7 +274,6 @@ class Httpclient * @param string|null $rawData The data to use */ public function rawData ($rawData = null) - // {{{ { if ($rawData === null) return $this->rawData; @@ -312,141 +283,120 @@ class Httpclient $this->formData = array (); return $this; } - // }}} /** Get / Set the Store of session cookies when analyzing the answer of the * server * @param boolean|null $cookiesSession Allow to store the session cookies */ public function cookiesSession ($cookiesSession = null) - // {{{ { if ($cookiesSession === null) return $this->cookiesSession; $this->cookiesSession = !! $cookiesSession; return $this; } - // }}} /** Get / Set the maximum number of redirect to follow before aborting * @param integer|null $redirectMaxCount The maximum number of redirect * before exception */ public function redirectMaxCount ($redirectMaxCount = null) - // {{{ { if ($redirectMaxCount === null) return $this->redirectMaxCount; $this->redirectMaxCount = intval ($redirectMaxCount); return $this; } - // }}} /** Get / Set the actual number of redirect * @param integer|null $redirectCount The actual number of redirect */ public function redirectCount ($redirectCount = null) - // {{{ { if ($redirectCount === null) return $this->redirectCount; $this->redirectCount = intval ($redirectCount); return $this; } - // }}} /** Get / Set the timeout in second before expiring the connection * 30s by default * @param integer|null $timeout The timeout value */ public function timeout ($timeout = null) - // {{{ { if ($timeout === null) return $this->timeout; $this->timeout = intval ($timeout); return $this; } - // }}} /** Get / Set the useragent sent to the server. If it is empty, it will not be * sent * @param string|null $useragent The user agent to use */ public function useragent ($useragent = null) - // {{{ { if ($useragent === null) return $this->useragent; $this->useragent = $useragent; return $this; } - // }}} /** Get/Set the referer page * @param string|null $referer The new referer that will be used on next * request */ public function referer ($referer = null) - // {{{ { if ($referer === null) return $this->referer; $this->referer = $referer; return $this; } - // }}} /** Get/Set the accept type of page wanted by the client * @param string|null $accept The accept types with weight */ public function accept ($accept = null) - // {{{ { if ($accept === null) return $this->accept; $this->accept = $accept; return $this; } - // }}} /** Get/Set the accept Language wanted by the client * @param string|null $acceptLanguage The languages with weight */ public function acceptLanguage ($acceptLanguage = null) - // {{{ { if ($acceptLanguage === null) return $this->acceptLanguage; $this->acceptLanguage = $acceptLanguage; return $this; } - // }}} /** Get/Set the accept Encoding wanted by the client * @param string|null $acceptEncoding The encoding requested */ public function acceptEncoding ($acceptEncoding = null) - // {{{ { if ($acceptEncoding === null) return $this->acceptEncoding; $this->acceptEncoding = $acceptEncoding; return $this; } - // }}} /** Set the authentication in Basic type * @param string $login The login to use * @param string $password The password to use */ public function authBasic ($login, $password) - // {{{ { $this->authentication = "Basic ". base64_encode ("$login:$password"); return $this; } - // }}} /** Get/Set authentication * To remove authentication, pass "" to $auth arg @@ -454,37 +404,31 @@ class Httpclient * @return value or $this */ public function authentication ($auth = null) - // {{{ { if ($auth === null) return $this->authentication; $this->authentication = $auth; return $this; } - // }}} /** Get/Set the ssl options * @param array|null $ssloptions The SSL Options to use * @return $this */ public function ssloptions ($ssloptions = null) - // {{{ { if ($ssloptions === null) return $this->ssloptions; $this->ssloptions = $ssloptions; return $this; } - // }}} /** Get meta data, like the timeout state, the crypto protocol and ciphers... */ public function getMeta () - // {{{ { return $this->tcpclient->getMeta (); } - // }}} /** Return the TCP infos of the connection */ @@ -509,14 +453,12 @@ class Httpclient * @return the page body */ public function getPage ($url, $ssloptions = null) - // {{{ { $this->method ("GET"); $this->url ($url); $this->connect ($ssloptions); return $this->getContent (); } - // }}} /** Init the connection to URL * Will fill the headersReceived, cookies and port properties. @@ -524,7 +466,6 @@ class Httpclient * @return $this */ public function connect ($ssloptions = null) - // {{{ { $this->log (2, "## URL Start $this->method $this->url"); if ($ssloptions !== null) @@ -535,7 +476,6 @@ class Httpclient if ($this->url === "") throw new \Exception ("No URL set to connect", 406); // Manage the URL (and the parameters in GET method) - // {{{ $parseURL = parse_url ($this->url); if (! key_exists ("scheme", $parseURL)) throw new \Exception ("Scheme must be set to http or https", 406); @@ -587,10 +527,8 @@ class Httpclient $path .= "#".$parseURL["fragment"]; if (! key_exists ("host", $parseURL)) throw new \Exception ("No host provided to URL", 406); - // }}} // Prepare the headers to be sent - // {{{ unset ($this->headersSent[0]); array_unshift ($this->headersSent, "$this->method $path HTTP/1.1"); @@ -647,10 +585,8 @@ class Httpclient $this->log (2, "Headers Send :"); $this->log (2, $this->headersSent); - // }}} // Send the request to the server - // {{{ if ($this->tcpclient === null) { $this->tcpclient = new Tcpclient ($parseURL["host"], $this->port); @@ -668,10 +604,8 @@ class Httpclient $this->tcpclient->send ("$header: $value\r\n"); } $this->tcpclient->send ("\r\n"); - // }}} // Send the POST data form if exists - // {{{ if ($this->method !== "GET" && ! empty ($this->formData)) { $i = 0; @@ -709,10 +643,8 @@ class Httpclient $this->tcpclient->send ($this->rawData); $this->log (3, $this->rawData."\n"); } - // }}} // Get the result header from the server - // {{{ $headers = array (); while (($header = $this->tcpclient->read (4095)) !== "") { @@ -785,15 +717,12 @@ class Httpclient $this->bodySize); else $this->log (1, "URL $this->method $this->url $this->httpCode 0"); - // }}} return $this; } - // }}} /** Get the content from the server and put it in memory */ public function getContent () - // {{{ { $url = $this->url; $content = ""; @@ -843,7 +772,6 @@ class Httpclient $this->redirectCount = 0; return $content; } - // }}} /** Read max MAXSIZE bytes * Return "" if all the file is received @@ -852,7 +780,6 @@ class Httpclient * @param integer $maxsize The maxsize to get in this read */ public function read ($maxsize = 4096) - // {{{ { if ($this->tcpclient === null) throw new \Exception ("HTTPClient : can not read non connected URL", 406); @@ -888,16 +815,13 @@ class Httpclient $this->log (3, $content); return $content; } - // }}} /** Disconnect the connection */ public function disconnect () - // {{{ { $this->tcpclient = null; } - // }}} /** Display the log message * @param integer $priority The minimal priority to display the message @@ -925,7 +849,6 @@ class Httpclient * @return the URL */ public function baseURL () - // {{{ { if ($this->url === "") throw new \Exception ("Can not get baseURL of empty url", 500); @@ -938,7 +861,6 @@ class Httpclient $pass = ($user || $pass) ? "$pass@" : ''; return "$scheme$user$pass$host$port"; } - // }}} ////////////////////////////////// //// COOKIES MANAGEMENT //// @@ -975,7 +897,6 @@ class Httpclient * @param string $cookie The cookie content to store */ public function cookieAdd ($domain, $cookie) - // {{{ { // echo "COOKIE = $cookie\n"; $content = explode (";", $cookie); @@ -1069,7 +990,6 @@ class Httpclient $this->cookies[] = $cookieLine; } } - // }}} /** Check if some stored cookies must be send to the server, because they are * in the same domain. @@ -1077,7 +997,6 @@ class Httpclient * @return array the cookies to add to the headers send to the server */ public function cookieToSend ($url) - // {{{ { $parseURL = parse_url ($this->url); if ($parseURL === false) @@ -1106,5 +1025,4 @@ class Httpclient } return $res; } - // }}} } diff --git a/src/Ipaddresses.php b/src/Ipaddresses.php index 90bcef4..84fef23 100644 --- a/src/Ipaddresses.php +++ b/src/Ipaddresses.php @@ -14,7 +14,6 @@ class Ipaddresses * @param string $ip The IP Address to validate */ public function validIPAddress ($ip) - // {{{ { if (!is_string ($ip) || $ip === "") throw new \Exception (dgettext ("domframework", "Invalid IP address"), @@ -25,13 +24,11 @@ class Ipaddresses $rc = $this->validIPv6Address ($ip); return $rc; } - // }}} /** Return true if the provided IP address is valid and is IPv4 * @param string $ip The IP Address to validate */ public function validIPv4Address ($ip) - // {{{ { if (!is_string ($ip) || $ip === "") throw new \Exception (dgettext ("domframework", "Invalid IPv4 address"), @@ -41,13 +38,11 @@ class Ipaddresses return FALSE; return TRUE; } - // }}} /** Return true if the provided IP address is valid and is IPv6 * @param string $ip The IP Address to validate */ public function validIPv6Address ($ip) - // {{{ { if (!is_string ($ip) || $ip === "") throw new \Exception (dgettext ("domframework", "Invalid IPv6 address"), @@ -57,14 +52,12 @@ class Ipaddresses return FALSE; return TRUE; } - // }}} /** Return true if the provided IP address is valid (IPv4 or IPv6) and the * provided CIDR is valid too * @param string $ip The IP Address to validate with a CIDR */ public function validIPAddressWithCIDR ($ip) - // {{{ { if (!is_string ($ip) || $ip === "") throw new \Exception (dgettext ("domframework", "Invalid IP address"), @@ -75,14 +68,12 @@ class Ipaddresses $rc = $this->validIPv6AddressWithCIDR ($ip); return $rc; } - // }}} /** Return true if the provided IP address is valid and is IPv4 and the * provided CIDR is valid too * @param string $ip The IP Address to validate with a CIDR */ public function validIPv4AddressWithCIDR ($ip) - // {{{ { if (!is_string ($ip) || $ip === "") throw new \Exception (dgettext ("domframework", "Invalid IPv4 address"), @@ -97,14 +88,12 @@ class Ipaddresses return false; return true; } - // }}} /** Return true if the provided IP address is valid and is IPv6 and the * provided CIDR is valid too * @param string $ip The IP Address to validate with a CIDR */ public function validIPv6AddressWithCIDR ($ip) - // {{{ { if (!is_string ($ip) || $ip === "") throw new \Exception (dgettext ("domframework", "Invalid IPv6 address"), @@ -119,7 +108,6 @@ class Ipaddresses return false; return true; } - // }}} /** Return true if the provided CIDR is valid. The CIDR can be valid in IPv4 * or IPv6 @@ -127,7 +115,6 @@ class Ipaddresses * @return boolean The CIDR is valid */ public function validCIDR ($cidr) - // {{{ { if (! is_integer ($cidr) && ! is_integer ($cidr)) throw new \Exception (dgettext ("domframework", "Invalid CIDR provided"), @@ -138,14 +125,12 @@ class Ipaddresses return false; return true; } - // }}} /** Return true if the provided CIDR is valid. The CIDR can be valid in IPv4. * @param integer $cidr The CIDR to test * @return boolean The CIDR is valid */ public function validIPv4CIDR ($cidr) - // {{{ { if (! is_integer ($cidr) && ! is_string ($cidr)) throw new \Exception (dgettext ("domframework", "Invalid CIDR provided"), @@ -156,14 +141,12 @@ class Ipaddresses return false; return true; } - // }}} /** Return true if the provided CIDR is valid. The CIDR can be valid in IPv6. * @param integer $cidr The CIDR to test * @return boolean The CIDR is valid */ public function validIPv6CIDR ($cidr) - // {{{ { if (! is_integer ($cidr) && ! is_string ($cidr)) throw new \Exception (dgettext ("domframework", "Invalid CIDR provided"), @@ -174,7 +157,6 @@ class Ipaddresses return false; return true; } - // }}} /** Return the IPv6 to compressed (or compact) form. * Remove the 0 when they are placed on the begin of the nibble. @@ -184,7 +166,6 @@ class Ipaddresses * @param string $ip The IP to compress */ public function compressIP ($ip) - // {{{ { if (strpos ($ip, ":") === false) return $ip; @@ -239,7 +220,6 @@ class Ipaddresses $ipHex = implode (":", $ipArr); return $ipHex; } - // }}} /** Return the IPv6 uncompressed (all the fields exists). They are not filled * by zeros @@ -252,7 +232,6 @@ class Ipaddresses * return "0:0:0:0:0:0:ffff:7f00:1" */ public function uncompressIPv6 ($ip) - // {{{ { if (! is_string ($ip) || $ip === "" || $this->validIPAddress ($ip) === false) @@ -299,7 +278,6 @@ class Ipaddresses } return $ip; } - // }}} /** Get an IPv6 address with the format * x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x @@ -309,7 +287,6 @@ class Ipaddresses * @param string $ipv6 The IPv6 to group */ public function groupIPv6 ($ipv6) - // {{{ { if (! is_string ($ipv6) || $ipv6 === "") throw new \Exception (dgettext ("domframework", "Invalid IPv6 address"), @@ -329,7 +306,6 @@ class Ipaddresses } return $new; } - // }}} /** Return the IP adddress with filling the fields with the missing zeros. * Valid only on IPv6 (but don't change anything if the provided address is @@ -341,7 +317,6 @@ class Ipaddresses * return "0000:0000:0000:0000:0000:0000:ffff:7f00:0001" */ public function completeAddressWithZero ($ip) - // {{{ { if (! is_string ($ip) || $ip === "") throw new \Exception (dgettext ("domframework", "Invalid IP address"), @@ -370,7 +345,6 @@ class Ipaddresses } throw new \Exception (dgettext ("domframework", "Invalid IP address"), 500); } - // }}} /** Return the provided CIDR in binary. Length must be in bytes. * Return FALSE if the parameters are invalid @@ -378,7 +352,6 @@ class Ipaddresses * @param integer $length The length to use */ public function cidrToBin ($cidr, $length) - // {{{ { if (! is_numeric ($cidr) || $cidr < 0 || $cidr > 128) throw new \Exception (dgettext ("domframework", "Invalid CIDR"), 500); @@ -392,7 +365,6 @@ class Ipaddresses } return pack ('H*', $this->str_base_convert ($val, 2, 16)); } - // }}} /** Base conversion with 128 bits support for IPv6 * Based on http://fr2.php.net/manual/en/function.base-convert.php#109660 @@ -403,7 +375,6 @@ class Ipaddresses * default) */ public function str_base_convert($str, $frombase=10, $tobase=36) - // {{{ { $str = trim ($str); if (intval ($frombase) != 10) @@ -438,7 +409,6 @@ class Ipaddresses return $s; } - // }}} /** Reverse the provided IP address * The IPv6 are returned in format : @@ -446,7 +416,6 @@ class Ipaddresses * @param string $ipReverse The IPv6 to reverse */ function reverseIPAddress ($ipReverse) - // {{{ { if (!is_string ($ipReverse) || $ipReverse === "") throw new \Exception (dgettext ("domframework", "Invalid IP address"), @@ -477,7 +446,6 @@ class Ipaddresses } throw new \Exception (dgettext ("domframework", "Invalid IP address"), 500); } - // }}} /** This function return the CIDR associated to the provided netmask * Ex. Return 24 for a mask 255.255.255.0 in direct @@ -490,7 +458,6 @@ class Ipaddresses * check a wildcard mask */ public function netmask2cidr ($netmask, $maskdirect = true) - // {{{ { $maskdirect = "". ($maskdirect + 0); $maskrevert = ($maskdirect === "0") ? "1" : "0"; @@ -523,7 +490,6 @@ class Ipaddresses return 32; return $res; } - // }}} /** This function return the netmask associated to a CIDR. * Work only on IPv4 addresses (CIDR between 0 and 32) @@ -534,7 +500,6 @@ class Ipaddresses * @return false if the CIDR is not between 0 and 32 */ public function cidr2netmask ($cidr, $maskdirect = true) - // {{{ { if ($cidr < 0 || $cidr > 32) return false; @@ -558,7 +523,6 @@ class Ipaddresses } return $res; } - // }}} /** This function return true if the provided address is in the provided * network with the associated cidr @@ -568,7 +532,6 @@ class Ipaddresses * @return boolean True if $ip is in $network/$cidr */ public function ipInNetwork ($ip, $network, $cidr) - // {{{ { if ($this->validIPAddress ($ip) === false) throw new \Exception (dgettext ("domframework", "Invalid IP address"), @@ -596,7 +559,6 @@ class Ipaddresses return ($this->networkFirstIP ($ip, $cidr) === $this->networkFirstIP ($network, $cidr)); } - // }}} /** Get the first IP of a network. * IPv4 and IPv6 compatible @@ -606,11 +568,9 @@ class Ipaddresses * Example : $ip="192.168.1.2", $cidr=24 => return "192.168.1.0" */ public function networkFirstIP ($ip, $cidr) - // {{{ { return $this->networkFirstLastIP ($ip, $cidr, "0"); } - // }}} /** Get the last IP of a network. * IPv4 and IPv6 compatible @@ -620,11 +580,9 @@ class Ipaddresses * Example : $ip="192.168.1.2", $cidr=24 => return "192.168.1.255" */ public function networkLastIP ($ip, $cidr) - // {{{ { return $this->networkFirstLastIP ($ip, $cidr, "1"); } - // }}} /** Get the network first IP. * IPv4 and IPv6 compatible @@ -636,7 +594,6 @@ class Ipaddresses * Example : $ip="192.168.1.2", $cidr=24 => return "192.168.1.0" */ private function networkFirstLastIP ($ip, $cidr, $map) - // {{{ { if ($this->validIPAddress ($ip) === false) throw new \Exception (dgettext ("domframework", "Invalid IP address"), @@ -714,5 +671,4 @@ class Ipaddresses } return $ipBase; } - // }}} } diff --git a/src/Jwt.php b/src/Jwt.php index eb68a14..9252a56 100644 --- a/src/Jwt.php +++ b/src/Jwt.php @@ -16,7 +16,6 @@ namespace Domframework; class Jwt { // PROPERTIES - // {{{ /** List the allowed algorithms to sign the token */ private $supportedAlgs = array ( @@ -24,7 +23,6 @@ class Jwt 'HS512' => array('hash_hmac', 'SHA512'), 'HS384' => array('hash_hmac', 'SHA384'), ); - // }}} /** Create the token based on payload, sign it with key, and optionally * encrypt it with ckey @@ -42,7 +40,6 @@ class Jwt */ public function encode ($payload, $key, $alg = "HS256", $ckey = null, $cipherMethod = "des-ede3-cbc") - // {{{ { if (! key_exists ($alg, $this->supportedAlgs)) throw new \Exception (dgettext ("domframework", @@ -62,7 +59,6 @@ class Jwt $segments[] = $this->urlsafeB64Encode ($signature); return implode ('.', $segments); } - // }}} /** Decode the provide JWT and return an array of the payload * @param string $jwt The token to examine @@ -78,7 +74,6 @@ class Jwt */ public function decode ($jwt, $key, $allowedAlg = null, $ckey = null, $cipherMethod = "des-ede3-cbc") - // {{{ { if ($allowedAlg === null) $allowedAlg = array_keys ($this->supportedAlgs); @@ -126,7 +121,6 @@ class Jwt "JWT Signature verification failed"), 403); return $payload; } - // }}} /** Verify the provided token with the key and generate an return true if it * can be verify @@ -137,7 +131,6 @@ class Jwt * @return boolean Return true if the input signed is valid */ private function verify ($input, $sign, $key, $alg) - // {{{ { $signature = $this->sign ($input, $key, $alg); if (function_exists ("hash_equals") && @@ -151,17 +144,14 @@ class Jwt $status |= ord ($signature[$i]) ^ ord ($sign[$i]); return $status === 0; } - // }}} /** Create a signing key * @return string the signing key proposed */ public function createKey () - // {{{ { return sha1 (microtime (true)); } - // }}} /** Sign the requested string with the provided key and based on the algorithm * @param string $input The string to sign @@ -170,7 +160,6 @@ class Jwt * @return string The signed string in binary */ private function sign ($input, $key, $alg) - // {{{ { if (! key_exists ($alg, $this->supportedAlgs)) throw new \Exception (dgettext ("domframework", @@ -185,7 +174,6 @@ class Jwt "Invalid method to sign the JWT"), 500); } } - // }}} /** Return the provided string in base64 without equal at the end * To be URL compliant, the slash and plus are converted to underscore and @@ -194,18 +182,15 @@ class Jwt * @return string The string converted in base64 */ private function urlsafeB64Encode ($str) - // {{{ { return rtrim (strtr (base64_encode ($str), '+/', '-_'), "="); } - // }}} /** Return the provided base64 to string * @param string $str The string the convert from base64 * @return string The string converted from base64 */ private function urlsafeB64Decode ($str) - // {{{ { $str = strtr ($str, '-_', '+/'); $remainder = strlen ($str) % 4; @@ -219,14 +204,12 @@ class Jwt } return base64_decode ($str); } - // }}} /** Return the provided array to JSON string * @param object $input The object to convert in JSON * @return string The JSON string */ private function jsonEncode ($input) - // {{{ { $json = json_encode ($input); if ($json === "null" && $input !== null) @@ -234,7 +217,6 @@ class Jwt "JSON Encode : Null result with non-null input"), 500); return $json; } - // }}} /** Decode the provided JSON string and return the result * If null, there is a decode problem @@ -242,9 +224,7 @@ class Jwt * @return mixed The decoded string in object */ private function jsonDecode ($input) - // {{{ { return json_decode ($input, false, 512, JSON_BIGINT_AS_STRING); } - // }}} } diff --git a/src/Macaddresses.php b/src/Macaddresses.php index 40f987b..9284e7d 100644 --- a/src/Macaddresses.php +++ b/src/Macaddresses.php @@ -29,7 +29,6 @@ class Macaddresses * @return bool */ public static function isMACAddress ($mac) - // {{{ { if (! is_string ($mac)) return false; @@ -38,7 +37,6 @@ class Macaddresses preg_match ("/^([a-fA-F0-9]{4}[.]){2}[a-fA-F0-9]{4}$/", $mac) === 1 || preg_match ("/^[a-fA-F0-9]{12}$/", $mac) === 1); } - // }}} /** Reform the mac address with the separator. * The provided mac MUST be without separator (can be removed by @@ -49,14 +47,12 @@ class Macaddresses * @return string The updated mac address with separators */ public static function addSeparator ($mac, $separator = ':', $nbdigit = 2) - // {{{ { if (strspn ($mac, "0132465789ABCDEFabcdef") !== strlen ($mac)) throw new \Exception (dgettext ("domframework", "Invalid mac address provided to addSeparator : bad chars"), 406); return join ($separator, str_split ($mac, $nbdigit)); } - // }}} /** Remove all the separators from the provided MAC address * @param string $mac the mac address to update @@ -65,9 +61,7 @@ class Macaddresses */ public static function removeSeparator ($mac, $separators = array (":", "-", ".")) - // {{{ { return str_replace ($separators, '', $mac); } - // }}} } diff --git a/src/Mail.php b/src/Mail.php index 1142b6d..e07dcf9 100644 --- a/src/Mail.php +++ b/src/Mail.php @@ -38,7 +38,6 @@ class Mail * returns */ private function printSections () - // {{{ { foreach ($this->sections as $sectionID=>$vals) { @@ -72,26 +71,22 @@ class Mail echo ")\n\n"; } } - // }}} /** Add a new section * @param array $param The parameters to store * @return the sectionID */ private function sectionAdd ($param) - // {{{ { $sectionID = md5 (microtime(true).rand()); $this->sections[$sectionID] = $param; return $sectionID; } - // }}} /** Add a new section with the default parameters * @return array The sectionID stored with the default parameters */ private function sectionAddDefault () - // {{{ { return $this->sectionAdd ( array ("_headerBodySeparator"=>$this->headerBodySeparator, @@ -101,7 +96,6 @@ class Mail "_contentEML"=>"", "_contentUTF"=>"")); } - // }}} /** Del an existing section * If there is one child, and the section was multiple, remove it and @@ -118,7 +112,6 @@ class Mail * @param string $sectionIDchild The sectionID of the child to add */ private function sectionAddChild ($sectionIDParent, $sectionIDchild) - // {{{ { if (! array_key_exists ($sectionIDParent, $this->sections)) throw new \Exception (dgettext ("domframework", @@ -126,14 +119,12 @@ class Mail $this->sections[$sectionIDParent]["_partsIDchild"][] = $sectionIDchild; $this->sections[$sectionIDchild]["_parentID"] = $sectionIDParent; } - // }}} /** Add a newChild to an existing section at the beginning of the list * @param string $sectionIDParent The parent modified by adding a child * @param string $sectionIDchild The sectionID of the child to add */ private function sectionAddChildFirst ($sectionIDParent, $sectionIDchild) - // {{{ { if (! array_key_exists ($sectionIDParent, $this->sections)) throw new \Exception (dgettext ("domframework", @@ -142,28 +133,24 @@ class Mail $sectionIDchild); $this->sections[$sectionIDchild]["_parentID"] = $sectionIDParent; } - // }}} /** Remove all the defined Childs in the section. Do not remove really the * childs ! * @param string $sectionID the section to clean */ private function sectionDelChilds ($sectionID) - // {{{ { if (! array_key_exists ($sectionID, $this->sections)) throw new \Exception (dgettext ("domframework", "Section not found"), 404); unset ($this->sections[$sectionID]["_partsIDchild"]); } - // }}} /** Update the content of an existing section * @param string $sectionID The section to modify * @param array $param The parameters to update */ private function sectionUpdate ($sectionID, $param) - // {{{ { if (! array_key_exists ($sectionID, $this->sections)) throw new \Exception (dgettext ("domframework", "Section not found"), @@ -176,23 +163,19 @@ class Mail $this->sections[$sectionID][$key] = $val; } } - // }}} /** Get the list of sections ID * @return array the defined sectionsID */ private function sectionList () - // {{{ { return array_keys ($this->sections); } - // }}} /** Get the section ID List with parents ID * @return array the defined sectionsID with the parent ID as value */ private function sectionListParent () - // {{{ { $res = array (); foreach ($this->sections as $sectionID=>$content) @@ -204,27 +187,23 @@ class Mail } return $res; } - // }}} /** Return the content array of the section * @param string $sectionID The section ID to get * @return array The content of the section */ private function sectionGet ($sectionID) - // {{{ { if (! array_key_exists ($sectionID, $this->sections)) throw new \Exception (dgettext ("domframework", "Section not found"), 404); return $this->sections[$sectionID]; } - // }}} /** Get the section ID of the main part * @return bool|string the section ID of the main part or FALSE if not found */ public function sectionMainID () - // {{{ { foreach ($this->sectionListParent () as $sectionID=>$parentID) { @@ -233,13 +212,11 @@ class Mail } return false; } - // }}} /** Refresh the _headersEML from the _headersArray * @param string $sectionID the section to refresh */ private function sectionRefreshHeadersEML ($sectionID) - // {{{ { $section = $this->sectionGet ($sectionID); $headersEML = ""; @@ -251,14 +228,12 @@ class Mail } $this->sections[$sectionID]["_headersEML"] = $headersEML; } - // }}} /** Read the complete mail to analyze * Destroy all the previous definitions of mail * @param string $content The complete mail to read */ public function readMail ($content) - // {{{ { $this->sections = array (); $this->completeEmailEML = $content; @@ -266,7 +241,6 @@ class Mail if ($partinfo !== null) $this->readMailContentRecurse ($partinfo); } - // }}} /** Read the content of the mail and allow the content to be also multipart. * Then the method is recursively called to generate the sections @@ -274,7 +248,6 @@ class Mail * @param string|null $sectionIDParent The parent sectionID to link with */ private function readMailContentRecurse ($partinfo, $sectionIDParent=false) - // {{{ { if (key_exists ("_contentType", $partinfo) && substr ($partinfo["_contentType"], 0, 10) === "multipart/") @@ -332,14 +305,12 @@ class Mail $sectionIDParent = $this->sectionAdd ($partinfo); } } - // }}} /** Return the data for a part of the mail * @param string $content The content of the mail to parse * @return array The data content in the mail */ private function parseMessagePart ($content) - // {{{ { // Get the HeaderBodySeparator $pos = strpos ($content, "\r\n\r\n"); @@ -462,12 +433,10 @@ class Mail $res["Content-ID"] = $contentID; return $res; } - // }}} /** The constuctor verify if the external libraries are available */ public function __construct () - // {{{ { if (! function_exists ("finfo_buffer")) throw new \Exception (dgettext ("domframework", @@ -482,7 +451,6 @@ class Mail $this->addHeader ("From", $user["name"]."@".php_uname('n')); $this->addHeader ("MIME-Version", "1.0"); } - // }}} /** Define a HTML body. If the HTML body already exists, overwrite it * If there is an text body, manage the boundary in alternative mode @@ -492,7 +460,6 @@ class Mail */ public function setBodyHTML ($htmlContent, $charset="utf-8", $encoding="quoted-printable") - // {{{ { // Look if there is an existing section with text (main or // multipart/alternative) @@ -588,7 +555,6 @@ class Mail $this->sectionUpdate ($sectionIDtoChange, $part); $this->createMailEML (); } - // }}} /** Add a Text body. If the text body already exists, overwrite it * If there is an HTML body, manage the boundary in alternative mode @@ -598,7 +564,6 @@ class Mail */ public function setBodyText ($textContent, $charset="utf-8", $encoding="quoted-printable") - // {{{ { // Look if there is an existing section with text (main or // multipart/alternative) @@ -676,7 +641,6 @@ class Mail $this->sectionUpdate ($sectionIDtoChange, $part); $this->createMailEML (); } - // }}} /** Return the HTML body if exists in UTF-8. If the body is not in UTF-8, it * is converted @@ -685,7 +649,6 @@ class Mail * no HTML part in the mail */ public function getBodyHTML () - // {{{ { $sectionList = $this->sectionList (); $sectionIDtoChange = ""; @@ -704,7 +667,6 @@ class Mail } return false; } - // }}} /** Get the text body if exists in UTF-8. If the body is not in UTF-8, it is * converted @@ -713,7 +675,6 @@ class Mail * no Text part in the mail */ public function getBodyText () - // {{{ { $sectionList = $this->sectionList (); $sectionIDtoChange = ""; @@ -732,7 +693,6 @@ class Mail } return false; } - // }}} /** Move the sections where the parent is defined to $oldParentID to the * $newParentID. @@ -742,7 +702,6 @@ class Mail * @param string|null $oldParentID The oldParent to look for */ private function moveChilds ($newParentID, $oldParentID=false) - // {{{ { if ($newParentID === $oldParentID) throw new \Exception ("moveChilds : old and new ParentID are the same", @@ -802,7 +761,6 @@ class Mail } } } - // }}} /** Add an attachment to the mail. * The allowed encodings are "quoted-printable" or "base64" @@ -816,7 +774,6 @@ class Mail */ public function addAttachment ($name, $fileContent, $encoding="base64", $inline=false) - // {{{ { if ($this->getBodyHTML() === false && $inline !== false) $this->setBodyHTML ("No HTML provided by inline file added"); @@ -899,7 +856,6 @@ class Mail if ($inline === true) return substr ($contentID, 1, -1); } - // }}} /** Add an inline attachment to the mail. * The allowed encodings are "quoted-printable" or "base64" @@ -912,11 +868,9 @@ class Mail * @return string The content ID created */ public function addAttachmentInline ($name, $fileContent, $encoding="base64") - // {{{ { return $this->addAttachment ($name, $fileContent, $encoding, true); } - // }}} /** Get an attachment of the mail * @param integer $number the number of attach to get starting to 0 @@ -924,7 +878,6 @@ class Mail * @return string the content of the attachment. Can be binary */ public function getAttachment ($number, $inline = false) - // {{{ { $attachmentIDs = $this->getAttachmentID ($inline); if (! array_key_exists ($number, $attachmentIDs)) @@ -935,7 +888,6 @@ class Mail $part["_headersArray"]); return $this->encodingDecode ($part["_contentEML"], $encoding); } - // }}} /** Get the attachment details * @param integer $number the number of attach to get starting to 0 @@ -943,7 +895,6 @@ class Mail * @return array containing the information of the attachment */ public function getAttachmentDetails ($number, $inline = false) - // {{{ { $attachmentIDs = $this->getAttachmentID ($inline); if (! array_key_exists ($number, $attachmentIDs)) @@ -965,7 +916,6 @@ class Mail } return $res; } - // }}} /** Return the list of the sectionID containing a attachment. Contains the * inline attachments too. @@ -973,7 +923,6 @@ class Mail * @return array The sectionIDs */ private function getAttachmentID ($inline = false) - // {{{ { $res = array (); foreach ($this->sections as $sectionID=>$section) @@ -1002,14 +951,12 @@ class Mail } return $res; } - // }}} /** Add a To: header. If it already exists, add a new recipient * @param string $toMail The mail to add * @param string|null $toName The name of the recipient */ public function addTo ($toMail, $toName = "") - // {{{ { if (strspn ($toName, "abcdefghijklmnopqrstuvwxyz". "ABCDEFGHIJKLMNOPQRSTUVWXYZ". @@ -1025,24 +972,20 @@ class Mail else $this->setHeader ("To", $toField); } - // }}} /** Get the To Header as it is written in the mail * @return string The To Header defined in the mail */ public function getTo () - // {{{ { return $this->getHeader ("To"); } - // }}} /** Add a From: header. If it already exists, overwrite the existing one * @param string $fromMail The from Mail to define * @param string|null $fromName The from Name to define */ public function setFrom ($fromMail, $fromName= "") - // {{{ { if (strspn ($fromName, "abcdefghijklmnopqrstuvwxyz". "ABCDEFGHIJKLMNOPQRSTUVWXYZ". @@ -1053,23 +996,19 @@ class Mail $fromName .= " "; $this->setHeader ("From", "$fromName<$fromMail>"); } - // }}} /** Return the From header as it is written in the mail * @return string The From Header defined in the mail */ public function getFrom () - // {{{ { return $this->getHeader ("From"); } - // }}} /** Return the From header converted to array with mail and name keys * @return array The From details */ public function getFromArray () - // {{{ { $from = $this->getHeader ("From"); $res = array (); @@ -1077,59 +1016,49 @@ class Mail $from = $this->convertPeopleToArray ($from); return reset ($from); } - // }}} /** Set the subject * @param string $subject In UTF8 */ public function setSubject ($subject) - // {{{ { $this->setHeader ("Subject", $this->encodeHeaders ("Subject", $subject, "quoted-printable")); } - // }}} /** Set the Date * @param string $date In RFC 2822 format */ public function setDate ($date) - // {{{ { // TODO : Check if the date format is valid $this->setHeader ("Date", $date); } - // }}} /** Set the Date * @param string $timestamp In Timestamp format */ public function setDateTimestamp ($timestamp) - // {{{ { // TODO : Check if the timestamp is valid $this->setHeader ("Date", date ("r", $timestamp)); } - // }}} /** Get the Date header if defined. * Return false if not defined * @return string|bool The date Header if defined or false if not defined */ public function getDate () - // {{{ { return $this->getHeader ("Date"); } - // }}} /** Return the Date header (if defined) in timestamp * Return false if not defined * @return integer|bool The date Header if defined or false if not defined */ public function getDateTimestamp () - // {{{ { $datetimestamp = false; $date = rtrim ($this->getDate ()); @@ -1145,7 +1074,6 @@ class Mail } return $dateTimestamp; } - // }}} /** Set a generic header * @param string $header The name of the Header (without colon) @@ -1153,7 +1081,6 @@ class Mail * @param string|null $sectionID The section to modify. If null, use the main */ public function setHeader ($header, $value, $sectionID=null) - // {{{ { if (substr ($value, -1) !== "\n" && substr ($value, -1) !== "\r" && @@ -1196,7 +1123,6 @@ class Mail $this->sections[$sectionMainID]["_headersEML"] = $_headerEML; $this->createMailEML (); } - // }}} /** Add a generic header * @param string $header The name of the Header (without colon) @@ -1204,7 +1130,6 @@ class Mail * @param string|null $sectionID The section to modify. If null, use the main */ public function addHeader ($header, $value, $sectionID=null) - // {{{ { if (substr ($value, -1) !== "\n" && substr ($value, -1) !== "\r" && @@ -1250,14 +1175,12 @@ class Mail } $this->createMailEML (); } - // }}} /** Delete a specific header * @param string $header The header to remove * @param string|null $sectionID The section to modify. If null, use the main */ public function delHeader ($header, $sectionID=null) - // {{{ { if ($sectionID === null) { @@ -1295,7 +1218,6 @@ class Mail $this->sections[$sectionMainID]["_headersEML"] = $_headerEML; $this->createMailEML (); } - // }}} /** Get all the headers, in the order in EML. The format is * [] => array ("header" => "value") @@ -1320,7 +1242,6 @@ class Mail * @return string|bool the literal value or false if it doesn't exist */ public function getHeader ($header, $headers=null) - // {{{ { $headers = $this->getHeaders ($headers); foreach ($headers as $key=>$val) @@ -1332,7 +1253,6 @@ class Mail } return false; } - // }}} /** Get a generic header with removing the carriage return * If there is multiple headers with the same name, return the first @@ -1341,7 +1261,6 @@ class Mail * @return string|bool the literal value or false if it doesn't exist */ public function getHeaderValue ($header, $headers=null) - // {{{ { $headers = $this->getHeaders ($headers); foreach ($headers as $key=>$val) @@ -1358,12 +1277,10 @@ class Mail } return false; } - // }}} /** Create the complete mail structure */ public function createMailEML () - // {{{ { $complete = ""; $this->recurse = 0; @@ -1380,13 +1297,11 @@ class Mail } $this->completeEmailEML = $complete; } - // }}} /** Recursive email EML creation for childs * @param array $parent The parent array */ private function createMailEMLSub ($parent) - // {{{ { $this->recurse++; if ($this->recurse > 120) @@ -1412,20 +1327,17 @@ class Mail $complete .= "--".$parent["_boundary"]."--".$parent["_boundaryCR"]; return $complete; } - // }}} /** Return the complete mail * @return string The complete mail */ public function getMail () - // {{{ { if (trim ($this->getBodyHTML()) === "No HTML provided by inline file added") throw new \Exception ("No HTML provided by inline file added", 500); return $this->completeEmailEML; } - // }}} /** Return an array with the details of the mail : * the number of attachments, the from, to, subject in UTF-8, if there is @@ -1433,7 +1345,6 @@ class Mail * @return array The details of the mail */ public function getDetails () - // {{{ { $bodyTextExists = false; $bodyHTMLExists = false; @@ -1475,13 +1386,11 @@ class Mail $subject = $this->decodeHeaders ("Subject", $this->getHeader ("Subject")); return get_defined_vars(); } - // }}} /** Create a boundary * @return string the textual boundary */ private function getBoundary () - // {{{ { $data = openssl_random_pseudo_bytes (16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0010 @@ -1489,13 +1398,11 @@ class Mail return "-----".vsprintf ('%s%s%s%s%s%s%s%s', str_split (bin2hex ($data), 4)); } - // }}} /** Create a messageID * @return string the textual MessageID */ public function provideMessageID () - // {{{ { $data = openssl_random_pseudo_bytes (16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0010 @@ -1504,7 +1411,6 @@ class Mail str_split (bin2hex ($data), 4))."@". php_uname('n').">"; } - // }}} /** Convert the content to correct encoding. * The allowed encodings are "quoted-printable" or "base64" or "flowed" @@ -1514,7 +1420,6 @@ class Mail * @return string the content encoded by $encoding */ private function encodingEncode ($content, $encoding) - // {{{ { if ($encoding === "quoted-printable") { @@ -1534,7 +1439,6 @@ class Mail dgettext ("domframework", "Invalid encoding provided to encodingEncode : %s"), $encoding), 500); } - // }}} /** Decode the content with correct encoding. * The allowed encodings are "quoted-printable" or "base64" or "8bit" @@ -1543,7 +1447,6 @@ class Mail * @return the content decoded by $encoding */ private function encodingDecode ($content, $encoding) - // {{{ { if ($encoding === "quoted-printable") return quoted_printable_decode ($content); @@ -1555,7 +1458,6 @@ class Mail dgettext ("domframework", "Invalid encoding provided to encodingDecode : '%s'"), $encoding), 500); } - // }}} /** Encode a string to be compliant with MIME (used in headers) * @param string $header The header to be used. Will not be returned, but the @@ -1566,7 +1468,6 @@ class Mail * @return string the content encoded by $encoding */ private function encodeHeaders ($header, $content, $encoding) - // {{{ { $prefs = array ("input-charset" => "utf-8", "output-charset" => "utf-8"); @@ -1580,7 +1481,6 @@ class Mail return substr (iconv_mime_encode ($header, $content, $prefs), strlen ($header)+2); } - // }}} /** Convert the header to text * @param string $header The header to decode @@ -1588,12 +1488,10 @@ class Mail * @return string the header converted */ private function decodeHeaders ($header, $content) - // {{{ { return substr (iconv_mime_decode ("$header: $content", 0, "utf-8"), strlen ($header)+2); } - // }}} /** Encode a header string not starting on first column. The number of chars * need to be skipped is passed as argument. The function will correctely @@ -1605,7 +1503,6 @@ class Mail * @return string the content encoded by $encoding */ private function encodeHeaderStringWithPosition ($content, $encoding, $blanks) - // {{{ { $prefs = array ("input-charset" => "utf-8", "output-charset" => "utf-8"); @@ -1620,7 +1517,6 @@ class Mail $prefs), $blanks+2); } - // }}} /** Convert a From/To string to array. Manage multiple recipients * Ex. : toto toto , titi @@ -1630,7 +1526,6 @@ class Mail * @return array The array with the converted data */ public function convertPeopleToArray ($data) - // {{{ { $elements = explode (",", $data); $res = array (); @@ -1652,14 +1547,12 @@ class Mail } return $res; } - // }}} /** Analyze the Content-Type line and return an array with the values * @param string $contentType The content Type to analyze * @return array The analyzed Content-Type */ public function contentTypeAnalyze ($contentType) - // {{{ { $contentType = preg_replace ("#[\r\n]+[ \t]+#", " ", $contentType); $elements = explode (";", $contentType); @@ -1678,5 +1571,4 @@ class Mail } return $res; } - // }}} } diff --git a/src/Outputdl.php b/src/Outputdl.php index 38fc870..b342250 100644 --- a/src/Outputdl.php +++ b/src/Outputdl.php @@ -34,14 +34,12 @@ class Outputdl * @return $this|boolean */ public function resumeAllow ($resumeAllow = null) - // {{{ { if ($resumeAllow === null) return $this->resumeAllow; $this->resumeAllow = !! $resumeAllow; return $this; } - // }}} /** Get/Set Base of filesystem * The base directory is use to secure the download. A user can not request @@ -52,39 +50,33 @@ class Outputdl * @return $this|string */ public function base ($base = null) - // {{{ { if ($base === null) return $this->base; $this->base = $base; return $this; } - // }}} /** Get headers from headers list * The headers can be tested too * @return array */ public function headers () - // {{{ { return $this->headers; } - // }}} /** Add a new header and send it if possible * @param string $header The header to send * @return $this */ private function header ($header) - // {{{ { if (! headers_sent()) header ($header); $this->headers[] = $header; return $this; } - // }}} /** Download a file with management of Partial Download (like resume) * Manage the HTTP headers to allow to resume the download if it is allowed @@ -93,7 +85,6 @@ class Outputdl * @param string|null $filename The filename to send to the browser */ public function downloadFile ($path, $filename = null) - // {{{ { if (!file_exists ($path)) throw new \Exception (dgettext ("domframework", @@ -195,7 +186,6 @@ class Outputdl exit; return; } - // }}} /** Download the file. Do not go through the renderer * @param string $path The path to download @@ -203,7 +193,6 @@ class Outputdl * @param integer $stop The stop range */ private function downloadFileRange ($path, $start, $stop) - // {{{ { $file = realpath ($path); $chunksize = 10*1024*1024; // how many bytes per chunk @@ -230,5 +219,4 @@ class Outputdl } fclose($handle); } - // }}} } diff --git a/src/Password.php b/src/Password.php index 3dd99af..6c5612e 100644 --- a/src/Password.php +++ b/src/Password.php @@ -17,7 +17,6 @@ class Password /** List all the allowed hashing methods, sort from weak to strong encryption */ private $methods = array ( - // {{{ "MYSQL" => array ( "hash" => "", "size" => "", "pre" => "", "post" => ""), "CRYPT_STD_DES" => array ( @@ -42,7 +41,6 @@ class Password "PASSWORD_ARGON2ID" => array ( "hash" => PASSWORD_ARGON2ID, "size" => "", "pre" => "", "post" => ""), ); - // }}} ///////////////// // METHODS // @@ -52,7 +50,6 @@ class Password * @return array ("PASSWORD_ARGON2ID" => PASSWORD_ARGON2ID); */ public function listMethods () - // {{{ { $res = array (); foreach ($this->methods as $key => $params) @@ -66,13 +63,11 @@ class Password } return $res; } - // }}} /** Create a salt, based on openssl_random_pseudo_bytes function * @return string a string salt */ public function salt () - // {{{ { if (function_exists ("openssl_random_pseudo_bytes")) $salt = substr (base64_encode (openssl_random_pseudo_bytes (17)), 0, 22); @@ -84,7 +79,6 @@ class Password $salt = str_replace ("+",".",$salt); return $salt; } - // }}} /** Crypt the provided password with the wanted crypt method * @param string $password The password to crypt @@ -93,7 +87,6 @@ class Password * @return string The hashed password */ public function cryptPassword ($password, $method = null) - // {{{ { if (! is_string ($password) && ! is_integer ($password)) throw new \Exception (dgettext ("domframework", @@ -123,19 +116,16 @@ class Password throw new \Exception (sprintf (dgettext ("domframework", "Password : Unknown method to crypt requested : %s"), $method), 500); } - // }}} /** Crypt the password with the best algorithm available * @param string $password The password to crypt * @return string The hashed password */ static public function cryptPasswd ($password) - // {{{ { $passwd = new Password (); return $passwd->cryptPassword ($password); } - // }}} /** Check if the clear password is valid against the hashed one * @param string $clear The clear password @@ -143,7 +133,6 @@ class Password * @return boolean true if the password correspond to the hash */ static public function checkPassword ($clear, $hashed) - // {{{ { if (! is_string ($clear)) throw new \Exception (dgettext ("domframework", @@ -159,7 +148,6 @@ class Password return true; return false; } - // }}} /** Create a random password with $nbChars chars, ASCII chars (with special * chars). @@ -168,7 +156,6 @@ class Password * @return string The random password */ static public function generateASCII ($nbChars = 12) - // {{{ { if (! is_int ($nbChars) || $nbChars < 1) throw new \Exception (dgettext ("domframework", @@ -189,7 +176,6 @@ class Password shuffle ($password); return implode ($password); } - // }}} /** Create a random password with $nbChars chars, Alphanumericals chars * (without special chars) @@ -197,7 +183,6 @@ class Password * @return string The random password */ static public function generateAlphanum ($nbChars = 12) - // {{{ { if (! is_int ($nbChars) || $nbChars < 1) throw new \Exception (dgettext ("domframework", @@ -214,7 +199,6 @@ class Password shuffle ($password); return implode ($password); } - // }}} /** Create a random password with $nbChars chars, Alphabeticals chars * (without special chars, neither numbers) @@ -222,7 +206,6 @@ class Password * @return string The random password */ static public function generateAlphabetical ($nbChars = 12) - // {{{ { if (! is_int ($nbChars) || $nbChars < 1) throw new \Exception (dgettext ("domframework", @@ -239,5 +222,4 @@ class Password shuffle ($password); return implode ($password); } - // }}} } diff --git a/src/Queuefile.php b/src/Queuefile.php index e5af1f1..47dae84 100644 --- a/src/Queuefile.php +++ b/src/Queuefile.php @@ -29,7 +29,6 @@ class Queuefile extends Queue * @return $this; */ public function connect ($dsn) - // {{{ { // The DSN format must be file:///tmp/queuefile.txt if (substr ($dsn, 0, 7) !== "file://") @@ -43,14 +42,12 @@ class Queuefile extends Queue $file->touch ($this->queue); return $this; } - // }}} /** Add a new entry to the end of the queue * @param mixed $entry The entry to add * @return $this; */ public function add ($entry) - // {{{ { $file = new File (); $file->lockEX ($this->queue); @@ -59,14 +56,12 @@ class Queuefile extends Queue $file->lockUN ($this->queue); return $this; } - // }}} /** Get all the entries of the queue * @param boolean|null $delete If true, delete the read entry * @return array */ public function getAll ($delete =false) - // {{{ { $file = new File (); if ($delete) @@ -86,12 +81,10 @@ class Queuefile extends Queue $file->lockUN ($this->queue); return $entries; } - // }}} /** Get the number of entries in the queue */ public function count () - // {{{ { $file = new File (); $file->lockSH ($this->queue); @@ -100,13 +93,11 @@ class Queuefile extends Queue $file->lockUN ($this->queue); return $count; } - // }}} /** Clear all the entries of the queue * @return $this; */ public function clear () - // {{{ { $file = new File (); $file->lockEX ($this->queue); @@ -114,7 +105,6 @@ class Queuefile extends Queue $file->lockUN ($this->queue); return $this; } - // }}} /** Get the first entry in the queue with optional removing of the entry * @param boolean|null $delete If true, delete the read entry @@ -122,7 +112,6 @@ class Queuefile extends Queue * queue (FIFO) */ public function getFirst ($delete = false) - // {{{ { $file = new File (); if ($delete) @@ -146,7 +135,6 @@ class Queuefile extends Queue $file->lockUN ($this->queue); return $res; } - // }}} /** Get the last entry in the queue with optional removing of the entry * @param boolean|null $delete If true, delete the read entry @@ -154,7 +142,6 @@ class Queuefile extends Queue * queue (LIFO) */ public function getLast ($delete = false) - // {{{ { $file = new File (); if ($delete) @@ -178,7 +165,6 @@ class Queuefile extends Queue $file->lockUN ($this->queue); return $res; } - // }}} /** Get X entries starting at position Y * @param integer $start the starting position (the entries start at position @@ -188,7 +174,6 @@ class Queuefile extends Queue * @return array An array of mixed entries */ public function getRange ($start, $number, $delete = false) - // {{{ { $file = new File (); if ($delete) @@ -224,5 +209,4 @@ class Queuefile extends Queue $file->lockUN ($this->queue); return $res; } - // }}} } diff --git a/src/Rest.php b/src/Rest.php index ab0ddbe..6da9ffe 100644 --- a/src/Rest.php +++ b/src/Rest.php @@ -29,7 +29,6 @@ class Rest * @return string like "json", "xml", "txt", "csv" */ public function chooseType () - // {{{ { $type = reset ($this->allowedtypes); if (isset ($_SERVER["HTTP_ACCEPT"])) @@ -45,7 +44,6 @@ class Rest } return $type; } - // }}} /** Display the message (which can be a string, an array, an integer...) * into the type asked by the client if it is allowed. @@ -54,7 +52,6 @@ class Rest * @param integer|null $code HTTP code to use */ function display ($message, $code = 200) - // {{{ { $http = new Http; $text = $http->codetext ($code); @@ -65,5 +62,4 @@ class Rest $obj = new $constr (); $obj->$method ($message); } - // }}} } diff --git a/src/Robotstxt.php b/src/Robotstxt.php index 5d03084..f953727 100644 --- a/src/Robotstxt.php +++ b/src/Robotstxt.php @@ -18,7 +18,6 @@ namespace Domframework; class Robotstxt { // PROPERTIES - // {{{ /** The allowed urls */ private $allow = array (); @@ -47,7 +46,6 @@ class Robotstxt * default is set */ private $errors = array (); - // }}} // METHODS /** Get the robots.txt file content and do the analyze @@ -56,7 +54,6 @@ class Robotstxt * @return $this */ public function __construct ($content, $crawlerName) - // {{{ { if (trim ($content) === "") { @@ -155,7 +152,6 @@ class Robotstxt $this->allow[] = "/"; return $this; } - // }}} /** Return true if the provided URL can be used against the robots.txt * definition or FALSE if it is not the case @@ -163,7 +159,6 @@ class Robotstxt * @return boolean The result of the test */ public function URLAllow ($url) - // {{{ { $parse = parse_url ($url); $path = (isset ($parse["path"])) ? $parse["path"] : "/"; @@ -224,7 +219,6 @@ class Robotstxt $this->matchRule = $disallowRule; return false; } - // }}} // GETTERS /** Return the lines where an error occured @@ -232,71 +226,57 @@ class Robotstxt * @return array The errors */ public function errors () - // {{{ { return $this->errors; } - // }}} /** Return the allowed urls * @return array $allow The array of allow rules */ public function allow () - // {{{ { return $this->allow; } - // }}} /** Return the disallowed urls * @return array $disallow The array of disallow rules */ public function disallow () - // {{{ { return $this->disallow; } - // }}} /** Return the sitemaps url * @return array $sitemap The array of sitemaps URL */ public function sitemaps () - // {{{ { return $this->sitemaps; } - // }}} /** Return the crawldelay * @return integer $crawldelay The crawlDelay defined in robots.txt */ public function crawldelay () - // {{{ { return $this->crawldelay; } - // }}} /** Return the host * @return string $host The Host string defined in robots.txt */ public function host () - // {{{ { return $this->host; } - // }}} /** Return the matchRule * @return string $matchRule The matchRule matching the URLAllow test */ public function matchRule () - // {{{ { return $this->matchRule; } - // }}} // PRIVATE METHODS /** Get a line from robots.txt file and return the associated value. @@ -305,11 +285,9 @@ class Robotstxt * @return string the value recorded on line */ private function getValueFromLine ($line) - // {{{ { preg_match_all ("#^(?P\S+):\s*(?P\S*)\s*". "(\#\s*(?P.+)\s*)?\$#", $line, $matches); return $matches["value"][0]; } - // }}} } diff --git a/src/Sitemap.php b/src/Sitemap.php index 8c1c041..0ef7c98 100644 --- a/src/Sitemap.php +++ b/src/Sitemap.php @@ -29,7 +29,6 @@ class Sitemap * @return array The content of the file if it is valid */ public function analyze ($content, $url) - // {{{ { $finfo = new \finfo (FILEINFO_MIME_TYPE); $type = $finfo->buffer ($content); @@ -48,7 +47,6 @@ class Sitemap else throw new \Exception ("Type of sitemap '$type' unknown for '$url'", 406); } - // }}} /** Return an array containing the URL in sitemap associated with an empty * array, as the Text format provide only URL, so return empty array. @@ -64,7 +62,6 @@ class Sitemap * @return array The content of the file if it is valid */ public function analyzeText ($content, $url) - // {{{ { if (strlen ($content) > 10000000) { @@ -77,7 +74,6 @@ class Sitemap $urls = array_fill_keys ($urls, array ()); return array ("urls" => $urls, "sitemaps" => array ()); } - // }}} /** Return an array containing the URL in sitemap associated with the * information of priority and changefreq (in seconds) @@ -95,7 +91,6 @@ class Sitemap * @return array The content of the file if it is valid */ public function analyzeXML ($content, $url) - // {{{ { if (strlen ($content) > 10000000) throw new \Exception ("Sitemap '$url' size is too big -> skip", 406); @@ -186,5 +181,4 @@ class Sitemap } return $res; } - // }}} } diff --git a/src/Spfcheck.php b/src/Spfcheck.php index 7cb6f5f..aa4ebbe 100644 --- a/src/Spfcheck.php +++ b/src/Spfcheck.php @@ -58,7 +58,6 @@ class Spfcheck * @return array (The netmasks to match, the last all) */ public function getRecords ($domain) - // {{{ { $this->errors = array (); $this->dnsCounter = 0; @@ -70,7 +69,6 @@ class Spfcheck "No catch all defined for the domain"); return $this->ipRecords; } - // }}} /** Try to match the provided IP address against the $domain SPF record to * be get @@ -79,7 +77,6 @@ class Spfcheck * @return string PASS/FAIL/SOFTFAIL */ public function ipCheckToSPF ($domain, $ip) - // {{{ { $ips = $this->getRecords ($domain); if (filter_var ($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) @@ -144,7 +141,6 @@ class Spfcheck "SFPCheck : Can not determine the SPF result with params '%s' and '%s'"), $domain, $ip), 403 ); } - // }}} ///////////////// // GETTERS // @@ -152,56 +148,44 @@ class Spfcheck /** Get the errors detected when reading the SPF record */ public function getErrors () - // {{{ { return $this->errors; } - // }}} /** Get the DNS requests done to get the SPF records */ public function getDNSRequests () - // {{{ { return $this->dnsRequests; } - // }}} /** Get the number of DNS queries */ public function getDNSRequestNumber () - // {{{ { return $this->dnsCounter; } - // }}} /** Get default case (if set) */ public function getDefaultCase () - // {{{ { return $this->catchAll; } - // }}} /** Get the matching rule when testing an IP against a SPF domain record */ public function getMatchRule () - // {{{ { return $this->matchRule; } - // }}} /** Get the IPs from the SPF records */ public function getIpRecords () - // {{{ { return $this->ipRecords; } - // }}} /** Get the DNS values set for the provided $domain/$part(/$entity) * @param string $search The search entity @@ -227,7 +211,6 @@ class Spfcheck * @return array (The netmasks to match, the last all) */ private function getRecordsRecurse ($domain) - // {{{ { $records = array (); $localAll = ""; @@ -265,7 +248,6 @@ class Spfcheck $part = substr ($part, 1); } if (stripos ($part, "redirect=") === 0) - // {{{ { if ($sign !== "") { @@ -285,10 +267,8 @@ class Spfcheck } $ips = $ips + $this->getRecordsRecurse ($ext); } - // }}} // "include:" part elseif (stripos ($part, "include:") === 0) - // {{{ { if ($sign !== "") { @@ -308,10 +288,8 @@ class Spfcheck } $ips = $ips + $this->getRecordsRecurse ($ext); } - // }}} // "mx:" / "mx" part elseif (stripos ($part, "mx:") === 0 || strtolower ($part) === "mx") - // {{{ { $partWithDomain = $part; if ($partWithDomain === "mx") @@ -343,10 +321,8 @@ class Spfcheck } sort ($ips[$domain][$sign.$part]); } - // }}} // "ip4:" part elseif (stripos ($part, "ip4:") === 0) - // {{{ { $ext = substr ($part, 4); if (! is_string ($ext) || trim ($ext) === "") @@ -378,10 +354,8 @@ class Spfcheck } $ips[$domain][$sign.$part][] = $ip.$mask; } - // }}} // "ip6:" part elseif (stripos ($part, "ip6:") === 0) - // {{{ { $ext = substr ($part, 4); if (! is_string ($ext) || trim ($ext) === "") @@ -413,10 +387,8 @@ class Spfcheck } $ips[$domain][$sign.$part][] = $ip.$mask; } - // }}} // "ptr:" MUST NOT BE USED elseif (stripos ($part, "ptr:") === 0 || strtolower ($part) === "ptr") - // {{{ { $this->errors[$domain][$sign.$part] = sprintf (dgettext ("domframework", @@ -424,10 +396,8 @@ class Spfcheck "(see RFC7208) : Skip it"), $domain, $part); continue; } - // }}} // "a:" part elseif (stripos ($part, "a:") === 0 || strtolower ($part) === "a") - // {{{ { $partWithDomain = $part; if ($partWithDomain === "a") @@ -454,10 +424,8 @@ class Spfcheck } sort ($ips[$domain][$sign.$part]); } - // }}} // "-all" / "~all" / "+all" part elseif (strtolower ($part) === "all") - // {{{ { $ips[$domain][$sign.$part] = array (); if ($localAll !== "") @@ -478,7 +446,6 @@ class Spfcheck $this->catchAll = $sign.$part; $this->catchAllDomain = $domain; } - // }}} else { $this->errors [$domain][$sign.$part] = @@ -489,7 +456,6 @@ class Spfcheck } return $ips; } - // }}} /** Get the requested hostname and get the type * @param string $hostname The hostname to get @@ -498,7 +464,6 @@ class Spfcheck * @return array (array (ip (for A), target (for TXT)); */ private function dns_get_record ($hostname, $type, $domain) - // {{{ { $typeStr = ""; switch ($type) @@ -566,6 +531,5 @@ class Spfcheck $this->dnsRequests[$domain] = $res; return $res; } - // }}} } diff --git a/src/Sse.php b/src/Sse.php index f4508bf..fa1b38b 100644 --- a/src/Sse.php +++ b/src/Sse.php @@ -22,7 +22,6 @@ class Sse ////////////////////////// //// PROPERTIES //// ////////////////////////// - // {{{ /** The backend File to use */ private $files; @@ -41,7 +40,6 @@ class Sse /** The handlers parameters */ private $handlersParams = array (); - // }}} ////////////////////////////// //// SETTER METHODS //// @@ -54,7 +52,6 @@ class Sse * @return $this */ final public function setBackendFiles ($files) - // {{{ { if (! is_array ($files)) $files = array ("data" => $files); @@ -76,14 +73,12 @@ class Sse $this->files = $files; return $this; } - // }}} /** The pingTime to use. Must be positive. If null, the ping is disabled * @param integer|float $pingTime The time in seconds between two keepalive * pings */ final public function setPingTime ($pingTime) - // {{{ { if (! is_float ($pingTime) && ! is_integer ($pingTime)) throw new \Exception (sprintf (dgettext ("domframework", @@ -96,7 +91,6 @@ class Sse $this->pingTime = $pingTime; return $this; } - // }}} /** The optional handler to use in DataOnly. Must be callable method * @param callable|null $handler The handler @@ -104,7 +98,6 @@ class Sse * @param mixed... $params The optional needed parameters */ final public function setHandlerDataonly ($handler, $params = null) - // {{{ { if (! is_callable ($handler) && $handler !== null) throw new \Exception (dgettext ("domframework", @@ -115,7 +108,6 @@ class Sse $this->handlersParams["data"] = $args; return $this; } - // }}} /** The optional handler to use in Events. Must be array of callable methods * @param array $handlers The handlers method, array[event=>callable] @@ -127,7 +119,6 @@ class Sse * if event=>null is set, remove the parameters for the event */ final public function setHandlersEvent ($handlers, $params = null) - // {{{ { if (! is_array ($handlers)) throw new \Exception (dgettext ("domframework", @@ -163,7 +154,6 @@ class Sse } return $this; } - // }}} ////////////////////////////// //// PUBLIC METHODS //// @@ -174,7 +164,6 @@ class Sse * Never return ! */ final public function loop () - // {{{ { if ($this->files === null) throw new \Exception (dgettext ("domframework", @@ -242,7 +231,6 @@ class Sse usleep(100000); } } - // }}} /////////////////////////////// //// PRIVATE METHODS //// @@ -250,7 +238,6 @@ class Sse /** Initialize the backend : open all the files and go at the end */ private function backendInit () - // {{{ { if ($this->files === null) throw new \Exception (dgettext ("domframework", @@ -265,7 +252,6 @@ class Sse } } } - // }}} /** Get the pending lines from requested backend * @param string $event The event to get data @@ -273,7 +259,6 @@ class Sse * @return string the data lines stored in the lines */ private function backendGet ($event) - // {{{ { // If the file was previously opened but doesn't exists anymore. Close it // and reopen it just after @@ -304,7 +289,6 @@ class Sse } return $res; } - // }}} /** Initialize the backend for one specific file. * @param string $event The event to start @@ -312,7 +296,6 @@ class Sse * @return boolean false if the file doesn't exists */ private function backendInitEvent ($event, $filePath) - // {{{ { clearstatcache (true, $filePath); if (! file_exists (dirname ($filePath))) @@ -337,5 +320,4 @@ class Sse $this->fps[$event] = $fp; return $this; } - // }}} } diff --git a/src/Tcpclient.php b/src/Tcpclient.php index bf69835..a17e331 100644 --- a/src/Tcpclient.php +++ b/src/Tcpclient.php @@ -21,7 +21,6 @@ namespace Domframework; class Tcpclient { // PROPERTIES // - // {{{ /** The IPv6 allowed for the server */ private $ipv6 = array (); @@ -54,14 +53,12 @@ class Tcpclient * 30s by default */ private $timeout = 30; - // }}} /** Initialize the object, by setting the name or the IP of the server * @param string $ipOrName The IP or the name of the server * @param integer $port The port of the server to connect */ public function __construct ($ipOrName, $port) - // {{{ { $providedIpOrName = $ipOrName; if (filter_var ($ipOrName, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) @@ -110,14 +107,12 @@ class Tcpclient shuffle ($this->ipv6); shuffle ($this->ipv4); } - // }}} /** Set/get the preferIPv4 property * @param boolean|null $preferIPv4 The preferIPv4 property to set (or to get * if null) */ public function preferIPv4 ($preferIPv4 = null) - // {{{ { if ($preferIPv4 === null) return $this->preferIPv4; @@ -127,13 +122,11 @@ class Tcpclient $this->preferIPv4 = !!$preferIPv4; return $this; } - // }}} /** Set/get the read mode : text or binary * @param string|null $readMode The mode to set (or get if null) */ public function readMode ($readMode = null) - // {{{ { if ($readMode === null) return $this->readMode; @@ -143,26 +136,22 @@ class Tcpclient $this->readMode = $readMode; return $this; } - // }}} /** Set/get the timeout * @param integer|null $timeout The timeout in seconds */ public function timeout ($timeout = null) - // {{{ { if ($timeout === null) return $this->timeout; $this->timeout = intval ($timeout); return $this; } - // }}} /** Initialize the connection to the server * Return the socket */ public function connect () - // {{{ { if ($this->preferIPv4) $ips = array_merge ($this->ipv4, $this->ipv6); @@ -191,7 +180,6 @@ class Tcpclient throw new \Exception ("Can not connect to server $this->ipOrName : ". $errstr, 500); } - // }}} /** Activate the SSL connection. * Put the socket in blocking mode, as it is mandatory to have SSL connection @@ -202,7 +190,6 @@ class Tcpclient * with the server */ public function cryptoEnable ($val, $cryptoMethod = null, $options = array ()) - // {{{ { if ($this->socket === null) throw new \Exception ("Can not send to server $this->ipOrName : ". @@ -231,14 +218,12 @@ class Tcpclient substr (strrchr ($php_errormsg, ":"), 1), 500); return $rc; } - // }}} /** Send a data to the server. * The connection must be established * @param mixed $data The data to send */ public function send ($data) - // {{{ { if ($this->socket === null) throw new \Exception ("Can not send to server $this->ipOrName : ". @@ -250,7 +235,6 @@ class Tcpclient throw new \Exception ("Can not send to server $this->ipOrName", 500); return $sentLen; } - // }}} /** Read the data from the server. * The connection must be established @@ -261,7 +245,6 @@ class Tcpclient * @return string The content */ public function read ($maxLength = 1024) - // {{{ { if ($this->socket === null) throw new \Exception ("Can not read from server $this->ipOrName : ". @@ -281,12 +264,10 @@ class Tcpclient } return $read; } - // }}} /** Disconnect the socket */ public function disconnect () - // {{{ { if ($this->socket === null) throw new \Exception ("Can not disconnect server $this->ipOrName : ". @@ -294,22 +275,18 @@ class Tcpclient @stream_socket_shutdown ($this->socket, STREAM_SHUT_RDWR); $this->socket = null; } - // }}} /** Get meta data, like the timeout state, the crypto protocol and ciphers... */ public function getMeta () - // {{{ { return stream_get_meta_data ($this->socket); } - // }}} /** Get the connection peer address, peer port and localaddress and localport * @return array */ public function getInfo () - // {{{ { if ($this->socket === null) throw new \Exception ("Can not getInfo for server $this->ipOrName : ". @@ -324,15 +301,12 @@ class Tcpclient $address = substr ($name, 0, $pos); return array ($address, $port, $localAddress, $localPort); } - // }}} /** Get the socket to direct access * @return resource The socket with the client */ public function getSock () - // {{{ { return $this->socket; } - // }}} } diff --git a/src/Tcpserver.php b/src/Tcpserver.php index 35c4973..b0abbaf 100644 --- a/src/Tcpserver.php +++ b/src/Tcpserver.php @@ -24,7 +24,6 @@ class Tcpserver //////////////////// // PROPERTIES // //////////////////// - // {{{ /** Allow to debug with messages on screen */ private $debug = false; @@ -66,7 +65,6 @@ class Tcpserver private $processName = "tcpserver"; private $ipOrName; - // }}} //////////////////////// // PUBLIC METHODS // @@ -75,27 +73,22 @@ class Tcpserver * stream_select () when the process is killed */ public function __construct () - // {{{ { $this->logDebug ("NEW OBJECT CONSTRUCTED"); set_error_handler([$this, 'errorHandler']); } - // }}} /** The destructor is a log for debug */ public function __destruct () - // {{{ { $this->logDebug ("Object destructed"); } - // }}} /** Set/get the max children, the maximum of concurrent connections * @param integer|null $val The number of child to get/set */ final public function maxChild ($val = null) - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($val === null) @@ -103,13 +96,11 @@ class Tcpserver $this->maxChild = intval ($val); return $this; } - // }}} /** Set/get the read mode : text or binary * @param string|null $val The mode to set (or get if null) */ final public function readMode ($val = null) - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($val === null) @@ -120,13 +111,11 @@ class Tcpserver $this->readMode = $val; return $this; } - // }}} /** Set the process name displayed in system * @param string|null $val The name of the process to set (or get if null) */ final public function processName ($val = null) - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($val === null) @@ -134,13 +123,11 @@ class Tcpserver $this->processName = $val; return $this; } - // }}} /** Set the timeout for open communication without any data transmited. * @param string|null $val The number of seconds to set (or get if null) */ final public function timeout ($val = null) - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($val === null) @@ -154,7 +141,6 @@ class Tcpserver $this->timeout = intval ($val); return $this; } - // }}} /** Set the address, port and handler that will be enabled by loop * @param string $address The server address (can be 0.0.0.0 for all IPv4 @@ -164,7 +150,6 @@ class Tcpserver * connected to the address:port */ final public function init ($address, $port, $handler) - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); $this->nbChild = 0; @@ -173,12 +158,10 @@ class Tcpserver $this->ports[] = $port; return $this; } - // }}} /** Start the main loop after the init and keep in it until loopStop */ final public function loop () - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if (empty ($this->addresses)) @@ -335,25 +318,21 @@ class Tcpserver } } } - // }}} /** Request the loop to stop. Will not allow new connections, but wait the * end of the existing processus * Block until all is closed */ final public function loopStop () - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); $this->loopStop = true; } - // }}} /** Start the main loop in background and do not wait its end * @return integer the PID of the child */ final public function loopInBackgroundStart () - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); $this->logDebug ("Start loopInBackground"); @@ -384,12 +363,10 @@ class Tcpserver $this->loop (); exit; } - // }}} /** Stop the main loop in background and wait until its end */ final public function loopInBackgroundStop () - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); $this->logDebug ("Request loopInBackgroundStop"); @@ -397,13 +374,11 @@ class Tcpserver pcntl_waitpid ($this->pidLoopInBackground, $status); $this->logDebug ("Request loopInBackgroundStop : END"); } - // }}} /** In child, get the socket to direct access * @return resource The socket with the client */ final public function getSock () - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($this->parent === true) @@ -412,7 +387,6 @@ class Tcpserver throw new \Exception ("Can not send to client : not connected", 500); return $this->socket; } - // }}} /** Get an array with the peer address, peer port, local address and local * port @@ -420,7 +394,6 @@ class Tcpserver * port) */ final public function getInfo () - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($this->parent === true) @@ -441,7 +414,6 @@ class Tcpserver $localAddress = substr ($localAddress, 8, -1); return array ($address, $port, $localAddress, $localPort); } - // }}} /** Activate the SSL connection * Put the socket in blocking mode, as it is mandatory to have SSL connection @@ -450,7 +422,6 @@ class Tcpserver */ final public function cryptoEnable ($val, $cryptoMethod = STREAM_CRYPTO_METHOD_TLS_SERVER) - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($this->socket === null) @@ -465,13 +436,11 @@ class Tcpserver stream_context_set_option ($this->socket, $options); return @stream_socket_enable_crypto ($this->socket, !!$val, $cryptoMethod); } - // }}} /** Set context SSL option. * @param array $options The ssl array to set */ final public function setSSLOptions ($options) - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($this->socket === null) @@ -479,14 +448,12 @@ class Tcpserver "The server is not connected", 500); return stream_context_set_option ($this->socket, array ("ssl" => $options)); } - // }}} /** Send data to the client * @param mixed $data The data to send * @return the length of data sent */ final public function send ($data) - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($this->parent === true) @@ -500,7 +467,6 @@ class Tcpserver $this->logSend ($data); return $sentLen; } - // }}} /** Read the data from the client. * The connection must be established @@ -510,7 +476,6 @@ class Tcpserver * @return string The content */ final public function read ($maxLength = 1024) - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($this->parent === true) @@ -534,12 +499,10 @@ class Tcpserver $this->logReceive ($read); return $read; } - // }}} /** Disconnect the socket */ final public function disconnect () - // {{{ { $this->logMethods (__METHOD__, func_get_args ()); if ($this->parent === true) @@ -549,14 +512,12 @@ class Tcpserver @stream_socket_shutdown ($this->socket, STREAM_SHUT_RDWR); $this->socket = null; } - // }}} /** Log the data send to the client. By default, do nothing, but can be * overrided by the user * @param string $data The data to store in log */ public function logSend ($data) - // {{{ { if (! $this->debug) return; @@ -564,14 +525,12 @@ class Tcpserver file_put_contents ("/tmp/debug", date ("H:i:s")." [".posix_getpid (). "] S> $data", FILE_APPEND); } - // }}} /** Log the data received from the client. By default, do nothing, but can be * overrided by the user * @param string $data The data to store in log */ public function logReceive ($data) - // {{{ { if (! $this->debug) return; @@ -579,7 +538,6 @@ class Tcpserver file_put_contents ("/tmp/debug", date ("H:i:s")." [".posix_getpid (). "] C> $data", FILE_APPEND); } - // }}} /** Log the methods called. By default, do nothing, but can be overrided by * the user @@ -587,7 +545,6 @@ class Tcpserver * @param mixed|null $args The data to store in log */ public function logMethods ($method, $args) - // {{{ { if (! $this->debug) return; @@ -617,33 +574,28 @@ class Tcpserver file_put_contents ("/tmp/debug", date ("H:i:s")." [".posix_getpid (). "] METHOD $data", FILE_APPEND); } - // }}} /** Log the debug, By defaul do nothing, but can be overrided by the user * @param mixed|null $params The data to store in log */ public function logDebug ($params) - // {{{ { if (! $this->debug) return; file_put_contents ("/tmp/debug", date ("H:i:s")." [".posix_getpid (). "] DEBUG $params\n", FILE_APPEND); } - // }}} /** Log the errors, By defaul do nothing, but can be overrided by the user * @param mixed|null $params The data to store in log */ public function logError ($params) - // {{{ { if (! $this->debug) return; file_put_contents ("/tmp/debug", date ("H:i:s")." [".posix_getpid (). "] ERROR $params\n", FILE_APPEND); } - // }}} /** Error catcher. * By default, do nothing, but can be overrided by the user @@ -653,38 +605,32 @@ class Tcpserver * @param integer $line The line where the error raised */ public function errorHandler ($errNo, $errMsg, $file, $line) - // {{{ { // @-operator : error suppressed if (0 === error_reporting()) return false; $this->logError ("line $line : $errMsg"); } - // }}} /** Exception catcher * By default do nothing, but can be overrided by the user * @param object $exception The exception to catch */ public function exceptionHandler ($exception) - // {{{ { $this->logError ("Exception ".$exception->getMessage () . " (". $exception->getFile ().":".$exception->getLine().")"); } - // }}} /** Manage the timeout handler * By default, disconnect and generate an exception */ public function timeoutHandler () - // {{{ { $this->disconnect (); throw new \Exception (dgettext ("domframework", "Disconnected for inactivity"), 500); } - // }}} ///////////////////////// // PRIVATE METHODS // @@ -692,7 +638,6 @@ class Tcpserver /** Manage the child stop signal */ private function sigCHLD () - // {{{ { $this->nbChild --; $this->logDebug ("One child finished : $this->nbChild childs remain ". @@ -701,17 +646,14 @@ class Tcpserver $rc = pcntl_wait ($status); $this->logDebug ( "One child finished : $rc"); } - // }}} /** Manage the term / int signals * Will catch the stop signal, but the real end will be done when the last * child will be closed */ private function sigTERMINT () - // {{{ { $this->logDebug ("Request TERM/INT : Wait for last childs"); $this->loopStop (); } - // }}} } diff --git a/src/Uuid.php b/src/Uuid.php index d36bda1..10fc7cd 100644 --- a/src/Uuid.php +++ b/src/Uuid.php @@ -16,7 +16,6 @@ class Uuid * @return string UUID created */ public static function uuid4 () - // {{{ { return sprintf ('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', @@ -39,5 +38,4 @@ class Uuid mt_rand (0, 0xffff), mt_rand (0, 0xffff), mt_rand (0, 0xffff) ); } - // }}} } diff --git a/src/Xdiff.php b/src/Xdiff.php index 4805e90..caf4f3c 100644 --- a/src/Xdiff.php +++ b/src/Xdiff.php @@ -44,7 +44,6 @@ class Xdiff * @param string $output The output mode [Normal|Unified|SideBySide] */ public function __construct ($output = "normal") - // {{{ { if (! method_exists ($this, "display".ucfirst ($output))) throw new \Exception ("Invalid output requested to xdiff", 406); @@ -52,13 +51,11 @@ class Xdiff $this->file1Time = date ("Y-m-d H:i:s.u000 O"); $this->file2Time = date ("Y-m-d H:i:s.u001 O"); } - // }}} /** Allow to set the side by side width to the maximum allowed by screenWidth * @param integer $screenWidth The maximum width of the screen */ public function setScreenWidth ($screenWidth) - // {{{ { for ($x = 20 ; $x > 0 ; $x--) { @@ -70,14 +67,12 @@ class Xdiff } } } - // }}} /** Compute the differences between two strings $string1 and $string2 * @param string $string1 The first string to compare * @param string $string2 The second string to compare */ public function diff ($string1, $string2) - // {{{ { if (! is_string ($string1)) throw new \Exception ( @@ -91,14 +86,12 @@ class Xdiff preg_split ("#(.*\\R)#", $string2, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)); } - // }}} /** Compute the differences between two files $file1 and $file2 * @param string $file1 The first file to use to compare * @param string $file2 The second file to use to compare */ public function diffFile ($file1, $file2) - // {{{ { if (! is_string ($file1)) throw new \Exception ( @@ -127,20 +120,17 @@ class Xdiff return $this->diff (file_get_contents ($file1), file_get_contents ($file2)); } - // }}} /** Compute the differences between two arrays $array1 and $array2 * @param array $array1 The first array to compare * @param array $array2 The second array to compare */ public function diffArray ($array1, $array2) - // {{{ { $diff = $this->computeArray ($array1, $array2); $method = $this->output; return $this->$method ($diff); } - // }}} /** Compute the differences between two arrays $array1 and $array2 * @param array $array1 The first array to compare @@ -148,7 +138,6 @@ class Xdiff * @return array The data in internal format */ final public function computeArray ($array1, $array2) - // {{{ { if (! is_array ($array1)) throw new \Exception ( @@ -267,14 +256,12 @@ class Xdiff } return $diff; } - // }}} /** Return a string like "diff -u" * @param array $diffArray The diff array analyzed by diffArray method * @return string */ private function displayUnified ($diffArray) - // {{{ { $d = ""; $i = 0 ; @@ -336,14 +323,12 @@ class Xdiff $e .= "+++ $this->filename2 $this->file2Time\n"; return $e.$d; } - // }}} /** Return a string like "diff" without parameter * @param array $diffArray The diff array analyzed by diffArray method * @return string */ private function displayNormal ($diffArray) - // {{{ { $d = ""; $i = 0 ; @@ -383,14 +368,12 @@ class Xdiff } return $d; } - // }}} /** Return a string like "diff -y" (Side by Side) * @param array $diffArray The diff array analyzed by diffArray method * @return string */ private function displaySideBySide ($diffArray) - // {{{ { $d = ""; $i = 0 ; @@ -434,7 +417,6 @@ class Xdiff } return $d; } - // }}} /** Return a string sideBySide. Used by displaySideBySide for each line * @param string $side1 The string to be displayed on side1 @@ -442,7 +424,6 @@ class Xdiff * @param string|null $symbol The symbol used to present the diff (<>|) */ private function side ($side1, $side2, $symbol = null) - // {{{ { $d = ""; if (! is_string ($side1)) @@ -478,7 +459,6 @@ class Xdiff $d .= "\n"; return $d; } - // }}} /** This function return the next common part between both arrays starting at * position $i for $array1 and $j for array2 @@ -490,7 +470,6 @@ class Xdiff * @return string */ private function lcs ($array1, $array2, $i, $j) - // {{{ { $found1 = false; $found2 = false; @@ -530,5 +509,4 @@ class Xdiff } return $array1[$i]; } - // }}} } diff --git a/src/Xmppclient.php b/src/Xmppclient.php index 4fb6731..73ed980 100644 --- a/src/Xmppclient.php +++ b/src/Xmppclient.php @@ -13,14 +13,11 @@ namespace Domframework; class Xmppclient { // CLASS CONSTANT // - // {{{ /** One send command each $RATE µs maximum */ const RATE = 30000; - // }}} // PROPERTIES // - // {{{ /** The connection socket when connected */ private $sock; @@ -45,7 +42,6 @@ class Xmppclient * microseconds. */ private $sendLastTime = 0; - // }}} // PUBLIC METHODS // /** Connect to XMPP server $server, on port $port (5222 by default) @@ -58,7 +54,6 @@ class Xmppclient */ public function connect ($server, $port, $login, $password, $debug = false) - // {{{ { // To have a really one microsecond precision in microtime function ini_set ("precision", 16); @@ -131,12 +126,10 @@ class Xmppclient $this->sock->timeout (5); return $this; } - // }}} /** Disconnect from the XMPP server */ public function disconnect () - // {{{ { if ($this->sock && $this->sock->getSock ()) { @@ -144,13 +137,11 @@ class Xmppclient $this->sock->disconnect (); } } - // }}} /** Call the Discovery Service to find the available services on the server * @return array The services available */ public function discoveryService () - // {{{ { $this->send ("". ""); @@ -163,7 +154,6 @@ class Xmppclient $this->id++; return $features[1]; } - // }}} /** Send a direct message to a recipient. The message subject can be omitted, * as it is not displayed on the clients @@ -173,7 +163,6 @@ class Xmppclient * @return $this */ public function sendMessagePrivate ($recipient, $message, $subject = null) - // {{{ { $this->send ("". @@ -183,47 +172,39 @@ class Xmppclient $this->id++; return $this; } - // }}} /** In case of destruction, try to disconnect the server properly */ public function __destruct () - // {{{ { $this->disconnect (); } - // }}} /** Each debug message is sent to stderr if $debug is set * @param string $msg The message to display */ public function debug ($msg) - // {{{ { if ($this->debug === false) return; file_put_contents ("php://stderr", $msg."\n"); } - // }}} // PRIVATE METHODS // /** Read fron socket * @return string the read value */ private function read () - // {{{ { $xml = $this->sock->read (4096); $this->debug ("Read: $xml"); return $xml; } - // }}} /** Send the data on socket, add the carriage return * @param string $msg The message to send */ private function send ($msg) - // {{{ { $start = microtime (true); $wait = intval (($start - $this->sendLastTime) * 100000); @@ -238,5 +219,4 @@ class Xmppclient $this->sendLastTime = microtime (true); return $this->sock->send ($msg."\n"); } - // }}} }