fix: page upload symlink

This commit is contained in:
Diego Najar 2024-06-23 21:46:43 +02:00
parent e770d6a972
commit 4bfa4a74a9
5 changed files with 274 additions and 257 deletions

View file

@ -25,8 +25,8 @@ if ($uuid) {
// Set upload directory // Set upload directory
if ($uuid && IMAGE_RESTRICT) { if ($uuid && IMAGE_RESTRICT) {
$imageDirectory = PATH_UPLOADS_PAGES.$uuid.DS; $imageDirectory = PATH_UPLOADS_PAGES . $uuid . DS;
$thumbnailDirectory = $imageDirectory.'thumbnails'.DS; $thumbnailDirectory = $imageDirectory . 'thumbnails' . DS;
if (!Filesystem::directoryExists($thumbnailDirectory)) { if (!Filesystem::directoryExists($thumbnailDirectory)) {
Filesystem::mkdir($thumbnailDirectory, true); Filesystem::mkdir($thumbnailDirectory, true);
} }
@ -36,10 +36,10 @@ if ($uuid && IMAGE_RESTRICT) {
} }
$images = array(); $images = array();
foreach ($_FILES['images']['name'] as $uuid=>$filename) { foreach ($_FILES['images']['name'] as $uuid => $filename) {
// Check for errors // Check for errors
if ($_FILES['images']['error'][$uuid] != 0) { 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); Log::set($message, LOG_TYPE_ERROR);
ajaxResponse(1, $message); ajaxResponse(1, $message);
} }
@ -57,27 +57,27 @@ foreach ($_FILES['images']['name'] as $uuid=>$filename) {
// Check file extension // Check file extension
$fileExtension = Filesystem::extension($filename); $fileExtension = Filesystem::extension($filename);
$fileExtension = Text::lowercase($fileExtension); $fileExtension = Text::lowercase($fileExtension);
if (!in_array($fileExtension, $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']); $message = $L->g('File type is not supported. Allowed types:') . ' ' . implode(', ', $GLOBALS['ALLOWED_IMG_EXTENSION']);
Log::set($message, LOG_TYPE_ERROR); Log::set($message, LOG_TYPE_ERROR);
ajaxResponse(1, $message); ajaxResponse(1, $message);
} }
// Check file MIME Type // Check file MIME Type
$fileMimeType = Filesystem::mimeType($_FILES['images']['tmp_name'][$uuid]); $fileMimeType = Filesystem::mimeType($_FILES['images']['tmp_name'][$uuid]);
if ($fileMimeType!==false) { if ($fileMimeType !== false) {
if (!in_array($fileMimeType, $GLOBALS['ALLOWED_IMG_MIMETYPES'])) { 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); Log::set($message, LOG_TYPE_ERROR);
ajaxResponse(1, $message); ajaxResponse(1, $message);
} }
} }
// Move from PHP tmp file to Bludit tmp directory // 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 // Transform the image and generate the thumbnail
$image = transformImage(PATH_TMP.$filename, $imageDirectory, $thumbnailDirectory); $image = transformImage(PATH_TMP . $filename, $imageDirectory, $thumbnailDirectory);
if ($image) { if ($image) {
chmod($image, 0644); chmod($image, 0644);
@ -91,7 +91,5 @@ foreach ($_FILES['images']['name'] as $uuid=>$filename) {
} }
ajaxResponse(0, 'Images uploaded.', array( ajaxResponse(0, 'Images uploaded.', array(
'images'=>$images 'images' => $images
)); ));
?>

View file

@ -7,7 +7,7 @@ define('BLUDIT_RELEASE_DATE', '2023-07-15');
define('BLUDIT_BUILD', '20230715'); define('BLUDIT_BUILD', '20230715');
// Change to TRUE for debugging // Change to TRUE for debugging
define('DEBUG_MODE', FALSE); define('DEBUG_MODE', TRUE);
define('DEBUG_TYPE', 'INFO'); // INFO, TRACE 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. // This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.

View file

@ -1,21 +1,23 @@
<?php defined('BLUDIT') or die('Bludit CMS.'); <?php defined('BLUDIT') or die('Bludit CMS.');
class Filesystem { class Filesystem
{
// Returns an array with the absolutes directories. // Returns an array with the absolutes directories.
public static function listDirectories($path, $regex='*', $sortByDate=false) public static function listDirectories($path, $regex = '*', $sortByDate = false)
{ {
$directories = glob($path.$regex, GLOB_ONLYDIR); $directories = glob($path . $regex, GLOB_ONLYDIR);
if(empty($directories)) { if (empty($directories)) {
return array(); return array();
} }
if($sortByDate) { if ($sortByDate) {
usort($directories, usort(
function($a, $b) { $directories,
return filemtime($b) - filemtime($a); function ($a, $b) {
} return filemtime($b) - filemtime($a);
}
); );
} }
@ -25,18 +27,19 @@ class Filesystem {
// Returns an array with the list of files with the absolute path // Returns an array with the list of files with the absolute path
// $sortByDate = TRUE, the first file is the newer file // $sortByDate = TRUE, the first file is the newer file
// $chunk = amount of chunks, FALSE if you don't want to chunk // $chunk = amount of chunks, FALSE if you don't want to chunk
public static function listFiles($path, $regex='*', $extension='*', $sortByDate=false, $chunk=false) public static function listFiles($path, $regex = '*', $extension = '*', $sortByDate = false, $chunk = false)
{ {
error_log($path.$regex.'.'.$extension); error_log($path . $regex . '.' . $extension);
$files = glob($path.$regex.'.'.$extension); $files = glob($path . $regex . '.' . $extension);
if (empty($files)) { if (empty($files)) {
return array(); return array();
} }
if ($sortByDate) { if ($sortByDate) {
usort($files, usort(
function($a, $b) { $files,
function ($a, $b) {
return filemtime($b) - filemtime($a); return filemtime($b) - filemtime($a);
} }
); );
@ -51,26 +54,27 @@ class Filesystem {
return $files; return $files;
} }
public static function mkdir($pathname, $recursive=false) public static function mkdir($pathname, $recursive = false)
{ {
Log::set('mkdir ' . $pathname . ' recursive = ' . $recursive, LOG_TYPE_INFO);
return mkdir($pathname, DIR_PERMISSIONS, $recursive); return mkdir($pathname, DIR_PERMISSIONS, $recursive);
} }
public static function rmdir($pathname) public static function rmdir($pathname)
{ {
Log::set('rmdir = '.$pathname, LOG_TYPE_INFO); Log::set('rmdir = ' . $pathname, LOG_TYPE_INFO);
return rmdir($pathname); return rmdir($pathname);
} }
public static function mv($oldname, $newname) public static function mv($oldname, $newname)
{ {
Log::set('mv '.$oldname.' '.$newname, LOG_TYPE_INFO); Log::set('mv ' . $oldname . ' ' . $newname, LOG_TYPE_INFO);
return rename($oldname, $newname); return rename($oldname, $newname);
} }
public static function rmfile($filename) public static function rmfile($filename)
{ {
Log::set('rmfile = '.$filename, LOG_TYPE_INFO); Log::set('rmfile = ' . $filename, LOG_TYPE_INFO);
return unlink($filename); return unlink($filename);
} }
@ -88,7 +92,7 @@ class Filesystem {
// If the destination directory not exists is created // If the destination directory not exists is created
// $source = /home/diego/example or /home/diego/example/ // $source = /home/diego/example or /home/diego/example/
// $destination = /home/diego/newplace or /home/diego/newplace/ // $destination = /home/diego/newplace or /home/diego/newplace/
public static function copyRecursive($source, $destination, $skipDirectory=false) public static function copyRecursive($source, $destination, $skipDirectory = false)
{ {
$source = rtrim($source, DS); $source = rtrim($source, DS);
$destination = rtrim($destination, DS); $destination = rtrim($destination, DS);
@ -107,15 +111,16 @@ class Filesystem {
} }
foreach ($iterator = new RecursiveIteratorIterator( foreach ($iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST) as $item) { RecursiveIteratorIterator::SELF_FIRST
) as $item) {
$currentDirectory = dirname($item->getPathName()); $currentDirectory = dirname($item->getPathName());
if ($skipDirectory !== $currentDirectory) { if ($skipDirectory !== $currentDirectory) {
if ($item->isDir()) { if ($item->isDir()) {
@mkdir($destination.DS.$iterator->getSubPathName()); @mkdir($destination . DS . $iterator->getSubPathName());
} else { } 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 // Delete a file or directory recursive
// The directory is delete // 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)) { if (!self::directoryExists($source)) {
return false; return false;
@ -135,12 +140,13 @@ class Filesystem {
foreach (new RecursiveIteratorIterator( foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS), new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST) as $item) { RecursiveIteratorIterator::CHILD_FIRST
if ($item->isFile() || $item->isLink()) { ) as $item) {
unlink($item); if ($item->isFile() || $item->isLink()) {
} else { unlink($item);
rmdir($item); } else {
} rmdir($item);
}
} }
if ($deleteDirectory) { if ($deleteDirectory) {
@ -209,7 +215,7 @@ class Filesystem {
return $zip->close(); return $zip->close();
} }
/* /*
| Returns the next filename if the filename already exist otherwise returns the original filename | Returns the next filename if the filename already exist otherwise returns the original filename
| |
| @path string Path | @path string Path
@ -217,7 +223,8 @@ class Filesystem {
| |
| @return string | @return string
*/ */
public static function nextFilename($filename, $path=PATH_UPLOADS) { public static function nextFilename($filename, $path = PATH_UPLOADS)
{
// Clean filename and get extension // Clean filename and get extension
$fileExtension = pathinfo($filename, PATHINFO_EXTENSION); $fileExtension = pathinfo($filename, PATHINFO_EXTENSION);
$fileExtension = Text::lowercase($fileExtension); $fileExtension = Text::lowercase($fileExtension);
@ -226,19 +233,19 @@ class Filesystem {
$filename = Text::removeQuotes($filename); $filename = Text::removeQuotes($filename);
// Search for the next filename // Search for the next filename
$tmpName = $filename.'.'.$fileExtension; $tmpName = $filename . '.' . $fileExtension;
if (Sanitize::pathFile($path.$tmpName)) { if (Sanitize::pathFile($path . $tmpName)) {
$number = 0; $number = 0;
$tmpName = $filename.'_'.$number.'.'.$fileExtension; $tmpName = $filename . '_' . $number . '.' . $fileExtension;
while (Sanitize::pathFile($path.$tmpName)) { while (Sanitize::pathFile($path . $tmpName)) {
$number = $number + 1; $number = $number + 1;
$tmpName = $filename.'_'.$number.'.'.$fileExtension; $tmpName = $filename . '_' . $number . '.' . $fileExtension;
} }
} }
return $tmpName; return $tmpName;
} }
/* /*
| Returns the filename | Returns the filename
| Example: | Example:
| @file /home/diego/dog.jpg | @file /home/diego/dog.jpg
@ -248,7 +255,8 @@ class Filesystem {
| |
| @return string | @return string
*/ */
public static function filename($file) { public static function filename($file)
{
return basename($file); return basename($file);
} }
@ -262,7 +270,8 @@ class Filesystem {
| |
| @return string | @return string
*/ */
public static function extension($file) { public static function extension($file)
{
return pathinfo($file, PATHINFO_EXTENSION); return pathinfo($file, PATHINFO_EXTENSION);
} }
@ -271,30 +280,32 @@ class Filesystem {
* @param [string] $fileOrDirectory * @param [string] $fileOrDirectory
* @return [int|bool] [bytes or false on error] * @return [int|bool] [bytes or false on error]
*/ */
public static function getSize($fileOrDirectory) { public static function getSize($fileOrDirectory)
{
// Files // Files
if (is_file($fileOrDirectory)) { if (is_file($fileOrDirectory)) {
return filesize($fileOrDirectory); return filesize($fileOrDirectory);
} }
// Directories // Directories
if (file_exists($fileOrDirectory)) { if (file_exists($fileOrDirectory)) {
$size = 0; $size = 0;
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($fileOrDirectory, FilesystemIterator::SKIP_DOTS)) as $file){ foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($fileOrDirectory, FilesystemIterator::SKIP_DOTS)) as $file) {
try { try {
$size += $file->getSize(); $size += $file->getSize();
} catch (Exception $e) { } catch (Exception $e) {
// SplFileInfo::getSize RuntimeException will be thrown on broken symlinks/errors // SplFileInfo::getSize RuntimeException will be thrown on broken symlinks/errors
} }
} }
return $size; return $size;
} }
return false; return false;
} }
public static function bytesToHumanFileSize($bytes, $decimals = 2) { public static function bytesToHumanFileSize($bytes, $decimals = 2)
$size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB'); {
$factor = floor((strlen($bytes) - 1) / 3); $size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
return sprintf("%.{$decimals}f ", $bytes / pow(1024, $factor)) . @$size[$factor]; $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 | @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')) { if (function_exists('mime_content_type')) {
return mime_content_type($file); return mime_content_type($file);
} }
@ -322,12 +334,13 @@ class Filesystem {
return false; return false;
} }
public static function symlink($from, $to) { public static function symlink($from, $to)
{
if (function_exists('symlink')) { if (function_exists('symlink')) {
Log::set('symlink from = ' . $from . ' to = ' . $to, LOG_TYPE_INFO);
return symlink($from, $to); return symlink($from, $to);
} else { } else {
return copy($from, $to); return copy($from, $to);
} }
} }
} }

View file

@ -1,27 +1,28 @@
<?php defined('BLUDIT') or die('Bludit CMS.'); <?php defined('BLUDIT') or die('Bludit CMS.');
class Pages extends dbJSON { class Pages extends dbJSON
{
protected $parentKeyList = array(); protected $parentKeyList = array();
protected $dbFields = array( protected $dbFields = array(
'title'=>'', 'title' => '',
'description'=>'', 'description' => '',
'username'=>'', 'username' => '',
'tags'=>array(), 'tags' => array(),
'type'=>'published', // published, static, draft, sticky, scheduled, autosave 'type' => 'published', // published, static, draft, sticky, scheduled, autosave
'date'=>'', 'date' => '',
'dateModified'=>'', 'dateModified' => '',
'position'=>0, 'position' => 0,
'coverImage'=>'', 'coverImage' => '',
'category'=>'', 'category' => '',
'md5file'=>'', 'md5file' => '',
'uuid'=>'', 'uuid' => '',
'allowComments'=>true, 'allowComments' => true,
'template'=>'', 'template' => '',
'noindex'=>false, 'noindex' => false,
'nofollow'=>false, 'nofollow' => false,
'noarchive'=>false, 'noarchive' => false,
'custom'=>array() 'custom' => array()
); );
function __construct() function __construct()
@ -47,7 +48,7 @@ class Pages extends dbJSON {
// Return TRUE if the page exists, FALSE otherwise // Return TRUE if the page exists, FALSE otherwise
public function exists($key) public function exists($key)
{ {
return isset( $this->db[$key] ); return isset($this->db[$key]);
} }
// Create a new page // Create a new page
@ -57,18 +58,18 @@ class Pages extends dbJSON {
$row = array(); $row = array();
// Predefined values // Predefined values
foreach ($this->dbFields as $field=>$value) { foreach ($this->dbFields as $field => $value) {
if ($field=='tags') { if ($field == 'tags') {
$tags = ''; $tags = '';
if (isset($args['tags'])) { if (isset($args['tags'])) {
$tags = $args['tags']; $tags = $args['tags'];
} }
$finalValue = $this->generateTags($tags); $finalValue = $this->generateTags($tags);
} elseif ($field=='custom') { } elseif ($field == 'custom') {
if (isset($args['custom'])) { if (isset($args['custom'])) {
global $site; global $site;
$customFields = $site->customFields(); $customFields = $site->customFields();
foreach ($args['custom'] as $customField=>$customValue) { foreach ($args['custom'] as $customField => $customValue) {
$html = Sanitize::html($customValue); $html = Sanitize::html($customValue);
// Store the custom field as defined type // Store the custom field as defined type
settype($html, $customFields[$customField]['type']); settype($html, $customFields[$customField]['type']);
@ -91,7 +92,7 @@ class Pages extends dbJSON {
// Content // Content
// This variable is not belong to the database so is not defined in $row // 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 // Parent
// This variable is not belong to the database so is not defined in $row // This variable is not belong to the database so is not defined in $row
@ -128,24 +129,24 @@ class Pages extends dbJSON {
} }
// Schedule page // 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'; $row['type'] = 'scheduled';
} }
// Create the directory // Create the directory
if (Filesystem::mkdir(PATH_PAGES.$key, true) === false) { 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); Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to create the directory [' . PATH_PAGES . $key . ']', LOG_TYPE_ERROR);
return false; return false;
} }
// Create the index.txt and save the file // Create the index.txt and save the file
if (file_put_contents(PATH_PAGES.$key.DS.FILENAME, $contentRaw) === false) { 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); Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to create the content in the file [' . FILENAME . ']', LOG_TYPE_ERROR);
return false; return false;
} }
// Checksum MD5 // Checksum MD5
$row['md5file'] = md5_file(PATH_PAGES.$key.DS.FILENAME); $row['md5file'] = md5_file(PATH_PAGES . $key . DS . FILENAME);
// Insert in database // Insert in database
$this->db[$key] = $row; $this->db[$key] = $row;
@ -156,10 +157,12 @@ class Pages extends dbJSON {
// Save database // Save database
$this->save(); $this->save();
// Create symlink for images directory // Create upload page directory for images
if (Filesystem::mkdir(PATH_UPLOADS_PAGES.$row['uuid'])) { if (!Filesystem::directoryExists(PATH_UPLOADS_PAGES . $row['uuid'])) {
Filesystem::symlink(PATH_UPLOADS_PAGES.$row['uuid'], PATH_UPLOADS_PAGES.$key); 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; return $key;
} }
@ -179,14 +182,14 @@ class Pages extends dbJSON {
// Check values from the arguments ($args) // Check values from the arguments ($args)
// If some field is missing the current value is taken // If some field is missing the current value is taken
foreach ($this->dbFields as $field=>$value) { foreach ($this->dbFields as $field => $value) {
if ( ($field=='tags') && isset($args['tags'])) { if (($field == 'tags') && isset($args['tags'])) {
$finalValue = $this->generateTags($args['tags']); $finalValue = $this->generateTags($args['tags']);
} elseif ($field=='custom') { } elseif ($field == 'custom') {
if (isset($args['custom'])) { if (isset($args['custom'])) {
global $site; global $site;
$customFields = $site->customFields(); $customFields = $site->customFields();
foreach ($args['custom'] as $customField=>$customValue) { foreach ($args['custom'] as $customField => $customValue) {
$html = Sanitize::html($customValue); $html = Sanitize::html($customValue);
// Store the custom field as defined type // Store the custom field as defined type
settype($html, $customFields[$customField]['type']); settype($html, $customFields[$customField]['type']);
@ -241,27 +244,27 @@ class Pages extends dbJSON {
$row['dateModified'] = Date::current(DB_DATE_FORMAT); $row['dateModified'] = Date::current(DB_DATE_FORMAT);
// Schedule page // 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'; $row['type'] = 'scheduled';
} }
// Move the directory from old key to new key only if the keys are different // Move the directory from old key to new key only if the keys are different
if ($newKey!==$key) { if ($newKey !== $key) {
if (Filesystem::mv(PATH_PAGES.$key, PATH_PAGES.$newKey) === false) { 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); Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to move the directory to ' . PATH_PAGES . $newKey);
return false; return false;
} }
// Regenerate the symlink to a proper directory // Regenerate the symlink to a proper directory
unlink(PATH_UPLOADS_PAGES.$key); unlink(PATH_UPLOADS_PAGES . $key);
Filesystem::symlink(PATH_UPLOADS_PAGES.$row['uuid'], PATH_UPLOADS_PAGES.$newKey); Filesystem::symlink(PATH_UPLOADS_PAGES . $row['uuid'], PATH_UPLOADS_PAGES . $newKey);
} }
// If the content was passed via arguments replace the content // If the content was passed via arguments replace the content
if (isset($args['content'])) { if (isset($args['content'])) {
// Make the index.txt and save the file. // Make the index.txt and save the file.
if (file_put_contents(PATH_PAGES.$newKey.DS.FILENAME, $args['content'])===false) { 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); Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to put the content in the file ' . FILENAME);
return false; return false;
} }
} }
@ -273,7 +276,7 @@ class Pages extends dbJSON {
$this->reindexChildren($key, $newKey); $this->reindexChildren($key, $newKey);
// Checksum MD5 // 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 // Insert in database the new row
$this->db[$newKey] = $row; $this->db[$newKey] = $row;
@ -289,14 +292,15 @@ class Pages extends dbJSON {
// This function reindex the orphan children with the new parent key // 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 // If a page has subpages and the page change his key is necesarry check the children key
public function reindexChildren($oldParentKey, $newParentKey) { public function reindexChildren($oldParentKey, $newParentKey)
if ($oldParentKey==$newParentKey){ {
if ($oldParentKey == $newParentKey) {
return false; return false;
} }
$tmp = $this->db; $tmp = $this->db;
foreach ($tmp as $key=>$fields) { foreach ($tmp as $key => $fields) {
if (Text::startsWith($key, $oldParentKey.'/')) { if (Text::startsWith($key, $oldParentKey . '/')) {
$newKey = Text::replace($oldParentKey.'/', $newParentKey.'/', $key); $newKey = Text::replace($oldParentKey . '/', $newParentKey . '/', $key);
$this->db[$newKey] = $this->db[$key]; $this->db[$newKey] = $this->db[$key];
unset($this->db[$key]); unset($this->db[$key]);
} }
@ -312,19 +316,19 @@ class Pages extends dbJSON {
// Page doesn't exist in database // Page doesn't exist in database
if (!$this->exists($key)) { 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; return false;
} }
// Delete directory and files // Delete directory and files
if (Filesystem::deleteRecursive(PATH_PAGES.$key) === false) { 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); 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 // Delete page images directory; The function already check if exists the directory
if (($uuid = $this->getUUID($key))) { if (($uuid = $this->getUUID($key))) {
if (Filesystem::deleteRecursive(PATH_UPLOADS_PAGES.$uuid) === false) { if (Filesystem::deleteRecursive(PATH_UPLOADS_PAGES . $uuid) === false) {
Log::set(__METHOD__.LOG_SEP.'Directory with images not found '.PATH_UPLOADS_PAGES.$uuid); 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]); unset($this->db[$key]);
// Save the database // Save the database
if ($this->save()===false) { if ($this->save() === false) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.'); Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to save the database file.');
} }
return true; return true;
@ -344,8 +348,8 @@ class Pages extends dbJSON {
{ {
$username = $args['username']; $username = $args['username'];
foreach ($this->db as $key=>$fields) { foreach ($this->db as $key => $fields) {
if ($fields['username']===$username) { if ($fields['username'] === $username) {
$this->delete($key); $this->delete($key);
} }
} }
@ -359,8 +363,8 @@ class Pages extends dbJSON {
$oldUsername = $args['oldUsername']; $oldUsername = $args['oldUsername'];
$newUsername = isset($args['newUsername']) ? $args['newUsername'] : 'admin'; $newUsername = isset($args['newUsername']) ? $args['newUsername'] : 'admin';
foreach ($this->db as $key=>$fields) { foreach ($this->db as $key => $fields) {
if ($fields['username']===$oldUsername) { if ($fields['username'] === $oldUsername) {
$this->db[$key]['username'] = $newUsername; $this->db[$key]['username'] = $newUsername;
} }
} }
@ -382,7 +386,7 @@ class Pages extends dbJSON {
// Returns a database with all pages // Returns a database with all pages
// $onlyKeys = true; Returns only the pages keys // $onlyKeys = true; Returns only the pages keys
// $onlyKeys = false; Returns part of the database, I do not recommend use this // $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; $tmp = $this->db;
if ($onlyKeys) { if ($onlyKeys) {
@ -394,11 +398,11 @@ class Pages extends dbJSON {
// Returns a database with published pages // Returns a database with published pages
// $onlyKeys = true; Returns only the pages keys // $onlyKeys = true; Returns only the pages keys
// $onlyKeys = false; Returns part of the database, I do not recommend use this // $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; $tmp = $this->db;
foreach ($tmp as $key=>$fields) { foreach ($tmp as $key => $fields) {
if ($fields['type']!='published') { if ($fields['type'] != 'published') {
unset($tmp[$key]); unset($tmp[$key]);
} }
} }
@ -410,11 +414,11 @@ class Pages extends dbJSON {
// Returns an array with a list of keys/database of static pages // Returns an array with a list of keys/database of static pages
// By default the static pages are sort by position // By default the static pages are sort by position
public function getStaticDB($onlyKeys=true) public function getStaticDB($onlyKeys = true)
{ {
$tmp = $this->db; $tmp = $this->db;
foreach ($tmp as $key=>$fields) { foreach ($tmp as $key => $fields) {
if ($fields['type']!='static') { if ($fields['type'] != 'static') {
unset($tmp[$key]); unset($tmp[$key]);
} }
} }
@ -426,11 +430,11 @@ class Pages extends dbJSON {
} }
// Returns an array with a list of keys/database of draft pages // 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; $tmp = $this->db;
foreach ($tmp as $key=>$fields) { foreach ($tmp as $key => $fields) {
if($fields['type']!='draft') { if ($fields['type'] != 'draft') {
unset($tmp[$key]); unset($tmp[$key]);
} }
} }
@ -441,11 +445,11 @@ class Pages extends dbJSON {
} }
// Returns an array with a list of keys/database of autosave pages // 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; $tmp = $this->db;
foreach ($tmp as $key=>$fields) { foreach ($tmp as $key => $fields) {
if($fields['type']!='autosave') { if ($fields['type'] != 'autosave') {
unset($tmp[$key]); unset($tmp[$key]);
} }
} }
@ -456,11 +460,11 @@ class Pages extends dbJSON {
} }
// Returns an array with a list of keys/database of scheduled pages // 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; $tmp = $this->db;
foreach ($tmp as $key=>$fields) { foreach ($tmp as $key => $fields) {
if($fields['type']!='scheduled') { if ($fields['type'] != 'scheduled') {
unset($tmp[$key]); unset($tmp[$key]);
} }
} }
@ -471,11 +475,11 @@ class Pages extends dbJSON {
} }
// Returns an array with a list of keys of sticky pages // Returns an array with a list of keys of sticky pages
public function getStickyDB($onlyKeys=true) public function getStickyDB($onlyKeys = true)
{ {
$tmp = $this->db; $tmp = $this->db;
foreach ($tmp as $key=>$fields) { foreach ($tmp as $key => $fields) {
if($fields['type']!='sticky') { if ($fields['type'] != 'sticky') {
unset($tmp[$key]); unset($tmp[$key]);
} }
} }
@ -489,8 +493,8 @@ class Pages extends dbJSON {
public function nextPositionNumber() public function nextPositionNumber()
{ {
$tmp = 1; $tmp = 1;
foreach ($this->db as $key=>$fields) { foreach ($this->db as $key => $fields) {
if ($fields['position']>$tmp) { if ($fields['position'] > $tmp) {
$tmp = $fields['position']; $tmp = $fields['position'];
} }
} }
@ -500,12 +504,12 @@ class Pages extends dbJSON {
// Returns the next page key of the current page key // Returns the next page key of the current page key
public function nextPageKey($currentKey) public function nextPageKey($currentKey)
{ {
if ($this->db[$currentKey]['type']=='published') { if ($this->db[$currentKey]['type'] == 'published') {
$keys = array_keys($this->db); $keys = array_keys($this->db);
$position = array_search($currentKey, $keys) - 1; $position = array_search($currentKey, $keys) - 1;
if (isset($keys[$position])) { if (isset($keys[$position])) {
$nextKey = $keys[$position]; $nextKey = $keys[$position];
if ($this->db[$nextKey]['type']=='published') { if ($this->db[$nextKey]['type'] == 'published') {
return $nextKey; return $nextKey;
} }
} }
@ -516,12 +520,12 @@ class Pages extends dbJSON {
// Returns the previous page key of the current page key // Returns the previous page key of the current page key
public function previousPageKey($currentKey) public function previousPageKey($currentKey)
{ {
if ($this->db[$currentKey]['type']=='published') { if ($this->db[$currentKey]['type'] == 'published') {
$keys = array_keys($this->db); $keys = array_keys($this->db);
$position = array_search($currentKey, $keys) + 1; $position = array_search($currentKey, $keys) + 1;
if (isset($keys[$position])) { if (isset($keys[$position])) {
$prevKey = $keys[$position]; $prevKey = $keys[$position];
if ($this->db[$prevKey]['type']=='published') { if ($this->db[$prevKey]['type'] == 'published') {
return $prevKey; return $prevKey;
} }
} }
@ -534,24 +538,24 @@ class Pages extends dbJSON {
// (int) $pageNumber, the page number // (int) $pageNumber, the page number
// (int) $numberOfItems, amount of items to return, if -1 returns all the items // (int) $numberOfItems, amount of items to return, if -1 returns all the items
// (boolean) $onlyPublished, TRUE to return only published pages // (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(); $list = array();
foreach ($this->db as $key=>$fields) { foreach ($this->db as $key => $fields) {
if ($published && $fields['type']=='published') { if ($published && $fields['type'] == 'published') {
array_push($list, $key); array_push($list, $key);
} elseif ($static && $fields['type']=='static') { } elseif ($static && $fields['type'] == 'static') {
array_push($list, $key); array_push($list, $key);
} elseif ($sticky && $fields['type']=='sticky') { } elseif ($sticky && $fields['type'] == 'sticky') {
array_push($list, $key); array_push($list, $key);
} elseif ($draft && $fields['type']=='draft') { } elseif ($draft && $fields['type'] == 'draft') {
array_push($list, $key); array_push($list, $key);
} elseif ($scheduled && $fields['type']=='scheduled') { } elseif ($scheduled && $fields['type'] == 'scheduled') {
array_push($list, $key); array_push($list, $key);
} }
} }
if ($numberOfItems==-1) { if ($numberOfItems == -1) {
return $list; return $list;
} }
@ -560,8 +564,8 @@ class Pages extends dbJSON {
$total = count($list); $total = count($list);
$init = (int) $numberOfItems * $realPageNumber; $init = (int) $numberOfItems * $realPageNumber;
$end = (int) min( ($init + $numberOfItems - 1), $total ); $end = (int) min(($init + $numberOfItems - 1), $total);
$outrange = $init<0 ? true : $init>$end; $outrange = $init < 0 ? true : $init > $end;
if (!$outrange) { if (!$outrange) {
return array_slice($list, $init, $numberOfItems, true); return array_slice($list, $init, $numberOfItems, true);
} }
@ -572,7 +576,7 @@ class Pages extends dbJSON {
// Returns the amount of pages // Returns the amount of pages
// (boolean) $onlyPublished, TRUE returns the total of published pages (without draft and scheduled) // (boolean) $onlyPublished, TRUE returns the total of published pages (without draft and scheduled)
// (boolean) $onlyPublished, FALSE returns the total of pages // (boolean) $onlyPublished, FALSE returns the total of pages
public function count($onlyPublished=true) public function count($onlyPublished = true)
{ {
if ($onlyPublished) { if ($onlyPublished) {
$db = $this->getPublishedDB(false); $db = $this->getPublishedDB(false);
@ -586,7 +590,7 @@ class Pages extends dbJSON {
public function getParents() public function getParents()
{ {
$db = $this->getPublishedDB(); $db = $this->getPublishedDB();
foreach ($db as $key=>$pageKey) { foreach ($db as $key => $pageKey) {
// if the key has slash then is a child // if the key has slash then is a child
if (Text::stringContains($pageKey, '/')) { if (Text::stringContains($pageKey, '/')) {
unset($db[$key]); unset($db[$key]);
@ -599,8 +603,8 @@ class Pages extends dbJSON {
{ {
$tmp = $this->db; $tmp = $this->db;
$list = array(); $list = array();
foreach ($tmp as $key=>$fields) { foreach ($tmp as $key => $fields) {
if (Text::startsWith($key, $parentKey.'/')) { if (Text::startsWith($key, $parentKey . '/')) {
array_push($list, $key); array_push($list, $key);
} }
} }
@ -609,16 +613,16 @@ class Pages extends dbJSON {
public function sortBy() public function sortBy()
{ {
if (ORDER_BY=='date') { if (ORDER_BY == 'date') {
return $this->sortByDate(true); return $this->sortByDate(true);
} }
return $this->sortByPosition(false); return $this->sortByPosition(false);
} }
// Sort pages by position // Sort pages by position
public function sortByPosition($HighToLow=false) public function sortByPosition($HighToLow = false)
{ {
if($HighToLow) { if ($HighToLow) {
uasort($this->db, array($this, 'sortByPositionHighToLow')); uasort($this->db, array($this, 'sortByPositionHighToLow'));
} else { } else {
uasort($this->db, array($this, 'sortByPositionLowToHigh')); uasort($this->db, array($this, 'sortByPositionLowToHigh'));
@ -628,17 +632,17 @@ class Pages extends dbJSON {
private function sortByPositionLowToHigh($a, $b) private function sortByPositionLowToHigh($a, $b)
{ {
return $a['position']>$b['position']; return $a['position'] > $b['position'];
} }
private function sortByPositionHighToLow($a, $b) private function sortByPositionHighToLow($a, $b)
{ {
return $a['position']<$b['position']; return $a['position'] < $b['position'];
} }
// Sort pages by date // Sort pages by date
public function sortByDate($HighToLow=true) public function sortByDate($HighToLow = true)
{ {
if($HighToLow) { if ($HighToLow) {
uasort($this->db, array($this, 'sortByDateHighToLow')); uasort($this->db, array($this, 'sortByDateHighToLow'));
} else { } else {
uasort($this->db, array($this, 'sortByDateLowToHigh')); uasort($this->db, array($this, 'sortByDateLowToHigh'));
@ -648,15 +652,16 @@ class Pages extends dbJSON {
private function sortByDateLowToHigh($a, $b) private function sortByDateLowToHigh($a, $b)
{ {
return $a['date']>$b['date']; return $a['date'] > $b['date'];
} }
private function sortByDateHighToLow($a, $b) private function sortByDateHighToLow($a, $b)
{ {
return $a['date']<$b['date']; return $a['date'] < $b['date'];
} }
function generateUUID() { function generateUUID()
return md5( uniqid().time() ); {
return md5(uniqid() . time());
} }
// Returns the UUID of a page, by the page key // 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 // if the UUID doesn't exits returns FALSE
function getByUUID($uuid) function getByUUID($uuid)
{ {
foreach ($this->db as $key=>$value) { foreach ($this->db as $key => $value) {
if ($value['uuid']==$uuid) { if ($value['uuid'] == $uuid) {
return $key; return $key;
} }
} }
@ -682,7 +687,7 @@ class Pages extends dbJSON {
// Returns string without HTML tags and truncated // 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::removeHTMLTags($text);
$tmpslug = Text::removeLineBreaks($tmpslug); $tmpslug = Text::removeLineBreaks($tmpslug);
@ -698,25 +703,24 @@ class Pages extends dbJSON {
$saveDatabase = false; $saveDatabase = false;
// The database need to be sorted by date // The database need to be sorted by date
foreach($this->db as $pageKey=>$fields) { foreach ($this->db as $pageKey => $fields) {
if($fields['type']=='scheduled') { if ($fields['type'] == 'scheduled') {
if($fields['date']<=$currentDate) { if ($fields['date'] <= $currentDate) {
$this->db[$pageKey]['type'] = 'published'; $this->db[$pageKey]['type'] = 'published';
$saveDatabase = true; $saveDatabase = true;
} }
} } elseif (($fields['type'] == 'published') && (ORDER_BY == 'date')) {
elseif( ($fields['type']=='published') && (ORDER_BY=='date') ) {
break; break;
} }
} }
if($saveDatabase) { if ($saveDatabase) {
if( $this->save() === false ) { if ($this->save() === false) {
Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.'); Log::set(__METHOD__ . LOG_SEP . 'Error occurred when trying to save the database file.');
return false; 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; return true;
} }
@ -724,7 +728,7 @@ class Pages extends dbJSON {
} }
// Generate a valid Key/Slug // 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 $L;
global $site; global $site;
@ -736,7 +740,7 @@ class Pages extends dbJSON {
if (Text::isEmpty($parent)) { if (Text::isEmpty($parent)) {
$newKey = Text::cleanUrl($text); $newKey = Text::cleanUrl($text);
} else { } else {
$newKey = Text::cleanUrl($parent).'/'.Text::cleanUrl($text); $newKey = Text::cleanUrl($parent) . '/' . Text::cleanUrl($text);
} }
// cleanURL can return empty string // cleanURL can return empty string
@ -744,14 +748,14 @@ class Pages extends dbJSON {
$newKey = $L->g('empty'); $newKey = $L->g('empty');
} }
if ($newKey!==$oldKey) { if ($newKey !== $oldKey) {
// Verify if the key is already been used // Verify if the key is already been used
if (isset($this->db[$newKey])) { if (isset($this->db[$newKey])) {
$i = 0; $i = 0;
while (isset($this->db[$newKey.'-'.$i])) { while (isset($this->db[$newKey . '-' . $i])) {
$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 // Change all pages with the old category key to the new category key
public function changeCategory($oldCategoryKey, $newCategoryKey) public function changeCategory($oldCategoryKey, $newCategoryKey)
{ {
foreach ($this->db as $key=>$value) { foreach ($this->db as $key => $value) {
if ($value['category']===$oldCategoryKey) { if ($value['category'] === $oldCategoryKey) {
$this->db[$key]['category'] = $newCategoryKey; $this->db[$key]['category'] = $newCategoryKey;
} }
} }
@ -806,8 +810,8 @@ class Pages extends dbJSON {
if (json_last_error() != JSON_ERROR_NONE) { if (json_last_error() != JSON_ERROR_NONE) {
return false; return false;
} }
foreach ($this->db as $pageKey=>$pageFields) { foreach ($this->db as $pageKey => $pageFields) {
foreach ($customFields as $customField=>$customValues) { foreach ($customFields as $customField => $customValues) {
if (!isset($pageFields['custom'][$customField])) { if (!isset($pageFields['custom'][$customField])) {
$defaultValue = ''; $defaultValue = '';
if (isset($customValues['default'])) { if (isset($customValues['default'])) {
@ -820,6 +824,4 @@ class Pages extends dbJSON {
return $this->save(); return $this->save();
} }
} }

View file

@ -1,6 +1,7 @@
<?php defined('BLUDIT') or die('Bludit CMS.'); <?php defined('BLUDIT') or die('Bludit CMS.');
class Page { class Page
{
protected $vars; protected $vars;
@ -12,19 +13,19 @@ class Page {
// If key is FALSE, the page is create with default values, like an empty page // If key is FALSE, the page is create with default values, like an empty page
// Useful for Page Not Found // Useful for Page Not Found
if ($key===false) { if ($key === false) {
$row = $pages->getDefaultFields(); $row = $pages->getDefaultFields();
} else { } else {
if (Text::isEmpty($key) || !$pages->exists($key)) { if (Text::isEmpty($key) || !$pages->exists($key)) {
$errorMessage = 'Page not found in database by key ['.$key.']'; $errorMessage = 'Page not found in database by key [' . $key . ']';
Log::set(__METHOD__.LOG_SEP.$errorMessage); Log::set(__METHOD__ . LOG_SEP . $errorMessage);
throw new Exception($errorMessage); throw new Exception($errorMessage);
} }
$row = $pages->getPageDB($key); $row = $pages->getPageDB($key);
} }
foreach ($row as $field=>$value) { foreach ($row as $field => $value) {
if ($field=='date') { if ($field == 'date') {
$this->setField('dateRaw', $value); $this->setField('dateRaw', $value);
} else { } else {
$this->setField($field, $value); $this->setField($field, $value);
@ -49,10 +50,10 @@ class Page {
// Returns the raw content // Returns the raw content
// This content is not markdown parser // This content is not markdown parser
// (boolean) $sanitize, TRUE returns the content sanitized // (boolean) $sanitize, TRUE returns the content sanitized
public function contentRaw($sanitize=false) public function contentRaw($sanitize = false)
{ {
$key = $this->key(); $key = $this->key();
$filePath = PATH_PAGES.$key.DS.FILENAME; $filePath = PATH_PAGES . $key . DS . FILENAME;
$contentRaw = file_get_contents($filePath); $contentRaw = file_get_contents($filePath);
if ($sanitize) { if ($sanitize) {
@ -64,7 +65,7 @@ class Page {
// Returns the full content // Returns the full content
// This content is markdown parser // This content is markdown parser
// (boolean) $sanitize, TRUE returns the content sanitized // (boolean) $sanitize, TRUE returns the content sanitized
public function content($sanitize=false) public function content($sanitize = false)
{ {
// If already set the content, return it // If already set the content, return it
$content = $this->getValue('content'); $content = $this->getValue('content');
@ -83,7 +84,7 @@ class Page {
// Parse img src relative to absolute (with domain) // Parse img src relative to absolute (with domain)
if (IMAGE_RELATIVE_TO_ABSOLUTE) { 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); $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 // Returns the first part of the content if the content is splited, otherwise is returned the full content
// This content is markdown parser // This content is markdown parser
// (boolean) $sanitize, TRUE returns the content sanitized // (boolean) $sanitize, TRUE returns the content sanitized
public function contentBreak($sanitize=false) public function contentBreak($sanitize = false)
{ {
$content = $this->content($sanitize); $content = $this->content($sanitize);
$explode = explode(PAGE_BREAK, $content); $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 // 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(); $dateRaw = $this->dateRaw();
if ($format===false) { if ($format === false) {
global $site; global $site;
$format = $site->dateFormat(); $format = $site->dateFormat();
} }
@ -122,10 +123,10 @@ class Page {
} }
// Returns the date according to locale settings and format settings // Returns the date according to locale settings and format settings
public function dateModified($format=false) public function dateModified($format = false)
{ {
$dateRaw = $this->getValue('dateModified'); $dateRaw = $this->getValue('dateModified');
if ($format===false) { if ($format === false) {
global $site; global $site;
$format = $site->dateFormat(); $format = $site->dateFormat();
} }
@ -146,16 +147,16 @@ class Page {
// Returns the permalink // Returns the permalink
// (boolean) $absolute, TRUE returns the page link with the DOMAIN, FALSE without the DOMAIN // (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 // Get the key of the page
$key = $this->key(); $key = $this->key();
if($absolute) { if ($absolute) {
return DOMAIN_PAGES.$key; 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 // Returns the previous page key
@ -199,7 +200,7 @@ class Page {
// Returns the category permalink // Returns the category permalink
public function categoryPermalink() public function categoryPermalink()
{ {
return DOMAIN_CATEGORIES.$this->categoryKey(); return DOMAIN_CATEGORIES . $this->categoryKey();
} }
// Returns the field from the array // Returns the field from the array
@ -210,9 +211,9 @@ class Page {
$categoryKey = $this->categoryKey(); $categoryKey = $this->categoryKey();
$map = $categories->getMap($categoryKey); $map = $categories->getMap($categoryKey);
if ($field=='key') { if ($field == 'key') {
return $this->categoryKey(); return $this->categoryKey();
} elseif(isset($map[$field])) { } elseif (isset($map[$field])) {
return $map[$field]; return $map[$field];
} }
@ -220,7 +221,7 @@ class Page {
} }
// Returns the user object or passing the method returns the object User method // 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(); $username = $this->username();
try { try {
@ -248,7 +249,7 @@ class Page {
// Returns the tags separated by comma // Returns the tags separated by comma
// (boolean) $returnsArray, TRUE to get the tags as an array, FALSE to get 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 ) // The tags in array format returns array( tagKey => tagName )
public function tags($returnsArray=false) public function tags($returnsArray = false)
{ {
$tags = $this->getValue('tags'); $tags = $this->getValue('tags');
if ($returnsArray) { if ($returnsArray) {
@ -267,7 +268,7 @@ class Page {
public function json($returnsArray=false) public function json($returnsArray = false)
{ {
$tmp['key'] = $this->key(); $tmp['key'] = $this->key();
$tmp['title'] = $this->title(); $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 // 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 // (boolean) $absolute, TRUE returns the complete URL, FALSE returns the filename
// If the user defined an external cover image the function returns it // 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'); $filename = $this->getValue('coverImage');
if (empty($filename)) { if (empty($filename)) {
@ -311,9 +312,9 @@ class Page {
if ($absolute) { if ($absolute) {
if (IMAGE_RESTRICT) { 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; return $filename;
@ -323,7 +324,7 @@ class Page {
public function thumbCoverImage() public function thumbCoverImage()
{ {
$filename = $this->coverImage(false); $filename = $this->coverImage(false);
if ($filename==false) { if ($filename == false) {
return false; return false;
} }
@ -333,9 +334,9 @@ class Page {
} }
if (IMAGE_RESTRICT) { 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 // 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 // (boolean) Returns TRUE if the page is published, FALSE otherwise
public function published() public function published()
{ {
return ($this->getValue('type')==='published'); return ($this->getValue('type') === 'published');
} }
// (boolean) Returns TRUE if the page is scheduled, FALSE otherwise // (boolean) Returns TRUE if the page is scheduled, FALSE otherwise
public function scheduled() public function scheduled()
{ {
return ($this->getValue('type')==='scheduled'); return ($this->getValue('type') === 'scheduled');
} }
// (boolean) Returns TRUE if the page is draft, FALSE otherwise // (boolean) Returns TRUE if the page is draft, FALSE otherwise
public function draft() public function draft()
{ {
return ($this->getValue('type')=='draft'); return ($this->getValue('type') == 'draft');
} }
// (boolean) Returns TRUE if the page is autosave, FALSE otherwise // (boolean) Returns TRUE if the page is autosave, FALSE otherwise
public function autosave() public function autosave()
{ {
return ($this->getValue('type')=='autosave'); return ($this->getValue('type') == 'autosave');
} }
// (boolean) Returns TRUE if the page is sticky, FALSE otherwise // (boolean) Returns TRUE if the page is sticky, FALSE otherwise
public function sticky() public function sticky()
{ {
return ($this->getValue('type')=='sticky'); return ($this->getValue('type') == 'sticky');
} }
// (boolean) Returns TRUE if the page is static, FALSE otherwise // (boolean) Returns TRUE if the page is static, FALSE otherwise
public function isStatic() public function isStatic()
{ {
return ($this->getValue('type')=='static'); return ($this->getValue('type') == 'static');
} }
// (string) Returns type of the page // (string) Returns type of the page
@ -460,7 +461,7 @@ class Page {
// Returns TRUE if the page is a parent, has or not children // Returns TRUE if the page is a parent, has or not children
public function isParent() 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 // 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 // Returns TRUE if the page is a child, FALSE otherwise
public function isChild() public function isChild()
{ {
return $this->parentKey()!==false; return $this->parentKey() !== false;
} }
// Returns TRUE if the page has children // Returns TRUE if the page has children
@ -519,7 +520,8 @@ class Page {
} }
// Returns the amount of minutes takes to read the page // Returns the amount of minutes takes to read the page
public function readingTime() { public function readingTime()
{
global $L; global $L;
$words = $this->content(true); $words = $this->content(true);
@ -528,11 +530,11 @@ class Page {
$average = $words / 200; $average = $words / 200;
$minutes = round($average); $minutes = round($average);
if ($minutes>1) { if ($minutes > 1) {
return $minutes.' '.$L->get('minutes'); return $minutes . ' ' . $L->get('minutes');
} }
return '~1 '.$L->get('minute'); return '~1 ' . $L->get('minute');
} }
// Returns relative time (e.g. "1 minute ago") // Returns relative time (e.g. "1 minute ago")
@ -540,7 +542,8 @@ class Page {
// Modified for Bludit // Modified for Bludit
// $complete = false : short version // $complete = false : short version
// $complete = true : full version // $complete = true : full version
public function relativeTime($complete = false) { public function relativeTime($complete = false)
{
$current = new DateTime; $current = new DateTime;
$past = new DateTime($this->getValue('dateRaw')); $past = new DateTime($this->getValue('dateRaw'));
$elapsed = $current->diff($past); $elapsed = $current->diff($past);
@ -558,16 +561,16 @@ class Page {
's' => 'second', 's' => 'second',
); );
foreach($string as $key => &$value) { foreach ($string as $key => &$value) {
if($elapsed->$key) { if ($elapsed->$key) {
$value = $elapsed->$key . ' ' . $value . ($elapsed->$key > 1 ? 's' : ' '); $value = $elapsed->$key . ' ' . $value . ($elapsed->$key > 1 ? 's' : ' ');
} else { } else {
unset($string[$key]); unset($string[$key]);
} }
} }
if(!$complete) { if (!$complete) {
$string = array_slice($string, 0 , 1); $string = array_slice($string, 0, 1);
} }
return $string ? implode(', ', $string) . ' ago' : 'Just now'; 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 // 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 // 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 (isset($this->vars['custom'][$field])) {
if ($options) { if ($options) {
@ -588,16 +591,17 @@ class Page {
// Returns an array with all pages key related to the page // Returns an array with all pages key related to the page
// The relation is based on the tags // The relation is based on the tags
public function related() { public function related()
{
global $tags; global $tags;
$pageTags = $this->tags(true); $pageTags = $this->tags(true);
$list = array(); $list = array();
// For each tag get the list of related pages // 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); $pagesRelated = $tags->getList($tagKey, 1, -1);
if(is_array($pagesRelated)) { if (is_array($pagesRelated)) {
$list = array_merge($list, $pagesRelated); $list = array_merge($list, $pagesRelated);
} }
} }
// Remove duplicates // Remove duplicates