diff options
author | vincent-peugnet <v.peugnet@free.fr> | 2020-04-17 19:01:05 +0200 |
---|---|---|
committer | vincent-peugnet <v.peugnet@free.fr> | 2020-04-17 19:01:05 +0200 |
commit | 802f5135b0979bab3bf30ae1733f9867e2caed7a (patch) | |
tree | 3575cb7dd353e7f1ce74b079aa1559b5d69054bf | |
parent | 74e2b3fdd66bfbe99bae771fa3a0b6c427fc0f86 (diff) | |
download | wcms-802f5135b0979bab3bf30ae1733f9867e2caed7a.tar.gz wcms-802f5135b0979bab3bf30ae1733f9867e2caed7a.zip |
apply psr12
-rw-r--r-- | app/class/Application.php | 46 | ||||
-rw-r--r-- | app/class/Colors.php | 6 | ||||
-rw-r--r-- | app/class/Config.php | 971 | ||||
-rw-r--r-- | app/class/Controller.php | 18 | ||||
-rw-r--r-- | app/class/Controlleradmin.php | 24 | ||||
-rw-r--r-- | app/class/Controllerpage.php | 2 | ||||
-rw-r--r-- | app/class/Event.php | 16 | ||||
-rw-r--r-- | app/class/Medialist.php | 2 | ||||
-rw-r--r-- | app/class/Model.php | 429 | ||||
-rw-r--r-- | app/class/Modeladmin.php | 14 | ||||
-rw-r--r-- | app/class/Modelauthtoken.php | 15 | ||||
-rw-r--r-- | app/class/Modelconfig.php | 53 | ||||
-rw-r--r-- | app/class/Modeldb.php | 71 | ||||
-rw-r--r-- | app/class/Modelfont.php | 39 | ||||
-rw-r--r-- | app/class/Modelhome.php | 165 | ||||
-rw-r--r-- | app/class/Modelmedia.php | 713 | ||||
-rw-r--r-- | app/class/Modelpage.php | 845 | ||||
-rw-r--r-- | app/class/Modelrender.php | 1259 | ||||
-rw-r--r-- | app/class/Modeltimeline.php | 263 | ||||
-rw-r--r-- | app/class/Modeluser.php | 48 | ||||
-rw-r--r-- | app/class/Opt.php | 863 | ||||
-rw-r--r-- | app/class/Optlist.php | 2 | ||||
-rw-r--r-- | app/class/Page.php | 1619 | ||||
-rw-r--r-- | app/class/Quickcss.php | 51 | ||||
-rw-r--r-- | app/class/Route.php | 12 | ||||
-rw-r--r-- | app/class/Routes.php | 17 | ||||
-rw-r--r-- | app/class/Summary.php | 21 | ||||
-rw-r--r-- | app/class/User.php | 77 |
28 files changed, 3826 insertions, 3835 deletions
diff --git a/app/class/Application.php b/app/class/Application.php index 48d898c..0f69064 100644 --- a/app/class/Application.php +++ b/app/class/Application.php @@ -1,4 +1,5 @@ <?php + namespace Wcms; class Application @@ -8,61 +9,71 @@ class Application */ protected $usermanager; - public function __construct() { + public function __construct() + { $this->usermanager = new Modeluser(); } public function wakeup() { - if(isset($_POST['configinit'])) { - if(Config::readconfig()) { + if (isset($_POST['configinit'])) { + if (Config::readconfig()) { Config::createconfig($_POST['configinit']); } else { Config::hydrate($_POST['configinit']); } Config::getdomain(); - if(!is_dir(Model::RENDER_DIR)) { + if (!is_dir(Model::RENDER_DIR)) { mkdir(Model::RENDER_DIR); } - if(!Config::savejson()) { + if (!Config::savejson()) { echo 'Cant write config file'; exit; - } else{ + } else { header('Location: ./'); exit; } - } elseif(isset($_POST['userinit']) && !empty($_POST['userinit']['id']) && !empty($_POST['userinit']['password'])) { + } elseif ( + isset($_POST['userinit']) + && !empty($_POST['userinit']['id']) + && !empty($_POST['userinit']['password']) + ) { $userdata = $_POST['userinit']; $userdata['level'] = 10; $user = new User($userdata); $this->usermanager->add($user); header('Location: ./'); exit; - } else { - if(Config::readconfig()) { - if(!Config::checkbasepath() || empty(Config::pagetable()) || !is_dir(Model::RENDER_DIR) || !Config::checkdomain() || empty(Config::secretkey())) { + if (Config::readconfig()) { + if ( + !Config::checkbasepath() + || empty(Config::pagetable()) + || !is_dir(Model::RENDER_DIR) + || !Config::checkdomain() + || empty(Config::secretkey()) + ) { echo '<ul>'; - if(!Config::checkbasepath()) { + if (!Config::checkbasepath()) { echo '<li>Wrong path</li>'; } - if(empty(Config::pagetable())) { + if (empty(Config::pagetable())) { echo '<li>Unset table name</li>'; } - if(!Config::checkdomain()) { + if (!Config::checkdomain()) { echo '<li>Need to recheck the domain</li>'; } - if(!is_dir(Model::RENDER_DIR)) { + if (!is_dir(Model::RENDER_DIR)) { echo '<li>Render path not existing</li>'; } - if(!is_dir(Model::RENDER_DIR)) { + if (!is_dir(Model::RENDER_DIR)) { echo '<li>Secret Key not set or not valid</li>'; } echo '</ul>'; $this->configform(); exit; } else { - if($this->usermanager->admincount() === 0) { + if ($this->usermanager->admincount() === 0) { echo 'missing admin user'; $this->adminform(); exit; @@ -129,7 +140,7 @@ class Application <h2> <label for="password">Your password</label> </h2> - <input type="password" name="userinit[password]" id="password" minlength="<?= Wcms\Model::PASSWORD_MIN_LENGTH ?>" maxlength="<?= Wcms\Model::PASSWORD_MAX_LENGTH ?>" required> + <input type="password" name="userinit[password]" id="password" minlength="<?= Model::PASSWORD_MIN_LENGTH ?>" maxlength="<?= Model::PASSWORD_MAX_LENGTH ?>" required> <p><i>Your user passworder as first administrator.</i></p> </div> <input type="submit" value="set"> @@ -137,7 +148,6 @@ class Application <?php } - } diff --git a/app/class/Colors.php b/app/class/Colors.php index 0ad5cca..06875b5 100644 --- a/app/class/Colors.php +++ b/app/class/Colors.php @@ -52,7 +52,7 @@ class Colors extends Item /** * Transform a CSS string in a array of `tag => background-color` - * + * * @return array Ouput array using TAG as key and Hex Color as value */ public function parsetagcss() @@ -111,14 +111,14 @@ class Colors extends Item public function setrawcss($rawcss) { - if(is_string($rawcss)) { + if (is_string($rawcss)) { $this->rawcss = $rawcss; } } public function settagcolor($tagcolor) { - if(is_array($tagcolor)) { + if (is_array($tagcolor)) { $this->tagcolor = $tagcolor; } } diff --git a/app/class/Config.php b/app/class/Config.php index 4736410..74f2757 100644 --- a/app/class/Config.php +++ b/app/class/Config.php @@ -1,495 +1,494 @@ <?php - namespace Wcms; use Http\Client\Common\Plugin\RetryPlugin; abstract class Config { - protected static $pagetable = 'mystore'; - protected static $domain = ''; - protected static $fontsize = 15; - protected static $basepath = ''; - protected static $route404; - protected static $alerttitle = ''; - protected static $alertlink = ''; - protected static $alertlinktext = ''; - protected static $existnot = 'This page does not exist yet'; - protected static $private = 'This page is private'; - protected static $notpublished = 'This page is not published'; - protected static $existnotpass = false; - protected static $privatepass = false; - protected static $notpublishedpass = false; - protected static $alertcss = false; - protected static $defaultbody = '%HEADER%' . PHP_EOL . PHP_EOL . '%NAV%' . PHP_EOL . PHP_EOL . '%ASIDE%' . PHP_EOL . PHP_EOL . '%MAIN%' . PHP_EOL . PHP_EOL . '%FOOTER%'; - protected static $defaultfavicon = ''; - protected static $defaultthumbnail = ''; - protected static $analytics = ''; - protected static $externallinkblank = true; - protected static $internallinkblank = false; - protected static $reccursiverender = true; - protected static $defaultprivacy = 0; - protected static $homepage = 'default'; - protected static $homeredirect = null; - protected static $interfacecss = null; - protected static $bookmark = []; - protected static $secretkey = null; - protected static $sentrydsn = ''; - - const SECRET_KEY_MIN = 16; - const SECRET_KEY_MAX = 128; - - - // _______________________________________ F U N _______________________________________ - - - - public static function hydrate(array $datas) - { - foreach ($datas as $key => $value) { - $method = 'set' . $key; - if (method_exists(get_called_class(), $method)) { - self::$method($value); - } - } - } - - public static function readconfig() - { - if (file_exists(Model::CONFIG_FILE)) { - $current = file_get_contents(Model::CONFIG_FILE); - $datas = json_decode($current, true); - self::hydrate($datas); - return true; - } else { - return false; - } - } - - public static function createconfig(array $datas) - { - self::hydrate($datas); - } - - - public static function savejson() - { - $json = self::tojson(); - return file_put_contents(Model::CONFIG_FILE, $json); - } - - - public static function tojson() - { - $arr = get_class_vars(__class__); - $json = json_encode($arr, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT); - return $json; - } - - public static function checkbasepath() - { - $path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . self::basepath() . DIRECTORY_SEPARATOR . Model::CONFIG_FILE; - return (file_exists($path)); - } - - /** - * Calculate Domain name - */ - public static function getdomain() - { - self::$domain = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']; - } - - /** - * Verify Domain name - */ - public static function checkdomain() - { - return (self::$domain === $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']); - } - - /** - * Generate full url adress where W is installed - * @return string url adress finished by a slash "/" - */ - public static function url($endslash = true): string - { - return self::$domain . (!empty(self::$basepath) ? '/' . self::$basepath : "") . ($endslash ? '/' : ''); - } - - // ________________________________________ G E T _______________________________________ - - public static function pagetable() - { - return self::$pagetable; - } - - public static function domain() - { - return self::$domain; - } - - public static function fontsize() - { - return self::$fontsize; - } - - /** - * @param bool $trailingslash If not empty basepath, add a trailing slash after the basepath - */ - public static function basepath(bool $trailingslash = false): string - { - if ($trailingslash && !empty(self::$basepath)) { - return self::$basepath . '/'; - } else { - return self::$basepath; - } - } - - public static function route404() - { - return self::$route404; - } - - public static function alerttitle() - { - return self::$alerttitle; - } - - public static function alertlink() - { - return self::$alertlink; - } - - public static function alertlinktext() - { - return self::$alertlinktext; - } - - public static function existnot() - { - return self::$existnot; - } - - public static function private() - { - return self::$private; - } - - public static function notpublished() - { - return self::$notpublished; - } - - public static function existnotpass() - { - return self::$existnotpass; - } - - public static function privatepass() - { - return self::$privatepass; - } - - public static function notpublishedpass() - { - return self::$notpublishedpass; - } - - public static function alertcss() - { - return self::$alertcss; - } - - public static function defaultbody() - { - return self::$defaultbody; - } - - public static function defaultfavicon() - { - return self::$defaultfavicon; - } - - public static function defaultthumbnail() - { - return self::$defaultthumbnail; - } - - public static function analytics() - { - return self::$analytics; - } - - public static function externallinkblank() - { - return self::$externallinkblank; - } - - public static function internallinkblank() - { - return self::$internallinkblank; - } - - public static function reccursiverender() - { - return self::$reccursiverender; - } - - public static function defaultprivacy() - { - return self::$defaultprivacy; - } - - public static function homepage() - { - return self::$homepage; - } - - public static function homeredirect() - { - return self::$homeredirect; - } - - public static function interfacecss() - { - return self::$interfacecss; - } - - public static function bookmark() - { - return self::$bookmark; - } - - public static function secretkey() - { - return self::$secretkey; - } - - public static function sentrydsn() - { - return self::$sentrydsn; - } - - - // __________________________________________ S E T ______________________________________ - - public static function setpagetable($pagetable) - { - self::$pagetable = strip_tags($pagetable); - } - - public static function setdomain($domain) - { - self::$domain = strip_tags(strtolower($domain)); - } - - public static function setfontsize($fontsize) - { - $fontsize = intval($fontsize); - if ($fontsize > 1) { - self::$fontsize = $fontsize; - } - } - - public static function setbasepath($basepath) - { - self::$basepath = strip_tags($basepath); - } - - public static function setroute404($id) - { - if (is_string($id)) { - self::$route404 = idclean($id); - } - } - - public static function setalerttitle($alerttitle) - { - if (is_string($alerttitle)) { - self::$alerttitle = strip_tags($alerttitle); - } - } - - public static function setalertlink($alertlink) - { - if (is_string($alertlink)) { - self::$alertlink = idclean(strip_tags($alertlink)); - } - } - - public static function setalertlinktext($alertlinktext) - { - if (is_string($alertlinktext)) { - self::$alertlinktext = strip_tags($alertlinktext); - } - } - - public static function setexistnot($existnot) - { - if (is_string($existnot)) { - self::$existnot = strip_tags($existnot); - } - } - - public static function setprivate($private) - { - if (is_string($private)) { - self::$private = strip_tags($private); - } - } - - public static function setnotpublished($notpublished) - { - if (is_string($notpublished)) { - self::$notpublished = strip_tags($notpublished); - } - } - - public static function setexistnotpass($existnotpass) - { - self::$existnotpass = boolval($existnotpass); - } - - public static function setprivatepass($privatepass) - { - self::$privatepass = boolval($privatepass); - } - - public static function setnotpublishedpass($notpublishedpass) - { - self::$notpublishedpass = boolval($notpublishedpass); - } - - public static function setalertcss($alertcss) - { - self::$alertcss = boolval($alertcss); - } - - public static function setdefaultbody($defaultbody) - { - if (is_string($defaultbody)) { - self::$defaultbody = $defaultbody; - } - } - - public static function setdefaultfavicon($defaultfavicon) - { - if (is_string($defaultfavicon)) { - self::$defaultfavicon = $defaultfavicon; - } - } - - public static function setdefaultthumbnail($defaultthumbnail) - { - if (is_string($defaultthumbnail)) { - self::$defaultthumbnail = $defaultthumbnail; - } - } - - public static function setanalytics($analytics) - { - if (is_string($analytics) && strlen($analytics) < 25) { - self::$analytics = $analytics; - } - } - - public static function setexternallinkblank($externallinkblank) - { - self::$externallinkblank = boolval($externallinkblank); - } - - public static function setinternallinkblank($internallinkblank) - { - self::$internallinkblank = boolval($internallinkblank); - } - - public static function setreccursiverender($reccursiverender) - { - self::$reccursiverender = boolval($reccursiverender); - } - - public static function setdefaultprivacy($defaultprivacy) - { - $defaultprivacy = intval($defaultprivacy); - if ($defaultprivacy >= 0 && $defaultprivacy <= 2) { - self::$defaultprivacy = $defaultprivacy; - } - } - - public static function sethomepage($homepage) - { - if (in_array($homepage, Model::HOMEPAGE)) { - self::$homepage = $homepage; - } - } - - public static function sethomeredirect($homeredirect) - { - if (is_string($homeredirect) && strlen($homeredirect) > 0) { - self::$homeredirect = idclean($homeredirect); - } else { - self::$homeredirect = null; - } - } - - public static function setinterfacecss($interfacecss) - { - if (is_string($interfacecss) && file_exists(Model::CSS_DIR . $interfacecss)) { - self::$interfacecss = $interfacecss; - } else { - self::$interfacecss = null; - } - } - - public static function setbookmark($bookmark) - { - if (is_array($bookmark)) { - self::$bookmark = $bookmark; - } - } - - public static function setsecretkey($secretkey) - { - if (is_string($secretkey)) { - $stripedsecretkey = strip_tags($secretkey); - if ($stripedsecretkey === $secretkey) { - $length = strlen($secretkey); - if ($length < self::SECRET_KEY_MAX && $length > self::SECRET_KEY_MIN) { - self::$secretkey = $secretkey; - } - } - } - } - - public static function setsentrydsn($sentrydsn) - { - if (is_string($sentrydsn)) { - self::$sentrydsn = $sentrydsn; - } - } - - - - - - - // ______________________________________ F U N _________________________________________ - - public static function addbookmark(string $id, string $query) - { - if (!empty($id) && !empty($query)) { - $id = idclean($id); - $id = substr($id, 0, 16); - self::$bookmark[$id] = $query; - } - } - - public static function deletebookmark(string $id) - { - if (key_exists($id, self::$bookmark)) { - unset(self::$bookmark[$id]); - } - } + protected static $pagetable = 'mystore'; + protected static $domain = ''; + protected static $fontsize = 15; + protected static $basepath = ''; + protected static $route404; + protected static $alerttitle = ''; + protected static $alertlink = ''; + protected static $alertlinktext = ''; + protected static $existnot = 'This page does not exist yet'; + protected static $private = 'This page is private'; + protected static $notpublished = 'This page is not published'; + protected static $existnotpass = false; + protected static $privatepass = false; + protected static $notpublishedpass = false; + protected static $alertcss = false; + protected static $defaultbody = '%HEADER%' . PHP_EOL . PHP_EOL . '%NAV%' . PHP_EOL . PHP_EOL . '%ASIDE%' . PHP_EOL . PHP_EOL . '%MAIN%' . PHP_EOL . PHP_EOL . '%FOOTER%'; + protected static $defaultfavicon = ''; + protected static $defaultthumbnail = ''; + protected static $analytics = ''; + protected static $externallinkblank = true; + protected static $internallinkblank = false; + protected static $reccursiverender = true; + protected static $defaultprivacy = 0; + protected static $homepage = 'default'; + protected static $homeredirect = null; + protected static $interfacecss = null; + protected static $bookmark = []; + protected static $secretkey = null; + protected static $sentrydsn = ''; + + public const SECRET_KEY_MIN = 16; + public const SECRET_KEY_MAX = 128; + + + // _______________________________________ F U N _______________________________________ + + + + public static function hydrate(array $datas) + { + foreach ($datas as $key => $value) { + $method = 'set' . $key; + if (method_exists(get_called_class(), $method)) { + self::$method($value); + } + } + } + + public static function readconfig() + { + if (file_exists(Model::CONFIG_FILE)) { + $current = file_get_contents(Model::CONFIG_FILE); + $datas = json_decode($current, true); + self::hydrate($datas); + return true; + } else { + return false; + } + } + + public static function createconfig(array $datas) + { + self::hydrate($datas); + } + + + public static function savejson() + { + $json = self::tojson(); + return file_put_contents(Model::CONFIG_FILE, $json); + } + + + public static function tojson() + { + $arr = get_class_vars(__class__); + $json = json_encode($arr, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT); + return $json; + } + + public static function checkbasepath() + { + $path = $_SERVER['DOCUMENT_ROOT'] . '/' . self::basepath() . '/' . Model::CONFIG_FILE; + return (file_exists($path)); + } + + /** + * Calculate Domain name + */ + public static function getdomain() + { + self::$domain = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']; + } + + /** + * Verify Domain name + */ + public static function checkdomain() + { + return (self::$domain === $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST']); + } + + /** + * Generate full url adress where W is installed + * @return string url adress finished by a slash "/" + */ + public static function url($endslash = true): string + { + return self::$domain . (!empty(self::$basepath) ? '/' . self::$basepath : "") . ($endslash ? '/' : ''); + } + + // ________________________________________ G E T _______________________________________ + + public static function pagetable() + { + return self::$pagetable; + } + + public static function domain() + { + return self::$domain; + } + + public static function fontsize() + { + return self::$fontsize; + } + + /** + * @param bool $trailingslash If not empty basepath, add a trailing slash after the basepath + */ + public static function basepath(bool $trailingslash = false): string + { + if ($trailingslash && !empty(self::$basepath)) { + return self::$basepath . '/'; + } else { + return self::$basepath; + } + } + + public static function route404() + { + return self::$route404; + } + + public static function alerttitle() + { + return self::$alerttitle; + } + + public static function alertlink() + { + return self::$alertlink; + } + + public static function alertlinktext() + { + return self::$alertlinktext; + } + + public static function existnot() + { + return self::$existnot; + } + + public static function private() + { + return self::$private; + } + + public static function notpublished() + { + return self::$notpublished; + } + + public static function existnotpass() + { + return self::$existnotpass; + } + + public static function privatepass() + { + return self::$privatepass; + } + + public static function notpublishedpass() + { + return self::$notpublishedpass; + } + + public static function alertcss() + { + return self::$alertcss; + } + + public static function defaultbody() + { + return self::$defaultbody; + } + + public static function defaultfavicon() + { + return self::$defaultfavicon; + } + + public static function defaultthumbnail() + { + return self::$defaultthumbnail; + } + + public static function analytics() + { + return self::$analytics; + } + + public static function externallinkblank() + { + return self::$externallinkblank; + } + + public static function internallinkblank() + { + return self::$internallinkblank; + } + + public static function reccursiverender() + { + return self::$reccursiverender; + } + + public static function defaultprivacy() + { + return self::$defaultprivacy; + } + + public static function homepage() + { + return self::$homepage; + } + + public static function homeredirect() + { + return self::$homeredirect; + } + + public static function interfacecss() + { + return self::$interfacecss; + } + + public static function bookmark() + { + return self::$bookmark; + } + + public static function secretkey() + { + return self::$secretkey; + } + + public static function sentrydsn() + { + return self::$sentrydsn; + } + + + // __________________________________________ S E T ______________________________________ + + public static function setpagetable($pagetable) + { + self::$pagetable = strip_tags($pagetable); + } + + public static function setdomain($domain) + { + self::$domain = strip_tags(strtolower($domain)); + } + + public static function setfontsize($fontsize) + { + $fontsize = intval($fontsize); + if ($fontsize > 1) { + self::$fontsize = $fontsize; + } + } + + public static function setbasepath($basepath) + { + self::$basepath = strip_tags($basepath); + } + + public static function setroute404($id) + { + if (is_string($id)) { + self::$route404 = idclean($id); + } + } + + public static function setalerttitle($alerttitle) + { + if (is_string($alerttitle)) { + self::$alerttitle = strip_tags($alerttitle); + } + } + + public static function setalertlink($alertlink) + { + if (is_string($alertlink)) { + self::$alertlink = idclean(strip_tags($alertlink)); + } + } + + public static function setalertlinktext($alertlinktext) + { + if (is_string($alertlinktext)) { + self::$alertlinktext = strip_tags($alertlinktext); + } + } + + public static function setexistnot($existnot) + { + if (is_string($existnot)) { + self::$existnot = strip_tags($existnot); + } + } + + public static function setprivate($private) + { + if (is_string($private)) { + self::$private = strip_tags($private); + } + } + + public static function setnotpublished($notpublished) + { + if (is_string($notpublished)) { + self::$notpublished = strip_tags($notpublished); + } + } + + public static function setexistnotpass($existnotpass) + { + self::$existnotpass = boolval($existnotpass); + } + + public static function setprivatepass($privatepass) + { + self::$privatepass = boolval($privatepass); + } + + public static function setnotpublishedpass($notpublishedpass) + { + self::$notpublishedpass = boolval($notpublishedpass); + } + + public static function setalertcss($alertcss) + { + self::$alertcss = boolval($alertcss); + } + + public static function setdefaultbody($defaultbody) + { + if (is_string($defaultbody)) { + self::$defaultbody = $defaultbody; + } + } + + public static function setdefaultfavicon($defaultfavicon) + { + if (is_string($defaultfavicon)) { + self::$defaultfavicon = $defaultfavicon; + } + } + + public static function setdefaultthumbnail($defaultthumbnail) + { + if (is_string($defaultthumbnail)) { + self::$defaultthumbnail = $defaultthumbnail; + } + } + + public static function setanalytics($analytics) + { + if (is_string($analytics) && strlen($analytics) < 25) { + self::$analytics = $analytics; + } + } + + public static function setexternallinkblank($externallinkblank) + { + self::$externallinkblank = boolval($externallinkblank); + } + + public static function setinternallinkblank($internallinkblank) + { + self::$internallinkblank = boolval($internallinkblank); + } + + public static function setreccursiverender($reccursiverender) + { + self::$reccursiverender = boolval($reccursiverender); + } + + public static function setdefaultprivacy($defaultprivacy) + { + $defaultprivacy = intval($defaultprivacy); + if ($defaultprivacy >= 0 && $defaultprivacy <= 2) { + self::$defaultprivacy = $defaultprivacy; + } + } + + public static function sethomepage($homepage) + { + if (in_array($homepage, Model::HOMEPAGE)) { + self::$homepage = $homepage; + } + } + + public static function sethomeredirect($homeredirect) + { + if (is_string($homeredirect) && strlen($homeredirect) > 0) { + self::$homeredirect = idclean($homeredirect); + } else { + self::$homeredirect = null; + } + } + + public static function setinterfacecss($interfacecss) + { + if (is_string($interfacecss) && file_exists(Model::CSS_DIR . $interfacecss)) { + self::$interfacecss = $interfacecss; + } else { + self::$interfacecss = null; + } + } + + public static function setbookmark($bookmark) + { + if (is_array($bookmark)) { + self::$bookmark = $bookmark; + } + } + + public static function setsecretkey($secretkey) + { + if (is_string($secretkey)) { + $stripedsecretkey = strip_tags($secretkey); + if ($stripedsecretkey === $secretkey) { + $length = strlen($secretkey); + if ($length < self::SECRET_KEY_MAX && $length > self::SECRET_KEY_MIN) { + self::$secretkey = $secretkey; + } + } + } + } + + public static function setsentrydsn($sentrydsn) + { + if (is_string($sentrydsn)) { + self::$sentrydsn = $sentrydsn; + } + } + + + + + + + // ______________________________________ F U N _________________________________________ + + public static function addbookmark(string $id, string $query) + { + if (!empty($id) && !empty($query)) { + $id = idclean($id); + $id = substr($id, 0, 16); + self::$bookmark[$id] = $query; + } + } + + public static function deletebookmark(string $id) + { + if (key_exists($id, self::$bookmark)) { + unset(self::$bookmark[$id]); + } + } } diff --git a/app/class/Controller.php b/app/class/Controller.php index bcfcdba..3133ecb 100644 --- a/app/class/Controller.php +++ b/app/class/Controller.php @@ -25,17 +25,18 @@ class Controller /** @var DateTimeImmutable */ protected $now; - public function __construct($router) { + public function __construct($router) + { $this->setuser(); $this->router = $router; $this->pagemanager = new Modelpage(); $this->initplates(); $this->now = new DateTimeImmutable(null, timezone_open("Europe/Paris")); - } + } public function setuser() { - $this->usermanager = new Modeluser; + $this->usermanager = new Modeluser(); $this->user = $this->usermanager->readsession(); } @@ -87,7 +88,7 @@ class Controller { $get = '?'; foreach ($vars as $key => $value) { - $get .= $key .'='. $value. '&'; + $get .= $key . '=' . $value . '&'; } $get = rtrim($get, '&'); $this->redirect($this->router->generate($route, []) . $get); @@ -100,7 +101,7 @@ class Controller } /** - * + * */ public function sendstatflashmessage(int $count, int $total, string $message) { @@ -112,11 +113,4 @@ class Controller Model::sendflashmessage($count . ' / ' . $total . ' ' . $message, 'error'); } } - } - - - - - -?>
\ No newline at end of file diff --git a/app/class/Controlleradmin.php b/app/class/Controlleradmin.php index cd166c2..d3ceab7 100644 --- a/app/class/Controlleradmin.php +++ b/app/class/Controlleradmin.php @@ -19,7 +19,7 @@ class Controlleradmin extends Controller public function desktop() { - if($this->user->isadmin()) { + if ($this->user->isadmin()) { $datas['pagelist'] = $this->pagemanager->list(); $this->mediamanager = new Modelmedia(); $datas['faviconlist'] = $this->mediamanager->listfavicon(); @@ -28,7 +28,7 @@ class Controlleradmin extends Controller $globalcssfile = Model::GLOBAL_DIR . 'global.css'; - if(is_file($globalcssfile)) { + if (is_file($globalcssfile)) { $datas['globalcss'] = file_get_contents($globalcssfile); } else { $datas['globalcss'] = ""; @@ -44,14 +44,14 @@ class Controlleradmin extends Controller } public function update() - { + { MODEL::dircheck(MODEL::GLOBAL_DIR); $globalcss = file_put_contents(Model::GLOBAL_DIR . 'global.css', $_POST['globalcss']); Config::hydrate($_POST); - if(Config::savejson() !== false && $globalcss !== false) { - $this->routedirect('admin'); + if (Config::savejson() !== false && $globalcss !== false) { + $this->routedirect('admin'); } else { echo 'Can\'t write config file or global css file'; } @@ -59,15 +59,15 @@ class Controlleradmin extends Controller public function database() { - if(!empty($_POST['action'])) { + if (!empty($_POST['action'])) { switch ($_POST['action']) { case 'duplicate': - if(!empty($_POST['dbsrc']) && !empty($_POST['dbtarget'])) { + if (!empty($_POST['dbsrc']) && !empty($_POST['dbtarget'])) { $this->adminmanager->copydb($_POST['dbsrc'], $_POST['dbtarget']); } - break; + break; case 'select': - if(!empty($_POST['pagetable'])) { + if (!empty($_POST['pagetable'])) { Config::hydrate($_POST); Config::savejson(); } @@ -76,10 +76,4 @@ class Controlleradmin extends Controller } $this->routedirect('admin'); } - } - - - - -?>
\ No newline at end of file diff --git a/app/class/Controllerpage.php b/app/class/Controllerpage.php index 53c978e..447f2c5 100644 --- a/app/class/Controllerpage.php +++ b/app/class/Controllerpage.php @@ -13,7 +13,7 @@ class Controllerpage extends Controller protected $fontmanager; protected $mediamanager; - const COMBINE = false; + public const COMBINE = false; public function __construct($router) { diff --git a/app/class/Event.php b/app/class/Event.php index 8c1e155..ca470f6 100644 --- a/app/class/Event.php +++ b/app/class/Event.php @@ -16,14 +16,14 @@ class Event extends Dbitem protected $message; protected $clap = 0; - const EVENT_TYPES = ['message', 'page_add', 'page_edit', 'page_delete', 'media_add', 'media_delete', 'font_add']; - const EVENT_BASE = ['message']; - const EVENT_ART = ['page_add', 'page_edit', 'page_delete']; - const EVENT_MEDIA = ['media_add', 'media_delete']; - const EVENT_FONT = ['font_add', 'font_delete']; - const MESSAGE_MAX_LENGTH = 2 ** 10; - - const VAR_DATE = ['date']; + public const EVENT_TYPES = ['message', 'page_add', 'page_edit', 'page_delete', 'media_add', 'media_delete', 'font_add']; + public const EVENT_BASE = ['message']; + public const EVENT_ART = ['page_add', 'page_edit', 'page_delete']; + public const EVENT_MEDIA = ['media_add', 'media_delete']; + public const EVENT_FONT = ['font_add', 'font_delete']; + public const MESSAGE_MAX_LENGTH = 2 ** 10; + + public const VAR_DATE = ['date']; public function __construct($datas) { diff --git a/app/class/Medialist.php b/app/class/Medialist.php index b0964e3..ddb5eaa 100644 --- a/app/class/Medialist.php +++ b/app/class/Medialist.php @@ -31,7 +31,7 @@ class Medialist extends Item /** @var string display the file name of the file */ protected $filename = 0; - const TYPES = ['image', 'sound', 'video', 'other']; + public const TYPES = ['image', 'sound', 'video', 'other']; diff --git a/app/class/Model.php b/app/class/Model.php index 73a800d..bc4c801 100644 --- a/app/class/Model.php +++ b/app/class/Model.php @@ -5,214 +5,229 @@ namespace Wcms; abstract class Model { - const CONFIG_FILE = 'config.json'; - const MAN_FILE = 'MANUAL.md'; - const CSS_DIR = 'assets' . DIRECTORY_SEPARATOR .'css' . DIRECTORY_SEPARATOR; - const JS_DIR = 'assets' . DIRECTORY_SEPARATOR .'js' . DIRECTORY_SEPARATOR; - const ICONS_DIR = 'assets' . DIRECTORY_SEPARATOR .'icons' . DIRECTORY_SEPARATOR; - const FONT_DIR = 'fonts' . DIRECTORY_SEPARATOR; - const MEDIA_DIR = 'media' . DIRECTORY_SEPARATOR; - const FAVICON_DIR = self::MEDIA_DIR . 'favicon' . DIRECTORY_SEPARATOR; - const THUMBNAIL_DIR = self::MEDIA_DIR . 'thumbnail' . DIRECTORY_SEPARATOR; - const TEMPLATES_DIR = '.'. DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR; - const RENDER_DIR = 'assets'. DIRECTORY_SEPARATOR . 'render' . DIRECTORY_SEPARATOR; - const HTML_RENDER_DIR = 'render' . DIRECTORY_SEPARATOR; - const GLOBAL_DIR = 'assets'. DIRECTORY_SEPARATOR . 'global' . DIRECTORY_SEPARATOR; - const DATABASE_DIR = '.' . DIRECTORY_SEPARATOR . 'database' . DIRECTORY_SEPARATOR; - const PAGES_DIR = self::DATABASE_DIR . 'pages' . DIRECTORY_SEPARATOR; - - const MEDIA_SORTBY = [ - 'id' => 'id', - 'size' => 'size', - 'type' => 'type', - 'date' => 'date', - 'extension' => 'extension' - ]; - - const MAP_LAYOUTS = [ + public const CONFIG_FILE = 'config.json'; + public const MAN_FILE = 'MANUAL.md'; + public const CSS_DIR = 'assets/css/'; + public const JS_DIR = 'assets/js/'; + public const ICONS_DIR = 'assets/icons/'; + public const FONT_DIR = 'fonts/'; + public const MEDIA_DIR = 'media/'; + public const FAVICON_DIR = self::MEDIA_DIR . 'favicon/'; + public const THUMBNAIL_DIR = self::MEDIA_DIR . 'thumbnail/'; + public const TEMPLATES_DIR = './app/view/templates/'; + public const RENDER_DIR = 'assets/render/'; + public const HTML_RENDER_DIR = 'render/'; + public const GLOBAL_DIR = 'assets/global/'; + public const DATABASE_DIR = './database/'; + public const PAGES_DIR = self::DATABASE_DIR . 'pages/'; + + public const MEDIA_SORTBY = [ + 'id' => 'id', + 'size' => 'size', + 'type' => 'type', + 'date' => 'date', + 'extension' => 'extension' + ]; + + public const MAP_LAYOUTS = [ 'cose' => 'cose', - 'cose-bilkent' => 'cose-bilkent', + 'cose-bilkent' => 'cose-bilkent', 'circle' => 'circle', - 'breadthfirst' => 'breadthfirst', - 'concentric' => 'concentric', - 'grid' => 'grid', - 'random' => 'random', + 'breadthfirst' => 'breadthfirst', + 'concentric' => 'concentric', + 'grid' => 'grid', + 'random' => 'random', + ]; + + + public const MEDIA_EXT = [ + 'jpg' => 'image', + 'jpeg' => 'image', + 'png' => 'image', + 'gif' => 'image', + 'ico' => 'image', + 'tiff' => 'image', + 'bmp' => 'image', + 'mp3' => 'sound', + 'opus' => 'sound', + 'wav' => 'sound', + 'ogg' => 'sound', + 'flac' => 'sound', + 'aiff' => 'sound', + 'm4a' => 'sound', + 'mp4' => 'video', + 'mkv' => 'video', + 'avi' => 'video', + 'mov' => 'video', + 'wmv' => 'video', + 'm4v' => 'video', + 'zip' => 'archive', + '7zip' => 'archive', + 'pdf' => 'document', + 'odt' => 'document', + 'doc' => 'document', + 'docx' => 'document', + 'woff' => 'font', + 'woff2' => 'font', + 'otf' => 'font', + 'ttf' => 'font', + 'js' => 'code', + 'html' => 'code', + 'css' => 'code', + 'php' => 'code', + '' => 'other' + ]; + + public const LIST_STYLES = [ + 'list' => 'list', + 'card' => 'card' ]; - - - const MEDIA_EXT = [ - 'jpg' => 'image', - 'jpeg' => 'image', - 'png' => 'image', - 'gif' => 'image', - 'ico' => 'image', - 'tiff' => 'image', - 'bmp' => 'image', - 'mp3' => 'sound', - 'opus' => 'sound', - 'wav' => 'sound', - 'ogg' => 'sound', - 'flac' => 'sound', - 'aiff' => 'sound', - 'm4a' => 'sound', - 'mp4' => 'video', - 'mkv' => 'video', - 'avi' => 'video', - 'mov' => 'video', - 'wmv' => 'video', - 'm4v' => 'video', - 'zip' => 'archive', - '7zip' => 'archive', - 'pdf' => 'document', - 'odt' => 'document', - 'doc' => 'document', - 'docx' => 'document', - 'woff' => 'font', - 'woff2' => 'font', - 'otf' => 'font', - 'ttf' => 'font', - 'js' => 'code', - 'html' => 'code', - 'css' => 'code', - 'php' => 'code', - '' => 'other' - ]; - - const LIST_STYLES = [ - 'list' => 'list', - 'card' => 'card' - ]; - - const FLASH_MESSAGE_TYPES = [ - 'info' =>'info', - 'warning' => 'warning', - 'success' => 'success', - 'error' => 'error' - ]; - - const COLUMNS = ['id', 'favicon', 'title', 'description', 'tag', 'date', 'datemodif', 'datecreation', 'secure', 'authors', 'linkto', 'visitcount', 'affcount', 'editcount']; - - const TEXT_ELEMENTS = ['header', 'nav', 'main', 'aside', 'footer']; - - const MAX_ID_LENGTH = 64; - const PASSWORD_MIN_LENGTH = 4; - const PASSWORD_MAX_LENGTH = 32; - const MAX_COOKIE_CONSERVATION = 365; - - /** RENDER OPTIONS */ - // add class in html element indicating from witch page the content come. - const RENDER_CLASS_ORIGIN = false; - // render empty CONTENT element as empty html element, if set to false, render html comment - const RENDER_EMPTY_ELEMENT = false; - - - /** CONFIG OPTIONS */ - const HOMEPAGE = ['default', 'search', 'redirect']; - - public static function dirtopath($dir) - { - $basepath = ''; - if(!empty(Config::basepath())) { - $basepath = Config::basepath() . '/' ; - } - $dir = str_replace('\\', '/', $dir); - return '/' . $basepath . $dir; - } - - public static function renderpath() - { - return self::dirtopath(Model::RENDER_DIR); - } - - public static function globalpath() - { - return self::dirtopath(Model::GLOBAL_DIR); - } - - public static function csspath() - { - return self::dirtopath(Model::CSS_DIR); - } - - public static function jspath() - { - return self::dirtopath(Model::JS_DIR); - } - - public static function mediapath() - { - return self::dirtopath(Model::MEDIA_DIR); - } - - public static function faviconpath() - { - return self::dirtopath(Model::FAVICON_DIR); - } - - public static function thumbnailpath() - { - return self::dirtopath(Model::THUMBNAIL_DIR); - } - - public static function fontpath() - { - return self::dirtopath(Model::FONT_DIR); - } - - public static function iconpath() - { - return self::dirtopath(Model::ICONS_DIR); - } - - /** - * Check if dir exist. If not, create it - * - * @param string $dir Directory to check - * - * @return bool return true if the dir already exist or was created succesfullt. Otherwise return false - */ - public static function dircheck(string $dir) : bool - { - if (!is_dir($dir)) { - return mkdir($dir); - } else { - return true; - } - } - - /** - * - */ - public static function mediatypes() - { - return array_unique(array_values(self::MEDIA_EXT)); - } - - public static function getflashmessages() - { - if (!empty($_SESSION['user' . Config::basepath()]['flashmessages'])) { - $flashmessage = $_SESSION['user' . Config::basepath()]['flashmessages']; - $_SESSION['user' . Config::basepath()]['flashmessages'] = []; - if (is_array($flashmessage)) { - return $flashmessage; - } else { - return []; - } - return $flashmessage; - } - } - - /** - * Add a message to flash message list - * - * @param string $content The message content - * @param string $type Message Type, can be `info|warning|success` - */ - public static function sendflashmessage(string $content, string $type = 'info') - { - if (!key_exists($type, self::FLASH_MESSAGE_TYPES)) { - $type = 'info'; - } - $_SESSION['user' . Config::basepath()]['flashmessages'][] = ['content' => $content, 'type' => $type]; - } + + public const FLASH_MESSAGE_TYPES = [ + 'info' => 'info', + 'warning' => 'warning', + 'success' => 'success', + 'error' => 'error' + ]; + + public const COLUMNS = [ + 'id', + 'favicon', + 'title', + 'description', + 'tag', + 'date', + 'datemodif', + 'datecreation', + 'secure', + 'authors', + 'linkto', + 'visitcount', + 'affcount', + 'editcount' + ]; + + public const TEXT_ELEMENTS = ['header', 'nav', 'main', 'aside', 'footer']; + + public const MAX_ID_LENGTH = 64; + public const PASSWORD_MIN_LENGTH = 4; + public const PASSWORD_MAX_LENGTH = 32; + public const MAX_COOKIE_CONSERVATION = 365; + + /** RENDER OPTIONS */ + // add class in html element indicating from witch page the content come. + public const RENDER_CLASS_ORIGIN = false; + // render empty CONTENT element as empty html element, if set to false, render html comment + public const RENDER_EMPTY_ELEMENT = false; + + + /** CONFIG OPTIONS */ + public const HOMEPAGE = ['default', 'search', 'redirect']; + + public static function dirtopath($dir) + { + $basepath = ''; + if (!empty(Config::basepath())) { + $basepath = Config::basepath() . '/' ; + } + $dir = str_replace('\\', '/', $dir); + return '/' . $basepath . $dir; + } + + public static function renderpath() + { + return self::dirtopath(Model::RENDER_DIR); + } + + public static function globalpath() + { + return self::dirtopath(Model::GLOBAL_DIR); + } + + public static function csspath() + { + return self::dirtopath(Model::CSS_DIR); + } + + public static function jspath() + { + return self::dirtopath(Model::JS_DIR); + } + + public static function mediapath() + { + return self::dirtopath(Model::MEDIA_DIR); + } + + public static function faviconpath() + { + return self::dirtopath(Model::FAVICON_DIR); + } + + public static function thumbnailpath() + { + return self::dirtopath(Model::THUMBNAIL_DIR); + } + + public static function fontpath() + { + return self::dirtopath(Model::FONT_DIR); + } + + public static function iconpath() + { + return self::dirtopath(Model::ICONS_DIR); + } + + /** + * Check if dir exist. If not, create it + * + * @param string $dir Directory to check + * + * @return bool return true if the dir already exist or was created succesfullt. Otherwise return false + */ + public static function dircheck(string $dir): bool + { + if (!is_dir($dir)) { + return mkdir($dir); + } else { + return true; + } + } + + /** + * + */ + public static function mediatypes() + { + return array_unique(array_values(self::MEDIA_EXT)); + } + + public static function getflashmessages() + { + if (!empty($_SESSION['user' . Config::basepath()]['flashmessages'])) { + $flashmessage = $_SESSION['user' . Config::basepath()]['flashmessages']; + $_SESSION['user' . Config::basepath()]['flashmessages'] = []; + if (is_array($flashmessage)) { + return $flashmessage; + } else { + return []; + } + return $flashmessage; + } + } + + /** + * Add a message to flash message list + * + * @param string $content The message content + * @param string $type Message Type, can be `info|warning|success` + */ + public static function sendflashmessage(string $content, string $type = 'info') + { + if (!key_exists($type, self::FLASH_MESSAGE_TYPES)) { + $type = 'info'; + } + $_SESSION['user' . Config::basepath()]['flashmessages'][] = ['content' => $content, 'type' => $type]; + } } diff --git a/app/class/Modeladmin.php b/app/class/Modeladmin.php index 54c4f0c..478bc77 100644 --- a/app/class/Modeladmin.php +++ b/app/class/Modeladmin.php @@ -8,10 +8,10 @@ class Modeladmin extends Model /** * List all availalble pages databases - * - * @return array + * + * @return array */ - public function pagesdblist() : array + public function pagesdblist(): array { $dblist = glob(self::PAGES_DIR . '*', GLOB_ONLYDIR); $dblist = array_map('basename', $dblist); @@ -21,7 +21,7 @@ class Modeladmin extends Model /** * Duplicate actual page database using new name - * + * * @param string $name of the new database */ public function duplicate(string $name) @@ -31,7 +31,7 @@ class Modeladmin extends Model /** * Copy database folder to a new folder if it doeas not already exsit - * + * * @param string $db name of source page database to copy * @param string $name of the destination database */ @@ -39,10 +39,8 @@ class Modeladmin extends Model { $dbdir = self::PAGES_DIR . $db; $newdbdir = self::PAGES_DIR . idclean($name); - if(is_dir($dbdir) && !is_dir($newdbdir)) { + if (is_dir($dbdir) && !is_dir($newdbdir)) { recurse_copy($dbdir, $newdbdir); } } } - -?>
\ No newline at end of file diff --git a/app/class/Modelauthtoken.php b/app/class/Modelauthtoken.php index 91a2a05..4536de6 100644 --- a/app/class/Modelauthtoken.php +++ b/app/class/Modelauthtoken.php @@ -8,8 +8,8 @@ use JamesMoss\Flywheel\Document; class Modelauthtoken extends Modeldb { - const AUTHTOKEN_REPO_NAME = 'authtoken'; - const AUTHTOKEN_ID_LENGTH = 30; + protected const AUTHTOKEN_REPO_NAME = 'authtoken'; + protected const AUTHTOKEN_ID_LENGTH = 30; public function __construct() { @@ -19,7 +19,7 @@ class Modelauthtoken extends Modeldb /** * Add a Token in the database according to the Users datas - * + * * @param User $user */ public function add(User $user) @@ -41,7 +41,6 @@ class Modelauthtoken extends Modeldb $tokendata->setId($id); return $this->repo->store($tokendata); - } public function getbytoken(string $token) @@ -61,12 +60,4 @@ class Modelauthtoken extends Modeldb { return $this->repo->query()->where('user', '==', $id)->orderBy('date')->execute(); } - } - - - - - - -?>
\ No newline at end of file diff --git a/app/class/Modelconfig.php b/app/class/Modelconfig.php index 518f64e..6c074eb 100644 --- a/app/class/Modelconfig.php +++ b/app/class/Modelconfig.php @@ -5,37 +5,24 @@ namespace Wcms; abstract class Modelconfig extends Model { public static function readconfig() - { - if (file_exists(self::CONFIG_FILE)) { - $current = file_get_contents(self::CONFIG_FILE); - $donnees = json_decode($current, true); - return new Config($donnees); - } else { - return 0; - } - - } - - public static function createconfig(array $donnees) - { - return new Config($donnees); - } - - - public static function savejson(string $json) - { - file_put_contents(self::CONFIG_FILE, $json); - } - - - - + { + if (file_exists(self::CONFIG_FILE)) { + $current = file_get_contents(self::CONFIG_FILE); + $donnees = json_decode($current, true); + return new Config($donnees); + } else { + return 0; + } + } + + public static function createconfig(array $donnees) + { + return new Config($donnees); + } + + + public static function savejson(string $json) + { + file_put_contents(self::CONFIG_FILE, $json); + } } - - - - - - - -?>
\ No newline at end of file diff --git a/app/class/Modeldb.php b/app/class/Modeldb.php index 953521f..784b45f 100644 --- a/app/class/Modeldb.php +++ b/app/class/Modeldb.php @@ -9,42 +9,37 @@ use Wcms\Flywheel\Repository; class Modeldb extends Model { - protected $database; - /** @var Repository */ - protected $repo; - - - public function __construct() - { - $this->dbinit(); - } - - - public function dbinit($dir = Model::DATABASE_DIR) - { - $this->database = new Flywheel\Config($dir , [ - 'query_class' => Query::class, - 'formatter' => new JSON, - ]); - } - - public function storeinit(string $repo) - { - $this->repo = new Repository($repo, $this->database); - } - - /** - * List every IDs of a database - * - * @return array of ID strings - */ - public function list() : array - { - return $this->repo->getAllIds(); - } - - - - - + protected $database; + /** @var Repository */ + protected $repo; + + + public function __construct() + { + $this->dbinit(); + } + + + public function dbinit($dir = Model::DATABASE_DIR) + { + $this->database = new Flywheel\Config($dir, [ + 'query_class' => Query::class, + 'formatter' => new JSON(), + ]); + } + + public function storeinit(string $repo) + { + $this->repo = new Repository($repo, $this->database); + } + + /** + * List every IDs of a database + * + * @return array of ID strings + */ + public function list(): array + { + return $this->repo->getAllIds(); + } } diff --git a/app/class/Modelfont.php b/app/class/Modelfont.php index 3f25e21..4353b1c 100644 --- a/app/class/Modelfont.php +++ b/app/class/Modelfont.php @@ -5,16 +5,16 @@ namespace Wcms; class Modelfont extends Model { - const FONT_TYPES = ['woff2', 'woff', 'otf', 'ttf', 'eot', 'svg']; + protected const FONT_TYPES = ['woff2', 'woff', 'otf', 'ttf', 'eot', 'svg']; - public function fontdircheck() - { - if(!is_dir(Model::FONT_DIR)) { - return mkdir(Model::FONT_DIR); - } else { - return true; - } - } + public function fontdircheck() + { + if (!is_dir(Model::FONT_DIR)) { + return mkdir(Model::FONT_DIR); + } else { + return true; + } + } public function getfontlist() { @@ -44,15 +44,12 @@ class Modelfont extends Model $list = []; while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { - $list[] = $entry; - } } } return $list; - } public function fontlist(array $list) @@ -82,7 +79,6 @@ class Modelfont extends Model { $write = file_put_contents(Model::GLOBAL_DIR . 'fonts.css', $fontface); if ($write !== false) { - } } @@ -101,9 +97,11 @@ class Modelfont extends Model $id = $infosfichier['filename']; } if (!file_exists($this::FONT_DIR . $id . '.' . $extension_upload)) { - $extension_upload = strtolower($extension_upload); - $uploadok = move_uploaded_file($file['font']['tmp_name'], $this::FONT_DIR . $id . '.' . $extension_upload); + $uploadok = move_uploaded_file( + $file['font']['tmp_name'], + $this::FONT_DIR . $id . '.' . $extension_upload + ); if ($uploadok) { $message = true; } else { @@ -111,22 +109,11 @@ class Modelfont extends Model } } else { $message = 'filealreadyexist'; - } } } else { $message = 'filetoobig'; - } return $message; } - - - - } - - - - -?>
\ No newline at end of file diff --git a/app/class/Modelhome.php b/app/class/Modelhome.php index e8bdbf8..b35fe6d 100644 --- a/app/class/Modelhome.php +++ b/app/class/Modelhome.php @@ -4,10 +4,11 @@ namespace Wcms; class Modelhome extends Modelpage { - - public function __construct() { - parent::__construct(); - } + + public function __construct() + { + parent::__construct(); + } public function optinit($table) { @@ -24,19 +25,19 @@ class Modelhome extends Modelpage /** - * @param array $pagelist of Pages objects as `id => Page` + * @param array $pagelist of Pages objects as `id => Page` * @param Opt $opt - * - * @param string $regex Regex to match. - * @param array $options Option search, could be `content` `title` `description`. - * - * @return array associative array of `Page` objects * + * + * @param string $regex Regex to match. + * @param array $options Option search, could be `content` `title` `description`. + * + * @return array associative array of `Page` objects * */ - public function pagetable(array $pagelist, Opt $opt, $regex = '', $searchopt = []) : array + public function pagetable(array $pagelist, Opt $opt, $regex = '', $searchopt = []): array { $pagelist = $this->filter($pagelist, $opt); - if(!empty($regex)) { - $pagelist = $this->deepsearch($pagelist, $regex , $searchopt); + if (!empty($regex)) { + $pagelist = $this->deepsearch($pagelist, $regex, $searchopt); } $pagelist = $this->sort($pagelist, $opt); @@ -47,14 +48,14 @@ class Modelhome extends Modelpage /** * Filter the pages list acording to the options and invert - * + * * @param array $pagelist of `Page` objects * @param Opt $opt - * + * * @return array of `string` pages id */ - public function filter(array $pagelist, Opt $opt) : array + public function filter(array $pagelist, Opt $opt): array { $filtertagfilter = $this->filtertagfilter($pagelist, $opt->tagfilter(), $opt->tagcompare()); @@ -64,7 +65,7 @@ class Modelhome extends Modelpage $filter = array_intersect($filtertagfilter, $filtersecure, $filterauthorfilter, $filterlinkto); - if($opt->invert()) { + if ($opt->invert()) { $idlist = array_keys($pagelist); $filter = array_diff($idlist, $filter); } @@ -76,17 +77,17 @@ class Modelhome extends Modelpage /** * Sort and limit an array of Pages - * + * * @param array $pagelist of `Page` objects * @param Opt $opt - * - * @return array associative array of `Page` objects + * + * @return array associative array of `Page` objects */ - public function sort(array $pagelist, Opt $opt) : array + public function sort(array $pagelist, Opt $opt): array { $this->pagelistsort($pagelist, $opt->sortby(), $opt->order()); - if($opt->limit() !== 0) { + if ($opt->limit() !== 0) { $pagelist = array_slice($pagelist, 0, $opt->limit()); } @@ -94,68 +95,72 @@ class Modelhome extends Modelpage } - /** - * Search for regex and count occurences - * - * @param array $page list Array of Pages. - * @param string $regex Regex to match. - * @param array $options Option search, could be `content` `title` `description`. - * - * @return array associative array of `Page` objects - */ - public function deepsearch(array $pagelist, string $regex, array $options) : array - { - if($options['casesensitive']) { + /** + * Search for regex and count occurences + * + * @param array $page list Array of Pages. + * @param string $regex Regex to match. + * @param array $options Option search, could be `content` `title` `description`. + * + * @return array associative array of `Page` objects + */ + public function deepsearch(array $pagelist, string $regex, array $options): array + { + if ($options['casesensitive']) { $case = ''; } else { $case = 'i'; } $regex = '/' . $regex . '/' . $case; $pageselected = []; - foreach ($pagelist as $page) { - $count = 0; - if($options['content']) { - $count += preg_match($regex, $page->main()); - $count += preg_match($regex, $page->nav()); - $count += preg_match($regex, $page->aside()); - $count += preg_match($regex, $page->header()); - $count += preg_match($regex, $page->footer()); - } - if ($options['other']) { - $count += preg_match($regex, $page->body()); - $count += preg_match($regex, $page->css()); - $count += preg_match($regex, $page->javascript()); - } - if ($options['id']) { - $count += preg_match($regex, $page->id()); - } - if ($options['title']) { - $count += preg_match($regex, $page->title()); - } - if ($options['description']) { - $count += preg_match($regex, $page->description()); - } - if ($count !== 0) { - $pageselected[$page->id()] = $page; - } - } - return $pageselected; + foreach ($pagelist as $page) { + $count = 0; + if ($options['content']) { + $count += preg_match($regex, $page->main()); + $count += preg_match($regex, $page->nav()); + $count += preg_match($regex, $page->aside()); + $count += preg_match($regex, $page->header()); + $count += preg_match($regex, $page->footer()); + } + if ($options['other']) { + $count += preg_match($regex, $page->body()); + $count += preg_match($regex, $page->css()); + $count += preg_match($regex, $page->javascript()); + } + if ($options['id']) { + $count += preg_match($regex, $page->id()); + } + if ($options['title']) { + $count += preg_match($regex, $page->title()); + } + if ($options['description']) { + $count += preg_match($regex, $page->description()); + } + if ($count !== 0) { + $pageselected[$page->id()] = $page; + } + } + return $pageselected; } /** * Transform list of page into list of nodes and edges - * + * * @param array $pagelist associative array of pages as `id => Page` - * @param string $layout + * @param string $layout * @param bool $showorphans if `false`, remove orphans pages * @param bool $showredirection if `true`, add redirections - * + * * @return array */ - public function cytodata(array $pagelist, string $layout = 'random', bool $showorphans = false, bool $showredirection = false) : array - { + public function cytodata( + array $pagelist, + string $layout = 'random', + bool $showorphans = false, + bool $showredirection = false + ): array { $datas['elements'] = $this->mapdata($pagelist, $showorphans, $showredirection); $datas['layout'] = [ @@ -216,14 +221,14 @@ class Modelhome extends Modelpage /** * Transform list of Pages into cytoscape nodes and edge datas - * + * * @param array $pagelist associative array of pages as `id => Page` * @param bool $showorphans if `false`, remove orphans pages * @param bool $showredirection if `true`, add redirections * * @return array of cytoscape datas */ - public function mapdata(array $pagelist, bool $showorphans = true, bool $showredirection = false) : array + public function mapdata(array $pagelist, bool $showorphans = true, bool $showredirection = false): array { $idlist = array_keys($pagelist); @@ -231,7 +236,7 @@ class Modelhome extends Modelpage $notorphans = []; foreach ($pagelist as $page) { foreach ($page->linkto() as $linkto) { - if(in_array($linkto, $idlist)) { + if (in_array($linkto, $idlist)) { $edge['group'] = 'edges'; $edge['data']['id'] = $page->id() . '>' . $linkto; $edge['data']['source'] = $page->id(); @@ -242,7 +247,7 @@ class Modelhome extends Modelpage } } // add redirection edge - if($showredirection && key_exists($page->redirection(), $pagelist)) { + if ($showredirection && key_exists($page->redirection(), $pagelist)) { $edger['group'] = 'edges'; $edger['data']['id'] = $page->id() . '>' . $page->redirection(); $edger['data']['refresh'] = $page->refresh(); @@ -259,7 +264,7 @@ class Modelhome extends Modelpage $nodes = []; foreach ($pagelist as $id => $page) { - if($showorphans || (!$showorphans && in_array($id, $notorphans))) { + if ($showorphans || (!$showorphans && in_array($id, $notorphans))) { $node['group'] = 'nodes'; $node['data']['id'] = $page->id(); $node['data']['edit'] = $page->id() . DIRECTORY_SEPARATOR . 'edit'; @@ -270,19 +275,18 @@ class Modelhome extends Modelpage } return array_merge($nodes, $edges); - } /** * @param array array of the columns to show from the user - * + * * @return array assoc each key columns to a boolean value to show or not */ - public function setcolumns(array $columns) : array + public function setcolumns(array $columns): array { foreach (Model::COLUMNS as $col) { - if(in_array($col, $columns)) { + if (in_array($col, $columns)) { $showcols[$col] = true; } else { $showcols[$col] = false; @@ -291,12 +295,3 @@ class Modelhome extends Modelpage return $showcols; } } - - - - - - - - -?>
\ No newline at end of file diff --git a/app/class/Modelmedia.php b/app/class/Modelmedia.php index 038f49e..fc8a727 100644 --- a/app/class/Modelmedia.php +++ b/app/class/Modelmedia.php @@ -5,357 +5,364 @@ namespace Wcms; class Modelmedia extends Model { - /** - * Get the Media Object - * - * @param string $entry Id of the file - * @param string $dir Directory of media file - * - * @return Media|bool - */ - public function getmedia(string $entry, string $dir) - { - $fileinfo = pathinfo($entry); - - if (isset($fileinfo['extension'])) { - $datas = array( - 'id' => str_replace('.' . $fileinfo['extension'], '', $fileinfo['filename']), - 'path' => $dir, - 'extension' => $fileinfo['extension'] - ); - return new Media($datas); - } else { - return false; - } - } - - public function medialistopt(Medialist $mediaopt) - { - $medialist = $this->getlistermedia($mediaopt->dir(), $mediaopt->type()); - $this->medialistsort($medialist, $mediaopt->sortby(), $mediaopt->order()); - - return $medialist; - } - - /** - * Display a list of media - * - * @param string $path - * @param array $type - * - * @return array of Media objects - */ - public function getlistermedia($dir, $type = []) - { - if (is_dir($dir)) { - if ($handle = opendir($dir)) { - $list = []; - while (false !== ($entry = readdir($handle))) { - if ($entry != "." && $entry != "..") { - - $media = $this->getmedia($entry, $dir); - - if ($media != false) { - - $media->analyse(); - - if (empty($type) || in_array($media->type(), $type)) { - $list[] = $media; - } - } - } - } - return $list; - } - } else { - return false; - } - } - - - /** - * Sort an array of media - * - * @param array $medialist - * @param string $sortby - * @param int order Can be 1 or -1 - */ - public function medialistsort(array &$medialist, string $sortby = 'id', int $order = 1): bool - { - $sortby = (in_array($sortby, self::MEDIA_SORTBY)) ? $sortby : 'id'; - $order = ($order === 1 || $order === -1) ? $order : 1; - return usort($medialist, $this->buildsorter($sortby, $order)); - } - - public function buildsorter($sortby, $order) - { - return function ($media1, $media2) use ($sortby, $order) { - $result = $this->mediacompare($media1, $media2, $sortby, $order); - return $result; - }; - } - - public function mediacompare($media1, $media2, $method = 'id', $order = 1) - { - $result = ($media1->$method() <=> $media2->$method()); - return $result * $order; - } - - - - - - public function listfavicon() - { - $faviconlist = $this->globlist(self::FAVICON_DIR, ['ico', 'png', 'jpg', 'jpeg', 'gif']); - return $faviconlist; - } - - public function listthumbnail() - { - $faviconlist = $this->globlist(self::THUMBNAIL_DIR, ['ico', 'png', 'jpg', 'jpeg', 'gif']); - return $faviconlist; - } - - - public function listinterfacecss() - { - $listinterfacecss = $this->globlist(self::CSS_DIR, ['css']); - $listinterfacecss = array_diff($listinterfacecss, ['edit.css', 'home.css', 'tagcolors.css']); - return $listinterfacecss; - } - - public function globlist (string $dir = '', array $extensions = []) : array - { - $list = []; - if(empty($extensions)) { - $glob = $dir . '*.'; - } else { - foreach ($extensions as $extension ) { - $glob = $dir . '*.' . $extension; - $list = array_merge($list, glob($glob)); - } - } - $list = array_map(function ($input){ - return basename($input); - }, $list); - return $list; - } - - - /** - * Generate an reccursive array where each folder is a array and containing a filecount in each folder - */ - public function listdir(string $dir) : array - { - $result = array(); - - $cdir = scandir($dir); - $result['dirfilecount'] = 0; - foreach ($cdir as $key => $value) { - if (!in_array($value, array(".", ".."))) { - if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) { - $result[$value] = $this->listdir($dir . DIRECTORY_SEPARATOR . $value); - } else { - $result['dirfilecount']++; - } - } - } - - return $result; - } - - /** - * Analyse reccursive array of content to generate list of path - * - * @param array $dirlist Array generated by the listdir function - * @param string $parent used to create the strings - * @param array $pathlist used by reference, must be an empty array - * - * @return array list of path as string - */ - public function listpath(array $dirlist, string $parent = '', array &$pathlist = []) - { - foreach ($dirlist as $dir => $content) { - if(is_array($content)) { - $pathlist[] = $parent . $dir . DIRECTORY_SEPARATOR; - $this->listpath($content, $parent . $dir . DIRECTORY_SEPARATOR, $pathlist); - } - } - } - - /** - * Upload single file - * - * @param string $index The file id - * @param string $destination File final destination - * @param bool|int $maxsize Max file size in octets - * @param bool|array $extensions List of authorized extensions - * @param bool $jpgrename Change the file exentension to .jpg - * - * @return bool If upload process is a succes or not - */ - function simpleupload(string $index, string $destination, $maxsize = false, $extensions = false, bool $jpgrename = false): bool - { - //Test1: if the file is corectly uploaded - if (!isset($_FILES[$index]) || $_FILES[$index]['error'] > 0) return false; - //Test2: check file size - if ($maxsize !== false && $_FILES[$index]['size'] > $maxsize) return false; - //Test3: check extension - $ext = substr(strrchr($_FILES[$index]['name'], '.'), 1); - if ($extensions !== false && !in_array($ext, $extensions)) return false; - if ($jpgrename !== false) { - $destination .= '.jpg'; - } else { - $destination .= '.' . $ext; - } - //Move to dir - return move_uploaded_file($_FILES[$index]['tmp_name'], $destination); - } - - /** - * Upload multiple files - * - * @param string $index Id of the file input - * @param string $target direction to save the files - */ - public function multiupload(string $index, string $target) - { - if ($target[strlen($target) - 1] != DIRECTORY_SEPARATOR) - $target .= DIRECTORY_SEPARATOR; - $count = 0; - $successcount = 0; - foreach ($_FILES[$index]['name'] as $filename) { - $fileinfo = pathinfo($filename); - $extension = idclean($fileinfo['extension']); - $id = idclean($fileinfo['filename']); - - $tmp = $_FILES['file']['tmp_name'][$count]; - $count ++; - $temp = $target . $id . '.' . $extension; - if(move_uploaded_file($tmp, $temp)) { - $successcount ++; - } - $temp = ''; - $tmp = ''; - } - Model::sendflashmessage($successcount . ' / ' . $count . ' files have been uploaded', 'success'); - } - - public function adddir($dir, $name) - { - $newdir = $dir . DIRECTORY_SEPARATOR . $name; - if (!is_dir($newdir)) { - return mkdir($newdir); - } else { - return false; - } - } - - /** - * Completely delete dir and it's content - * - * @param string $dir Directory to destroy - * - * @return bool depending on operation success - */ - public function deletedir(string $dir) : bool - { - if(substr($dir, -1) !== '/') { - $dir .= '/'; - } - if(is_dir($dir)) { - return $this->deltree($dir); - } else { - return false; - } - } - - /** - * Function do reccursively delete a directory - */ - public function deltree(string $dir) - { - $files = array_diff(scandir($dir), array('.','..')); - foreach ($files as $file) { - (is_dir("$dir/$file")) ? $this->deltree("$dir/$file") : unlink("$dir/$file"); - } - return rmdir($dir); - } - - /** - * Delete a file - */ - public function deletefile(string $filedir) - { - if(is_file($filedir) && is_writable(dirname($filedir))) { - return unlink($filedir); - } else { - return false; - } - } - - public function multifiledelete(array $filelist) - { - $success = []; - foreach ($filelist as $filedir ) { - if(is_string($filedir)) { - $success[] = $this->deletefile($filedir); - } - } - Model::sendflashmessage(count(array_filter($success)) . ' / ' . count($filelist) . ' files have been deleted', 'success'); - if(in_array(false, $success)) { - return false; - } else { - return true; - } - } - - /** - * @param string $filedir current file path - * @param string $dir New directory to move file to - * - * @return bool True in case of success, false if the file does not exist or if `rename()` fail - */ - public function movefile(string $filedir, string $dir) : bool - { - if(substr($dir, -1) !== '/') { - $dir .= '/'; - } - if(is_file($filedir)) { - $newdir = $dir . basename($filedir); - return rename($filedir, $newdir); - } else { - return false; - } - } - - /** - * @param array $filedirlist Ordered array of file list - * @param string $dir New directory to move file to - * - * @return bool False if any of moves failed, otherwise true - */ - public function multimovefile(array $filedirlist, string $dir) : bool - { - $count = 0; - foreach ($filedirlist as $filedir ) { - if(is_string($filedir)) { - if($this->movefile($filedir, $dir)) { - $count ++; - } - } - } - $total = count($filedirlist); - if($count !== $total) { - Model::sendflashmessage($count . ' / ' . $total . ' files have been moved', 'error'); - return false; - } else { - Model::sendflashmessage($count . ' / ' . $total . ' files have been moved', 'success'); - return true; - } - } - - - + /** + * Get the Media Object + * + * @param string $entry Id of the file + * @param string $dir Directory of media file + * + * @return Media|bool + */ + public function getmedia(string $entry, string $dir) + { + $fileinfo = pathinfo($entry); + + if (isset($fileinfo['extension'])) { + $datas = array( + 'id' => str_replace('.' . $fileinfo['extension'], '', $fileinfo['filename']), + 'path' => $dir, + 'extension' => $fileinfo['extension'] + ); + return new Media($datas); + } else { + return false; + } + } + + public function medialistopt(Medialist $mediaopt) + { + $medialist = $this->getlistermedia($mediaopt->dir(), $mediaopt->type()); + $this->medialistsort($medialist, $mediaopt->sortby(), $mediaopt->order()); + + return $medialist; + } + + /** + * Display a list of media + * + * @param string $path + * @param array $type + * + * @return array of Media objects + */ + public function getlistermedia($dir, $type = []) + { + if (is_dir($dir)) { + if ($handle = opendir($dir)) { + $list = []; + while (false !== ($entry = readdir($handle))) { + if ($entry != "." && $entry != "..") { + $media = $this->getmedia($entry, $dir); + + if ($media != false) { + $media->analyse(); + + if (empty($type) || in_array($media->type(), $type)) { + $list[] = $media; + } + } + } + } + return $list; + } + } else { + return false; + } + } + + + /** + * Sort an array of media + * + * @param array $medialist + * @param string $sortby + * @param int order Can be 1 or -1 + */ + public function medialistsort(array &$medialist, string $sortby = 'id', int $order = 1): bool + { + $sortby = (in_array($sortby, self::MEDIA_SORTBY)) ? $sortby : 'id'; + $order = ($order === 1 || $order === -1) ? $order : 1; + return usort($medialist, $this->buildsorter($sortby, $order)); + } + + public function buildsorter($sortby, $order) + { + return function ($media1, $media2) use ($sortby, $order) { + $result = $this->mediacompare($media1, $media2, $sortby, $order); + return $result; + }; + } + + public function mediacompare($media1, $media2, $method = 'id', $order = 1) + { + $result = ($media1->$method() <=> $media2->$method()); + return $result * $order; + } + + + + + + public function listfavicon() + { + $faviconlist = $this->globlist(self::FAVICON_DIR, ['ico', 'png', 'jpg', 'jpeg', 'gif']); + return $faviconlist; + } + + public function listthumbnail() + { + $faviconlist = $this->globlist(self::THUMBNAIL_DIR, ['ico', 'png', 'jpg', 'jpeg', 'gif']); + return $faviconlist; + } + + + public function listinterfacecss() + { + $listinterfacecss = $this->globlist(self::CSS_DIR, ['css']); + $listinterfacecss = array_diff($listinterfacecss, ['edit.css', 'home.css', 'tagcolors.css']); + return $listinterfacecss; + } + + public function globlist(string $dir = '', array $extensions = []): array + { + $list = []; + if (empty($extensions)) { + $glob = $dir . '*.'; + } else { + foreach ($extensions as $extension) { + $glob = $dir . '*.' . $extension; + $list = array_merge($list, glob($glob)); + } + } + $list = array_map(function ($input) { + return basename($input); + }, $list); + return $list; + } + + + /** + * Generate an reccursive array where each folder is a array and containing a filecount in each folder + */ + public function listdir(string $dir): array + { + $result = array(); + + $cdir = scandir($dir); + $result['dirfilecount'] = 0; + foreach ($cdir as $key => $value) { + if (!in_array($value, array(".", ".."))) { + if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) { + $result[$value] = $this->listdir($dir . DIRECTORY_SEPARATOR . $value); + } else { + $result['dirfilecount']++; + } + } + } + + return $result; + } + + /** + * Analyse reccursive array of content to generate list of path + * + * @param array $dirlist Array generated by the listdir function + * @param string $parent used to create the strings + * @param array $pathlist used by reference, must be an empty array + * + * @return array list of path as string + */ + public function listpath(array $dirlist, string $parent = '', array &$pathlist = []) + { + foreach ($dirlist as $dir => $content) { + if (is_array($content)) { + $pathlist[] = $parent . $dir . DIRECTORY_SEPARATOR; + $this->listpath($content, $parent . $dir . DIRECTORY_SEPARATOR, $pathlist); + } + } + } + + /** + * Upload single file + * + * @param string $index The file id + * @param string $destination File final destination + * @param bool|int $maxsize Max file size in octets + * @param bool|array $extensions List of authorized extensions + * @param bool $jpgrename Change the file exentension to .jpg + * + * @return bool If upload process is a succes or not + */ + public function simpleupload( + string $index, + string $destination, + $maxsize = false, + $extensions = false, + bool $jpgrename = false + ): bool { + //Test1: if the file is corectly uploaded + if (!isset($_FILES[$index]) || $_FILES[$index]['error'] > 0) { + return false; + } + //Test2: check file size + if ($maxsize !== false && $_FILES[$index]['size'] > $maxsize) { + return false; + } + //Test3: check extension + $ext = substr(strrchr($_FILES[$index]['name'], '.'), 1); + if ($extensions !== false && !in_array($ext, $extensions)) { + return false; + } + if ($jpgrename !== false) { + $destination .= '.jpg'; + } else { + $destination .= '.' . $ext; + } + //Move to dir + return move_uploaded_file($_FILES[$index]['tmp_name'], $destination); + } + + /** + * Upload multiple files + * + * @param string $index Id of the file input + * @param string $target direction to save the files + */ + public function multiupload(string $index, string $target) + { + if ($target[strlen($target) - 1] != DIRECTORY_SEPARATOR) { + $target .= DIRECTORY_SEPARATOR; + } + $count = 0; + $successcount = 0; + foreach ($_FILES[$index]['name'] as $filename) { + $fileinfo = pathinfo($filename); + $extension = idclean($fileinfo['extension']); + $id = idclean($fileinfo['filename']); + + $tmp = $_FILES['file']['tmp_name'][$count]; + $count++; + $temp = $target . $id . '.' . $extension; + if (move_uploaded_file($tmp, $temp)) { + $successcount++; + } + $temp = ''; + $tmp = ''; + } + Model::sendflashmessage($successcount . ' / ' . $count . ' files have been uploaded', 'success'); + } + + public function adddir($dir, $name) + { + $newdir = $dir . DIRECTORY_SEPARATOR . $name; + if (!is_dir($newdir)) { + return mkdir($newdir); + } else { + return false; + } + } + + /** + * Completely delete dir and it's content + * + * @param string $dir Directory to destroy + * + * @return bool depending on operation success + */ + public function deletedir(string $dir): bool + { + if (substr($dir, -1) !== '/') { + $dir .= '/'; + } + if (is_dir($dir)) { + return $this->deltree($dir); + } else { + return false; + } + } + + /** + * Function do reccursively delete a directory + */ + public function deltree(string $dir) + { + $files = array_diff(scandir($dir), array('.','..')); + foreach ($files as $file) { + (is_dir("$dir/$file")) ? $this->deltree("$dir/$file") : unlink("$dir/$file"); + } + return rmdir($dir); + } + + /** + * Delete a file + */ + public function deletefile(string $filedir) + { + if (is_file($filedir) && is_writable(dirname($filedir))) { + return unlink($filedir); + } else { + return false; + } + } + + public function multifiledelete(array $filelist) + { + $success = []; + foreach ($filelist as $filedir) { + if (is_string($filedir)) { + $success[] = $this->deletefile($filedir); + } + } + Model::sendflashmessage(count(array_filter($success)) . ' / ' . count($filelist) . ' files have been deleted', 'success'); + if (in_array(false, $success)) { + return false; + } else { + return true; + } + } + + /** + * @param string $filedir current file path + * @param string $dir New directory to move file to + * + * @return bool True in case of success, false if the file does not exist or if `rename()` fail + */ + public function movefile(string $filedir, string $dir): bool + { + if (substr($dir, -1) !== '/') { + $dir .= '/'; + } + if (is_file($filedir)) { + $newdir = $dir . basename($filedir); + return rename($filedir, $newdir); + } else { + return false; + } + } + + /** + * @param array $filedirlist Ordered array of file list + * @param string $dir New directory to move file to + * + * @return bool False if any of moves failed, otherwise true + */ + public function multimovefile(array $filedirlist, string $dir): bool + { + $count = 0; + foreach ($filedirlist as $filedir) { + if (is_string($filedir)) { + if ($this->movefile($filedir, $dir)) { + $count++; + } + } + } + $total = count($filedirlist); + if ($count !== $total) { + Model::sendflashmessage($count . ' / ' . $total . ' files have been moved', 'error'); + return false; + } else { + Model::sendflashmessage($count . ' / ' . $total . ' files have been moved', 'success'); + return true; + } + } } diff --git a/app/class/Modelpage.php b/app/class/Modelpage.php index cf07c2b..8bfa757 100644 --- a/app/class/Modelpage.php +++ b/app/class/Modelpage.php @@ -6,436 +6,439 @@ use Exception; use JamesMoss\Flywheel\Document; use DateTimeImmutable; - class Modelpage extends Modeldb { - protected $pagelist = []; - - - public function __construct() - { - $this->dbinit(Model::PAGES_DIR); - $this->storeinit(Config::pagetable()); - if(!$this->dircheck(Model::HTML_RENDER_DIR)) { - throw new Exception("Media error : Cant create /render folder"); - } - } - - /** - * Scan library for all pages as objects. - * If a scan has already been perform, it will just - * read `pagelist` Propriety - * - * @return array of Pages objects as `id => Page` - */ - public function pagelist() - { - if(empty($this->pagelist)) { - $list = $this->repo->findAll(); - foreach ($list as $pagedata) { - $this->pagelist[$pagedata->id] = new Page($pagedata); - } - } - return $this->pagelist; - } - - - /** - * Scan database for specific pages IDs and return array of Pages objects - * - * @param array $idlist list of ID strings - * - * @return Page[] array of Page objects - */ - public function pagelistbyid(array $idlist = []) : array - { - $pagedatalist = $this->repo->query() - ->where('__id', 'IN', $idlist) - ->execute(); - - $pagelist = []; - foreach ($pagedatalist as $id => $pagedata) { - $pagelist[$id] = new Page($pagedata); - } - return $pagelist; - } - - /** - * Store new page in the database - * - * @param Page $page object - * @return bool depending on database storing - */ - public function add(Page $page) : bool - { - - $pagedata = new Document($page->dry()); - $pagedata->setId($page->id()); - return $this->repo->store($pagedata); - } - - /** - * Obtain a page object from the database - * - * @param Page|string $id could be an Page object or a id string - * - * @return Page|false The Page object or false if it does not exist. - */ - public function get($id) - { - if ($id instanceof Page) { - $id = $id->id(); - } - if (is_string($id)) { - $pagedata = $this->repo->findById($id); - if ($pagedata !== false) { - return new Page($pagedata); - } else { - return false; - } - } else { - return false; - } - } - - /** - * Transform File to Page Oject - * - * @return false|Page - */ - public function getfromfile() - { - if(!isset($_FILES['pagefile']) || $_FILES['pagefile']['error'] > 0 ) return false; - - $ext = substr(strrchr($_FILES['pagefile']['name'],'.'),1); - if($ext !== 'json') return false; - - $files = $_FILES; - - $json = file_get_contents($_FILES['pagefile']['tmp_name']); - $pagedata = json_decode($json, true); - - if($pagedata === false) return false; - - $page = new Page($pagedata); - - return $page; - - } - - public function getpageelement($id, $element) - { - if (in_array($element, Model::TEXT_ELEMENTS)) { - $page = $this->get($id); - if ($page !== false) { - return $page->$element(); - } else { - return false; - } - } - } - - /** - * Delete a page and it's linked rendered html and css files - * - * @param Page|string $id could be an Page object or a id string - * - * @return bool true if success otherwise false - */ - public function delete($page) : bool - { - if ($page instanceof Page) { - $page = $page->id(); - } - if (is_string($page)) { - $this->unlink($page); - return $this->repo->delete($page); - } else { - return false; - } - } - - /** - * Delete rendered CSS and HTML files - */ - public function unlink(string $pageid) - { - $files = ['.css', '.quick.css', '.js']; - foreach ($files as $file) { - if (file_exists(Model::RENDER_DIR . $pageid . $file)) { - unlink(Model::RENDER_DIR . $pageid . $file); - } - } - if(file_exists(Model::HTML_RENDER_DIR . $pageid . '.html')) { - unlink(Model::HTML_RENDER_DIR . $pageid . '.html'); - } - } - - /** - * Update a page in the database - * - * @todo Check if page already exist before updating ? - * - * @param Page $page The page that is going to be updated - * - * @return bool True if success otherwise, false - * - */ - public function update(Page $page) - { - $pagedata = new Document($page->dry()); - $pagedata->setId($page->id()); - return $this->repo->store($pagedata); - } - - public function combine(Page $pagea, Page $pageb) - { - $mergepage = $pagea; - $merge = []; - $diff = []; - foreach ($pagea::TABS as $element) { - if($pagea->$element() !== $pageb->$element()) { - $merge[$element] = compare($pagea->$element(), $pageb->$element()); - $diff[] = $element; - } - } - $mergepage->hydrate($merge); - - return ['diff' => $diff, 'mergepage' => $mergepage]; - } - - // public function diffpageelement(Page $pagea, Page $pageb) - // { - // $diff = []; - // foreach ($pagea::TABS as $element) { - // if($pagea->$element() !== $pageb->$element()) { - // $diff[] = $element; - // } - // } - // return $diff; - // } - - public function pagecompare($page1, $page2, $method = 'id', $order = 1) - { - $result = ($page1->$method('sort') <=> $page2->$method('sort')); - return $result * $order; - } - - public function buildsorter($sortby, $order) - { - return function ($page1, $page2) use ($sortby, $order) { - $result = $this->pagecompare($page1, $page2, $sortby, $order); - return $result; - }; - } - - - - public function pagelistsort(&$pagelist, $sortby, $order = 1) - { - return uasort($pagelist, $this->buildsorter($sortby, $order)); - } - - - /** - * @param array $pagelist List of Page - * @param array $tagchecked list of tags - * @param string $tagcompare string, can be 'OR' or 'AND', set the tag filter method - * - * @return array $array of `string` page id - */ - - public function filtertagfilter(array $pagelist, array $tagchecked, $tagcompare = 'OR') - { - - $filteredlist = []; - foreach ($pagelist as $page) { - if (empty($tagchecked)) { - $filteredlist[] = $page->id(); - } else { - $inter = (array_intersect($page->tag('array'), $tagchecked)); - if ($tagcompare == 'OR') { - if (!empty($inter)) { - $filteredlist[] = $page->id(); - } - } elseif ($tagcompare == 'AND') { - if (!array_diff($tagchecked, $page->tag('array'))) { - $filteredlist[] = $page->id(); - } - } - } - } - return $filteredlist; - } - - - - /** - * @param array $pagelist List of Page - * @param array $authorchecked list of authors - * @param string $authorcompare, can be 'OR' or 'AND', set the author filter method - * - * @return array $array of `string` page id - */ - - public function filterauthorfilter(array $pagelist, array $authorchecked, $authorcompare = 'OR') - { - - $filteredlist = []; - foreach ($pagelist as $page) { - if (empty($authorchecked)) { - $filteredlist[] = $page->id(); - } else { - $inter = (array_intersect($page->authors('array'), $authorchecked)); - if ($authorcompare == 'OR') { - if (!empty($inter)) { - $filteredlist[] = $page->id(); - } - } elseif ($authorcompare == 'AND') { - if (!array_diff($authorchecked, $page->authors('array'))) { - $filteredlist[] = $page->id(); - } - } - } - } - return $filteredlist; - } - - /** - * @param array $pagelist List of Page - * @param int $secure secure level - * @param string $authorcompare, can be 'OR' or 'AND', set the author filter method - * - * @return array $array of `string` page id - */ - - public function filtersecure(array $pagelist, int $secure) : array - { - $filteredlist = []; - foreach ($pagelist as $page) { - if ($page->secure() == intval($secure)) { - $filteredlist[] = $page->id(); - } elseif (intval($secure) >= 4) { - $filteredlist[] = $page->id(); - } - } - return $filteredlist; - } - - /** - * @param array $pagelist Array of Page object - * @param string $linkto - */ - public function filterlinkto(array $pagelist, string $linkto) : array - { - $filteredlist = []; - foreach ($pagelist as $page) { - if (in_array( $linkto, $page->linkto('array'))) { - $filteredlist[] = $page->id(); - } elseif (empty($linkto)) { - $filteredlist[] = $page->id(); - } - } - return $filteredlist; - } - - - public function tag(array $pagelist, $tagchecked) - { - $pagecheckedlist = []; - foreach ($pagelist as $page) { - if (in_array($tagchecked, $page->tag('array'))) { - $pagecheckedlist[] = $page; - } - } - return $pagecheckedlist; - } - - public function taglist(array $pagelist, array $tagcheckedlist) - { - $taglist = []; - foreach ($tagcheckedlist as $tag) { - $taglist[$tag] = $this->tag($pagelist, $tag); - } - return $taglist; - } - - /** - * @param array $taglist list of tags - * @param array $pagelist list of Page - * - * @return array list of tags each containing list of id - */ - - public function tagpagelist(array $taglist, array $pagelist) - { - $tagpagelist = []; - foreach ($taglist as $tag) { - $tagpagelist[$tag] = $this->filtertagfilter($pagelist, [$tag]); - } - return $tagpagelist; - } - - public function lasteditedpagelist(int $last, array $pagelist) - { - $this->pagelistsort($pagelist, 'datemodif', -1); - $pagelist = array_slice($pagelist, 0, $last); - $idlist = []; - foreach ($pagelist as $page) { - $idlist[] = $page->id(); - } - return $idlist; - } - - /** - * Edit a page based on meta infos - * - * @param string $pageid - * @param array $datas - * @param array $reset - * @param string $addtag - * @param string $addauthor - * - * @return bool Depending on update success - */ - public function pageedit($pageid, $datas, $reset, $addtag, $addauthor) : bool - { - $page = $this->get($pageid); - $page = $this->reset($page, $reset); - $page->hydrate($datas); - $page->addtag($addtag); - $page->addauthor($addauthor); - return $this->update($page); - } - - /** - * Reset values of a page - * - * @param Page $page Page object to be reseted - * @param array $reset List of parameters needing reset - * - * @return Page The reseted page object - */ - public function reset(Page $page, array $reset) : Page + protected $pagelist = []; + + + public function __construct() + { + $this->dbinit(Model::PAGES_DIR); + $this->storeinit(Config::pagetable()); + if (!$this->dircheck(Model::HTML_RENDER_DIR)) { + throw new Exception("Media error : Cant create /render folder"); + } + } + + /** + * Scan library for all pages as objects. + * If a scan has already been perform, it will just + * read `pagelist` Propriety + * + * @return array of Pages objects as `id => Page` + */ + public function pagelist() + { + if (empty($this->pagelist)) { + $list = $this->repo->findAll(); + foreach ($list as $pagedata) { + $this->pagelist[$pagedata->id] = new Page($pagedata); + } + } + return $this->pagelist; + } + + + /** + * Scan database for specific pages IDs and return array of Pages objects + * + * @param array $idlist list of ID strings + * + * @return Page[] array of Page objects + */ + public function pagelistbyid(array $idlist = []): array + { + $pagedatalist = $this->repo->query() + ->where('__id', 'IN', $idlist) + ->execute(); + + $pagelist = []; + foreach ($pagedatalist as $id => $pagedata) { + $pagelist[$id] = new Page($pagedata); + } + return $pagelist; + } + + /** + * Store new page in the database + * + * @param Page $page object + * @return bool depending on database storing + */ + public function add(Page $page): bool + { + + $pagedata = new Document($page->dry()); + $pagedata->setId($page->id()); + return $this->repo->store($pagedata); + } + + /** + * Obtain a page object from the database + * + * @param Page|string $id could be an Page object or a id string + * + * @return Page|false The Page object or false if it does not exist. + */ + public function get($id) + { + if ($id instanceof Page) { + $id = $id->id(); + } + if (is_string($id)) { + $pagedata = $this->repo->findById($id); + if ($pagedata !== false) { + return new Page($pagedata); + } else { + return false; + } + } else { + return false; + } + } + + /** + * Transform File to Page Oject + * + * @return false|Page + */ + public function getfromfile() + { + if (!isset($_FILES['pagefile']) || $_FILES['pagefile']['error'] > 0) { + return false; + } + + $ext = substr(strrchr($_FILES['pagefile']['name'], '.'), 1); + if ($ext !== 'json') { + return false; + } + + $files = $_FILES; + + $json = file_get_contents($_FILES['pagefile']['tmp_name']); + $pagedata = json_decode($json, true); + + if ($pagedata === false) { + return false; + } + + $page = new Page($pagedata); + + return $page; + } + + public function getpageelement($id, $element) + { + if (in_array($element, Model::TEXT_ELEMENTS)) { + $page = $this->get($id); + if ($page !== false) { + return $page->$element(); + } else { + return false; + } + } + } + + /** + * Delete a page and it's linked rendered html and css files + * + * @param Page|string $id could be an Page object or a id string + * + * @return bool true if success otherwise false + */ + public function delete($page): bool + { + if ($page instanceof Page) { + $page = $page->id(); + } + if (is_string($page)) { + $this->unlink($page); + return $this->repo->delete($page); + } else { + return false; + } + } + + /** + * Delete rendered CSS and HTML files + */ + public function unlink(string $pageid) + { + $files = ['.css', '.quick.css', '.js']; + foreach ($files as $file) { + if (file_exists(Model::RENDER_DIR . $pageid . $file)) { + unlink(Model::RENDER_DIR . $pageid . $file); + } + } + if (file_exists(Model::HTML_RENDER_DIR . $pageid . '.html')) { + unlink(Model::HTML_RENDER_DIR . $pageid . '.html'); + } + } + + /** + * Update a page in the database + * + * @todo Check if page already exist before updating ? + * + * @param Page $page The page that is going to be updated + * + * @return bool True if success otherwise, false + * + */ + public function update(Page $page) + { + $pagedata = new Document($page->dry()); + $pagedata->setId($page->id()); + return $this->repo->store($pagedata); + } + + public function combine(Page $pagea, Page $pageb) + { + $mergepage = $pagea; + $merge = []; + $diff = []; + foreach ($pagea::TABS as $element) { + if ($pagea->$element() !== $pageb->$element()) { + $merge[$element] = compare($pagea->$element(), $pageb->$element()); + $diff[] = $element; + } + } + $mergepage->hydrate($merge); + + return ['diff' => $diff, 'mergepage' => $mergepage]; + } + + // public function diffpageelement(Page $pagea, Page $pageb) + // { + // $diff = []; + // foreach ($pagea::TABS as $element) { + // if($pagea->$element() !== $pageb->$element()) { + // $diff[] = $element; + // } + // } + // return $diff; + // } + + public function pagecompare($page1, $page2, $method = 'id', $order = 1) { - $now = new DateTimeImmutable(null, timezone_open("Europe/Paris")); - if($reset['tag']) { + $result = ($page1->$method('sort') <=> $page2->$method('sort')); + return $result * $order; + } + + public function buildsorter($sortby, $order) + { + return function ($page1, $page2) use ($sortby, $order) { + $result = $this->pagecompare($page1, $page2, $sortby, $order); + return $result; + }; + } + + + + public function pagelistsort(&$pagelist, $sortby, $order = 1) + { + return uasort($pagelist, $this->buildsorter($sortby, $order)); + } + + + /** + * @param array $pagelist List of Page + * @param array $tagchecked list of tags + * @param string $tagcompare string, can be 'OR' or 'AND', set the tag filter method + * + * @return array $array of `string` page id + */ + + public function filtertagfilter(array $pagelist, array $tagchecked, $tagcompare = 'OR') + { + + $filteredlist = []; + foreach ($pagelist as $page) { + if (empty($tagchecked)) { + $filteredlist[] = $page->id(); + } else { + $inter = (array_intersect($page->tag('array'), $tagchecked)); + if ($tagcompare == 'OR') { + if (!empty($inter)) { + $filteredlist[] = $page->id(); + } + } elseif ($tagcompare == 'AND') { + if (!array_diff($tagchecked, $page->tag('array'))) { + $filteredlist[] = $page->id(); + } + } + } + } + return $filteredlist; + } + + + + /** + * @param array $pagelist List of Page + * @param array $authorchecked list of authors + * @param string $authorcompare, can be 'OR' or 'AND', set the author filter method + * + * @return array $array of `string` page id + */ + + public function filterauthorfilter(array $pagelist, array $authorchecked, $authorcompare = 'OR') + { + + $filteredlist = []; + foreach ($pagelist as $page) { + if (empty($authorchecked)) { + $filteredlist[] = $page->id(); + } else { + $inter = (array_intersect($page->authors('array'), $authorchecked)); + if ($authorcompare == 'OR') { + if (!empty($inter)) { + $filteredlist[] = $page->id(); + } + } elseif ($authorcompare == 'AND') { + if (!array_diff($authorchecked, $page->authors('array'))) { + $filteredlist[] = $page->id(); + } + } + } + } + return $filteredlist; + } + + /** + * @param array $pagelist List of Page + * @param int $secure secure level + * @param string $authorcompare, can be 'OR' or 'AND', set the author filter method + * + * @return array $array of `string` page id + */ + + public function filtersecure(array $pagelist, int $secure): array + { + $filteredlist = []; + foreach ($pagelist as $page) { + if ($page->secure() == intval($secure)) { + $filteredlist[] = $page->id(); + } elseif (intval($secure) >= 4) { + $filteredlist[] = $page->id(); + } + } + return $filteredlist; + } + + /** + * @param array $pagelist Array of Page object + * @param string $linkto + */ + public function filterlinkto(array $pagelist, string $linkto): array + { + $filteredlist = []; + foreach ($pagelist as $page) { + if (in_array($linkto, $page->linkto('array'))) { + $filteredlist[] = $page->id(); + } elseif (empty($linkto)) { + $filteredlist[] = $page->id(); + } + } + return $filteredlist; + } + + + public function tag(array $pagelist, $tagchecked) + { + $pagecheckedlist = []; + foreach ($pagelist as $page) { + if (in_array($tagchecked, $page->tag('array'))) { + $pagecheckedlist[] = $page; + } + } + return $pagecheckedlist; + } + + public function taglist(array $pagelist, array $tagcheckedlist) + { + $taglist = []; + foreach ($tagcheckedlist as $tag) { + $taglist[$tag] = $this->tag($pagelist, $tag); + } + return $taglist; + } + + /** + * @param array $taglist list of tags + * @param array $pagelist list of Page + * + * @return array list of tags each containing list of id + */ + + public function tagpagelist(array $taglist, array $pagelist) + { + $tagpagelist = []; + foreach ($taglist as $tag) { + $tagpagelist[$tag] = $this->filtertagfilter($pagelist, [$tag]); + } + return $tagpagelist; + } + + public function lasteditedpagelist(int $last, array $pagelist) + { + $this->pagelistsort($pagelist, 'datemodif', -1); + $pagelist = array_slice($pagelist, 0, $last); + $idlist = []; + foreach ($pagelist as $page) { + $idlist[] = $page->id(); + } + return $idlist; + } + + /** + * Edit a page based on meta infos + * + * @param string $pageid + * @param array $datas + * @param array $reset + * @param string $addtag + * @param string $addauthor + * + * @return bool Depending on update success + */ + public function pageedit($pageid, $datas, $reset, $addtag, $addauthor): bool + { + $page = $this->get($pageid); + $page = $this->reset($page, $reset); + $page->hydrate($datas); + $page->addtag($addtag); + $page->addauthor($addauthor); + return $this->update($page); + } + + /** + * Reset values of a page + * + * @param Page $page Page object to be reseted + * @param array $reset List of parameters needing reset + * + * @return Page The reseted page object + */ + public function reset(Page $page, array $reset): Page + { + $now = new DateTimeImmutable(null, timezone_open("Europe/Paris")); + if ($reset['tag']) { $page->settag([]); } - if($reset['author']) { + if ($reset['author']) { $page->setauthors([]); } - if($reset['redirection']) { + if ($reset['redirection']) { $page->setredirection(''); } - if($reset['date']) { - $page->setdate($now); - } - if($reset['datemodif']) { - $page->setdatemodif($now); - } - return $page; + if ($reset['date']) { + $page->setdate($now); + } + if ($reset['datemodif']) { + $page->setdatemodif($now); + } + return $page; } - } diff --git a/app/class/Modelrender.php b/app/class/Modelrender.php index 091179d..8df813b 100644 --- a/app/class/Modelrender.php +++ b/app/class/Modelrender.php @@ -7,286 +7,284 @@ use Michelf\MarkdownExtra; class Modelrender extends Modelpage { - /** @var \AltoRouter */ - protected $router; - /** @var Page Actual page being rendered*/ - protected $page; - protected $linkto = []; - protected $sum = []; - protected $internallinkblank = ''; - protected $externallinkblank = ''; - - const RENDER_VERBOSE = 1; - - public function __construct(\AltoRouter $router) - { - parent::__construct(); - - $this->router = $router; - $this->pagelist = $this->pagelist(); - - if (Config::internallinkblank()) { - $this->internallinkblank = ' target="_blank" '; - } - - if (Config::externallinkblank()) { - $this->externallinkblank = ' target="_blank" '; - } - } - - /** - * Used to convert the markdown user manual to html document - * - * @param string $text Input text in markdown - * @return string html formated text - */ - public function rendermanual(string $text): string - { - $text = $this->markdown($text); - $text = $this->headerid($text, 1, 5); - return $text; - } - - - /** - * Generate page relative link for given page_id including basepath - * - * @param string $id given page ID - * @return string Relative URL - */ - public function upage(string $id): string - { - return $this->router->generate('pageread/', ['page' => $id]); - } - - - /** - * Main function - * - * @param Page $page page to render - */ - public function render(Page $page) - { - $this->page = $page; - - $this->write($this->gethmtl()); - } - - /** - * Combine body and head to create html file - * - * @return string html string - */ - public function gethmtl() - { - - $head = $this->gethead(); - $body = $this->getbody($this->readbody()); - $parsebody = $this->bodyparser($body); - - $html = '<!DOCTYPE html>' . PHP_EOL . '<html>' . PHP_EOL . '<head>' . PHP_EOL . $head . PHP_EOL . '</head>' . PHP_EOL . $parsebody . PHP_EOL . '</html>'; - - return $html; - } - - - public function readbody() - { - if (!empty($this->page->templatebody())) { - $templateid = $this->page->templatebody(); - $templatepage = $this->get($templateid); - if ($templatepage !== false) { - $body = $templatepage->body(); - } else { - $body = $this->page->body(); - $this->page->settemplatebody(''); - } - } else { - $body = $this->page->body(); - } - $body = $this->article($body); - $body = $this->automedialist($body); - return $body; - } - - - /** - * Analyse BODY, call the corresponding CONTENTs and render everything - * - * @param string $body as the string BODY of the page - * - * @return string as the full rendered BODY of the page - */ - public function getbody(string $body): string - { - // Elements that can be detected - $types = ['HEADER', 'NAV', 'MAIN', 'ASIDE', 'FOOTER']; - - // First level regex - $regex = implode("|", $types); - - $matches = $this->match($body, $regex); - - // First, analyse the synthax and call the corresponding methods - if (isset($matches)) { - foreach ($matches as $key => $match) { - $element = new Element($match, $this->page->id()); - $element->setcontent($this->getelementcontent($element->sources(), $element->type())); - $element->setcontent($this->elementparser($element)); - $element->addtags(); - $body = str_replace($element->fullmatch(), $element->content(), $body); - } - } - - - - return $body; - } - - /** - * Foreach $sources (pages), this will get the corresponding $type element content - * - * @param array $sources Array of pages ID - * @param string $type Type of element - */ - public function getelementcontent(array $sources, string $type) - { - $content = ''; - $subseparator = PHP_EOL . PHP_EOL; - foreach ($sources as $source) { - if ($source !== $this->page->id()) { - $subcontent = $this->getpageelement($source, $type); - if ($subcontent !== false) { - if (empty($subcontent && self::RENDER_VERBOSE > 0)) { - $subcontent = PHP_EOL . '<!-- The ' . strtoupper($type) . ' from page "' . $source . '" is currently empty ! -->' . PHP_EOL; - } - } else { - $read = '<h2>Rendering error :</h2><p>The page <strong><code>' . $source . '</code></strong>, does not exist yet.</p>'; - //throw new Exception($read); - } - } else { - $subcontent = $this->page->$type(); - } - $content .= $subseparator . $subcontent; - } - return $content . $subseparator; - } - - public function elementparser(Element $element) - { - $content = $this->article($element->content()); - $content = $this->automedialist($content); - $content = $this->pageoptlist($content); - $content = $this->date($content); - $content = $this->thumbnail($content); - if ($element->autolink()) { - $content = $this->everylink($content, $element->autolink()); - } - if ($element->markdown()) { - $content = $this->markdown($content); - } - $content = $this->desctitle($content, $this->page->description(), $this->page->title()); - if($element->headerid()) { - $content = $this->headerid($content, $element->minheaderid(), $element->maxheaderid(), $element->type()); - } - - return $content; - } - - - /** - * Write css javascript and html as files in the assets folder - */ - public function write(string $html) - { - file_put_contents(Model::HTML_RENDER_DIR . $this->page->id() . '.html', $html); - file_put_contents(Model::RENDER_DIR . $this->page->id() . '.css', $this->page->css()); - //file_put_contents(Model::RENDER_DIR . $this->page->id() . '.quick.css', $this->page->quickcss()); - file_put_contents(Model::RENDER_DIR . $this->page->id() . '.js', $this->page->javascript()); - } - - - - public function writetemplates() - { - if (array_key_exists('css', $this->page->template('array'))) { - $tempaltecsspage = $this->get($this->page->template('array')['css']); - file_put_contents(Model::RENDER_DIR . $tempaltecsspage->id() . '.css', $tempaltecsspage->css()); - } - if (array_key_exists('javascript', $this->page->template('array'))) { - $templatejspage = $this->get($this->page->template('array')['javascript']); - file_put_contents(Model::RENDER_DIR . $templatejspage->id() . '.js', $templatejspage->javascript()); - } - } - - - - - public function gethead() - { - - $head = ''; - - $head .= '<meta charset="utf-8" />' . PHP_EOL; - $head .= '<title>' . $this->page->title() . '</title>' . PHP_EOL; - if (!empty($this->page->favicon())) { - $head .= '<link rel="shortcut icon" href="' . Model::faviconpath() . $this->page->favicon() . '" type="image/x-icon">'; - } elseif (!empty(Config::defaultfavicon())) { - $head .= '<link rel="shortcut icon" href="' . Model::faviconpath() . Config::defaultfavicon() . '" type="image/x-icon">'; - } - $head .= '<meta name="description" content="' . $this->page->description() . '" />' . PHP_EOL; - $head .= '<meta name="viewport" content="width=device-width" />' . PHP_EOL; - - - $head .= '<meta property="og:title" content="' . $this->page->title() . '">' . PHP_EOL; - $head .= '<meta property="og:description" content="' . $this->page->description() . '">' . PHP_EOL; - - if (!empty($this->page->thumbnail())) { - $head .= '<meta property="og:image" content="' . Config::domain() . self::thumbnailpath() . $this->page->thumbnail() . '">' . PHP_EOL; - } elseif (!empty(Config::defaultthumbnail())) { - $head .= '<meta property="og:image" content="' . Config::domain() . self::thumbnailpath() . Config::defaultthumbnail() . '">' . PHP_EOL; - } - - $head .= '<meta property="og:url" content="' . Config::url() . $this->page->id() . '/">' . PHP_EOL; - - - foreach ($this->page->externalcss() as $externalcss) { - $head .= '<link href="' . $externalcss . '" rel="stylesheet" />' . PHP_EOL; - } - - if (!empty($this->page->templatecss() && in_array('externalcss', $this->page->templateoptions()))) { - $templatecss = $this->get($this->page->templatecss()); - if ($templatecss !== false) { - - foreach ($templatecss->externalcss() as $externalcss) { - $head .= '<link href="' . $externalcss . '" rel="stylesheet" />' . PHP_EOL; - } - } - } - - $head .= PHP_EOL . $this->page->customhead() . PHP_EOL; - - - $head .= '<link href="' . Model::globalpath() . 'fonts.css" rel="stylesheet" />' . PHP_EOL; - $head .= '<link href="' . Model::globalpath() . 'global.css" rel="stylesheet" />' . PHP_EOL; - - if (!empty($this->page->templatecss())) { - $tempaltecsspage = $this->page->templatecss(); - $head .= '<link href="' . Model::renderpath() . $tempaltecsspage . '.css" rel="stylesheet" />' . PHP_EOL; - } - $head .= '<link href="' . Model::renderpath() . $this->page->id() . '.css" rel="stylesheet" />' . PHP_EOL; - - if (!empty($this->page->templatejavascript())) { - $templatejspage = $this->page->templatejavascript(); - $head .= '<script src="' . Model::renderpath() . $templatejspage . '.js" async/></script>' . PHP_EOL; - } - if (!empty($this->page->javascript())) { - $head .= '<script src="' . Model::renderpath() . $this->page->id() . '.js" async/></script>' . PHP_EOL; - } + /** @var \AltoRouter */ + protected $router; + /** @var Page Actual page being rendered*/ + protected $page; + protected $linkto = []; + protected $sum = []; + protected $internallinkblank = ''; + protected $externallinkblank = ''; + + public const RENDER_VERBOSE = 1; + + public function __construct(\AltoRouter $router) + { + parent::__construct(); + + $this->router = $router; + $this->pagelist = $this->pagelist(); + + if (Config::internallinkblank()) { + $this->internallinkblank = ' target="_blank" '; + } + + if (Config::externallinkblank()) { + $this->externallinkblank = ' target="_blank" '; + } + } + + /** + * Used to convert the markdown user manual to html document + * + * @param string $text Input text in markdown + * @return string html formated text + */ + public function rendermanual(string $text): string + { + $text = $this->markdown($text); + $text = $this->headerid($text, 1, 5); + return $text; + } + + + /** + * Generate page relative link for given page_id including basepath + * + * @param string $id given page ID + * @return string Relative URL + */ + public function upage(string $id): string + { + return $this->router->generate('pageread/', ['page' => $id]); + } + + + /** + * Main function + * + * @param Page $page page to render + */ + public function render(Page $page) + { + $this->page = $page; + + $this->write($this->gethmtl()); + } + + /** + * Combine body and head to create html file + * + * @return string html string + */ + public function gethmtl() + { + + $head = $this->gethead(); + $body = $this->getbody($this->readbody()); + $parsebody = $this->bodyparser($body); + + $html = '<!DOCTYPE html>' . PHP_EOL . '<html>' . PHP_EOL . '<head>' . PHP_EOL . $head . PHP_EOL . '</head>' . PHP_EOL . $parsebody . PHP_EOL . '</html>'; + + return $html; + } + + + public function readbody() + { + if (!empty($this->page->templatebody())) { + $templateid = $this->page->templatebody(); + $templatepage = $this->get($templateid); + if ($templatepage !== false) { + $body = $templatepage->body(); + } else { + $body = $this->page->body(); + $this->page->settemplatebody(''); + } + } else { + $body = $this->page->body(); + } + $body = $this->article($body); + $body = $this->automedialist($body); + return $body; + } + + + /** + * Analyse BODY, call the corresponding CONTENTs and render everything + * + * @param string $body as the string BODY of the page + * + * @return string as the full rendered BODY of the page + */ + public function getbody(string $body): string + { + // Elements that can be detected + $types = ['HEADER', 'NAV', 'MAIN', 'ASIDE', 'FOOTER']; + + // First level regex + $regex = implode("|", $types); + + $matches = $this->match($body, $regex); + + // First, analyse the synthax and call the corresponding methods + if (isset($matches)) { + foreach ($matches as $key => $match) { + $element = new Element($match, $this->page->id()); + $element->setcontent($this->getelementcontent($element->sources(), $element->type())); + $element->setcontent($this->elementparser($element)); + $element->addtags(); + $body = str_replace($element->fullmatch(), $element->content(), $body); + } + } + + + + return $body; + } + + /** + * Foreach $sources (pages), this will get the corresponding $type element content + * + * @param array $sources Array of pages ID + * @param string $type Type of element + */ + public function getelementcontent(array $sources, string $type) + { + $content = ''; + $subseparator = PHP_EOL . PHP_EOL; + foreach ($sources as $source) { + if ($source !== $this->page->id()) { + $subcontent = $this->getpageelement($source, $type); + if ($subcontent !== false) { + if (empty($subcontent && self::RENDER_VERBOSE > 0)) { + $subcontent = PHP_EOL . '<!-- The ' . strtoupper($type) . ' from page "' . $source . '" is currently empty ! -->' . PHP_EOL; + } + } else { + $read = '<h2>Rendering error :</h2><p>The page <strong><code>' . $source . '</code></strong>, does not exist yet.</p>'; + //throw new Exception($read); + } + } else { + $subcontent = $this->page->$type(); + } + $content .= $subseparator . $subcontent; + } + return $content . $subseparator; + } + + public function elementparser(Element $element) + { + $content = $this->article($element->content()); + $content = $this->automedialist($content); + $content = $this->pageoptlist($content); + $content = $this->date($content); + $content = $this->thumbnail($content); + if ($element->autolink()) { + $content = $this->everylink($content, $element->autolink()); + } + if ($element->markdown()) { + $content = $this->markdown($content); + } + $content = $this->desctitle($content, $this->page->description(), $this->page->title()); + if ($element->headerid()) { + $content = $this->headerid($content, $element->minheaderid(), $element->maxheaderid(), $element->type()); + } + + return $content; + } + + + /** + * Write css javascript and html as files in the assets folder + */ + public function write(string $html) + { + file_put_contents(Model::HTML_RENDER_DIR . $this->page->id() . '.html', $html); + file_put_contents(Model::RENDER_DIR . $this->page->id() . '.css', $this->page->css()); + //file_put_contents(Model::RENDER_DIR . $this->page->id() . '.quick.css', $this->page->quickcss()); + file_put_contents(Model::RENDER_DIR . $this->page->id() . '.js', $this->page->javascript()); + } + + + + public function writetemplates() + { + if (array_key_exists('css', $this->page->template('array'))) { + $tempaltecsspage = $this->get($this->page->template('array')['css']); + file_put_contents(Model::RENDER_DIR . $tempaltecsspage->id() . '.css', $tempaltecsspage->css()); + } + if (array_key_exists('javascript', $this->page->template('array'))) { + $templatejspage = $this->get($this->page->template('array')['javascript']); + file_put_contents(Model::RENDER_DIR . $templatejspage->id() . '.js', $templatejspage->javascript()); + } + } + + + + + public function gethead() + { + + $head = ''; + + $head .= '<meta charset="utf-8" />' . PHP_EOL; + $head .= '<title>' . $this->page->title() . '</title>' . PHP_EOL; + if (!empty($this->page->favicon())) { + $head .= '<link rel="shortcut icon" href="' . Model::faviconpath() . $this->page->favicon() . '" type="image/x-icon">'; + } elseif (!empty(Config::defaultfavicon())) { + $head .= '<link rel="shortcut icon" href="' . Model::faviconpath() . Config::defaultfavicon() . '" type="image/x-icon">'; + } + $head .= '<meta name="description" content="' . $this->page->description() . '" />' . PHP_EOL; + $head .= '<meta name="viewport" content="width=device-width" />' . PHP_EOL; + + + $head .= '<meta property="og:title" content="' . $this->page->title() . '">' . PHP_EOL; + $head .= '<meta property="og:description" content="' . $this->page->description() . '">' . PHP_EOL; + + if (!empty($this->page->thumbnail())) { + $head .= '<meta property="og:image" content="' . Config::domain() . self::thumbnailpath() . $this->page->thumbnail() . '">' . PHP_EOL; + } elseif (!empty(Config::defaultthumbnail())) { + $head .= '<meta property="og:image" content="' . Config::domain() . self::thumbnailpath() . Config::defaultthumbnail() . '">' . PHP_EOL; + } + + $head .= '<meta property="og:url" content="' . Config::url() . $this->page->id() . '/">' . PHP_EOL; + + + foreach ($this->page->externalcss() as $externalcss) { + $head .= '<link href="' . $externalcss . '" rel="stylesheet" />' . PHP_EOL; + } + + if (!empty($this->page->templatecss() && in_array('externalcss', $this->page->templateoptions()))) { + $templatecss = $this->get($this->page->templatecss()); + if ($templatecss !== false) { + foreach ($templatecss->externalcss() as $externalcss) { + $head .= '<link href="' . $externalcss . '" rel="stylesheet" />' . PHP_EOL; + } + } + } + + $head .= PHP_EOL . $this->page->customhead() . PHP_EOL; + + + $head .= '<link href="' . Model::globalpath() . 'fonts.css" rel="stylesheet" />' . PHP_EOL; + $head .= '<link href="' . Model::globalpath() . 'global.css" rel="stylesheet" />' . PHP_EOL; + + if (!empty($this->page->templatecss())) { + $tempaltecsspage = $this->page->templatecss(); + $head .= '<link href="' . Model::renderpath() . $tempaltecsspage . '.css" rel="stylesheet" />' . PHP_EOL; + } + $head .= '<link href="' . Model::renderpath() . $this->page->id() . '.css" rel="stylesheet" />' . PHP_EOL; + + if (!empty($this->page->templatejavascript())) { + $templatejspage = $this->page->templatejavascript(); + $head .= '<script src="' . Model::renderpath() . $templatejspage . '.js" async/></script>' . PHP_EOL; + } + if (!empty($this->page->javascript())) { + $head .= '<script src="' . Model::renderpath() . $this->page->id() . '.js" async/></script>' . PHP_EOL; + } - if (!empty(Config::analytics())) { - - $head .= PHP_EOL . ' + if (!empty(Config::analytics())) { + $head .= PHP_EOL . ' <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=' . Config::analytics() . '"></script> <script> @@ -297,368 +295,367 @@ class Modelrender extends Modelpage gtag(\'config\', \'' . Config::analytics() . '\'); </script> ' . PHP_EOL; - } - - if (!empty($this->page->redirection())) { - if (preg_match('%https?:\/\/\S*%', $this->page->redirection(), $out)) { - $url = $out[0]; - $head .= PHP_EOL . '<meta http-equiv="refresh" content="' . $this->page->refresh() . '; URL=' . $url . '" />'; - } elseif (key_exists($this->page->redirection(), $this->pagelist())) { - $url = $this->upage($this->page->redirection()); - $head .= PHP_EOL . '<meta http-equiv="refresh" content="' . $this->page->refresh() . '; URL=' . $url . '" />'; - } - } - - - return $head; - } - - public function desctitle($text, $desc, $title) - { - $text = str_replace('%TITLE%', $title, $text); - $text = str_replace('%DESCRIPTION%', $desc, $text); - return $text; - } - - - public function bodyparser(string $text) - { - $text = $this->media($text); - - $text = $this->summary($text); - - $text = $this->wurl($text); - $text = $this->wikiurl($text); - - - - $text = str_replace('href="http', "class=\"external\" $this->externallinkblank href=\"http", $text); - - $text = $this->shortenurl($text); - - $text = $this->autourl($text); - - $text = $this->authenticate($text); - - return $text; - } - - public function media(string $text): string - { - $text = preg_replace('%(src|href)="([\w-_]+(\/([\w-_])+)*\.[a-z0-9]{1,5})"%', '$1="' . Model::mediapath() . '$2" target="_blank" class="media"', $text); - if (!is_string($text)) { - //throw new Exception('Rendering error -> media module'); - } - return $text; - } - - /** - * Shorten the urls of links whose content equals the href. - * - * @param string $text the page text as html - */ - public function shortenurl(string $text): string - { - $text = preg_replace('#<a(.*href="(https?:\/\/(.+))".*)>\2</a>#', "<a$1>$3</a>", $text); - return $text; - } - - - public function autourl($text) - { - $text = preg_replace( - '#( |\R|(>)|(<))(https?:\/\/(\S+\.[^< ]+))(((?(3)>|))(?(2)</[^a]|))#', - "$1<a href=\"$4\" class=\"external\" $this->externallinkblank>$4</a>$6", - $text - ); - return $text; - } - - public function wurl(string $text) - { - $linkto = []; - $rend = $this; - $text = preg_replace_callback( - '%href="([\w-]+)\/?(#?[a-z-_]*)"%', - function ($matches) use ($rend, &$linkto) { - $matchpage = $rend->get($matches[1]); - if (!$matchpage) { - $link = 'href="' . $rend->upage($matches[1]) . '"" title="' . Config::existnot() . '" class="internal existnot"' . $this->internallinkblank; - } else { - $linkto[] = $matchpage->id(); - $link = 'href="' . $rend->upage($matches[1]) . $matches[2] . '" title="' . $matchpage->description() . '" class="internal exist ' . $matchpage->secure('string') . '"' . $this->internallinkblank; - } - return $link; - }, - $text - ); - $this->linkto = array_unique(array_merge($this->linkto, $linkto)); - return $text; - } - - public function wikiurl(string $text) - { - $linkto = []; - $rend = $this; - $text = preg_replace_callback( - '%\[([\w-]+)\/?#?([a-z-_]*)\]%', - function ($matches) use ($rend, &$linkto) { - $matchpage = $rend->get($matches[1]); - if (!$matchpage) { - return '<a href="' . $rend->upage($matches[1]) . '"" title="' . Config::existnot() . '" class="internal existnot" ' . $this->internallinkblank . ' >' . $matches[1] . '</a>'; - } else { - $linkto[] = $matchpage->id(); - return '<a href="' . $rend->upage($matches[1]) . $matches[2] . '" title="' . $matchpage->description() . '" class="internal exist ' . $matchpage->secure('string') . '" ' . $this->internallinkblank . ' >' . $matchpage->title() . '</a>'; - } - }, - $text - ); - $this->linkto = array_unique(array_merge($this->linkto, $linkto)); - return $text; - } - - /** - * Add Id to html header elements and store the titles in the `$this->sum` var - * - * @param string $text Input html document to scan - * @param int $min Maximum header deepness to look for. Min = 1 Max = 6 Default = 1 - * @param int $max Maximum header deepness to look for. Min = 1 Max = 6 Default = 6 - * @param string $element Name of element being analysed - * - * @return string text with id in header - */ - - public function headerid(string $text, int $min = 1, int $max = 6, string $element = 'body') : string - { - if ($min > 6 || $min < 1) { - $min = 6; - } - if ($max > 6 || $max < 1) { - $max = 6; - } - - $text = preg_replace_callback( - "/<h([$min-$max])((.*)id=\"([^\"]*)\"(.*)|.*)>(.+)<\/h[$min-$max]>/mU", - function ($matches) { - $level = $matches[1]; - $beforeid = $matches[3]; - $id = $matches[4]; - $afterid = $matches[5]; - $content = $matches[6]; - // if no custom id is defined, use idclean of the content as id - if (empty($id)) { - $id = idclean($content); - } - $this->sum[] = new Header($id, intval($level), $content); - return "<h$level $beforeid id=\"$id\" $afterid>$content</h$level>"; - }, - $text - ); - return $text; - } - - public function markdown($text) - { - $fortin = new MarkdownExtra; - // id in headers - // $fortin->header_id_func = function ($header) { - // return preg_replace('/[^\w]/', '', strtolower($header)); - // }; - $fortin->hard_wrap = true; - $text = $fortin->transform($text); - return $text; - } - - - - public function article($text) - { - $pattern = '/(\R\R|^\R|^)[=]{3,}([\w-]*)\R\R(.*)(?=\R\R[=]{3,}[\w-]*\R)/sUm'; - $text = preg_replace_callback($pattern, function ($matches) { - if (!empty($matches[2])) { - $id = ' id="' . $matches[2] . '" '; - } else { - $id = ' '; - } - return '<article ' . $id . ' markdown="1" >' . PHP_EOL . PHP_EOL . $matches[3] . PHP_EOL . PHP_EOL . '</article>' . PHP_EOL . PHP_EOL; - }, $text); - $text = preg_replace('/\R\R[=]{3,}([\w-]*)\R/', '', $text); - return $text; - } - - /** - * Match `%INCLUDE?params=values&...%` - * - * @param string $text Input text to scan - * @param string $include word to match - * - * @return array $matches Ordered array containing an array of `fullmatch` and `filter` - */ - public function match(string $text, string $include): array - { - preg_match_all('~\%(' . $include . ')(\?([a-zA-Z0-9\[\]\&=\-_\/\%\+\*\;]*))?\%~', $text, $out); - - $matches = []; - - foreach ($out[0] as $key => $match) { - $matches[$key] = ['fullmatch' => $match, 'type' => $out[1][$key], 'options' => $out[3][$key]]; - } - return $matches; - } - - /** - * Check for media list call in the text and insert media list - * @param string $text Text to scan and replace - * - * @return string Output text - */ - public function automedialist(string $text): string - { - $matches = $this->match($text, 'MEDIA'); - - if (isset($matches)) { - foreach ($matches as $match) { - $medialist = new Medialist($match); - $medialist->readoptions(); - $text = str_replace($medialist->fullmatch(), $medialist->generatecontent(), $text); - } - } - return $text; - } - - /** - * Check for Summary calls in the text and insert html summary - * @param string $text Text to scan and replace - * - * @return string Output text - */ - public function summary(string $text): string - { - $matches = $this->match($text, 'SUMMARY'); - - - if (!empty($matches)) { - foreach ($matches as $match) { - $data = array_merge($match, ['sum' => $this->sum]); - $summary = new Summary($data); - $text = str_replace($summary->fullmatch(), $summary->sumparser(), $text); - } - } - return $text; - } - - - /** - * Render pages list - */ - public function pageoptlist(string $text): string - { - $matches = $this->match($text, 'LIST'); - - $modelhome = new Modelhome(); - - if (isset($matches)) { - - foreach ($matches as $match) { - $optlist = new Optlist(['render' => $this]); - $optlist->parsehydrate($match['options']); - $pagetable = $modelhome->pagetable($this->pagelist(), $optlist, '', []); - $content = $optlist->listhtml($pagetable, $this->page, $this); - $text = str_replace($match['fullmatch'], $content, $text); - } - } - return $text; - } - - - - public function date(string $text): string - { - $page = $this->page; - $text = preg_replace_callback('~\%DATE\%~', function ($matches) use ($page) { - return '<time datetime=' . $page->date('string') . '>' . $page->date('dmy') . '</time>'; - }, $text); - $text = preg_replace_callback('~\%TIME\%~', function ($matches) use ($page) { - return '<time datetime=' . $page->date('string') . '>' . $page->date('ptime') . '</time>'; - }, $text); - - return $text; - } - - /** - * Render thumbnail of the page - * - * @param string $text Text to analyse - * - * @return string The rendered output - */ - public function thumbnail(string $text): string - { - $img = '<img class="thumbnail" src="' . Model::thumbnailpath() . $this->page->thumbnail() . '" alt="' . $this->page->title() . '">'; - $img = PHP_EOL . $img . PHP_EOL; - $text = str_replace('%THUMBNAIL%', $img, $text); - - return $text; - } - - /** - * Autolink Function : transform every word of more than $limit characters in internal link - * - * @param string $text The input text to be converted - * - * @return string Conversion output - */ - public function everylink(string $text, int $limit): string - { - $regex = '~([\w-_éêèùïüîçà]{' . $limit . ',})(?![^<]*>|[^<>]*<\/)~'; - $text = preg_replace_callback($regex, function ($matches) { - return '<a href="' . idclean($matches[1]) . '">' . $matches[1] . '</a>'; - }, $text); - return $text; - } - - - - /** - * @param string $text content to analyse and replace - * - * @return string text ouput - */ - public function authenticate(string $text): string - { - $id = $this->page->id(); - $regex = '~\%CONNECT(\?dir=([a-zA-Z0-9-_]+))?\%~'; - $text = preg_replace_callback($regex, function ($matches) use ($id) { - if (isset($matches[2])) { - $id = $matches[2]; - } - $form = '<form action="' . $this->dirtopath('!co') . '" method="post"> + } + + if (!empty($this->page->redirection())) { + if (preg_match('%https?:\/\/\S*%', $this->page->redirection(), $out)) { + $url = $out[0]; + $head .= PHP_EOL . '<meta http-equiv="refresh" content="' . $this->page->refresh() . '; URL=' . $url . '" />'; + } elseif (key_exists($this->page->redirection(), $this->pagelist())) { + $url = $this->upage($this->page->redirection()); + $head .= PHP_EOL . '<meta http-equiv="refresh" content="' . $this->page->refresh() . '; URL=' . $url . '" />'; + } + } + + + return $head; + } + + public function desctitle($text, $desc, $title) + { + $text = str_replace('%TITLE%', $title, $text); + $text = str_replace('%DESCRIPTION%', $desc, $text); + return $text; + } + + + public function bodyparser(string $text) + { + $text = $this->media($text); + + $text = $this->summary($text); + + $text = $this->wurl($text); + $text = $this->wikiurl($text); + + + + $text = str_replace('href="http', "class=\"external\" $this->externallinkblank href=\"http", $text); + + $text = $this->shortenurl($text); + + $text = $this->autourl($text); + + $text = $this->authenticate($text); + + return $text; + } + + public function media(string $text): string + { + $text = preg_replace('%(src|href)="([\w-_]+(\/([\w-_])+)*\.[a-z0-9]{1,5})"%', '$1="' . Model::mediapath() . '$2" target="_blank" class="media"', $text); + if (!is_string($text)) { + //throw new Exception('Rendering error -> media module'); + } + return $text; + } + + /** + * Shorten the urls of links whose content equals the href. + * + * @param string $text the page text as html + */ + public function shortenurl(string $text): string + { + $text = preg_replace('#<a(.*href="(https?:\/\/(.+))".*)>\2</a>#', "<a$1>$3</a>", $text); + return $text; + } + + + public function autourl($text) + { + $text = preg_replace( + '#( |\R|(>)|(<))(https?:\/\/(\S+\.[^< ]+))(((?(3)>|))(?(2)</[^a]|))#', + "$1<a href=\"$4\" class=\"external\" $this->externallinkblank>$4</a>$6", + $text + ); + return $text; + } + + public function wurl(string $text) + { + $linkto = []; + $rend = $this; + $text = preg_replace_callback( + '%href="([\w-]+)\/?(#?[a-z-_]*)"%', + function ($matches) use ($rend, &$linkto) { + $matchpage = $rend->get($matches[1]); + if (!$matchpage) { + $link = 'href="' . $rend->upage($matches[1]) . '"" title="' . Config::existnot() . '" class="internal existnot"' . $this->internallinkblank; + } else { + $linkto[] = $matchpage->id(); + $link = 'href="' . $rend->upage($matches[1]) . $matches[2] . '" title="' . $matchpage->description() . '" class="internal exist ' . $matchpage->secure('string') . '"' . $this->internallinkblank; + } + return $link; + }, + $text + ); + $this->linkto = array_unique(array_merge($this->linkto, $linkto)); + return $text; + } + + public function wikiurl(string $text) + { + $linkto = []; + $rend = $this; + $text = preg_replace_callback( + '%\[([\w-]+)\/?#?([a-z-_]*)\]%', + function ($matches) use ($rend, &$linkto) { + $matchpage = $rend->get($matches[1]); + if (!$matchpage) { + return '<a href="' . $rend->upage($matches[1]) . '"" title="' . Config::existnot() . '" class="internal existnot" ' . $this->internallinkblank . ' >' . $matches[1] . '</a>'; + } else { + $linkto[] = $matchpage->id(); + return '<a href="' . $rend->upage($matches[1]) . $matches[2] . '" title="' . $matchpage->description() . '" class="internal exist ' . $matchpage->secure('string') . '" ' . $this->internallinkblank . ' >' . $matchpage->title() . '</a>'; + } + }, + $text + ); + $this->linkto = array_unique(array_merge($this->linkto, $linkto)); + return $text; + } + + /** + * Add Id to html header elements and store the titles in the `$this->sum` var + * + * @param string $text Input html document to scan + * @param int $min Maximum header deepness to look for. Min = 1 Max = 6 Default = 1 + * @param int $max Maximum header deepness to look for. Min = 1 Max = 6 Default = 6 + * @param string $element Name of element being analysed + * + * @return string text with id in header + */ + + public function headerid(string $text, int $min = 1, int $max = 6, string $element = 'body'): string + { + if ($min > 6 || $min < 1) { + $min = 6; + } + if ($max > 6 || $max < 1) { + $max = 6; + } + + $text = preg_replace_callback( + "/<h([$min-$max])((.*)id=\"([^\"]*)\"(.*)|.*)>(.+)<\/h[$min-$max]>/mU", + function ($matches) { + $level = $matches[1]; + $beforeid = $matches[3]; + $id = $matches[4]; + $afterid = $matches[5]; + $content = $matches[6]; + // if no custom id is defined, use idclean of the content as id + if (empty($id)) { + $id = idclean($content); + } + $this->sum[] = new Header($id, intval($level), $content); + return "<h$level $beforeid id=\"$id\" $afterid>$content</h$level>"; + }, + $text + ); + return $text; + } + + public function markdown($text) + { + $fortin = new MarkdownExtra(); + // id in headers + // $fortin->header_id_func = function ($header) { + // return preg_replace('/[^\w]/', '', strtolower($header)); + // }; + $fortin->hard_wrap = true; + $text = $fortin->transform($text); + return $text; + } + + + + public function article($text) + { + $pattern = '/(\R\R|^\R|^)[=]{3,}([\w-]*)\R\R(.*)(?=\R\R[=]{3,}[\w-]*\R)/sUm'; + $text = preg_replace_callback($pattern, function ($matches) { + if (!empty($matches[2])) { + $id = ' id="' . $matches[2] . '" '; + } else { + $id = ' '; + } + return '<article ' . $id . ' markdown="1" >' . PHP_EOL . PHP_EOL . $matches[3] . PHP_EOL . PHP_EOL . '</article>' . PHP_EOL . PHP_EOL; + }, $text); + $text = preg_replace('/\R\R[=]{3,}([\w-]*)\R/', '', $text); + return $text; + } + + /** + * Match `%INCLUDE?params=values&...%` + * + * @param string $text Input text to scan + * @param string $include word to match + * + * @return array $matches Ordered array containing an array of `fullmatch` and `filter` + */ + public function match(string $text, string $include): array + { + preg_match_all('~\%(' . $include . ')(\?([a-zA-Z0-9\[\]\&=\-_\/\%\+\*\;]*))?\%~', $text, $out); + + $matches = []; + + foreach ($out[0] as $key => $match) { + $matches[$key] = ['fullmatch' => $match, 'type' => $out[1][$key], 'options' => $out[3][$key]]; + } + return $matches; + } + + /** + * Check for media list call in the text and insert media list + * @param string $text Text to scan and replace + * + * @return string Output text + */ + public function automedialist(string $text): string + { + $matches = $this->match($text, 'MEDIA'); + + if (isset($matches)) { + foreach ($matches as $match) { + $medialist = new Medialist($match); + $medialist->readoptions(); + $text = str_replace($medialist->fullmatch(), $medialist->generatecontent(), $text); + } + } + return $text; + } + + /** + * Check for Summary calls in the text and insert html summary + * @param string $text Text to scan and replace + * + * @return string Output text + */ + public function summary(string $text): string + { + $matches = $this->match($text, 'SUMMARY'); + + + if (!empty($matches)) { + foreach ($matches as $match) { + $data = array_merge($match, ['sum' => $this->sum]); + $summary = new Summary($data); + $text = str_replace($summary->fullmatch(), $summary->sumparser(), $text); + } + } + return $text; + } + + + /** + * Render pages list + */ + public function pageoptlist(string $text): string + { + $matches = $this->match($text, 'LIST'); + + $modelhome = new Modelhome(); + + if (isset($matches)) { + foreach ($matches as $match) { + $optlist = new Optlist(['render' => $this]); + $optlist->parsehydrate($match['options']); + $pagetable = $modelhome->pagetable($this->pagelist(), $optlist, '', []); + $content = $optlist->listhtml($pagetable, $this->page, $this); + $text = str_replace($match['fullmatch'], $content, $text); + } + } + return $text; + } + + + + public function date(string $text): string + { + $page = $this->page; + $text = preg_replace_callback('~\%DATE\%~', function ($matches) use ($page) { + return '<time datetime=' . $page->date('string') . '>' . $page->date('dmy') . '</time>'; + }, $text); + $text = preg_replace_callback('~\%TIME\%~', function ($matches) use ($page) { + return '<time datetime=' . $page->date('string') . '>' . $page->date('ptime') . '</time>'; + }, $text); + + return $text; + } + + /** + * Render thumbnail of the page + * + * @param string $text Text to analyse + * + * @return string The rendered output + */ + public function thumbnail(string $text): string + { + $img = '<img class="thumbnail" src="' . Model::thumbnailpath() . $this->page->thumbnail() . '" alt="' . $this->page->title() . '">'; + $img = PHP_EOL . $img . PHP_EOL; + $text = str_replace('%THUMBNAIL%', $img, $text); + + return $text; + } + + /** + * Autolink Function : transform every word of more than $limit characters in internal link + * + * @param string $text The input text to be converted + * + * @return string Conversion output + */ + public function everylink(string $text, int $limit): string + { + $regex = '~([\w-_éêèùïüîçà]{' . $limit . ',})(?![^<]*>|[^<>]*<\/)~'; + $text = preg_replace_callback($regex, function ($matches) { + return '<a href="' . idclean($matches[1]) . '">' . $matches[1] . '</a>'; + }, $text); + return $text; + } + + + + /** + * @param string $text content to analyse and replace + * + * @return string text ouput + */ + public function authenticate(string $text): string + { + $id = $this->page->id(); + $regex = '~\%CONNECT(\?dir=([a-zA-Z0-9-_]+))?\%~'; + $text = preg_replace_callback($regex, function ($matches) use ($id) { + if (isset($matches[2])) { + $id = $matches[2]; + } + $form = '<form action="' . $this->dirtopath('!co') . '" method="post"> <input type="password" name="pass" id="loginpass" placeholder="password"> <input type="hidden" name="route" value="pageread/"> <input type="hidden" name="id" value="' . $id . '"> <input type="submit" name="log" value="login" id="button"> </form>'; - return $form; - }, $text); - return $text; - } + return $form; + }, $text); + return $text; + } - public function linkto() - { - sort($this->linkto); - $linkto = $this->linkto; - $this->linkto = []; - return $linkto; - } + public function linkto() + { + sort($this->linkto); + $linkto = $this->linkto; + $this->linkto = []; + return $linkto; + } - // _________________________ G E T ___________________________________ + // _________________________ G E T ___________________________________ - public function sum() - { - return $this->sum; - } + public function sum() + { + return $this->sum; + } } diff --git a/app/class/Modeltimeline.php b/app/class/Modeltimeline.php index 3e8cf99..db9c4f5 100644 --- a/app/class/Modeltimeline.php +++ b/app/class/Modeltimeline.php @@ -6,138 +6,133 @@ use JamesMoss\Flywheel\Document; class Modeltimeline extends Modeldb { - const EVENT_BASE = ['message']; - const EVENT_ART = ['page_add', 'page_edit', 'page_delete']; - const EVENT_MEDIA = ['media_add', 'media_delete']; - const EVENT_FONT = ['font_add', 'font_delete']; - - public function __construct() - { - parent::__construct(); - $this->storeinit('timeline'); - } - - public function get(int $id) - { - $eventdata = $this->repo->findById($id); - if ($eventdata !== false) { - return new Event($eventdata); - } else { - return false; - } - } - - /** - * Retrun a list of Event objects - * - * @return array array of Event where the key is the Event id. - */ - public function getlister() : array - { - $eventlist = []; - $datalist = $this->repo->findAll(); - foreach ($datalist as $eventdata) { - $event = new Event($eventdata); - $id = intval($event->id()); - $eventlist[$id] = $event; - } - return $eventlist; - } - - - public function pagelistbyid(array $idlist = []) : array - { - $eventdatalist = $this->repo->query() - ->where('__id', 'IN', $idlist) - ->execute(); - - $eventlist = []; - foreach ($eventdatalist as $id => $eventdata) { - $eventlist[$id] = new Event($eventdata); - } - return $eventlist; - } - - - /** - * Store event - * - * @param Event The event to be stored in the repositery - * - * @return bool retrun true if it works, false if it fails - */ - public function add(Event $event) : bool - { - $eventdata = new Document($event->dry()); - $eventdata->setId($event->id()); - $result = $this->repo->store($eventdata); - return $result; - } - - /** - * Return last free id - * - * @return int id - */ - public function getlastfreeid() : int - { - $idlist = $this->list(); - - if (!empty($idlist)) { - $id = max($idlist); - $id++; - } else { - $id = 1; - } - return $id; - } - - public function group(array $events) - { - $id = 0; - $subid = 0; - $lastuser = null; - foreach ($events as $event) { - if($event->user() !== $lastuser) { - $subid = 0; - $id ++; - $groupedevents[$id]['user'] = $event->user(); - } else { - $subid ++; - } - $groupedevents[$id][$subid] = $event; - $lastuser = $event->user(); - } - return $groupedevents; - } - - public function showlast(array $types, int $qty = 25, int $offset = 0) - { - $types = array_intersect($types, $this->types()); - - $eventdatalist = $this->repo->query() - ->where('type', 'IN', $types) - ->orderBy('date DESC') - ->limit($qty, $offset) - ->execute(); - - $eventlist = []; - foreach ($eventdatalist as $id => $eventdata) { - $eventlist[] = new Event($eventdata); - } - - $eventlist = array_reverse($eventlist); - return $eventlist; - } - - - public function types() - { - return array_merge(self::EVENT_ART, self::EVENT_BASE, self::EVENT_MEDIA, self::EVENT_MEDIA); - } - - + protected const EVENT_BASE = ['message']; + protected const EVENT_ART = ['page_add', 'page_edit', 'page_delete']; + protected const EVENT_MEDIA = ['media_add', 'media_delete']; + protected const EVENT_FONT = ['font_add', 'font_delete']; + + public function __construct() + { + parent::__construct(); + $this->storeinit('timeline'); + } + + public function get(int $id) + { + $eventdata = $this->repo->findById($id); + if ($eventdata !== false) { + return new Event($eventdata); + } else { + return false; + } + } + + /** + * Retrun a list of Event objects + * + * @return array array of Event where the key is the Event id. + */ + public function getlister(): array + { + $eventlist = []; + $datalist = $this->repo->findAll(); + foreach ($datalist as $eventdata) { + $event = new Event($eventdata); + $id = intval($event->id()); + $eventlist[$id] = $event; + } + return $eventlist; + } + + + public function pagelistbyid(array $idlist = []): array + { + $eventdatalist = $this->repo->query() + ->where('__id', 'IN', $idlist) + ->execute(); + + $eventlist = []; + foreach ($eventdatalist as $id => $eventdata) { + $eventlist[$id] = new Event($eventdata); + } + return $eventlist; + } + + + /** + * Store event + * + * @param Event The event to be stored in the repositery + * + * @return bool retrun true if it works, false if it fails + */ + public function add(Event $event): bool + { + $eventdata = new Document($event->dry()); + $eventdata->setId($event->id()); + $result = $this->repo->store($eventdata); + return $result; + } + + /** + * Return last free id + * + * @return int id + */ + public function getlastfreeid(): int + { + $idlist = $this->list(); + + if (!empty($idlist)) { + $id = max($idlist); + $id++; + } else { + $id = 1; + } + return $id; + } + + public function group(array $events) + { + $id = 0; + $subid = 0; + $lastuser = null; + foreach ($events as $event) { + if ($event->user() !== $lastuser) { + $subid = 0; + $id++; + $groupedevents[$id]['user'] = $event->user(); + } else { + $subid++; + } + $groupedevents[$id][$subid] = $event; + $lastuser = $event->user(); + } + return $groupedevents; + } + + public function showlast(array $types, int $qty = 25, int $offset = 0) + { + $types = array_intersect($types, $this->types()); + + $eventdatalist = $this->repo->query() + ->where('type', 'IN', $types) + ->orderBy('date DESC') + ->limit($qty, $offset) + ->execute(); + + $eventlist = []; + foreach ($eventdatalist as $id => $eventdata) { + $eventlist[] = new Event($eventdata); + } + + $eventlist = array_reverse($eventlist); + return $eventlist; + } + + + public function types() + { + return array_merge(self::EVENT_ART, self::EVENT_BASE, self::EVENT_MEDIA, self::EVENT_MEDIA); + } } - - -?>
\ No newline at end of file diff --git a/app/class/Modeluser.php b/app/class/Modeluser.php index 3f459b2..0e3cc5f 100644 --- a/app/class/Modeluser.php +++ b/app/class/Modeluser.php @@ -6,14 +6,14 @@ use JamesMoss\Flywheel\Document; class Modeluser extends Modeldb { - const ADMIN = 10; - const SUPEREDITOR = 4; - const EDITOR = 3; - const INVITE = 2; - const READ = 1; - const FREE = 0; + public const ADMIN = 10; + public const SUPEREDITOR = 4; + public const EDITOR = 3; + public const INVITE = 2; + public const READ = 1; + public const FREE = 0; - const USER_REPO_NAME = 'user'; + public const USER_REPO_NAME = 'user'; public function __construct() { @@ -23,7 +23,7 @@ class Modeluser extends Modeldb /** * Write session cookie according to users datas and define the current authtoken being used - * + * * @param User $user Current user to keep in session */ public function writesession(User $user) @@ -36,32 +36,33 @@ class Modeluser extends Modeldb public function readsession() { $userdatas = []; - if (array_key_exists('user' . Config::basepath(), $_SESSION) && isset($_SESSION['user' . Config::basepath()]['id'])) { + if ( + array_key_exists('user' . Config::basepath(), $_SESSION) + && isset($_SESSION['user' . Config::basepath()]['id']) + ) { $userdatas = $_SESSION['user' . Config::basepath()]; $user = new User($userdatas); $user = $this->get($user); return $user; } - if(isset($_COOKIE['authtoken']) && strpos($_COOKIE['authtoken'], ':')) { + if (isset($_COOKIE['authtoken']) && strpos($_COOKIE['authtoken'], ':')) { list($cookietoken, $cookiemac) = explode(':', $_COOKIE['authtoken']); $authtokenmanager = new Modelauthtoken(); $dbtoken = $authtokenmanager->getbytoken($cookietoken); if ($dbtoken !== false) { - if(hash_equals($cookiemac, secrethash($dbtoken->getId()))) { + if (hash_equals($cookiemac, secrethash($dbtoken->getId()))) { $user = $this->get($dbtoken->user); if ($user !== false) { $this->writesession($user, $_COOKIE['authtoken']); } return $user; } - } } return new User(['id' => '', 'level' => 0]); - } @@ -125,10 +126,10 @@ class Modeluser extends Modeldb /** * Check if the password is used, and return by who - * + * * @param string $userid user ID * @param string $pass password clear - * + * * @return User|bool User or false */ public function passwordcheck(string $userid, string $pass) @@ -142,7 +143,7 @@ class Modeluser extends Modeldb } else { if ($user->password() === $pass) { return $user; - } + } } } return false; @@ -150,10 +151,10 @@ class Modeluser extends Modeldb /** * @param User $user - * + * * @return bool depending on success */ - public function add(User $user) : bool + public function add(User $user): bool { $userdata = new Document($user->dry()); $userdata->setId($user->id()); @@ -163,7 +164,7 @@ class Modeluser extends Modeldb /** * @param string|User $id Can be an User object or a string ID - * + * * @return User|false User object or false in case of error */ public function get($id) @@ -187,13 +188,4 @@ class Modeluser extends Modeldb { $this->repo->delete($user->id()); } - - } - - - - - - -?>
\ No newline at end of file diff --git a/app/class/Opt.php b/app/class/Opt.php index ecfbbc1..0dc99cf 100644 --- a/app/class/Opt.php +++ b/app/class/Opt.php @@ -4,420 +4,451 @@ namespace Wcms; class Opt extends Item { - protected $sortby = 'id'; - protected $order = 1; - protected $tagfilter = []; - protected $tagcompare = 'AND'; - protected $authorfilter = []; - protected $authorcompare = 'AND'; - protected $secure = 4; - protected $linkto = ''; - protected $taglist = []; - protected $authorlist = []; - protected $invert = 0; - protected $limit = 0; - - protected $pageidlist = []; - - protected $pagevarlist; - - public function __construct(array $data = []) - { - $this->hydrate($data); - $page = new Page(); - $this->pagevarlist = ($page->getobjectvars()); - } - - - - - - public function resetall() - { - $varlist = get_class_vars(self::class); - - foreach ($varlist as $var => $default) { - $method = 'set' . $var; - $this->$method($default); - } - } - - public function reset($var) - { - $varlist = get_class_vars(self::class); - if (in_array($var, $varlist)) { - $this->$var = $varlist[$var]; - } - } - - public function submit() - { - if (isset($_GET['submit'])) { - if ($_GET['submit'] == 'reset') { - $_SESSION['opt'] = []; - } elseif ($_GET['submit'] == 'filter') { - $this->getall(); - } - } else { - $this->sessionall(); - } - } - - public function getall() - { - $optlist = ['sortby', 'order', 'secure', 'tagcompare', 'tagfilter', 'authorcompare', 'authorfilter', 'limit', 'invert', 'linkto']; - - foreach ($optlist as $method) { - if (method_exists($this, $method)) { - if (isset($_GET[$method])) { - $setmethod = 'set' . $method; - $this->$setmethod($_GET[$method]); - } else { - $this->reset($method); - } - $_SESSION['opt'][$method] = $this->$method(); - } - } - } - - public function sessionall() - { - if (isset($_SESSION['opt'])) { - $this->hydrate($_SESSION['opt']); - } - } - - public function getadress() - { - $object = $this->drylist(['sortby', 'order', 'secure', 'tagfilter', 'tagcompare', 'authorfilter', 'authorcompare', 'invert', 'limit']); - $object['submit'] = 'filter'; - - return '?' . urldecode(http_build_query($object)); - } - - public function sortbyorder($sortby = "") - { - $object = $this->drylist(['sortby', 'order', 'secure', 'tagfilter', 'tagcompare', 'authorfilter', 'authorcompare', 'invert', 'limit']); - if (!empty($sortby)) { - $object['sortby'] = $sortby; - } - $object['order'] = $object['order'] * -1; - $object['submit'] = 'filter'; - - return '?' . urldecode(http_build_query($object)); - } - - /** - * Get the link list for each tags of a page - * - * @param array $taglist List of tag to be abalysed - * @return string html code to be printed - */ - public function taglinks(array $taglist = []): string - { - $tagstring = ""; - foreach ($taglist as $tag) { - $tagstring .= '<a class="tag tag_' . $tag . '" href="?' . $this->getfilteradress(['tagfilter' => [$tag]]) . '" >' . $tag . '</a>' . PHP_EOL; - } - return $tagstring; - } - - /** - * Get the link list for each authors of an page - * - * @param array $authorlist List of author to be - * @return string html code to be printed - */ - public function authorlinks(array $authorlist = []): string - { - $authorstring = ""; - foreach ($authorlist as $author) { - $authorstring .= '<a class="author author_' . $author . '" href="?' . $this->getfilteradress(['authorfilter' => [$author]]) . '" >' . $author . '</a>' . PHP_EOL; - } - return $authorstring; - } - - public function securelink(int $level, string $secure) - { - return '<a class="secure ' . $secure . '" href="?' . $this->getfilteradress(['secure' => $level]) . '">' . $secure . '</a>' . PHP_EOL; - } - - public function linktolink(array $linktolist) - { - $linktostring = ""; - foreach ($linktolist as $linkto ) { - $linktostring .= '<a class="linkto" href="?' . $this->getfilteradress(['linkto' => $linkto]) . '" >' . $linkto . '</a>' . PHP_EOL; - } - return $linktostring; - } - - - public function getfilteradress(array $vars = []) - { - $varlist = ['sortby', 'order', 'secure', 'tagfilter', 'tagcompare', 'authorfilter', 'authorcompare', 'linkto', 'invert', 'limit']; - // array_filter($vars, function ()) - $object = $this->drylist($varlist); - $object = array_merge($object, $vars); - $object['submit'] = 'filter'; - return urldecode(http_build_query($object)); - } - - - - /** - * Get the query as http string - * - * @return string The resulted query - */ - public function getquery(): string - { - $class = get_class_vars(get_class($this)); - $object = get_object_vars($this); - $class['pagevarlist'] = $object['pagevarlist']; - $class['taglist'] = $object['taglist']; - $class['authorlist'] = $object['authorlist']; - $query = array_diff_assoc_recursive($object, $class); - - return urldecode(http_build_query($query)); - } - - public function parsetagcss(string $cssstring) - { - $classprefix = 'tag'; - $pattern = '%a\.' . $classprefix . '\_([a-z0-9\-\_]*)\s*\{\s*(background-color):\s*(#[A-F0-6]{6})\;\s*\}%'; - preg_match($pattern, $cssstring, $matches); - foreach ($matches as $value) { - } - } - - public function tocss($cssdatas) - { - $string = ''; - foreach ($cssdatas as $element => $css) { - $string .= PHP_EOL . $element . ' {'; - foreach ($css as $param => $value) { - $string .= PHP_EOL . ' ' . $param . ': ' . $value . ';'; - } - $string .= PHP_EOL . '}' . PHP_EOL; - } - return $string; - } - - - // _______________________________________________ G E T _______________________________________________ - - public function sortby() - { - return $this->sortby; - } - - public function order() - { - return $this->order; - } - - public function secure() - { - return $this->secure; - } - - public function tagfilter($type = 'array') - { - return $this->tagfilter; - } - - public function tagcompare() - { - return $this->tagcompare; - } - - public function authorfilter($type = 'array') - { - return $this->authorfilter; - } - - public function authorcompare() - { - return $this->authorcompare; - } - - public function linkto($type = 'string') - { - return $this->linkto; - } - - public function taglist() - { - return $this->taglist; - } - - public function authorlist() - { - return $this->authorlist; - } - - public function invert() - { - return $this->invert; - } - - public function pagevarlist() - { - return $this->pagevarlist; - } - - public function limit() - { - return $this->limit; - } - - public function pageidlist() - { - return $this->pageidlist; - } - - - // __________________________________________________ S E T _____________________________________________ - - public function setsortby($sortby) - { - if (is_string($sortby) && in_array($sortby, $this->pagevarlist) && in_array($sortby, Model::COLUMNS)) { - $this->sortby = strtolower(strip_tags($sortby)); - } - } - - public function setorder($order) - { - $order = intval($order); - if (in_array($order, [-1, 0, 1])) { - $this->order = $order; - } - } - - public function settagfilter($tagfilter) - { - if (!empty($tagfilter) && is_array($tagfilter)) { - $this->tagfilter = $tagfilter; - } - } - - public function settagcompare($tagcompare) - { - if (in_array($tagcompare, ['OR', 'AND'])) { - $this->tagcompare = $tagcompare; - } - } - - public function setauthorfilter($authorfilter) - { - if (!empty($authorfilter) && is_array($authorfilter)) { - $this->authorfilter = $authorfilter; - } - } - - public function setauthorcompare($authorcompare) - { - if (in_array($authorcompare, ['OR', 'AND'])) { - $this->authorcompare = $authorcompare; - } - } - - public function setsecure($secure) - { - if ($secure >= 0 && $secure <= 5) { - $this->secure = intval($secure); - } - } - - public function setlinkto($linkto) : bool - { - if (is_string($linkto)) { - if(empty($this->pageidlist)) { - $this->linkto = idclean($linkto); - return true; - } elseif (in_array($linkto, $this->pageidlist)) { - $this->linkto = idclean($linkto); - return true; - } else { - return false; - } - } else { - return false; - } - } - - public function settaglist(array $pagelist) - { - $taglist = []; - foreach ($pagelist as $page) { - foreach ($page->tag('array') as $tag) { - if (!array_key_exists($tag, $taglist)) { - $taglist[$tag] = 1; - } else { - $taglist[$tag]++; - } - } - } - $taglistsorted = arsort($taglist); - $this->taglist = $taglist; - } - - public function setauthorlist(array $pagelist) - { - $authorlist = []; - foreach ($pagelist as $page) { - foreach ($page->authors('array') as $author) { - if (!array_key_exists($author, $authorlist)) { - $authorlist[$author] = 1; - } else { - $authorlist[$author]++; - } - } - } - $authorlistsorted = arsort($authorlist); - $this->authorlist = $authorlist; - } - - public function setinvert(int $invert) - { - if ($invert == 0 || $invert == 1) { - $this->invert = $invert; - } else { - $this->invert = 0; - } - } - - public function setlimit($limit) - { - $limit = intval($limit); - if ($limit < 0) { - $limit = 0; - } elseif ($limit >= 10000) { - $limit = 9999; - } - $this->limit = $limit; - } - - /** - * Import list of pages IDs - * - * @param array $pageidlist could be array of IDs or array of Page Object - * - * @return bool false if array content isn't string or Pages, otherwise : true - */ - public function setpageidlist(array $pageidlist) : bool - { - $idlist = []; - foreach ($pageidlist as $item) { - if (is_string($item)) { - $idlist[] = $item; - } elseif ($item instanceof Page) { - $idlist[] = $item->id(); - } else { - return false; - } - } - $this->pageidlist = $idlist; - return true; - } + protected $sortby = 'id'; + protected $order = 1; + protected $tagfilter = []; + protected $tagcompare = 'AND'; + protected $authorfilter = []; + protected $authorcompare = 'AND'; + protected $secure = 4; + protected $linkto = ''; + protected $taglist = []; + protected $authorlist = []; + protected $invert = 0; + protected $limit = 0; + + protected $pageidlist = []; + + protected $pagevarlist; + + public function __construct(array $data = []) + { + $this->hydrate($data); + $page = new Page(); + $this->pagevarlist = ($page->getobjectvars()); + } + + + + + + public function resetall() + { + $varlist = get_class_vars(self::class); + + foreach ($varlist as $var => $default) { + $method = 'set' . $var; + $this->$method($default); + } + } + + public function reset($var) + { + $varlist = get_class_vars(self::class); + if (in_array($var, $varlist)) { + $this->$var = $varlist[$var]; + } + } + + public function submit() + { + if (isset($_GET['submit'])) { + if ($_GET['submit'] == 'reset') { + $_SESSION['opt'] = []; + } elseif ($_GET['submit'] == 'filter') { + $this->getall(); + } + } else { + $this->sessionall(); + } + } + + public function getall() + { + $optlist = [ + 'sortby', + 'order', + 'secure', + 'tagcompare', + 'tagfilter', + 'authorcompare', + 'authorfilter', + 'limit', + 'invert', + 'linkto' + ]; + + foreach ($optlist as $method) { + if (method_exists($this, $method)) { + if (isset($_GET[$method])) { + $setmethod = 'set' . $method; + $this->$setmethod($_GET[$method]); + } else { + $this->reset($method); + } + $_SESSION['opt'][$method] = $this->$method(); + } + } + } + + public function sessionall() + { + if (isset($_SESSION['opt'])) { + $this->hydrate($_SESSION['opt']); + } + } + + public function getadress() + { + $object = $this->drylist([ + 'sortby', + 'order', + 'secure', + 'tagfilter', + 'tagcompare', + 'authorfilter', + 'authorcompare', + 'invert', + 'limit' + ]); + $object['submit'] = 'filter'; + + return '?' . urldecode(http_build_query($object)); + } + + public function sortbyorder($sortby = "") + { + $object = $this->drylist([ + 'sortby', + 'order', + 'secure', + 'tagfilter', + 'tagcompare', + 'authorfilter', + 'authorcompare', + 'invert', + 'limit' + ]); + if (!empty($sortby)) { + $object['sortby'] = $sortby; + } + $object['order'] = $object['order'] * -1; + $object['submit'] = 'filter'; + + return '?' . urldecode(http_build_query($object)); + } + + /** + * Get the link list for each tags of a page + * + * @param array $taglist List of tag to be abalysed + * @return string html code to be printed + */ + public function taglinks(array $taglist = []): string + { + $tagstring = ""; + foreach ($taglist as $tag) { + $tagstring .= '<a class="tag tag_' . $tag . '" href="?' . $this->getfilteradress(['tagfilter' => [$tag]]) . '" >' . $tag . '</a>' . PHP_EOL; + } + return $tagstring; + } + + /** + * Get the link list for each authors of an page + * + * @param array $authorlist List of author to be + * @return string html code to be printed + */ + public function authorlinks(array $authorlist = []): string + { + $authorstring = ""; + foreach ($authorlist as $author) { + $authorstring .= '<a class="author author_' . $author . '" href="?' . $this->getfilteradress(['authorfilter' => [$author]]) . '" >' . $author . '</a>' . PHP_EOL; + } + return $authorstring; + } + + public function securelink(int $level, string $secure) + { + return '<a class="secure ' . $secure . '" href="?' . $this->getfilteradress(['secure' => $level]) . '">' . $secure . '</a>' . PHP_EOL; + } + + public function linktolink(array $linktolist) + { + $linktostring = ""; + foreach ($linktolist as $linkto) { + $linktostring .= '<a class="linkto" href="?' . $this->getfilteradress(['linkto' => $linkto]) . '" >' . $linkto . '</a>' . PHP_EOL; + } + return $linktostring; + } + + + public function getfilteradress(array $vars = []) + { + $varlist = ['sortby', 'order', 'secure', 'tagfilter', 'tagcompare', 'authorfilter', 'authorcompare', 'linkto', 'invert', 'limit']; + // array_filter($vars, function ()) + $object = $this->drylist($varlist); + $object = array_merge($object, $vars); + $object['submit'] = 'filter'; + return urldecode(http_build_query($object)); + } + + + + /** + * Get the query as http string + * + * @return string The resulted query + */ + public function getquery(): string + { + $class = get_class_vars(get_class($this)); + $object = get_object_vars($this); + $class['pagevarlist'] = $object['pagevarlist']; + $class['taglist'] = $object['taglist']; + $class['authorlist'] = $object['authorlist']; + $query = array_diff_assoc_recursive($object, $class); + + return urldecode(http_build_query($query)); + } + + public function parsetagcss(string $cssstring) + { + $classprefix = 'tag'; + $pattern = '%a\.' . $classprefix . '\_([a-z0-9\-\_]*)\s*\{\s*(background-color):\s*(#[A-F0-6]{6})\;\s*\}%'; + preg_match($pattern, $cssstring, $matches); + foreach ($matches as $value) { + } + } + + public function tocss($cssdatas) + { + $string = ''; + foreach ($cssdatas as $element => $css) { + $string .= PHP_EOL . $element . ' {'; + foreach ($css as $param => $value) { + $string .= PHP_EOL . ' ' . $param . ': ' . $value . ';'; + } + $string .= PHP_EOL . '}' . PHP_EOL; + } + return $string; + } + + + // _______________________________________________ G E T _______________________________________________ + + public function sortby() + { + return $this->sortby; + } + + public function order() + { + return $this->order; + } + + public function secure() + { + return $this->secure; + } + + public function tagfilter($type = 'array') + { + return $this->tagfilter; + } + + public function tagcompare() + { + return $this->tagcompare; + } + + public function authorfilter($type = 'array') + { + return $this->authorfilter; + } + + public function authorcompare() + { + return $this->authorcompare; + } + + public function linkto($type = 'string') + { + return $this->linkto; + } + + public function taglist() + { + return $this->taglist; + } + + public function authorlist() + { + return $this->authorlist; + } + + public function invert() + { + return $this->invert; + } + + public function pagevarlist() + { + return $this->pagevarlist; + } + + public function limit() + { + return $this->limit; + } + + public function pageidlist() + { + return $this->pageidlist; + } + + + // __________________________________________________ S E T _____________________________________________ + + public function setsortby($sortby) + { + if (is_string($sortby) && in_array($sortby, $this->pagevarlist) && in_array($sortby, Model::COLUMNS)) { + $this->sortby = strtolower(strip_tags($sortby)); + } + } + + public function setorder($order) + { + $order = intval($order); + if (in_array($order, [-1, 0, 1])) { + $this->order = $order; + } + } + + public function settagfilter($tagfilter) + { + if (!empty($tagfilter) && is_array($tagfilter)) { + $this->tagfilter = $tagfilter; + } + } + + public function settagcompare($tagcompare) + { + if (in_array($tagcompare, ['OR', 'AND'])) { + $this->tagcompare = $tagcompare; + } + } + + public function setauthorfilter($authorfilter) + { + if (!empty($authorfilter) && is_array($authorfilter)) { + $this->authorfilter = $authorfilter; + } + } + + public function setauthorcompare($authorcompare) + { + if (in_array($authorcompare, ['OR', 'AND'])) { + $this->authorcompare = $authorcompare; + } + } + + public function setsecure($secure) + { + if ($secure >= 0 && $secure <= 5) { + $this->secure = intval($secure); + } + } + + public function setlinkto($linkto): bool + { + if (is_string($linkto)) { + if (empty($this->pageidlist)) { + $this->linkto = idclean($linkto); + return true; + } elseif (in_array($linkto, $this->pageidlist)) { + $this->linkto = idclean($linkto); + return true; + } else { + return false; + } + } else { + return false; + } + } + + public function settaglist(array $pagelist) + { + $taglist = []; + foreach ($pagelist as $page) { + foreach ($page->tag('array') as $tag) { + if (!array_key_exists($tag, $taglist)) { + $taglist[$tag] = 1; + } else { + $taglist[$tag]++; + } + } + } + $taglistsorted = arsort($taglist); + $this->taglist = $taglist; + } + + public function setauthorlist(array $pagelist) + { + $authorlist = []; + foreach ($pagelist as $page) { + foreach ($page->authors('array') as $author) { + if (!array_key_exists($author, $authorlist)) { + $authorlist[$author] = 1; + } else { + $authorlist[$author]++; + } + } + } + $authorlistsorted = arsort($authorlist); + $this->authorlist = $authorlist; + } + + public function setinvert(int $invert) + { + if ($invert == 0 || $invert == 1) { + $this->invert = $invert; + } else { + $this->invert = 0; + } + } + + public function setlimit($limit) + { + $limit = intval($limit); + if ($limit < 0) { + $limit = 0; + } elseif ($limit >= 10000) { + $limit = 9999; + } + $this->limit = $limit; + } + + /** + * Import list of pages IDs + * + * @param array $pageidlist could be array of IDs or array of Page Object + * + * @return bool false if array content isn't string or Pages, otherwise : true + */ + public function setpageidlist(array $pageidlist): bool + { + $idlist = []; + foreach ($pageidlist as $item) { + if (is_string($item)) { + $idlist[] = $item; + } elseif ($item instanceof Page) { + $idlist[] = $item->id(); + } else { + return false; + } + } + $this->pageidlist = $idlist; + return true; + } } diff --git a/app/class/Optlist.php b/app/class/Optlist.php index 37f9343..63536ee 100644 --- a/app/class/Optlist.php +++ b/app/class/Optlist.php @@ -38,9 +38,7 @@ class Optlist extends Opt $li = ''; foreach ($pagelist as $page) { - // ================= Class ============= - $classdata = []; if ($page->id() === $actualpage->id()) { $classdata['actual'] = 'current_page'; diff --git a/app/class/Page.php b/app/class/Page.php index da19f61..760521b 100644 --- a/app/class/Page.php +++ b/app/class/Page.php @@ -8,809 +8,824 @@ use DateTimeZone; class Page extends Dbitem { - protected $id; - protected $title; - protected $description; - protected $tag; - protected $date; - protected $datecreation; - protected $datemodif; - protected $daterender; - protected $css; - protected $javascript; - protected $body; - protected $header; - protected $main; - protected $nav; - protected $aside; - protected $footer; - protected $externalcss; - protected $customhead; - protected $secure; - protected $interface; - protected $linkto; - protected $templatebody; - protected $templatecss; - protected $templatejavascript; - protected $templateoptions; - protected $favicon; - protected $thumbnail; - protected $authors; - protected $invites; - protected $readers; - protected $affcount; - protected $visitcount; - protected $editcount; - protected $editby; - protected $sleep; - protected $redirection; - protected $refresh; - - - const LEN = 255; - const LENTEXT = 2**20; - const SECUREMAX = 2; - const TABS = ['main', 'css', 'header', 'body', 'nav', 'aside', 'footer', 'javascript']; - const VAR_DATE = ['date', 'datecreation', 'datemodif', 'daterender']; - - - + protected $id; + protected $title; + protected $description; + protected $tag; + protected $date; + protected $datecreation; + protected $datemodif; + protected $daterender; + protected $css; + protected $javascript; + protected $body; + protected $header; + protected $main; + protected $nav; + protected $aside; + protected $footer; + protected $externalcss; + protected $customhead; + protected $secure; + protected $interface; + protected $linkto; + protected $templatebody; + protected $templatecss; + protected $templatejavascript; + protected $templateoptions; + protected $favicon; + protected $thumbnail; + protected $authors; + protected $invites; + protected $readers; + protected $affcount; + protected $visitcount; + protected $editcount; + protected $editby; + protected $sleep; + protected $redirection; + protected $refresh; + + + public const LEN = 255; + public const LENTEXT = 2 ** 20; + public const SECUREMAX = 2; + public const TABS = ['main', 'css', 'header', 'body', 'nav', 'aside', 'footer', 'javascript']; + public const VAR_DATE = ['date', 'datecreation', 'datemodif', 'daterender']; + + + // _____________________________________________________ F U N ____________________________________________________ - public function __construct($datas = []) - { - $this->reset(); - $this->hydrate($datas); - } - - public function getobjectvars() : array - { - return get_object_vars($this); - } - - public function reset() - { - $now = new DateTimeImmutable(null, timezone_open("Europe/Paris")); - - $this->settitle($this->id()); - $this->setdescription(''); - $this->settag([]); - $this->setdate($now); - $this->setdatecreation($now); - $this->setdatecreation($now); - $this->setdatemodif($now); - $this->setdaterender($now); - $this->setcss(''); - $this->setjavascript(''); - $this->setbody(Config::defaultbody()); - $this->setheader(''); - $this->setmain(''); - $this->setnav(''); - $this->setaside(''); - $this->setfooter(''); - $this->setexternalcss([]); - $this->setcustomhead(''); - $this->setsecure(Config::defaultprivacy()); - $this->setinterface('main'); - $this->setlinkto([]); - $this->settemplatebody(''); - $this->settemplatecss(''); - $this->settemplatejavascript(''); - $this->settemplateoptions(['externalcss', 'externaljavascript', 'favicon', 'thumbnail', 'reccursivecss']); - $this->setfavicon(''); - $this->setthumbnail(''); - $this->setauthors([]); - $this->setinvites([]); - $this->setreaders([]); - $this->setaffcount(0); - $this->setvisitcount(0); - $this->seteditcount(0); - $this->seteditby([]); - $this->setsleep(0); - $this->setredirection(''); - $this->setrefresh(0); - - } - - // _____________________________________________________ G E T ____________________________________________________ - - public function id($type = 'string') - { - return $this->id; - } - - public function title($type = 'string') - { - if($type == 'sort') { - return strtolower($this->title); - } else { - return $this->title; - } - } - - public function description($type = 'string') - { - if($type == 'short' && strlen($this->description) > 15 ) { - return substr($this->description, 0, 20) . '...'; - } else { - return $this->description; - } - } - - public function tag($option = 'array') - { - if ($option == 'string') { - return implode(", ", $this->tag); - } elseif ($option == 'array') { - return $this->tag; - } elseif ($option == 'sort') { - return count($this->tag); - } - } - - public function date($option = 'date') - { - return $this->datetransform('date', $option); - } - - public function datecreation($option = 'date') - { - return $this->datetransform('datecreation', $option); - } - - - public function datemodif($option = 'date') - { - return $this->datetransform('datemodif', $option); - } - - public function daterender($option = 'date') - { - return $this->datetransform('daterender', $option); - } - - public function css($type = 'string') - { - return $this->css; - } - - public function javascript($type = 'string') - { - return $this->javascript; - } - - public function body($type = 'string') - { - return $this->body; - } - - public function header($type = 'string') - { - return $this->header; - } - - public function main($type = 'string') - { - return $this->main; - } - - public function nav($type = "string") - { - return $this->nav; - } - - public function aside($type = "string") - { - return $this->aside; - } - - public function externalcss($type = "array") - { - return $this->externalcss; - } - - public function customhead($type = "string") - { - if($type === 'string') { - return $this->customhead; - } elseif($type === 'int') { - return substr_count($this->customhead, PHP_EOL) + 1; - } - } - - public function footer($type = "string") - { - return $this->footer; - } - - public function secure($type = 'int') - { - if ($type == 'string') { - if ($this->secure == 0) $secure = 'public'; - if ($this->secure == 1) $secure = 'private'; - if ($this->secure == 2) $secure = 'not_published'; - return $secure; - } else { - return $this->secure; - } - } - - public function invitepassword($type = 'string') - { - return $this->invitepassword; - } - - public function readpassword($type = 'string') - { - return $this->readpassword; - } - - public function interface($type = 'string') - { - return $this->interface; - } - - public function linkto($option = 'array') - { - if ($option == 'json') { - $linkto = json_encode($this->linkto); - } elseif ($option == 'array') { - $linkto = $this->linkto; - } elseif ($option == 'sort') { - return count($this->linkto); - } elseif ($option == 'string') { - return implode(', ', $this->linkto); - } - return $linkto; - - } - - public function templatebody($type = 'string') - { - return $this->templatebody; - } - - public function templatecss($type = 'string') - { - return $this->templatecss; - } - - public function templatejavascript($type = 'string') - { - return $this->templatejavascript; - } - - public function template() - { - $template['body'] = $this->templatebody; - $template['css'] = $this->templatecss; - $template['javascript'] = $this->templatejavascript; - - $template['cssreccursive'] = $this->checkoption('reccursive'); - $template['externalcss'] = $this->checkoption('externalcss'); - $template['cssfavicon'] = $this->checkoption('favicon'); - $template['cssthumbnail'] = $this->checkoption('thumbnail'); - - $template['externaljavascript'] = $this->checkoption('externaljavascript'); - - return $template; - } - - public function templateoptions($type = 'array') - { - return $this->templateoptions; - } - - function checkoption($option) - { - if (in_array($option, $this->templateoptions)) { - return true; - } else { - return false; - } - } - - public function favicon($type = 'string') - { - return $this->favicon; - } - - public function thumbnail($type = 'string') - { - return $this->thumbnail; - } - - public function authors($type = 'array') - { - if($type == 'string') { - return implode(', ', $this->authors); - } elseif ($type == 'array') { - return $this->authors; - } elseif ($type == 'sort') { - return count($this->authors); - } - } - - public function invites($type = 'array') - { - return $this->invites; - } - - public function readers($type = 'array') - { - return $this->invites; - } - - public function affcount($type = 'int') - { - return $this->affcount; - } - - public function visitcount($type = 'int') - { - return $this->visitcount; - } - - public function editcount($type = 'int') - { - return $this->editcount; - } - - public function editby($type = 'array') - { - return $this->editby; - } - - public function sleep($type = 'int') - { - return $this->sleep; - } - - public function redirection($type = 'string') - { - return $this->redirection; - } - - public function refresh($type = 'int') - { - return $this->refresh; - } - - - - - // _____________________________________________________ S E T ____________________________________________________ - - public function setid($id) - { - if (strlen($id) <= Model::MAX_ID_LENGTH and is_string($id)) { - $this->id = strip_tags(strtolower(str_replace(" ", "", $id))); - } - } - - public function settitle($title) - { - if (strlen($title) < self::LEN and is_string($title)) { - $this->title = strip_tags(trim($title)); - } - } - - public function setdescription($description) - { - if (strlen($description) < self::LEN and is_string($description)) { - $this->description = strip_tags(trim($description)); - } - } - - public function settag($tag) - { - if (is_string($tag) && strlen($tag) < self::LEN) { - $tag = $this->tagtoarray($tag); - } - if (is_array($tag)) { - $tag = array_map('idclean', $tag); - $tag = array_filter($tag); - $this->tag = $tag; - } - } - - public function setdate($date) - { - if ($date instanceof DateTimeImmutable) { - $this->date = $date; - } else { - $this->date = DateTimeImmutable::createFromFormat(DateTime::ISO8601, $date, new DateTimeZone('Europe/Paris')); - } - } - - public function setptime($ptime) - { - if(is_string($ptime) && DateTime::createFromFormat('H:i', $ptime) !== FALSE) { - $time = explode(':', $ptime); - $this->date = $this->date->setTime($time[0], $time[1]); - } - } - - public function setpdate($pdate) - { - if(is_string($pdate) && DateTime::createFromFormat('Y-m-d', $pdate) !== FALSE) { - $date = explode('-', $pdate); - $this->date = $this->date->setDate($date[0], $date[1], $date[2]); - } - } - - /** - * DateTimeImmutable : set date - * string ISO8601 : set date - * true : reset to now - * - * @param string|DateTimeImmutable|true $datecreation Set or reset date of creation - */ - public function setdatecreation($datecreation) - { - if ($datecreation instanceof DateTimeImmutable) { - $this->datecreation = $datecreation; - } elseif ($datecreation === true) { - $this->datecreation = new DateTimeImmutable(null, timezone_open("Europe/Paris")); - } else { - $this->datecreation = DateTimeImmutable::createFromFormat(DateTime::ISO8601, $datecreation, new DateTimeZone('Europe/Paris')); - } - } - - public function setdatemodif($datemodif) - { - if ($datemodif instanceof DateTimeImmutable) { - $this->datemodif = $datemodif; - } else { - $this->datemodif = DateTimeImmutable::createFromFormat(DateTime::ISO8601, $datemodif, new DateTimeZone('Europe/Paris')); - } - } - - public function setdaterender($daterender) - { - if ($daterender instanceof DateTimeImmutable) { - $this->daterender = $daterender; - } else { - $this->daterender = DateTimeImmutable::createFromFormat(DateTime::ISO8601, $daterender, new DateTimeZone('Europe/Paris')); - } - } - - - public function setcss($css) - { - if (strlen($css) < self::LENTEXT and is_string($css)) { - $this->css = trim(strtolower($css)); - } - } - - - - public function setjavascript($javascript) - { - if (strlen($javascript < self::LENTEXT && is_string($javascript))) { - $this->javascript = $javascript; - } - } - - - public function setbody($body) - { - if (strlen($body < self::LENTEXT && is_string($body))) { - $this->body = $body; - } - } - - public function setheader($header) - { - if (strlen($header < self::LENTEXT && is_string($header))) { - $this->header = $header; - } - } - - public function setmain($main) - { - if (strlen($main) < self::LENTEXT and is_string($main)) { - $this->main = $main; - } - } - - public function setnav($nav) - { - if (strlen($nav) < self::LENTEXT and is_string($nav)) { - $this->nav = $nav; - } - } - - public function setaside($aside) - { - if (strlen($aside) < self::LENTEXT and is_string($aside)) { - $this->aside = $aside; - } - } - - public function setexternalcss($externalcss) - { - if(is_array($externalcss)) { - $this->externalcss = array_values(array_filter($externalcss)); - } - } - - public function setcustomhead(string $customhead) - { - if(is_string($customhead)) { - $this->customhead = $customhead; - } - } - - public function setfooter($footer) - { - if (strlen($footer) < self::LENTEXT and is_string($footer)) { - $this->footer = $footer; - } - } - - public function setsecure($secure) - { - if ($secure >= 0 and $secure <= self::SECUREMAX) { - $this->secure = intval($secure); - } - } - - public function setinvitepassword($invitepassword) - { - if (is_string($invitepassword) && strlen($invitepassword) < self::LEN) { - $this->invitepassword = $invitepassword; - } - } - - public function setreadpassword($readpassword) - { - if (is_string($readpassword) && strlen($readpassword) < self::LEN) { - $this->readpassword = $readpassword; - } - } - - public function setinterface($interface) - { - if (in_array($interface, self::TABS)) { - $this->interface = $interface; - } - } - - public function setlinkto($linkto) - { - if (is_array($linkto)) { - $this->linkto = $linkto; - } elseif (is_string($linkto)) { - $linktojson = json_decode($linkto); - if (is_array($linktojson)) { - $this->linkto = $linktojson; - } - } elseif ($linkto === null) { - $this->linkto = []; - } - } - - public function settemplatebody($templatebody) - { - if (is_string($templatebody)) { - $this->templatebody = $templatebody; - } - } - - public function settemplatecss($templatecss) - { - if (is_string($templatecss)) { - $this->templatecss = $templatecss; - } - } - - public function settemplatejavascript($templatejavascript) - { - if (is_string($templatejavascript)) { - $this->templatejavascript = $templatejavascript; - } - } - - public function settemplateoptions($templateoptions) - { - if(is_array($templateoptions)) { - $this->templateoptions = array_values(array_filter($templateoptions)); - } - } - - public function setfavicon($favicon) - { - if (is_string($favicon)) { - $this->favicon = $favicon; - } - } - - public function setthumbnail($thumbnail) - { - if (is_string($thumbnail)) { - $this->thumbnail = $thumbnail; - } - } - - public function setauthors($authors) - { - if(is_array($authors)) { - $this->authors = array_unique(array_values(array_filter($authors))); - } - } - - public function setinvites($invites) - { - if(is_array($invites)) { - $this->invites = array_values(array_filter($invites)); - } - } - - public function setreaders($readers) - { - if(is_array($readers)) { - $this->readers = array_values(array_filter($readers)); - } - } - - public function setaffcount($affcount) - { - if (is_int($affcount)) { - $this->affcount = $affcount; - } elseif (is_numeric($affcount)) { - $this->affcount = intval($affcount); - } - } - - public function setvisitcount($visitcount) - { - if (is_int($visitcount)) { - $this->visitcount = $visitcount; - } elseif (is_numeric($visitcount)) { - $this->visitcount = intval($visitcount); - } - } - - public function seteditcount($editcount) - { - if (is_int($editcount)) { - $this->editcount = $editcount; - } elseif (is_numeric($editcount)) { - $this->editcount = intval($editcount); - } - } - - public function seteditby($editby) - { - if(is_array($editby)) { - $this->editby = $editby; - } - } - - public function setredirection($redirection) - { - if(is_string($redirection) && strlen($redirection) <= 64) { - $redirection = strip_tags($redirection); - if(preg_match('%https?:\/\/\S*%', $redirection, $out)) { - $this->redirection = $out[0]; - } else { - $redirection = idclean($redirection); - if ($redirection !== $this->id) { - $this->redirection = $redirection; - } - } - } - } - - public function setrefresh($refresh) - { - $refresh = intval($refresh); - if($refresh > 180) { - $refresh = 180; - } elseif ($refresh < 0) { - $refresh = 0; - } - $this->refresh = $refresh; - } - - - // __________________________________ C O U N T E R S ______________________________ - - - public function addeditcount() - { - $this->editcount++; - } - - public function addaffcount() - { - $this->affcount++; - } - - public function addvisitcount() - { - $this->visitcount++; - } - - public function updateedited() - { - $now = new DateTimeImmutable(null, timezone_open("Europe/Paris")); - $this->setdatemodif($now); - $this->addeditcount(); - } - - public function addauthor(string $id) - { - if(!in_array($id, $this->authors)) { - $this->authors[] = $id; - } - } - - public function addeditby(string $id) - { - $this->editby[$id] = true; - } - - public function removeeditby(string $id) - { - unset($this->editby[$id]); - } - - public function iseditedby() - { - return count($this->editby) > 0; - } - - public function setsleep($sleep) - { - $sleep = abs(intval($sleep)); - if($sleep > 180) { - $sleep = 180; - } - $this->sleep = $sleep; - } - - /** - * Merge new tag with actual tags - * - * @param string|array $tag Could be tags as string or array - */ - - public function addtag($tag) - { - if (is_string($tag)) { - $tag = $this->tagtoarray($tag); - } - if(is_array($tag)) { - $tag = array_map('idclean', $tag); - $tag = array_filter($tag); - $this->tag = array_unique(array_merge($this->tag, $tag)); - } - } - - - // _________________________________ T O O L S ______________________________________ - - /** - * Convert a tag string to an array ready to be stored - * - * @param string $tagstring Tag as string separated by commas - * @return array Tags stored as an array - */ - - private function tagtoarray(string $tagstring) : array - { - $tag = strip_tags(trim(strtolower($tagstring))); - $tag = str_replace(' ', '', $tag); - $taglist = explode(",", $tag); - $taglist = array_filter($taglist); - return $taglist; - } - - + public function __construct($datas = []) + { + $this->reset(); + $this->hydrate($datas); + } + + public function getobjectvars(): array + { + return get_object_vars($this); + } + + public function reset() + { + $now = new DateTimeImmutable(null, timezone_open("Europe/Paris")); + + $this->settitle($this->id()); + $this->setdescription(''); + $this->settag([]); + $this->setdate($now); + $this->setdatecreation($now); + $this->setdatecreation($now); + $this->setdatemodif($now); + $this->setdaterender($now); + $this->setcss(''); + $this->setjavascript(''); + $this->setbody(Config::defaultbody()); + $this->setheader(''); + $this->setmain(''); + $this->setnav(''); + $this->setaside(''); + $this->setfooter(''); + $this->setexternalcss([]); + $this->setcustomhead(''); + $this->setsecure(Config::defaultprivacy()); + $this->setinterface('main'); + $this->setlinkto([]); + $this->settemplatebody(''); + $this->settemplatecss(''); + $this->settemplatejavascript(''); + $this->settemplateoptions(['externalcss', 'externaljavascript', 'favicon', 'thumbnail', 'reccursivecss']); + $this->setfavicon(''); + $this->setthumbnail(''); + $this->setauthors([]); + $this->setinvites([]); + $this->setreaders([]); + $this->setaffcount(0); + $this->setvisitcount(0); + $this->seteditcount(0); + $this->seteditby([]); + $this->setsleep(0); + $this->setredirection(''); + $this->setrefresh(0); + } + + // _____________________________________________________ G E T ____________________________________________________ + + public function id($type = 'string') + { + return $this->id; + } + + public function title($type = 'string') + { + if ($type == 'sort') { + return strtolower($this->title); + } else { + return $this->title; + } + } + + public function description($type = 'string') + { + if ($type == 'short' && strlen($this->description) > 15) { + return substr($this->description, 0, 20) . '...'; + } else { + return $this->description; + } + } + + public function tag($option = 'array') + { + if ($option == 'string') { + return implode(", ", $this->tag); + } elseif ($option == 'array') { + return $this->tag; + } elseif ($option == 'sort') { + return count($this->tag); + } + } + + public function date($option = 'date') + { + return $this->datetransform('date', $option); + } + + public function datecreation($option = 'date') + { + return $this->datetransform('datecreation', $option); + } + + + public function datemodif($option = 'date') + { + return $this->datetransform('datemodif', $option); + } + + public function daterender($option = 'date') + { + return $this->datetransform('daterender', $option); + } + + public function css($type = 'string') + { + return $this->css; + } + + public function javascript($type = 'string') + { + return $this->javascript; + } + + public function body($type = 'string') + { + return $this->body; + } + + public function header($type = 'string') + { + return $this->header; + } + + public function main($type = 'string') + { + return $this->main; + } + + public function nav($type = "string") + { + return $this->nav; + } + + public function aside($type = "string") + { + return $this->aside; + } + + public function externalcss($type = "array") + { + return $this->externalcss; + } + + public function customhead($type = "string") + { + if ($type === 'string') { + return $this->customhead; + } elseif ($type === 'int') { + return substr_count($this->customhead, PHP_EOL) + 1; + } + } + + public function footer($type = "string") + { + return $this->footer; + } + + public function secure($type = 'int') + { + if ($type == 'string') { + if ($this->secure == 0) { + $secure = 'public'; + } + if ($this->secure == 1) { + $secure = 'private'; + } + if ($this->secure == 2) { + $secure = 'not_published'; + } + return $secure; + } else { + return $this->secure; + } + } + + public function invitepassword($type = 'string') + { + return $this->invitepassword; + } + + public function readpassword($type = 'string') + { + return $this->readpassword; + } + + public function interface($type = 'string') + { + return $this->interface; + } + + public function linkto($option = 'array') + { + if ($option == 'json') { + $linkto = json_encode($this->linkto); + } elseif ($option == 'array') { + $linkto = $this->linkto; + } elseif ($option == 'sort') { + return count($this->linkto); + } elseif ($option == 'string') { + return implode(', ', $this->linkto); + } + return $linkto; + } + + public function templatebody($type = 'string') + { + return $this->templatebody; + } + + public function templatecss($type = 'string') + { + return $this->templatecss; + } + + public function templatejavascript($type = 'string') + { + return $this->templatejavascript; + } + + public function template() + { + $template['body'] = $this->templatebody; + $template['css'] = $this->templatecss; + $template['javascript'] = $this->templatejavascript; + + $template['cssreccursive'] = $this->checkoption('reccursive'); + $template['externalcss'] = $this->checkoption('externalcss'); + $template['cssfavicon'] = $this->checkoption('favicon'); + $template['cssthumbnail'] = $this->checkoption('thumbnail'); + + $template['externaljavascript'] = $this->checkoption('externaljavascript'); + + return $template; + } + + public function templateoptions($type = 'array') + { + return $this->templateoptions; + } + + public function checkoption($option) + { + if (in_array($option, $this->templateoptions)) { + return true; + } else { + return false; + } + } + + public function favicon($type = 'string') + { + return $this->favicon; + } + + public function thumbnail($type = 'string') + { + return $this->thumbnail; + } + + public function authors($type = 'array') + { + if ($type == 'string') { + return implode(', ', $this->authors); + } elseif ($type == 'array') { + return $this->authors; + } elseif ($type == 'sort') { + return count($this->authors); + } + } + + public function invites($type = 'array') + { + return $this->invites; + } + + public function readers($type = 'array') + { + return $this->invites; + } + + public function affcount($type = 'int') + { + return $this->affcount; + } + + public function visitcount($type = 'int') + { + return $this->visitcount; + } + + public function editcount($type = 'int') + { + return $this->editcount; + } + + public function editby($type = 'array') + { + return $this->editby; + } + + public function sleep($type = 'int') + { + return $this->sleep; + } + + public function redirection($type = 'string') + { + return $this->redirection; + } + + public function refresh($type = 'int') + { + return $this->refresh; + } + + + + + // _____________________________________________________ S E T ____________________________________________________ + + public function setid($id) + { + if (strlen($id) <= Model::MAX_ID_LENGTH and is_string($id)) { + $this->id = strip_tags(strtolower(str_replace(" ", "", $id))); + } + } + + public function settitle($title) + { + if (strlen($title) < self::LEN and is_string($title)) { + $this->title = strip_tags(trim($title)); + } + } + + public function setdescription($description) + { + if (strlen($description) < self::LEN and is_string($description)) { + $this->description = strip_tags(trim($description)); + } + } + + public function settag($tag) + { + if (is_string($tag) && strlen($tag) < self::LEN) { + $tag = $this->tagtoarray($tag); + } + if (is_array($tag)) { + $tag = array_map('idclean', $tag); + $tag = array_filter($tag); + $this->tag = $tag; + } + } + + public function setdate($date) + { + if ($date instanceof DateTimeImmutable) { + $this->date = $date; + } else { + $this->date = DateTimeImmutable::createFromFormat( + DateTime::ISO8601, + $date, + new DateTimeZone('Europe/Paris') + ); + } + } + + public function setptime($ptime) + { + if (is_string($ptime) && DateTime::createFromFormat('H:i', $ptime) !== false) { + $time = explode(':', $ptime); + $this->date = $this->date->setTime($time[0], $time[1]); + } + } + + public function setpdate($pdate) + { + if (is_string($pdate) && DateTime::createFromFormat('Y-m-d', $pdate) !== false) { + $date = explode('-', $pdate); + $this->date = $this->date->setDate($date[0], $date[1], $date[2]); + } + } + + /** + * DateTimeImmutable : set date + * string ISO8601 : set date + * true : reset to now + * + * @param string|DateTimeImmutable|true $datecreation Set or reset date of creation + */ + public function setdatecreation($datecreation) + { + if ($datecreation instanceof DateTimeImmutable) { + $this->datecreation = $datecreation; + } elseif ($datecreation === true) { + $this->datecreation = new DateTimeImmutable(null, timezone_open("Europe/Paris")); + } else { + $this->datecreation = DateTimeImmutable::createFromFormat( + DateTime::ISO8601, + $datecreation, + new DateTimeZone('Europe/Paris') + ); + } + } + + public function setdatemodif($datemodif) + { + if ($datemodif instanceof DateTimeImmutable) { + $this->datemodif = $datemodif; + } else { + $this->datemodif = DateTimeImmutable::createFromFormat( + DateTime::ISO8601, + $datemodif, + new DateTimeZone('Europe/Paris') + ); + } + } + + public function setdaterender($daterender) + { + if ($daterender instanceof DateTimeImmutable) { + $this->daterender = $daterender; + } else { + $this->daterender = DateTimeImmutable::createFromFormat( + DateTime::ISO8601, + $daterender, + new DateTimeZone('Europe/Paris') + ); + } + } + + + public function setcss($css) + { + if (strlen($css) < self::LENTEXT and is_string($css)) { + $this->css = trim(strtolower($css)); + } + } + + + + public function setjavascript($javascript) + { + if (strlen($javascript < self::LENTEXT && is_string($javascript))) { + $this->javascript = $javascript; + } + } + + + public function setbody($body) + { + if (strlen($body < self::LENTEXT && is_string($body))) { + $this->body = $body; + } + } + + public function setheader($header) + { + if (strlen($header < self::LENTEXT && is_string($header))) { + $this->header = $header; + } + } + + public function setmain($main) + { + if (strlen($main) < self::LENTEXT and is_string($main)) { + $this->main = $main; + } + } + + public function setnav($nav) + { + if (strlen($nav) < self::LENTEXT and is_string($nav)) { + $this->nav = $nav; + } + } + + public function setaside($aside) + { + if (strlen($aside) < self::LENTEXT and is_string($aside)) { + $this->aside = $aside; + } + } + + public function setexternalcss($externalcss) + { + if (is_array($externalcss)) { + $this->externalcss = array_values(array_filter($externalcss)); + } + } + + public function setcustomhead(string $customhead) + { + if (is_string($customhead)) { + $this->customhead = $customhead; + } + } + + public function setfooter($footer) + { + if (strlen($footer) < self::LENTEXT and is_string($footer)) { + $this->footer = $footer; + } + } + + public function setsecure($secure) + { + if ($secure >= 0 and $secure <= self::SECUREMAX) { + $this->secure = intval($secure); + } + } + + public function setinvitepassword($invitepassword) + { + if (is_string($invitepassword) && strlen($invitepassword) < self::LEN) { + $this->invitepassword = $invitepassword; + } + } + + public function setreadpassword($readpassword) + { + if (is_string($readpassword) && strlen($readpassword) < self::LEN) { + $this->readpassword = $readpassword; + } + } + + public function setinterface($interface) + { + if (in_array($interface, self::TABS)) { + $this->interface = $interface; + } + } + + public function setlinkto($linkto) + { + if (is_array($linkto)) { + $this->linkto = $linkto; + } elseif (is_string($linkto)) { + $linktojson = json_decode($linkto); + if (is_array($linktojson)) { + $this->linkto = $linktojson; + } + } elseif ($linkto === null) { + $this->linkto = []; + } + } + + public function settemplatebody($templatebody) + { + if (is_string($templatebody)) { + $this->templatebody = $templatebody; + } + } + + public function settemplatecss($templatecss) + { + if (is_string($templatecss)) { + $this->templatecss = $templatecss; + } + } + + public function settemplatejavascript($templatejavascript) + { + if (is_string($templatejavascript)) { + $this->templatejavascript = $templatejavascript; + } + } + + public function settemplateoptions($templateoptions) + { + if (is_array($templateoptions)) { + $this->templateoptions = array_values(array_filter($templateoptions)); + } + } + + public function setfavicon($favicon) + { + if (is_string($favicon)) { + $this->favicon = $favicon; + } + } + + public function setthumbnail($thumbnail) + { + if (is_string($thumbnail)) { + $this->thumbnail = $thumbnail; + } + } + + public function setauthors($authors) + { + if (is_array($authors)) { + $this->authors = array_unique(array_values(array_filter($authors))); + } + } + + public function setinvites($invites) + { + if (is_array($invites)) { + $this->invites = array_values(array_filter($invites)); + } + } + + public function setreaders($readers) + { + if (is_array($readers)) { + $this->readers = array_values(array_filter($readers)); + } + } + + public function setaffcount($affcount) + { + if (is_int($affcount)) { + $this->affcount = $affcount; + } elseif (is_numeric($affcount)) { + $this->affcount = intval($affcount); + } + } + + public function setvisitcount($visitcount) + { + if (is_int($visitcount)) { + $this->visitcount = $visitcount; + } elseif (is_numeric($visitcount)) { + $this->visitcount = intval($visitcount); + } + } + + public function seteditcount($editcount) + { + if (is_int($editcount)) { + $this->editcount = $editcount; + } elseif (is_numeric($editcount)) { + $this->editcount = intval($editcount); + } + } + + public function seteditby($editby) + { + if (is_array($editby)) { + $this->editby = $editby; + } + } + + public function setredirection($redirection) + { + if (is_string($redirection) && strlen($redirection) <= 64) { + $redirection = strip_tags($redirection); + if (preg_match('%https?:\/\/\S*%', $redirection, $out)) { + $this->redirection = $out[0]; + } else { + $redirection = idclean($redirection); + if ($redirection !== $this->id) { + $this->redirection = $redirection; + } + } + } + } + + public function setrefresh($refresh) + { + $refresh = intval($refresh); + if ($refresh > 180) { + $refresh = 180; + } elseif ($refresh < 0) { + $refresh = 0; + } + $this->refresh = $refresh; + } + + + // __________________________________ C O U N T E R S ______________________________ + + + public function addeditcount() + { + $this->editcount++; + } + + public function addaffcount() + { + $this->affcount++; + } + + public function addvisitcount() + { + $this->visitcount++; + } + + public function updateedited() + { + $now = new DateTimeImmutable(null, timezone_open("Europe/Paris")); + $this->setdatemodif($now); + $this->addeditcount(); + } + + public function addauthor(string $id) + { + if (!in_array($id, $this->authors)) { + $this->authors[] = $id; + } + } + + public function addeditby(string $id) + { + $this->editby[$id] = true; + } + + public function removeeditby(string $id) + { + unset($this->editby[$id]); + } + + public function iseditedby() + { + return count($this->editby) > 0; + } + + public function setsleep($sleep) + { + $sleep = abs(intval($sleep)); + if ($sleep > 180) { + $sleep = 180; + } + $this->sleep = $sleep; + } + + /** + * Merge new tag with actual tags + * + * @param string|array $tag Could be tags as string or array + */ + + public function addtag($tag) + { + if (is_string($tag)) { + $tag = $this->tagtoarray($tag); + } + if (is_array($tag)) { + $tag = array_map('idclean', $tag); + $tag = array_filter($tag); + $this->tag = array_unique(array_merge($this->tag, $tag)); + } + } + + + // _________________________________ T O O L S ______________________________________ + + /** + * Convert a tag string to an array ready to be stored + * + * @param string $tagstring Tag as string separated by commas + * @return array Tags stored as an array + */ + + private function tagtoarray(string $tagstring): array + { + $tag = strip_tags(trim(strtolower($tagstring))); + $tag = str_replace(' ', '', $tag); + $taglist = explode(",", $tag); + $taglist = array_filter($taglist); + return $taglist; + } } - - -?>
\ No newline at end of file diff --git a/app/class/Quickcss.php b/app/class/Quickcss.php index b55a57b..bddea66 100644 --- a/app/class/Quickcss.php +++ b/app/class/Quickcss.php @@ -14,11 +14,22 @@ class Quickcss extends Item private $quickcss = []; - const COLOR = ['color', 'background-color', 'border-color', 'text-decoration-color']; - const SIZE = ['width', 'height', 'margin', 'padding', 'border-radius', 'border-width', 'left', 'right', 'top', 'bottom']; - const UNIQUE = ['background-image', 'opacity', 'font-size']; + public const COLOR = ['color', 'background-color', 'border-color', 'text-decoration-color']; + public const SIZE = [ + 'width', + 'height', + 'margin', + 'padding', + 'border-radius', + 'border-width', + 'left', + 'right', + 'top', + 'bottom' + ]; + public const UNIQUE = ['background-image', 'opacity', 'font-size']; - const OPTIONS = [ + public const OPTIONS = [ 'text-align' => ['left', 'right', 'center', 'justify'], 'border-style' => ['solid', 'double', 'outset', 'ridge'], 'font-family' => ['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy'], @@ -35,18 +46,18 @@ class Quickcss extends Item private static function getparams() { $params = array_merge(self::COLOR, self::SIZE, self::getselect(), self::UNIQUE); - sort($params, SORT_STRING ); + sort($params, SORT_STRING); return $params; } public function __construct($data) { - $this->hydrate($data); + $this->hydrate($data); } public function calc() { - $quickcss = $this->intersect($this->values,$this->active); + $quickcss = $this->intersect($this->values, $this->active); $quickcss = $this->merge($quickcss, $this->new); $quickcss = $this->addunits($quickcss, $this->units); $quickcss = $this->merge($this->jsoncss, $quickcss); @@ -60,21 +71,21 @@ class Quickcss extends Item public function setvalues($data) { - if(is_array($data)) { + if (is_array($data)) { $this->values = $data; } } public function setunits($data) { - if(is_array($data)) { + if (is_array($data)) { $this->units = $data; } } public function setactive($data) { - if(is_array($data)) { + if (is_array($data)) { $this->active = $data; } } @@ -90,9 +101,9 @@ class Quickcss extends Item public function setjson($jsoncss) { - if(!empty($jsoncss) && is_string($jsoncss)) { + if (!empty($jsoncss) && is_string($jsoncss)) { $jsoncss = json_decode($jsoncss); - if(is_array($jsoncss)) { + if (is_array($jsoncss)) { $this->jsoncss = $jsoncss; } else { $this->jsoncss = []; @@ -165,7 +176,6 @@ class Quickcss extends Item $this->inputs($this->quickcss); echo '</br><input type="submit" value="submit">'; echo '</form>'; - } public function inputs($quickcss) @@ -175,7 +185,7 @@ class Quickcss extends Item echo '<input type="text" name="new[element]" list="used">'; echo '<datalist id="used">'; foreach (array_keys($quickcss) as $element) { - echo '<option value ="'.$element.'">'; + echo '<option value ="' . $element . '">'; } echo '</datalist>'; @@ -188,7 +198,6 @@ class Quickcss extends Item foreach ($quickcss as $element => $css) { echo '<h3>' . $element . '</h3>'; foreach ($css as $param => $value) { - echo '<div class="quicklabel">'; echo '<input type="checkbox" name="active[' . $element . '][' . $param . ']" id="active[' . $element . '][' . $param . ']" checked>'; echo '<label for="active[' . $element . '][' . $param . ']">' . $param . '</label>'; @@ -218,8 +227,6 @@ class Quickcss extends Item echo '</div>'; } } - - } @@ -240,7 +247,6 @@ class Quickcss extends Item <option value="%" <?= $unit == '%' ? 'selected' : '' ?>>%</option> </select> <?php - } public function fontsizeinput($element, $param, $value) @@ -254,7 +260,6 @@ class Quickcss extends Item <option value="em" <?= $unit == 'em' ? 'selected' : '' ?>>em</option> </select> <?php - } public function opacityinput($element, $param, $value) @@ -266,16 +271,14 @@ class Quickcss extends Item { echo '<select name="values[' . $element . '][' . $param . ']">'; foreach (self::OPTIONS[$param] as $option) { - if($option == $value) { - echo '<option value="'.$option.'" selected>'.$option.'</option>'; + if ($option == $value) { + echo '<option value="' . $option . '" selected>' . $option . '</option>'; } else { - echo '<option value="'.$option.'">'.$option.'</option>'; + echo '<option value="' . $option . '">' . $option . '</option>'; } } echo '</select>'; } - - } diff --git a/app/class/Route.php b/app/class/Route.php index 32dfaf5..79379aa 100644 --- a/app/class/Route.php +++ b/app/class/Route.php @@ -9,7 +9,7 @@ class Route extends Item protected $action = null; protected $redirect = null; - const AFF = ['read', 'edit', 'admin', 'media']; + public const AFF = ['read', 'edit', 'admin', 'media']; public function __construct($vars) { @@ -23,7 +23,7 @@ class Route extends Item $array[] = 'page'; } if (!empty($this->aff)) { - $array[] = 'aff='.$this->aff; + $array[] = 'aff=' . $this->aff; } if (!empty($this->action)) { $array[] = 'action=' . $this->action; @@ -36,7 +36,7 @@ class Route extends Item return $array; } - function tostring() + public function tostring() { return implode(' ', $this->toarray()); } @@ -51,7 +51,6 @@ class Route extends Item public function setaff($aff) { $this->aff = $aff; - } public function setaction($action) @@ -69,8 +68,3 @@ class Route extends Item return $this->id; } } - - - - -?>
\ No newline at end of file diff --git a/app/class/Routes.php b/app/class/Routes.php index 03e193c..c58de95 100644 --- a/app/class/Routes.php +++ b/app/class/Routes.php @@ -12,7 +12,7 @@ class Routes public function match() { $router = new AltoRouter(); - if(!empty(Config::basepath())) { + if (!empty(Config::basepath())) { $router->setBasePath('/' . Config::basepath()); } $router->addMatchTypes(array('cid' => '[a-zA-Z0-9-_+,\'!%@&.$€=\(\|\)]+')); @@ -72,17 +72,10 @@ class Routes $methodName = $callableParts[1]; $controller = new $controllerName($router); - + call_user_func_array(array($controller, $methodName), $match['params']); - } - //404 - else { - if(!empty(Config::route404())) { - $controller = new Controller($router); - $controller->routedirect('pageread/', ['page' => Config::route404()]); - } else { - header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found'); - } + } else { + header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found'); } } -}
\ No newline at end of file +} diff --git a/app/class/Summary.php b/app/class/Summary.php index b8b17e9..3ee0db0 100644 --- a/app/class/Summary.php +++ b/app/class/Summary.php @@ -40,11 +40,11 @@ class Summary extends Item } - /** - * Generate a Summary based on header ids. Need to use `$this->headerid` before to scan text - * - * @return string html list with anchor link - */ + /** + * Generate a Summary based on header ids. Need to use `$this->headerid` before to scan text + * + * @return string html list with anchor link + */ public function sumparser() { $sumstring = ''; @@ -76,7 +76,7 @@ class Summary extends Item - // __________________________________________________ G E T ____________________________________________________________ + // ________________________________________________ G E T ________________________________________________________ public function fullmatch() @@ -95,7 +95,7 @@ class Summary extends Item } - // __________________________________________________ S E T ____________________________________________________________ + // ________________________________________________ S E T ________________________________________________________ public function setfullmatch(string $fullmatch) @@ -114,7 +114,7 @@ class Summary extends Item public function setmin($min) { $min = intval($min); - if($min >= 1 && $min <= 6) { + if ($min >= 1 && $min <= 6) { $this->min = $min; } } @@ -122,7 +122,7 @@ class Summary extends Item public function setmax($max) { $max = intval($max); - if($max >= 1 && $max <= 6) { + if ($max >= 1 && $max <= 6) { $this->max = $max; } } @@ -134,9 +134,8 @@ class Summary extends Item public function setelement(string $element) { - if(in_array($element, Model::TEXT_ELEMENTS)) { + if (in_array($element, Model::TEXT_ELEMENTS)) { $this->element = $element; } } - } diff --git a/app/class/User.php b/app/class/User.php index dba43e8..ecb4507 100644 --- a/app/class/User.php +++ b/app/class/User.php @@ -74,30 +74,30 @@ class User extends Item public function expiredate(string $type = 'string') { - if ($type == 'string') { - if(!empty($this->expiredate)) { + if ($type == 'string') { + if (!empty($this->expiredate)) { return $this->expiredate->format('Y-m-d'); } else { return false; } - } elseif ($type == 'date') { - if(!empty($this->expiredate)) { + } elseif ($type == 'date') { + if (!empty($this->expiredate)) { return $this->expiredate; } else { return false; } - } elseif ($type == 'hrdi') { - if(empty($this->expiredate)) { + } elseif ($type == 'hrdi') { + if (empty($this->expiredate)) { return 'never'; } else { $now = new DateTimeImmutable(null, timezone_open("Europe/Paris")); - if($this->expiredate < $now) { + if ($this->expiredate < $now) { return 'expired'; } else { return hrdi($this->expiredate->diff($now)); } } - } + } } public function bookmark() @@ -142,7 +142,6 @@ class User extends Item return false; } } - } public function setsignature(string $signature) @@ -155,13 +154,12 @@ class User extends Item public function setpasswordhashed($passwordhashed) { $this->passwordhashed = boolval($passwordhashed); - } public function setcookie($cookie) { $cookie = intval($cookie); - if($cookie <= Model::MAX_COOKIE_CONSERVATION && $cookie >= 0) { + if ($cookie <= Model::MAX_COOKIE_CONSERVATION && $cookie >= 0) { $this->cookie = $cookie; return true; } else { @@ -171,7 +169,7 @@ class User extends Item public function setcolumns($columns) { - if(is_array($columns)) { + if (is_array($columns)) { $columns = array_filter(array_intersect(array_unique($columns), Model::COLUMNS)); $this->columns = $columns; } @@ -179,30 +177,34 @@ class User extends Item public function setconnectcount($connectcount) { - if(is_int($connectcount) && $connectcount >= 0) { + if (is_int($connectcount) && $connectcount >= 0) { $this->connectcount = $connectcount; } } public function setexpiredate($expiredate) { - if ($expiredate instanceof DateTimeImmutable) { - $this->expiredate = $expiredate; - } else { - $this->expiredate = DateTimeImmutable::createFromFormat('Y-m-d', $expiredate, new DateTimeZone('Europe/Paris')); - } + if ($expiredate instanceof DateTimeImmutable) { + $this->expiredate = $expiredate; + } else { + $this->expiredate = DateTimeImmutable::createFromFormat( + 'Y-m-d', + $expiredate, + new DateTimeZone('Europe/Paris') + ); + } } public function setbookmark($bookmark) { - if(is_array($bookmark)) { + if (is_array($bookmark)) { $this->bookmark = $bookmark; } } public function setdisplay($display) { - if(is_array($display)) { + if (is_array($display)) { $this->display = $display; } } @@ -222,10 +224,10 @@ class User extends Item /** * Hash the password and set `$passwordhashed` to true. - * + * * @return bool true in cas of success, otherwise false. */ - public function hashpassword() : bool + public function hashpassword(): bool { $hashedpassword = password_hash($this->password, PASSWORD_DEFAULT); if (!empty($hashedpassword)) { @@ -239,8 +241,11 @@ class User extends Item public function validpassword() { - if(is_string($this->password)) { - if(strlen($this->password) >= Model::PASSWORD_MIN_LENGTH && strlen($this->password) <= Model::PASSWORD_MAX_LENGTH) { + if (is_string($this->password)) { + if ( + strlen($this->password) >= Model::PASSWORD_MIN_LENGTH + && strlen($this->password) <= Model::PASSWORD_MAX_LENGTH + ) { return true; } } @@ -281,24 +286,18 @@ class User extends Item } public function addbookmark(string $id, string $query) - { - if(!empty($id) && !empty($query)) { + { + if (!empty($id) && !empty($query)) { $id = idclean($id); $id = substr($id, 0, 16); $this->bookmark[$id] = $query; } - } - - public function deletebookmark(string $id) - { - if(key_exists($id, $this->bookmark)) { - unset($this->bookmark[$id]); - } - } - + } + public function deletebookmark(string $id) + { + if (key_exists($id, $this->bookmark)) { + unset($this->bookmark[$id]); + } + } } - - - -?>
\ No newline at end of file |