From 4bfa4a74a94d50f3b3c7f72e90a38b57a5f1d192 Mon Sep 17 00:00:00 2001 From: Diego Najar Date: Sun, 23 Jun 2024 21:46:43 +0200 Subject: [PATCH] fix: page upload symlink --- bl-kernel/ajax/upload-images.php | 24 +-- bl-kernel/boot/init.php | 2 +- bl-kernel/helpers/filesystem.class.php | 119 ++++++----- bl-kernel/pages.class.php | 274 +++++++++++++------------ bl-kernel/pagex.class.php | 112 +++++----- 5 files changed, 274 insertions(+), 257 deletions(-) diff --git a/bl-kernel/ajax/upload-images.php b/bl-kernel/ajax/upload-images.php index 1ca8c406..74e88d4d 100644 --- a/bl-kernel/ajax/upload-images.php +++ b/bl-kernel/ajax/upload-images.php @@ -25,8 +25,8 @@ if ($uuid) { // Set upload directory if ($uuid && IMAGE_RESTRICT) { - $imageDirectory = PATH_UPLOADS_PAGES.$uuid.DS; - $thumbnailDirectory = $imageDirectory.'thumbnails'.DS; + $imageDirectory = PATH_UPLOADS_PAGES . $uuid . DS; + $thumbnailDirectory = $imageDirectory . 'thumbnails' . DS; if (!Filesystem::directoryExists($thumbnailDirectory)) { Filesystem::mkdir($thumbnailDirectory, true); } @@ -36,10 +36,10 @@ if ($uuid && IMAGE_RESTRICT) { } $images = array(); -foreach ($_FILES['images']['name'] as $uuid=>$filename) { +foreach ($_FILES['images']['name'] as $uuid => $filename) { // Check for errors if ($_FILES['images']['error'][$uuid] != 0) { - $message = $L->g('Maximum load file size allowed:').' '.ini_get('upload_max_filesize'); + $message = $L->g('Maximum load file size allowed:') . ' ' . ini_get('upload_max_filesize'); Log::set($message, LOG_TYPE_ERROR); ajaxResponse(1, $message); } @@ -57,27 +57,27 @@ foreach ($_FILES['images']['name'] as $uuid=>$filename) { // Check file extension $fileExtension = Filesystem::extension($filename); $fileExtension = Text::lowercase($fileExtension); - if (!in_array($fileExtension, $GLOBALS['ALLOWED_IMG_EXTENSION']) ) { - $message = $L->g('File type is not supported. Allowed types:').' '.implode(', ',$GLOBALS['ALLOWED_IMG_EXTENSION']); + if (!in_array($fileExtension, $GLOBALS['ALLOWED_IMG_EXTENSION'])) { + $message = $L->g('File type is not supported. Allowed types:') . ' ' . implode(', ', $GLOBALS['ALLOWED_IMG_EXTENSION']); Log::set($message, LOG_TYPE_ERROR); ajaxResponse(1, $message); } // Check file MIME Type $fileMimeType = Filesystem::mimeType($_FILES['images']['tmp_name'][$uuid]); - if ($fileMimeType!==false) { + if ($fileMimeType !== false) { if (!in_array($fileMimeType, $GLOBALS['ALLOWED_IMG_MIMETYPES'])) { - $message = $L->g('File mime type is not supported. Allowed types:').' '.implode(', ',$GLOBALS['ALLOWED_IMG_MIMETYPES']); + $message = $L->g('File mime type is not supported. Allowed types:') . ' ' . implode(', ', $GLOBALS['ALLOWED_IMG_MIMETYPES']); Log::set($message, LOG_TYPE_ERROR); ajaxResponse(1, $message); } } // Move from PHP tmp file to Bludit tmp directory - Filesystem::mv($_FILES['images']['tmp_name'][$uuid], PATH_TMP.$filename); + Filesystem::mv($_FILES['images']['tmp_name'][$uuid], PATH_TMP . $filename); // Transform the image and generate the thumbnail - $image = transformImage(PATH_TMP.$filename, $imageDirectory, $thumbnailDirectory); + $image = transformImage(PATH_TMP . $filename, $imageDirectory, $thumbnailDirectory); if ($image) { chmod($image, 0644); @@ -91,7 +91,5 @@ foreach ($_FILES['images']['name'] as $uuid=>$filename) { } ajaxResponse(0, 'Images uploaded.', array( - 'images'=>$images + 'images' => $images )); - -?> diff --git a/bl-kernel/boot/init.php b/bl-kernel/boot/init.php index 0ec65774..4e8af5f2 100644 --- a/bl-kernel/boot/init.php +++ b/bl-kernel/boot/init.php @@ -7,7 +7,7 @@ define('BLUDIT_RELEASE_DATE', '2023-07-15'); define('BLUDIT_BUILD', '20230715'); // Change to TRUE for debugging -define('DEBUG_MODE', FALSE); +define('DEBUG_MODE', TRUE); define('DEBUG_TYPE', 'INFO'); // INFO, TRACE // This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user. diff --git a/bl-kernel/helpers/filesystem.class.php b/bl-kernel/helpers/filesystem.class.php index 3776a5c2..e2fca3f2 100644 --- a/bl-kernel/helpers/filesystem.class.php +++ b/bl-kernel/helpers/filesystem.class.php @@ -1,21 +1,23 @@ getPathName()); if ($skipDirectory !== $currentDirectory) { if ($item->isDir()) { - @mkdir($destination.DS.$iterator->getSubPathName()); + @mkdir($destination . DS . $iterator->getSubPathName()); } else { - copy($item, $destination.DS.$iterator->getSubPathName()); + copy($item, $destination . DS . $iterator->getSubPathName()); } } } @@ -125,9 +130,9 @@ class Filesystem { // Delete a file or directory recursive // The directory is delete - public static function deleteRecursive($source, $deleteDirectory=true) + public static function deleteRecursive($source, $deleteDirectory = true) { - Log::set('deleteRecursive = '.$source, LOG_TYPE_INFO); + Log::set('deleteRecursive = ' . $source, LOG_TYPE_INFO); if (!self::directoryExists($source)) { return false; @@ -135,12 +140,13 @@ class Filesystem { foreach (new RecursiveIteratorIterator( new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS), - RecursiveIteratorIterator::CHILD_FIRST) as $item) { - if ($item->isFile() || $item->isLink()) { - unlink($item); - } else { - rmdir($item); - } + RecursiveIteratorIterator::CHILD_FIRST + ) as $item) { + if ($item->isFile() || $item->isLink()) { + unlink($item); + } else { + rmdir($item); + } } if ($deleteDirectory) { @@ -209,7 +215,7 @@ class Filesystem { return $zip->close(); } - /* + /* | Returns the next filename if the filename already exist otherwise returns the original filename | | @path string Path @@ -217,7 +223,8 @@ class Filesystem { | | @return string */ - public static function nextFilename($filename, $path=PATH_UPLOADS) { + public static function nextFilename($filename, $path = PATH_UPLOADS) + { // Clean filename and get extension $fileExtension = pathinfo($filename, PATHINFO_EXTENSION); $fileExtension = Text::lowercase($fileExtension); @@ -226,19 +233,19 @@ class Filesystem { $filename = Text::removeQuotes($filename); // Search for the next filename - $tmpName = $filename.'.'.$fileExtension; - if (Sanitize::pathFile($path.$tmpName)) { + $tmpName = $filename . '.' . $fileExtension; + if (Sanitize::pathFile($path . $tmpName)) { $number = 0; - $tmpName = $filename.'_'.$number.'.'.$fileExtension; - while (Sanitize::pathFile($path.$tmpName)) { + $tmpName = $filename . '_' . $number . '.' . $fileExtension; + while (Sanitize::pathFile($path . $tmpName)) { $number = $number + 1; - $tmpName = $filename.'_'.$number.'.'.$fileExtension; + $tmpName = $filename . '_' . $number . '.' . $fileExtension; } } return $tmpName; } - /* + /* | Returns the filename | Example: | @file /home/diego/dog.jpg @@ -248,7 +255,8 @@ class Filesystem { | | @return string */ - public static function filename($file) { + public static function filename($file) + { return basename($file); } @@ -262,7 +270,8 @@ class Filesystem { | | @return string */ - public static function extension($file) { + public static function extension($file) + { return pathinfo($file, PATHINFO_EXTENSION); } @@ -271,30 +280,32 @@ class Filesystem { * @param [string] $fileOrDirectory * @return [int|bool] [bytes or false on error] */ - public static function getSize($fileOrDirectory) { + public static function getSize($fileOrDirectory) + { // Files if (is_file($fileOrDirectory)) { return filesize($fileOrDirectory); } // Directories if (file_exists($fileOrDirectory)) { - $size = 0; - foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($fileOrDirectory, FilesystemIterator::SKIP_DOTS)) as $file){ + $size = 0; + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($fileOrDirectory, FilesystemIterator::SKIP_DOTS)) as $file) { try { $size += $file->getSize(); } catch (Exception $e) { // SplFileInfo::getSize RuntimeException will be thrown on broken symlinks/errors } - } - return $size; + } + return $size; } return false; } - public static function bytesToHumanFileSize($bytes, $decimals = 2) { - $size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB'); - $factor = floor((strlen($bytes) - 1) / 3); - return sprintf("%.{$decimals}f ", $bytes / pow(1024, $factor)) . @$size[$factor]; + public static function bytesToHumanFileSize($bytes, $decimals = 2) + { + $size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); + $factor = floor((strlen($bytes) - 1) / 3); + return sprintf("%.{$decimals}f ", $bytes / pow(1024, $factor)) . @$size[$factor]; } /* @@ -307,7 +318,8 @@ class Filesystem { | | @return [string|bool] Mime type as string or FALSE if not possible to get the mime type */ - public static function mimeType($file) { + public static function mimeType($file) + { if (function_exists('mime_content_type')) { return mime_content_type($file); } @@ -322,12 +334,13 @@ class Filesystem { return false; } - public static function symlink($from, $to) { + public static function symlink($from, $to) + { if (function_exists('symlink')) { + Log::set('symlink from = ' . $from . ' to = ' . $to, LOG_TYPE_INFO); return symlink($from, $to); } else { return copy($from, $to); } } - } diff --git a/bl-kernel/pages.class.php b/bl-kernel/pages.class.php index 0da47ab0..f14bc393 100644 --- a/bl-kernel/pages.class.php +++ b/bl-kernel/pages.class.php @@ -1,27 +1,28 @@ '', - 'description'=>'', - 'username'=>'', - 'tags'=>array(), - 'type'=>'published', // published, static, draft, sticky, scheduled, autosave - 'date'=>'', - 'dateModified'=>'', - 'position'=>0, - 'coverImage'=>'', - 'category'=>'', - 'md5file'=>'', - 'uuid'=>'', - 'allowComments'=>true, - 'template'=>'', - 'noindex'=>false, - 'nofollow'=>false, - 'noarchive'=>false, - 'custom'=>array() + 'title' => '', + 'description' => '', + 'username' => '', + 'tags' => array(), + 'type' => 'published', // published, static, draft, sticky, scheduled, autosave + 'date' => '', + 'dateModified' => '', + 'position' => 0, + 'coverImage' => '', + 'category' => '', + 'md5file' => '', + 'uuid' => '', + 'allowComments' => true, + 'template' => '', + 'noindex' => false, + 'nofollow' => false, + 'noarchive' => false, + 'custom' => array() ); function __construct() @@ -47,7 +48,7 @@ class Pages extends dbJSON { // Return TRUE if the page exists, FALSE otherwise public function exists($key) { - return isset( $this->db[$key] ); + return isset($this->db[$key]); } // Create a new page @@ -57,18 +58,18 @@ class Pages extends dbJSON { $row = array(); // Predefined values - foreach ($this->dbFields as $field=>$value) { - if ($field=='tags') { + foreach ($this->dbFields as $field => $value) { + if ($field == 'tags') { $tags = ''; if (isset($args['tags'])) { $tags = $args['tags']; } $finalValue = $this->generateTags($tags); - } elseif ($field=='custom') { + } elseif ($field == 'custom') { if (isset($args['custom'])) { global $site; $customFields = $site->customFields(); - foreach ($args['custom'] as $customField=>$customValue) { + foreach ($args['custom'] as $customField => $customValue) { $html = Sanitize::html($customValue); // Store the custom field as defined type settype($html, $customFields[$customField]['type']); @@ -91,7 +92,7 @@ class Pages extends dbJSON { // Content // This variable is not belong to the database so is not defined in $row - $contentRaw = (empty($args['content'])?'':$args['content']); + $contentRaw = (empty($args['content']) ? '' : $args['content']); // Parent // This variable is not belong to the database so is not defined in $row @@ -128,24 +129,24 @@ class Pages extends dbJSON { } // Schedule page - if (($row['date']>Date::current(DB_DATE_FORMAT)) && ($row['type']=='published')) { + if (($row['date'] > Date::current(DB_DATE_FORMAT)) && ($row['type'] == 'published')) { $row['type'] = 'scheduled'; } // Create the directory - if (Filesystem::mkdir(PATH_PAGES.$key, true) === false) { - Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to create the directory ['.PATH_PAGES.$key.']',LOG_TYPE_ERROR); + if (Filesystem::mkdir(PATH_PAGES . $key, true) === false) { + Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to create the directory [' . PATH_PAGES . $key . ']', LOG_TYPE_ERROR); return false; } // Create the index.txt and save the file - if (file_put_contents(PATH_PAGES.$key.DS.FILENAME, $contentRaw) === false) { - Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to create the content in the file ['.FILENAME.']',LOG_TYPE_ERROR); + if (file_put_contents(PATH_PAGES . $key . DS . FILENAME, $contentRaw) === false) { + Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to create the content in the file [' . FILENAME . ']', LOG_TYPE_ERROR); return false; } // Checksum MD5 - $row['md5file'] = md5_file(PATH_PAGES.$key.DS.FILENAME); + $row['md5file'] = md5_file(PATH_PAGES . $key . DS . FILENAME); // Insert in database $this->db[$key] = $row; @@ -156,10 +157,12 @@ class Pages extends dbJSON { // Save database $this->save(); - // Create symlink for images directory - if (Filesystem::mkdir(PATH_UPLOADS_PAGES.$row['uuid'])) { - Filesystem::symlink(PATH_UPLOADS_PAGES.$row['uuid'], PATH_UPLOADS_PAGES.$key); + // Create upload page directory for images + if (!Filesystem::directoryExists(PATH_UPLOADS_PAGES . $row['uuid'])) { + Filesystem::mkdir(PATH_UPLOADS_PAGES . $row['uuid']); } + // Create a symlink to the upload page directory for images for better SEO + Filesystem::symlink(PATH_UPLOADS_PAGES . $row['uuid'], PATH_UPLOADS_PAGES . $key); return $key; } @@ -179,14 +182,14 @@ class Pages extends dbJSON { // Check values from the arguments ($args) // If some field is missing the current value is taken - foreach ($this->dbFields as $field=>$value) { - if ( ($field=='tags') && isset($args['tags'])) { + foreach ($this->dbFields as $field => $value) { + if (($field == 'tags') && isset($args['tags'])) { $finalValue = $this->generateTags($args['tags']); - } elseif ($field=='custom') { + } elseif ($field == 'custom') { if (isset($args['custom'])) { global $site; $customFields = $site->customFields(); - foreach ($args['custom'] as $customField=>$customValue) { + foreach ($args['custom'] as $customField => $customValue) { $html = Sanitize::html($customValue); // Store the custom field as defined type settype($html, $customFields[$customField]['type']); @@ -241,27 +244,27 @@ class Pages extends dbJSON { $row['dateModified'] = Date::current(DB_DATE_FORMAT); // Schedule page - if (($row['date']>Date::current(DB_DATE_FORMAT)) && ($row['type']=='published')) { + if (($row['date'] > Date::current(DB_DATE_FORMAT)) && ($row['type'] == 'published')) { $row['type'] = 'scheduled'; } // Move the directory from old key to new key only if the keys are different - if ($newKey!==$key) { - if (Filesystem::mv(PATH_PAGES.$key, PATH_PAGES.$newKey) === false) { - Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to move the directory to '.PATH_PAGES.$newKey); + if ($newKey !== $key) { + if (Filesystem::mv(PATH_PAGES . $key, PATH_PAGES . $newKey) === false) { + Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to move the directory to ' . PATH_PAGES . $newKey); return false; } // Regenerate the symlink to a proper directory - unlink(PATH_UPLOADS_PAGES.$key); - Filesystem::symlink(PATH_UPLOADS_PAGES.$row['uuid'], PATH_UPLOADS_PAGES.$newKey); + unlink(PATH_UPLOADS_PAGES . $key); + Filesystem::symlink(PATH_UPLOADS_PAGES . $row['uuid'], PATH_UPLOADS_PAGES . $newKey); } // If the content was passed via arguments replace the content if (isset($args['content'])) { // Make the index.txt and save the file. - if (file_put_contents(PATH_PAGES.$newKey.DS.FILENAME, $args['content'])===false) { - Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to put the content in the file '.FILENAME); + if (file_put_contents(PATH_PAGES . $newKey . DS . FILENAME, $args['content']) === false) { + Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to put the content in the file ' . FILENAME); return false; } } @@ -273,7 +276,7 @@ class Pages extends dbJSON { $this->reindexChildren($key, $newKey); // Checksum MD5 - $row['md5file'] = md5_file(PATH_PAGES.$newKey.DS.FILENAME); + $row['md5file'] = md5_file(PATH_PAGES . $newKey . DS . FILENAME); // Insert in database the new row $this->db[$newKey] = $row; @@ -289,14 +292,15 @@ class Pages extends dbJSON { // This function reindex the orphan children with the new parent key // If a page has subpages and the page change his key is necesarry check the children key - public function reindexChildren($oldParentKey, $newParentKey) { - if ($oldParentKey==$newParentKey){ + public function reindexChildren($oldParentKey, $newParentKey) + { + if ($oldParentKey == $newParentKey) { return false; } $tmp = $this->db; - foreach ($tmp as $key=>$fields) { - if (Text::startsWith($key, $oldParentKey.'/')) { - $newKey = Text::replace($oldParentKey.'/', $newParentKey.'/', $key); + foreach ($tmp as $key => $fields) { + if (Text::startsWith($key, $oldParentKey . '/')) { + $newKey = Text::replace($oldParentKey . '/', $newParentKey . '/', $key); $this->db[$newKey] = $this->db[$key]; unset($this->db[$key]); } @@ -312,19 +316,19 @@ class Pages extends dbJSON { // Page doesn't exist in database if (!$this->exists($key)) { - Log::set(__METHOD__.LOG_SEP.'The page does not exist. Key: '.$key); + Log::set(__METHOD__ . LOG_SEP . 'The page does not exist. Key: ' . $key); return false; } // Delete directory and files - if (Filesystem::deleteRecursive(PATH_PAGES.$key) === false) { - Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to delete the directory '.PATH_PAGES.$key, LOG_TYPE_ERROR); + if (Filesystem::deleteRecursive(PATH_PAGES . $key) === false) { + Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to delete the directory ' . PATH_PAGES . $key, LOG_TYPE_ERROR); } // Delete page images directory; The function already check if exists the directory if (($uuid = $this->getUUID($key))) { - if (Filesystem::deleteRecursive(PATH_UPLOADS_PAGES.$uuid) === false) { - Log::set(__METHOD__.LOG_SEP.'Directory with images not found '.PATH_UPLOADS_PAGES.$uuid); + if (Filesystem::deleteRecursive(PATH_UPLOADS_PAGES . $uuid) === false) { + Log::set(__METHOD__ . LOG_SEP . 'Directory with images not found ' . PATH_UPLOADS_PAGES . $uuid); } } @@ -332,8 +336,8 @@ class Pages extends dbJSON { unset($this->db[$key]); // Save the database - if ($this->save()===false) { - Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.'); + if ($this->save() === false) { + Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to save the database file.'); } return true; @@ -344,8 +348,8 @@ class Pages extends dbJSON { { $username = $args['username']; - foreach ($this->db as $key=>$fields) { - if ($fields['username']===$username) { + foreach ($this->db as $key => $fields) { + if ($fields['username'] === $username) { $this->delete($key); } } @@ -359,8 +363,8 @@ class Pages extends dbJSON { $oldUsername = $args['oldUsername']; $newUsername = isset($args['newUsername']) ? $args['newUsername'] : 'admin'; - foreach ($this->db as $key=>$fields) { - if ($fields['username']===$oldUsername) { + foreach ($this->db as $key => $fields) { + if ($fields['username'] === $oldUsername) { $this->db[$key]['username'] = $newUsername; } } @@ -382,7 +386,7 @@ class Pages extends dbJSON { // Returns a database with all pages // $onlyKeys = true; Returns only the pages keys // $onlyKeys = false; Returns part of the database, I do not recommend use this - public function getDB($onlyKeys=true) + public function getDB($onlyKeys = true) { $tmp = $this->db; if ($onlyKeys) { @@ -394,11 +398,11 @@ class Pages extends dbJSON { // Returns a database with published pages // $onlyKeys = true; Returns only the pages keys // $onlyKeys = false; Returns part of the database, I do not recommend use this - public function getPublishedDB($onlyKeys=true) + public function getPublishedDB($onlyKeys = true) { $tmp = $this->db; - foreach ($tmp as $key=>$fields) { - if ($fields['type']!='published') { + foreach ($tmp as $key => $fields) { + if ($fields['type'] != 'published') { unset($tmp[$key]); } } @@ -410,11 +414,11 @@ class Pages extends dbJSON { // Returns an array with a list of keys/database of static pages // By default the static pages are sort by position - public function getStaticDB($onlyKeys=true) + public function getStaticDB($onlyKeys = true) { $tmp = $this->db; - foreach ($tmp as $key=>$fields) { - if ($fields['type']!='static') { + foreach ($tmp as $key => $fields) { + if ($fields['type'] != 'static') { unset($tmp[$key]); } } @@ -426,11 +430,11 @@ class Pages extends dbJSON { } // Returns an array with a list of keys/database of draft pages - public function getDraftDB($onlyKeys=true) + public function getDraftDB($onlyKeys = true) { $tmp = $this->db; - foreach ($tmp as $key=>$fields) { - if($fields['type']!='draft') { + foreach ($tmp as $key => $fields) { + if ($fields['type'] != 'draft') { unset($tmp[$key]); } } @@ -441,11 +445,11 @@ class Pages extends dbJSON { } // Returns an array with a list of keys/database of autosave pages - public function getAutosaveDB($onlyKeys=true) + public function getAutosaveDB($onlyKeys = true) { $tmp = $this->db; - foreach ($tmp as $key=>$fields) { - if($fields['type']!='autosave') { + foreach ($tmp as $key => $fields) { + if ($fields['type'] != 'autosave') { unset($tmp[$key]); } } @@ -456,11 +460,11 @@ class Pages extends dbJSON { } // Returns an array with a list of keys/database of scheduled pages - public function getScheduledDB($onlyKeys=true) + public function getScheduledDB($onlyKeys = true) { $tmp = $this->db; - foreach ($tmp as $key=>$fields) { - if($fields['type']!='scheduled') { + foreach ($tmp as $key => $fields) { + if ($fields['type'] != 'scheduled') { unset($tmp[$key]); } } @@ -471,11 +475,11 @@ class Pages extends dbJSON { } // Returns an array with a list of keys of sticky pages - public function getStickyDB($onlyKeys=true) + public function getStickyDB($onlyKeys = true) { $tmp = $this->db; - foreach ($tmp as $key=>$fields) { - if($fields['type']!='sticky') { + foreach ($tmp as $key => $fields) { + if ($fields['type'] != 'sticky') { unset($tmp[$key]); } } @@ -489,8 +493,8 @@ class Pages extends dbJSON { public function nextPositionNumber() { $tmp = 1; - foreach ($this->db as $key=>$fields) { - if ($fields['position']>$tmp) { + foreach ($this->db as $key => $fields) { + if ($fields['position'] > $tmp) { $tmp = $fields['position']; } } @@ -500,12 +504,12 @@ class Pages extends dbJSON { // Returns the next page key of the current page key public function nextPageKey($currentKey) { - if ($this->db[$currentKey]['type']=='published') { + if ($this->db[$currentKey]['type'] == 'published') { $keys = array_keys($this->db); $position = array_search($currentKey, $keys) - 1; if (isset($keys[$position])) { $nextKey = $keys[$position]; - if ($this->db[$nextKey]['type']=='published') { + if ($this->db[$nextKey]['type'] == 'published') { return $nextKey; } } @@ -516,12 +520,12 @@ class Pages extends dbJSON { // Returns the previous page key of the current page key public function previousPageKey($currentKey) { - if ($this->db[$currentKey]['type']=='published') { + if ($this->db[$currentKey]['type'] == 'published') { $keys = array_keys($this->db); $position = array_search($currentKey, $keys) + 1; if (isset($keys[$position])) { $prevKey = $keys[$position]; - if ($this->db[$prevKey]['type']=='published') { + if ($this->db[$prevKey]['type'] == 'published') { return $prevKey; } } @@ -534,24 +538,24 @@ class Pages extends dbJSON { // (int) $pageNumber, the page number // (int) $numberOfItems, amount of items to return, if -1 returns all the items // (boolean) $onlyPublished, TRUE to return only published pages - public function getList($pageNumber, $numberOfItems, $published=true, $static=false, $sticky=false, $draft=false, $scheduled=false) + public function getList($pageNumber, $numberOfItems, $published = true, $static = false, $sticky = false, $draft = false, $scheduled = false) { $list = array(); - foreach ($this->db as $key=>$fields) { - if ($published && $fields['type']=='published') { + foreach ($this->db as $key => $fields) { + if ($published && $fields['type'] == 'published') { array_push($list, $key); - } elseif ($static && $fields['type']=='static') { + } elseif ($static && $fields['type'] == 'static') { array_push($list, $key); - } elseif ($sticky && $fields['type']=='sticky') { + } elseif ($sticky && $fields['type'] == 'sticky') { array_push($list, $key); - } elseif ($draft && $fields['type']=='draft') { + } elseif ($draft && $fields['type'] == 'draft') { array_push($list, $key); - } elseif ($scheduled && $fields['type']=='scheduled') { + } elseif ($scheduled && $fields['type'] == 'scheduled') { array_push($list, $key); } } - if ($numberOfItems==-1) { + if ($numberOfItems == -1) { return $list; } @@ -560,8 +564,8 @@ class Pages extends dbJSON { $total = count($list); $init = (int) $numberOfItems * $realPageNumber; - $end = (int) min( ($init + $numberOfItems - 1), $total ); - $outrange = $init<0 ? true : $init>$end; + $end = (int) min(($init + $numberOfItems - 1), $total); + $outrange = $init < 0 ? true : $init > $end; if (!$outrange) { return array_slice($list, $init, $numberOfItems, true); } @@ -572,7 +576,7 @@ class Pages extends dbJSON { // Returns the amount of pages // (boolean) $onlyPublished, TRUE returns the total of published pages (without draft and scheduled) // (boolean) $onlyPublished, FALSE returns the total of pages - public function count($onlyPublished=true) + public function count($onlyPublished = true) { if ($onlyPublished) { $db = $this->getPublishedDB(false); @@ -586,7 +590,7 @@ class Pages extends dbJSON { public function getParents() { $db = $this->getPublishedDB(); - foreach ($db as $key=>$pageKey) { + foreach ($db as $key => $pageKey) { // if the key has slash then is a child if (Text::stringContains($pageKey, '/')) { unset($db[$key]); @@ -599,8 +603,8 @@ class Pages extends dbJSON { { $tmp = $this->db; $list = array(); - foreach ($tmp as $key=>$fields) { - if (Text::startsWith($key, $parentKey.'/')) { + foreach ($tmp as $key => $fields) { + if (Text::startsWith($key, $parentKey . '/')) { array_push($list, $key); } } @@ -609,16 +613,16 @@ class Pages extends dbJSON { public function sortBy() { - if (ORDER_BY=='date') { + if (ORDER_BY == 'date') { return $this->sortByDate(true); } return $this->sortByPosition(false); } // Sort pages by position - public function sortByPosition($HighToLow=false) + public function sortByPosition($HighToLow = false) { - if($HighToLow) { + if ($HighToLow) { uasort($this->db, array($this, 'sortByPositionHighToLow')); } else { uasort($this->db, array($this, 'sortByPositionLowToHigh')); @@ -628,17 +632,17 @@ class Pages extends dbJSON { private function sortByPositionLowToHigh($a, $b) { - return $a['position']>$b['position']; + return $a['position'] > $b['position']; } private function sortByPositionHighToLow($a, $b) { - return $a['position']<$b['position']; + return $a['position'] < $b['position']; } // Sort pages by date - public function sortByDate($HighToLow=true) + public function sortByDate($HighToLow = true) { - if($HighToLow) { + if ($HighToLow) { uasort($this->db, array($this, 'sortByDateHighToLow')); } else { uasort($this->db, array($this, 'sortByDateLowToHigh')); @@ -648,15 +652,16 @@ class Pages extends dbJSON { private function sortByDateLowToHigh($a, $b) { - return $a['date']>$b['date']; + return $a['date'] > $b['date']; } private function sortByDateHighToLow($a, $b) { - return $a['date']<$b['date']; + return $a['date'] < $b['date']; } - function generateUUID() { - return md5( uniqid().time() ); + function generateUUID() + { + return md5(uniqid() . time()); } // Returns the UUID of a page, by the page key @@ -672,8 +677,8 @@ class Pages extends dbJSON { // if the UUID doesn't exits returns FALSE function getByUUID($uuid) { - foreach ($this->db as $key=>$value) { - if ($value['uuid']==$uuid) { + foreach ($this->db as $key => $value) { + if ($value['uuid'] == $uuid) { return $key; } } @@ -682,7 +687,7 @@ class Pages extends dbJSON { // Returns string without HTML tags and truncated - private function generateSlug($text, $truncateLength=60) + private function generateSlug($text, $truncateLength = 60) { $tmpslug = Text::removeHTMLTags($text); $tmpslug = Text::removeLineBreaks($tmpslug); @@ -698,25 +703,24 @@ class Pages extends dbJSON { $saveDatabase = false; // The database need to be sorted by date - foreach($this->db as $pageKey=>$fields) { - if($fields['type']=='scheduled') { - if($fields['date']<=$currentDate) { + foreach ($this->db as $pageKey => $fields) { + if ($fields['type'] == 'scheduled') { + if ($fields['date'] <= $currentDate) { $this->db[$pageKey]['type'] = 'published'; $saveDatabase = true; } - } - elseif( ($fields['type']=='published') && (ORDER_BY=='date') ) { + } elseif (($fields['type'] == 'published') && (ORDER_BY == 'date')) { break; } } - if($saveDatabase) { - if( $this->save() === false ) { - Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.'); + if ($saveDatabase) { + if ($this->save() === false) { + Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to save the database file.'); return false; } - Log::set(__METHOD__.LOG_SEP.'New pages published from the scheduler.'); + Log::set(__METHOD__ . LOG_SEP . 'New pages published from the scheduler.'); return true; } @@ -724,7 +728,7 @@ class Pages extends dbJSON { } // Generate a valid Key/Slug - public function generateKey($text, $parent=false, $returnSlug=false, $oldKey='') + public function generateKey($text, $parent = false, $returnSlug = false, $oldKey = '') { global $L; global $site; @@ -736,7 +740,7 @@ class Pages extends dbJSON { if (Text::isEmpty($parent)) { $newKey = Text::cleanUrl($text); } else { - $newKey = Text::cleanUrl($parent).'/'.Text::cleanUrl($text); + $newKey = Text::cleanUrl($parent) . '/' . Text::cleanUrl($text); } // cleanURL can return empty string @@ -744,14 +748,14 @@ class Pages extends dbJSON { $newKey = $L->g('empty'); } - if ($newKey!==$oldKey) { + if ($newKey !== $oldKey) { // Verify if the key is already been used if (isset($this->db[$newKey])) { $i = 0; - while (isset($this->db[$newKey.'-'.$i])) { + while (isset($this->db[$newKey . '-' . $i])) { $i++; } - $newKey = $newKey.'-'.$i; + $newKey = $newKey . '-' . $i; } } @@ -788,8 +792,8 @@ class Pages extends dbJSON { // Change all pages with the old category key to the new category key public function changeCategory($oldCategoryKey, $newCategoryKey) { - foreach ($this->db as $key=>$value) { - if ($value['category']===$oldCategoryKey) { + foreach ($this->db as $key => $value) { + if ($value['category'] === $oldCategoryKey) { $this->db[$key]['category'] = $newCategoryKey; } } @@ -806,8 +810,8 @@ class Pages extends dbJSON { if (json_last_error() != JSON_ERROR_NONE) { return false; } - foreach ($this->db as $pageKey=>$pageFields) { - foreach ($customFields as $customField=>$customValues) { + foreach ($this->db as $pageKey => $pageFields) { + foreach ($customFields as $customField => $customValues) { if (!isset($pageFields['custom'][$customField])) { $defaultValue = ''; if (isset($customValues['default'])) { @@ -820,6 +824,4 @@ class Pages extends dbJSON { return $this->save(); } - - } diff --git a/bl-kernel/pagex.class.php b/bl-kernel/pagex.class.php index b6183ac8..d72bb1d8 100644 --- a/bl-kernel/pagex.class.php +++ b/bl-kernel/pagex.class.php @@ -1,6 +1,7 @@ getDefaultFields(); } else { if (Text::isEmpty($key) || !$pages->exists($key)) { - $errorMessage = 'Page not found in database by key ['.$key.']'; - Log::set(__METHOD__.LOG_SEP.$errorMessage); + $errorMessage = 'Page not found in database by key [' . $key . ']'; + Log::set(__METHOD__ . LOG_SEP . $errorMessage); throw new Exception($errorMessage); } $row = $pages->getPageDB($key); } - foreach ($row as $field=>$value) { - if ($field=='date') { + foreach ($row as $field => $value) { + if ($field == 'date') { $this->setField('dateRaw', $value); } else { $this->setField($field, $value); @@ -49,10 +50,10 @@ class Page { // Returns the raw content // This content is not markdown parser // (boolean) $sanitize, TRUE returns the content sanitized - public function contentRaw($sanitize=false) + public function contentRaw($sanitize = false) { $key = $this->key(); - $filePath = PATH_PAGES.$key.DS.FILENAME; + $filePath = PATH_PAGES . $key . DS . FILENAME; $contentRaw = file_get_contents($filePath); if ($sanitize) { @@ -64,7 +65,7 @@ class Page { // Returns the full content // This content is markdown parser // (boolean) $sanitize, TRUE returns the content sanitized - public function content($sanitize=false) + public function content($sanitize = false) { // If already set the content, return it $content = $this->getValue('content'); @@ -83,7 +84,7 @@ class Page { // Parse img src relative to absolute (with domain) if (IMAGE_RELATIVE_TO_ABSOLUTE) { - $domain = IMAGE_RESTRICT?DOMAIN_UPLOADS_PAGES.$this->uuid().'/':DOMAIN_UPLOADS; + $domain = IMAGE_RESTRICT ? DOMAIN_UPLOADS_PAGES . $this->uuid() . '/' : DOMAIN_UPLOADS; $content = Text::imgRel2Abs($content, $domain); } @@ -96,7 +97,7 @@ class Page { // Returns the first part of the content if the content is splited, otherwise is returned the full content // This content is markdown parser // (boolean) $sanitize, TRUE returns the content sanitized - public function contentBreak($sanitize=false) + public function contentBreak($sanitize = false) { $content = $this->content($sanitize); $explode = explode(PAGE_BREAK, $content); @@ -104,10 +105,10 @@ class Page { } // Returns the date according to locale settings and the format defined in the system - public function date($format=false) + public function date($format = false) { $dateRaw = $this->dateRaw(); - if ($format===false) { + if ($format === false) { global $site; $format = $site->dateFormat(); } @@ -122,10 +123,10 @@ class Page { } // Returns the date according to locale settings and format settings - public function dateModified($format=false) + public function dateModified($format = false) { $dateRaw = $this->getValue('dateModified'); - if ($format===false) { + if ($format === false) { global $site; $format = $site->dateFormat(); } @@ -146,16 +147,16 @@ class Page { // Returns the permalink // (boolean) $absolute, TRUE returns the page link with the DOMAIN, FALSE without the DOMAIN - public function permalink($absolute=true) + public function permalink($absolute = true) { // Get the key of the page $key = $this->key(); - if($absolute) { - return DOMAIN_PAGES.$key; + if ($absolute) { + return DOMAIN_PAGES . $key; } - return HTML_PATH_ROOT.PAGE_URI_FILTER.$key; + return HTML_PATH_ROOT . PAGE_URI_FILTER . $key; } // Returns the previous page key @@ -199,7 +200,7 @@ class Page { // Returns the category permalink public function categoryPermalink() { - return DOMAIN_CATEGORIES.$this->categoryKey(); + return DOMAIN_CATEGORIES . $this->categoryKey(); } // Returns the field from the array @@ -210,9 +211,9 @@ class Page { $categoryKey = $this->categoryKey(); $map = $categories->getMap($categoryKey); - if ($field=='key') { + if ($field == 'key') { return $this->categoryKey(); - } elseif(isset($map[$field])) { + } elseif (isset($map[$field])) { return $map[$field]; } @@ -220,7 +221,7 @@ class Page { } // Returns the user object or passing the method returns the object User method - public function user($method=false) + public function user($method = false) { $username = $this->username(); try { @@ -248,7 +249,7 @@ class Page { // Returns the tags separated by comma // (boolean) $returnsArray, TRUE to get the tags as an array, FALSE to get the tags separated by comma // The tags in array format returns array( tagKey => tagName ) - public function tags($returnsArray=false) + public function tags($returnsArray = false) { $tags = $this->getValue('tags'); if ($returnsArray) { @@ -267,7 +268,7 @@ class Page { - public function json($returnsArray=false) + public function json($returnsArray = false) { $tmp['key'] = $this->key(); $tmp['title'] = $this->title(); @@ -297,7 +298,7 @@ class Page { // Returns the endpoint of the coverimage, FALSE if the page doesn't have a cover image // (boolean) $absolute, TRUE returns the complete URL, FALSE returns the filename // If the user defined an external cover image the function returns it - public function coverImage($absolute=true) + public function coverImage($absolute = true) { $filename = $this->getValue('coverImage'); if (empty($filename)) { @@ -311,9 +312,9 @@ class Page { if ($absolute) { if (IMAGE_RESTRICT) { - return DOMAIN_UPLOADS_PAGES.$this->uuid().'/'.$filename; + return DOMAIN_UPLOADS_PAGES . $this->uuid() . '/' . $filename; } - return DOMAIN_UPLOADS.$filename; + return DOMAIN_UPLOADS . $filename; } return $filename; @@ -323,7 +324,7 @@ class Page { public function thumbCoverImage() { $filename = $this->coverImage(false); - if ($filename==false) { + if ($filename == false) { return false; } @@ -333,9 +334,9 @@ class Page { } if (IMAGE_RESTRICT) { - return DOMAIN_UPLOADS_PAGES.$this->uuid().'/thumbnails/'.$filename; + return DOMAIN_UPLOADS_PAGES . $this->uuid() . '/thumbnails/' . $filename; } - return DOMAIN_UPLOADS_THUMBNAILS.$filename; + return DOMAIN_UPLOADS_THUMBNAILS . $filename; } // Returns TRUE if the content has the text splited @@ -359,37 +360,37 @@ class Page { // (boolean) Returns TRUE if the page is published, FALSE otherwise public function published() { - return ($this->getValue('type')==='published'); + return ($this->getValue('type') === 'published'); } // (boolean) Returns TRUE if the page is scheduled, FALSE otherwise public function scheduled() { - return ($this->getValue('type')==='scheduled'); + return ($this->getValue('type') === 'scheduled'); } // (boolean) Returns TRUE if the page is draft, FALSE otherwise public function draft() { - return ($this->getValue('type')=='draft'); + return ($this->getValue('type') == 'draft'); } // (boolean) Returns TRUE if the page is autosave, FALSE otherwise public function autosave() { - return ($this->getValue('type')=='autosave'); + return ($this->getValue('type') == 'autosave'); } // (boolean) Returns TRUE if the page is sticky, FALSE otherwise public function sticky() { - return ($this->getValue('type')=='sticky'); + return ($this->getValue('type') == 'sticky'); } // (boolean) Returns TRUE if the page is static, FALSE otherwise public function isStatic() { - return ($this->getValue('type')=='static'); + return ($this->getValue('type') == 'static'); } // (string) Returns type of the page @@ -460,7 +461,7 @@ class Page { // Returns TRUE if the page is a parent, has or not children public function isParent() { - return $this->parentKey()===false; + return $this->parentKey() === false; } // Returns the parent method output, if the page doesn't have a parent returns FALSE @@ -482,7 +483,7 @@ class Page { // Returns TRUE if the page is a child, FALSE otherwise public function isChild() { - return $this->parentKey()!==false; + return $this->parentKey() !== false; } // Returns TRUE if the page has children @@ -519,7 +520,8 @@ class Page { } // Returns the amount of minutes takes to read the page - public function readingTime() { + public function readingTime() + { global $L; $words = $this->content(true); @@ -528,11 +530,11 @@ class Page { $average = $words / 200; $minutes = round($average); - if ($minutes>1) { - return $minutes.' '.$L->get('minutes'); + if ($minutes > 1) { + return $minutes . ' ' . $L->get('minutes'); } - return '~1 '.$L->get('minute'); + return '~1 ' . $L->get('minute'); } // Returns relative time (e.g. "1 minute ago") @@ -540,7 +542,8 @@ class Page { // Modified for Bludit // $complete = false : short version // $complete = true : full version - public function relativeTime($complete = false) { + public function relativeTime($complete = false) + { $current = new DateTime; $past = new DateTime($this->getValue('dateRaw')); $elapsed = $current->diff($past); @@ -558,16 +561,16 @@ class Page { 's' => 'second', ); - foreach($string as $key => &$value) { - if($elapsed->$key) { + foreach ($string as $key => &$value) { + if ($elapsed->$key) { $value = $elapsed->$key . ' ' . $value . ($elapsed->$key > 1 ? 's' : ' '); } else { unset($string[$key]); } } - if(!$complete) { - $string = array_slice($string, 0 , 1); + if (!$complete) { + $string = array_slice($string, 0, 1); } return $string ? implode(', ', $string) . ' ago' : 'Just now'; @@ -575,7 +578,7 @@ class Page { // Returns the value from the field, false if the fields doesn't exists // If you set the $option as TRUE, the function returns an array with all the values of the field - public function custom($field, $options=false) + public function custom($field, $options = false) { if (isset($this->vars['custom'][$field])) { if ($options) { @@ -588,16 +591,17 @@ class Page { // Returns an array with all pages key related to the page // The relation is based on the tags - public function related() { + public function related() + { global $tags; $pageTags = $this->tags(true); $list = array(); // For each tag get the list of related pages - foreach ($pageTags as $tagKey=>$tagName) { + foreach ($pageTags as $tagKey => $tagName) { $pagesRelated = $tags->getList($tagKey, 1, -1); - if(is_array($pagesRelated)) { - $list = array_merge($list, $pagesRelated); - } + if (is_array($pagesRelated)) { + $list = array_merge($list, $pagesRelated); + } } // Remove duplicates