diff --git a/class-FileUploader.php b/class-FileUploader.php index 9d82c8d..50580de 100644 --- a/class-FileUploader.php +++ b/class-FileUploader.php @@ -1,487 +1,506 @@ . // error defaults define('UPLOAD_EXTRA_ERR_INVALID_REQUEST', 101); define('UPLOAD_EXTRA_ERR_GENERIC_ERROR', 102); define('UPLOAD_EXTRA_ERR_CANT_READ_MIMETYPE', 103); define('UPLOAD_EXTRA_ERR_UNALLOWED_MIMETYPE', 104); define('UPLOAD_EXTRA_ERR_UNALLOWED_FILE', 105); define('UPLOAD_EXTRA_ERR_OVERSIZE', 106); define('UPLOAD_EXTRA_ERR_FILENAME_TOO_SHORT', 107); define('UPLOAD_EXTRA_ERR_FILENAME_TOO_LONG', 108); define('UPLOAD_EXTRA_ERR_CANT_SAVE_FILE', 109); // fifo system default define_default( 'MAGIC_MIME_FILE', null ); +// default permissions for new directories +define_default( 'CHMOD_WRITABLE_DIRECTORY', 0755 ); + /** * Manage uploads with security in mind */ class FileUploader { private $fileEntry; private $args; private $mimeTypes; /** * Create a FileUploader object. * * @param string $fileEntry See it as $_POST[ $fileEntry ]. * @param array $args Arguments. * @see FileUploader::setArgs() */ function __construct( $fileEntry, $args = [], $mimeTypes = null ) { $this->fileEntry = $fileEntry; $this->setArgs($args); if( null === $mimeTypes ) { $this->mimeTypes = expect( 'mimeTypes' ); } else { $this->mimeTypes = $mimeTypes; } } /** * Set options. * * @param array $args Arguments. * 'i' => int * If the user uploaded multiple filenames, this is the index. * 'slug' => bool * If the filename have to be slugged. * Default: true * 'override-filename' => string * The filename is preserved if you don't specify it here. * E.g.: 'my-pic' * Default: The original filename. * 'pre-filename' => string * Filename prefix. * E.g.: date('Y-m-d-') * Default: '' * 'post-filename' => string * Filename suffix. * E.g.: '_XL' * Default: '' * 'category' => string|null * Allowed MIME category/categories. * Default: null (all the categories) * 'min-length-filename' => int * Min length of the filename (no extension, no pathname). * E.g.: 5 * Default: 2 * 'max-length-filename' => int * Max length of the filename (no extension, no pathname). * E.g.: 40 * Default: 200 * 'dont-overwrite' => boolean * If the filename already exists can append a progressive number. * E.g.: false (overwrite the file if already exists) * Default: true */ public function setArgs( $args ) { $this->args = array_replace( [ 'i' => null, 'slug' => true, 'override-filename' => null, 'pre-filename' => '', 'post-filename' => '', 'autoincrement' => '-%d', 'category' => null, 'max-filesize' => null, 'min-length-filename' => 2, 'max-length-filename' => 200, 'dont-overwrite' => true ], $args ); } /** * Have this request any sense? * * @return bool */ public function uploadRequestOK() { $err = $this->getFileInfo( 'error' ); return null !== $err && ! is_array( $err ); } /** * Check if the user "is uploading" a file. * * This obviusly see if this request have sense. * * @return bool If the user have sent a valid file or not. */ public function fileChoosed() { return $this->uploadRequestOK() && $this->getFileInfo( 'error' ) !== UPLOAD_ERR_NO_FILE; } /** * Get a file property */ public function getFileInfo( $property ) { $v = @ $_FILES[ $this->fileEntry ][ $property ]; $i = $this->args[ 'i' ]; if( isset( $i ) ) { $v = @ $v[ $i ]; } return $v; } /** * Upload the filename to a filepath. * * @param string $pathname The absolute folder WITHOUT trailing slash * @param int $status Exception code * @param string $filename File name without extension * @param string $ext File extension with dot * @param string $mime MIME type */ public function uploadTo( $pathname, & $status, & $filename = null, & $ext = null, & $mime = null ) { if( ! $this->uploadRequestOK() ) { $status = UPLOAD_EXTRA_ERR_INVALID_REQUEST; return false; } $status = $this->getFileInfo( 'error ' ); switch( $status ) { case UPLOAD_ERR_NO_FILE: case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_TMP_DIR: case UPLOAD_ERR_CANT_WRITE: case UPLOAD_ERR_EXTENSION: // Return the same error return false; case UPLOAD_ERR_OK: // It's OK break; default: error( "unexpected FileUploader error status: $status" ); $status = UPLOAD_EXTRA_ERR_GENERIC_ERROR; return false; } // Check filesize (too much or zero) if( $this->args['max-filesize'] !== null && $this->getFileInfo( 'size' ) > $this->args['max-filesize'] || ! $this->getFileInfo( 'size' ) ) { $status = UPLOAD_EXTRA_ERR_OVERSIZE; return false; } // Check original MIME type $mime = self::fileMimetype( $this->getFileInfo( 'tmp_name' ) ); if( ! $mime ) { $status = UPLOAD_EXTRA_ERR_CANT_READ_MIMETYPE; return false; } // Check if MIME type it's allowed if( ! $GLOBALS['mimeTypes']->isMimetypeInCategory( $mime, $this->args['category'] ) ) { $status = UPLOAD_EXTRA_ERR_UNALLOWED_MIMETYPE; return false; } // Check original file extension $ext = $GLOBALS['mimeTypes']->getFileExtensionFromExpectations( $this->getFileInfo( 'name' ), $this->args['category'], $mime ); if( ! $ext ) { $status = UPLOAD_EXTRA_ERR_UNALLOWED_FILE; return false; } if( $this->args['override-filename'] === null ) { // Strip original complete file name from extension $filename = substr( $this->getFileInfo( 'name' ), 0, - ( strlen( $ext ) + 1 ) ); } else { // Override file name $filename = $this->args['override-filename']; } // Append prefix (if any) $filename = $this->args['pre-filename'] . $filename; if( $this->args['slug'] ) { $filename = generate_slug( $filename ); } // Make sure that the destination folder exists create_path( $pathname ); // Append a suffix to the filename if it already exists $filename = self::searchFreeFilename( $pathname . _ , $filename, $ext, $this->args ); // File name with extension $complete_filename = "$filename.$ext"; // File name length if( strlen($complete_filename) < $this->args['min-length-filename'] ) { $status = UPLOAD_EXTRA_ERR_FILENAME_TOO_SHORT; return false; } // File name length if( strlen($complete_filename) > $this->args['max-length-filename'] ) { $status = UPLOAD_EXTRA_ERR_FILENAME_TOO_LONG; return false; } $moved = move_uploaded_file( $this->getFileInfo( 'tmp_name' ), $pathname . _ . $complete_filename ); if( ! $moved ) { $status = UPLOAD_EXTRA_ERR_CANT_SAVE_FILE; return false; } $status = UPLOAD_ERR_OK; return $complete_filename; } /** * Prefilled error messages. * * @param int $status The $status var from FileUploader::uploadTo() * @return string The proper error message. */ public function getErrorMessage( $status ) { switch( $status ) { case UPLOAD_ERR_OK: // You should avoid this. Is not an error! return __("Upload completato con successo."); case UPLOAD_ERR_NO_FILE: return __("Non è stato selezionato alcun file."); case UPLOAD_ERR_INI_SIZE: return sprintf( __( "Il file eccede i limiti di sistema (%s)." ), human_filesize( self::uploadMaxFilesize() ) ); case UPLOAD_ERR_FORM_SIZE: return __("Il file eccede i limiti imposti."); case UPLOAD_EXTRA_ERR_OVERSIZE: $size = $this->getFileInfo( 'size' ); return sprintf( __( "Il file pesa %s. Non può superare %s."), $size ? human_filesize( $this->getFileInfo( 'size' ) ) : __( "troppo" ), human_filesize( $this->args['max-filesize'] ) ); case UPLOAD_EXTRA_ERR_CANT_SAVE_FILE: return __("Impossibile salvare il file."); case UPLOAD_EXTRA_ERR_CANT_READ_MIMETYPE: return __("Il MIME del file non è validabile."); case UPLOAD_EXTRA_ERR_UNALLOWED_MIMETYPE: $mime = self::fileMimetype( $this->getFileInfo( 'tmp_name' ) ); return sprintf( __("Il file é di un MIME type non concesso: %s."), esc_html( $mime ) ); case UPLOAD_EXTRA_ERR_UNALLOWED_FILE: $mime = self::fileMimetype( $this->getFileInfo( 'tmp_name' ) ); $allowed_filetypes = $this->mimeTypes->getFiletypes( $this->args['category'], $mime ); return multi_text( count( $allowed_filetypes ), sprintf( __("Il file ha un'estensione non valida. Estensioni attese: %s."), esc_html( implode(', ', $allowed_filetypes ) ) ), sprintf( __("Il file ha un'estensione non valida. Estensione attesa: %s."), esc_html( $allowed_filetypes[0] ) ) ); case UPLOAD_EXTRA_ERR_FILENAME_TOO_SHORT: return __("Il file ha un nome troppo breve."); case UPLOAD_EXTRA_ERR_FILENAME_TOO_LONG: return __("Il file ha un nome troppo lungo."); case UPLOAD_EXTRA_ERR_GENERIC_ERROR: return __("Errore di caricamento sconosciuto."); } error( "unexpected FileUploader error status: $status" ); return __("Errore di caricamento alquanto sconosciuto."); } /** * When you want a not-taken file name WITHOUT extension. * * @param string $filepath Absolute directory with trailing slash * @param string $filename 1° arg of FileUploader::buildFilename() * @param string $ext 2° arg of FileUploader::buildFilename() * @param string $args 3° args of FileUploader::buildFilename() * @param null|string $build_filename NULL for 'FileUploader::buildFilename' * @return string */ public static function searchFreeFilename( $filepath, $filename, $ext, $args, $build_filename = null ) { if( null === $build_filename ) { $build_filename = 'FileUploader::buildFilename'; } if( ! is_callable( $build_filename ) ) { error_die( sprintf( __("Il 5° argomento di %s dovrebbe essere il nome di una funzione ma non esiste alcuna funzione '%s'."), __FUNCTION__, esc_html( $build_filename ) ) ); } $i = null; while( file_exists( $filepath . call_user_func($build_filename, $filename, $ext, $args, $i) . ".$ext" ) ) { // http://php.net/manual/en/language.operators.increment.php // «Decrementing NULL values has no effect too, but incrementing them results in 1.» $i++; if($i === 30) { exit; } } return call_user_func( $build_filename, $filename, $ext, $args, $i ); } /** * Default mode to build a file name WITHOUT extension. * It's called multiple times in FileUploader::searchFreeFilename(). * * Create your own but NEVER get two equal strings if $i changes. * * @param string $filename File name without extension * @param string $ext File name extension without dot * @param array $args Custom stuff * @param int $i Received from FileUploader::searchFreeFilename() as * auto increment if the precedent file name already exists. * To be used to-get (or not-to-get) a suffix. * It's NULL during the first call. * @return string File name (with extension) */ public static function buildFilename( $filename, $ext, $args, $i = null ) { if( empty( $args['autoincrement'] ) ) { $args['autoincrement'] = '-%d'; } if( empty( $args['post-filename'] ) ) { $args['post-filename'] = ''; } $suffix = ( $i === null ) ? '' : sprintf( $args['autoincrement'], $i ); return $filename . $suffix . $args['post-filename']; } /** * Guess the MIME type from a file. * It requires the existence of the MAGIC_MIME_FILE. * * @param string $filepath The file path. * @param bool $pure true for 'image/png; something'; or false for 'image/png'. * @return string|false */ public static function fileMimetype( $filepath, $pure = false ) { $finfo = finfo_open(FILEINFO_MIME, MAGIC_MIME_FILE); if( ! $finfo ) { error( sprintf( 'error opening fileinfo database placed in %s', MAGIC_MIME_FILE ) ); return false; } $mime = finfo_file( $finfo, $filepath ); if( ! $mime ) { error( "can't detect MIME of file $filepath" ); return false; } if( ! $pure ) { $mime = explode(';', $mime, 2); // Split "; charset" $mime = $mime[0]; } return $mime; } /** * Generate multiple FileUploader constructors * * @generator */ public static function multiple( $name, $args = [] ) { $files = isset( $_FILES[ $name ] ) ? $_FILES[ $name ] : []; foreach( $files[ 'name' ] as $i => $_ ) { yield new self( $name, array_replace( $args, [ 'i' => $i ] ) ); } } /** * Convert a php.ini name with a file weight value to bytes * * @param $name string php_ini variable name * @return int bytes */ public static function iniToBytes( $name ) { $v = trim( ini_get( $name ) ); $last = strtolower( $v[ strlen( $v ) - 1 ] ); switch( $last ) { case 'g': $v *= 1024; case 'm': $v *= 1024; case 'k': $v *= 1024; } return (int) $v; } /** * Get the max_post_size in bytes * * @return int */ public static function maxPOSTSize() { return self::iniToBytes( 'post_max_size' ); } /** * Get the upload_max_filesize in bytes * * @return int */ public static function uploadMaxFilesize() { return self::iniToBytes( 'upload_max_filesize' ); } /** * Check if the request is over the max_post_size * * @return bool */ public static function isOverMaxPOSTSize() { return isset( $_SERVER[ 'CONTENT_LENGTH' ] ) && $_SERVER[ 'CONTENT_LENGTH' ] > self::maxPOSTSize(); } /** * Check if the request is over the upload_max_filesize * * @return bool */ public static function isOverMaxUploadFilesize() { return empty( $_FILES ) && isset( $_SERVER[ 'CONTENT_LENGTH' ] ) && $_SERVER[ 'CONTENT_LENGTH' ] > self::uploadMaxFilesize(); } + + /* + * Create a pathname in the filesystem + * + * @param $path string + * @param $chmod string + */ + public static function createPath( $path, $chmod = null ) { + if( null === $chmod ) { + $chmod = CHMOD_WRITABLE_DIRECTORY; + } + if( file_exists( $path ) || mkdir( $path, $chmod, true ) ) { + return true; + } + error( "unable to create path $path" ); + } } diff --git a/functions.php b/functions.php index 873db98..deb0578 100644 --- a/functions.php +++ b/functions.php @@ -1,765 +1,764 @@ . // unuseful shortcuts when you want a SELECT * query define('DOT', '.'); define('STAR', '*'); function define_default( $constant_name, $default_value ) { defined( $constant_name ) or define( $constant_name, $default_value ); } function selected( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { return html_property_when_matching( 'selected', 'selected', $helper, $current, $force); } function checked( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { return html_property_when_matching( 'checked', 'checked', $helper, $current, $force); } function disabled( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { return html_property_when_matching( 'disabled', 'disabled', $helper, $current, $force ); } function _checked( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { echo checked( $helper, $current, $force ); } function _selected( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { echo selected( $helper, $current, $force ); } function _disabled( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { echo disabled( $helper, $current, $force ); } function html_property_when_matching( $property, $value, $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { if( $helper === $current || $helper && PHP_INT_MAX === $current || $force ) { return HTML::property( $property, $value ); } return ''; } function _value( $v ) { echo HTML::property( 'value', $v ); } /** * Force something to be an array. * * @return mixed|array * @return array */ function force_array( & $a ) { if( ! is_array( $a ) ) { $a = [ $a ]; } } /** * Enfatize a substring */ function enfatize_substr( $heystack, $needle, $pre = '', $post = '' ) { return StringStuff::enfatizeSubstr( $heystack, $needle, $pre, $post ); } /** * SQL query escape string * @see DB#escapeString() */ function esc_sql($s) { return DB::instance()->escapeString($s); } /** * Same as esc_sql() but also avoid '%'s. * * @param string $s * @return string */ function esc_sql_like($s) { $s = str_replace('%', '\%', $s); return esc_sql($s); } /** * HTML escape * * @param string $s * @return string */ function esc_html($s) { return htmlspecialchars($s); } /** * HTML escape print * * @param string * @return void */ function _esc_html($s) { echo htmlentities($s); } /** * Execute a simple query. * @see DB#getResults() */ function query($query) { return DB::instance()->query($query); } /** * Execute a query and return an array of objects. * * @param string $query SQL query * @param string $class Class name to encapsulate the result set * @return array * @see DB#getResults() */ function query_results($query, $class = null, $args = [] ) { return DB::instance()->getResults($query, $class, $args); } /** * Execute a query and return a Generator * * @param string $query SQL query * @param string $class Class name to encapsulate the result set * @generator * @see DB#getGenerator() */ function query_generator( $query, $class = null, $args = [] ) { return DB::instance()->getGenerator( $query, $class, $args ); } /** * Execute a query and return an object. * * @param string $query SQL query * @param string $class Class name to encapsulate the result set * @return null|Object * @see DB#getRow() */ function query_row($query, $class = null, $args = [] ) { return DB::instance()->getRow($query, $class, $args); } /** * Execute a query and return a single value. * @see DB#getValue() */ function query_value($query, $value, $class = null) { return DB::instance()->getValue($query, $value, $class); } /** * Executes one or multiple queries which are concatenated by a semicolon * @see DB#multiQuery() */ function multiquery( $queries ) { return DB::instance()->multiQuery( $queries ); } /** * Database table full with prefix. * * @param string $t Table name (as 'test') * @return string Table name with prefix (as '`site01_test`') * @see DB#getTable() */ function T($t, $as = false) { return DB::instance()->getTable($t, $as); } define('T', 'T'); define('JOIN', 'JOIN'); // Stupid shurtcut for string context $GLOBALS[T] = function($t, $as = false) { return T($t, $as = false); }; // Stupid shortcut for string context for listing tables $GLOBALS[JOIN] = function($t) { return DB::instance()->getTables( func_get_args() ); }; /** * Insert a row in the specified database table. * @param string $table * @param DBCols[] * @param $args array * @see DB#insertRow() */ function insert_row( $table, $cols, $args = [] ) { return DB::instance()->insertRow( $table, $cols, $args ); } /** * If the table has an AUTOINCREMENT you can get the last inserted index * after an insert_row(). * @return int * @see DB#getLastInsertedID() */ function last_inserted_ID() { if( ! DB::instanced() ) { error_die( 'cannot obtain last inserted ID without database connection' ); } return DB::instance()->getLastInsertedID(); } /** * Insert multiple values in the specified database table * @param string $table * @param array $cols * @param array $values * @see DB#insert() */ function insert_values($table, $cols, $values) { return DB::instance()->insert($table, $cols, $values); } /** * Update rows in the specified database table * @param string $table * @param DBCol[] $cols * @param string $condition * @see DB#update() */ function query_update($table, $cols, $condition, $after = '') { DB::instance()->update($table, $cols, $condition, $after); } /** * Alias for htmlspecialchars(). * @param string $s * @return string */ function esc_attr($s) { return htmlspecialchars($s); } /** * @param string * @return void */ function _esc_attr($s) { echo htmlspecialchars($s); } /* * Friendly symlinks */ function register_mimetypes($category, $mimetypes) { MimeTypes::instance()->registerMimetypes($category, $mimetypes); } function get_mimetypes($category = null) { return MimeTypes::instance()->getMimetypes($category); } /** * @param string $role User role * @param string|string[] $permissions Permissions */ function register_permissions($role, $permissions) { Permissions::instance()->registerPermissions($role, $permissions); } /** * @param string $role_to New role * @param string $role_from Existing role */ function inherit_permissions($role_to, $role_from, $other_permissions = []) { Permissions::instance()->inheritPermissions($role_to, $role_from, $other_permissions); } function register_js($javascript_uid, $url, $position = null) { return RegisterJS::instance()->register( $javascript_uid, $url, $position ); } function enqueue_js($javascript_uid, $position = null) { return RegisterJS::instance()->enqueue( $javascript_uid, $position ); } function register_css($css_uid, $url) { return RegisterCSS::instance()->register($css_uid, $url); } function enqueue_css($css_uid) { return RegisterCSS::instance()->enqueue($css_uid); } function add_menu_entries($menuEntries) { Menu::instance()->add($menuEntries); } function get_menu_entry($uid) { return Menu::instance()->getMenuEntry($uid); } function get_children_menu_entries($parentUid) { return Menu::instance()->getChildrenMenuEntries($parentUid); } function register_module($module_uid) { return RegisterModule::instance()->register($module_uid); } function inject_in_module($module_uid, $callback) { return RegisterModule::instance()->injectFunction($module_uid, $callback); } function load_module($module_uid) { return RegisterModule::instance()->loadModule($module_uid); } function get_table_prefix() { return DB::instance()->getPrefix(); } function register_option($option_name) { return DB::instance()->registerOption($option_name); } function get_option( $name, $default = '' ) { return Options::instance()->get( $name, $default ); } function set_option( $name, $value, $autoload = true ) { return Options::instance()->set( $name, $value, $autoload ); } function remove_option( $name ) { return Options::instance()->remove( $name ); } /** * Get the current logged user. * * @param null|string $property Property name * @return mixed|Sessionuser Property, or entire Sessionuser object. */ function get_user( $property = null ) { $user = Session::instance()->getUser(); if( null === $property ) { return $user; } return $user ? $user->get( $property ) : null; } /** * Try to login using $_POST['user_uid'] and $_POST['user_password']. * * @param int $status * @see Session::login() */ function login(& $status = null, $user_uid = null, $user_password = null) { return Session::instance()->login($status, $user_uid, $user_password); } function logout() { return Session::instance()->destroy(); } function register_language($code, $aliases = [], $encode = null, $iso = null, $human = null) { return RegisterLanguage::instance()->registerLanguage($code, $aliases, $encode, $iso, $human); } function register_default_language($default) { return RegisterLanguage::instance()->setDefaultLanguage($default); } function find_language($language_alias) { return RegisterLanguage::instance()->getLanguage($language_alias); } function apply_language($language_alias = null) { return RegisterLanguage::instance()->applyLanguage($language_alias); } function latest_language() { return RegisterLanguage::instance()->getLatestLanguageApplied(); } function all_languages() { return RegisterLanguage::instance()->getAll(); } function get_num_queries() { if( DB::instanced() ) { return DB::instance()->getNumQueries(); } return 0; } function is_logged() { return Session::instance()->isLogged(); } /** * @param string $permission Permission uid * @param User|null $user Specified user * @return bool */ function has_permission($permission, $user = null) { if( ! $user ) { $user = Session::instance()->getUser(); } $role = $user ? $user->get( 'user_role' ) : false; if( ! $role ) { $role = DEFAULT_USER_ROLE; } return Permissions::instance()->hasPermission($role, $permission); } /** * Add a directory to a base URL or a pathname. * If the base URL it is not defined, a slash ('/') is appended to the URL. * The base URL could end with a slash ('/') or not. * * @param string $base_URL Base URL with/without any slash at start * @param string $dir Directory without any slash * @return string URL / Pathname */ function append_dir( $base_URL, $dir = '/' ) { $base_URL = rtrim( $base_URL, '/' ); $dir = ltrim( $dir, '/' ); return $base_URL . _ . $dir; } /** * Normalize a site page * * @param $page string Whatever, a full URL, a relative pathname e.g. 'page', an absolute one, etc. * @param $full_url boolean As default it try to avoid full URLs */ function site_page( $page, $full_url = false ) { $first = @$page[ 0 ]; if( $first === '#' ) { return $page; // '#anchor' } if( $first === '/' ) { if( @$page[ 1 ] === '/' ) { return $page; // "//example.org" } return append_dir( $full_url ? BASE_URL : '', $page ); } elseif( preg_match( '#^[a-z]+://#', $page ) === 1 ) { return $page; // "ftp://example.org" } return append_dir( $full_url ? URL : ROOT, $page ); } function single_quotes($s) { return "'$s'"; } function double_quotes($s) { return '"' . $s . '"'; } function this_folder() { return dirname( $_SERVER['PHP_SELF'] ); } /** * Truncate a string if it's over a specific length. * You can specify the end of the string if it's truncated. * * @param string %s Input string * @param int $max_length Max string length * @param string $blabla Optional. If string length is over $max_length, $blabla it's appended after $string * @deprecated Use mb_strimwidth */ function str_truncate($s, $max_length, $blabla = '', $encoding = null ) { if( ! $encoding ) { $encoding = mb_internal_encoding(); } return mb_strimwidth($s, 0, $max_length, $blabla, $encoding); } /** * Choose the appropriate string. * '%' will be replaced with the input number. * * @param int $n Input number. * @param string $text_multi Text displayed if n > 1 * @param string $text_one Text displayed if n == 1 * @param string $text_no Text displayed if n < 1 */ function multi_text($n, $text_multi, $text_one, $text_no = '') { if($n > 1) { return str_replace('%', $n, $text_multi); } elseif($n == 1) { return $text_one; } return $text_no; } /** * Simple HTTP redirects. */ function http_redirect($url, $http_response_code = 0) { header("Location: $url", true, $http_response_code); exit; } /** * Check if the request is under HTTPS */ function is_https() { return ! empty( $_SERVER['HTTPS'] ); } /** * Get the protocol of the request * @see use PROTOCOL */ function URL_protocol() { return is_https() ? 'https://' : 'http://'; } /** * Get the domain of the request * @see DOMAIN */ function URL_domain() { return isset( $_SERVER[ 'SERVER_NAME' ] ) ? $_SERVER[ 'SERVER_NAME' ] : php_uname( 'n' ); } /** * Get the explicit port of the request * @see PORT * @return string */ function URL_port() { if( isset( $_SERVER[ 'SERVER_PORT' ] ) ) { $p = (int) $_SERVER[ 'SERVER_PORT' ]; if( 80 !== $p && 443 !== $p ) { return ":$p"; } } return ''; } function URL_root() { $root = this_folder(); if( $root === _ ) { return ''; } return $root; } /** * Get a secured version of a string */ function generate_slug($s, $max_length = -1, $glue = '-', & $truncated = false) { return StringStuff::slug($s, $max_length, $glue, $truncated); } function http_build_get_query( $url, $data ) { $data = http_build_query( $data ); return $data ? "$url?$data" : $url; } /** * HTTP 503 headers */ function http_503() { OutputUtilities::header503(); } /** * It scares the user with an error message (and dies). */ function error_die( $msg ) { OutputUtilities::WSOD( $msg ); } /** * It logs an error message and eventually prints it when DEBUG * * @return void */ function error( $msg ) { OutputUtilities::error( $msg ); } /** * Translates a string * * @param string $msgid String to be translated * @return string Translated string (or original) */ function __( $msgid ) { // is native GNU GETTEXT implementation? static $native = null; if( null === $native ) { $native = RegisterLanguage::instance()->isNative(); } // low-level GNU Gettext call if( $native ) { return _( $msgid ); } // high-level GNU Gettext (simpler but slower) static $instance = false; if( ! $instance ) { $instance = MoLoader::instance()->getTranslator(); } return $instance->gettext( $msgid ); } /** * Shortcut for echoing a translated string */ function _e( $s ) { echo __( $s ); } function http_json_header($charset = null) { if( null === $charset ) { $charset = CHARSET; } header( "Content-Type: application/json; charset=$charset" ); } /** * Unset the empty values in an array or an object as well recursively * * @param $data mixed * @return array */ function array_unset_empty( $data ) { $is_array = is_array( $data ); if( $is_array || is_object( $data ) ) { foreach( $data as $k => $v ) { if( is_array( $v ) || is_object( $v ) ) { if( $is_array ) { $data [ $k ] = array_unset_empty( $v ); } else { $data->{ $k } = array_unset_empty( $v ); } } elseif( empty( $v ) && ! is_int( $v ) ) { if( $is_array ) { unset( $data [ $k ] ); } else { unset( $data->{ $k } ); } } } } return $data; } /** * Send a JSON (stripping out unuseful values) and quit * * Falsy elements are not returned * * @param $data mixed */ function json( $data ) { http_json_header(); echo json_encode( array_unset_empty( $data ) ); exit; } /** * Send a JSON error and quit * * @param $http_code int HTTP response code * @param $code string Error code * @param $msg string Error human message */ function json_error( $http_code, $code, $msg ) { http_response_code( $http_code ); json( [ 'error' => [ 'code' => $code, 'message' => $msg, ] ] ); } /** * Get the MIME type of a file. * @see MimeTypes::fileMimetype() */ function get_mimetype($filepath, $pure = false) { return MimeTypes::fileMimetype( $filepath, $pure = false ); } /** * Know if a file belongs to a certain category * @see MimeTypes::isMimetypeInCategory() */ function is_file_in_category($filepath, $category) { $mime = get_mimetype($filepath); return MimeTypes::instance()->isMimetypeInCategory($mime , $category); } /** * Get the file extension */ function get_file_extension_from_expectations($filename, $category) { return MimeTypes::instance()->getFileExtensionFromExpectations($filename, $category); } function is_image($filepath) { return is_file_in_category($filepath, 'image'); } function is_audio($filepath) { return is_file_in_category($filepath, 'audio'); } function is_video($filepath) { return is_file_in_category($filepath, 'video'); } function is_document($filepath) { return is_file_in_category($filepath, 'document'); } function is_closure($t) { return is_object($t) && ($t instanceof Closure); } /** * Get the human filesize from bytes * * @param $filesize int bytes * @param $glue string * @return string */ function human_filesize( $filesize, $glue = ' ' ) { return OutputUtilities::humanFilesize( $filesize, $glue = ' ' ); } /* - * Create a pathname in the filesystem + * Create a directory + * + * @param $path string + * @param $chmod string */ -function create_path($path, $chmod = CHMOD_WRITABLE_DIRECTORY) { - if( file_exists($path) || mkdir($path, $chmod, true) ) { - return true; - } - error( "unable to create path $path" ); - return false; +function create_path( $path, $chmod = null ) { + return FileUploader::createPath( $path, $chmd ); } /** * @see FileUploader::searchFreeFilename() */ function search_free_filename( $filepath, $filename, $ext, $args, $build_filename = null ) { return FileUploader::searchFreeFilename( $filepath, $filename, $ext, $args, $build_filename = null ); } /** * I use this to clean user input before DB#insert() * * @param string $s Input string * @param int $max Max length */ function luser_input($s, $max) { return mb_strimwidth( trim($s), 0, $max, ''); } /** * Used to know much is the page load * * @return mixed Execution time */ function get_page_load( $decimals = 6 ) { return round( microtime( true ) - $_SERVER[ 'REQUEST_TIME_FLOAT' ], $decimals ); } diff --git a/load.php b/load.php index eff6945..975f0e7 100644 --- a/load.php +++ b/load.php @@ -1,90 +1,84 @@ . /* * Start the boz-php framework */ // URL slash defined('_') or define('_', '/'); // directory separator defined('__') or define('__', DIRECTORY_SEPARATOR); // boz-php directory define('BOZ_PHP', __DIR__ ); // load the functions require BOZ_PHP . __ . 'functions.php'; // default anonymous user role define_default( 'DEFAULT_USER_ROLE', 'UNREGISTERED' ); // in debug mode you see errors in HTML define_default( 'DEBUG', false ); // log every SQL query and eventually print them in HTML whenever DEBUG is also enabled define_default( 'DEBUG_QUERIES', false ); // HTTP protocol e.g. 'https' define_default( 'PROTOCOL', URL_protocol() ); // domain name e.g. 'reyboz.it' define_default( 'DOMAIN', URL_domain() ); // HTTP port e.g. ':8080' define_default( 'PORT', URL_port() ); // absolute URL directory without trailing slash e.g. '/myapp' or '' define_default( 'ROOT', URL_root() ); // URL without the ROOT define_default( 'BASE_URL', PROTOCOL . DOMAIN . PORT ); // URL with the ROOT define_default( 'URL', BASE_URL . ROOT ); -// default permissions for new directories -define_default( 'CHMOD_WRITABLE_DIRECTORY', 0777 ); - -// default permissions for new files -define_default( 'CHMOD_WRITABLE_FILE', 0666 ); - // request charset define_default( 'CHARSET', 'utf-8' ); // trailing JavaScript / CSS parameter e.g. 'v=1' (will be automatically prefixed with &/?) define_default( 'CACHE_BUSTER', '' ); // autoload boz-php classes spl_autoload_register( function( $c ) { $path = BOZ_PHP . __ . "class-$c.php"; if( is_file( $path ) ) { require $path; } } ); if( ! defined( 'REQUIRE_LOAD_POST' ) ) { if( defined( 'ABSPATH' ) ) { define( 'REQUIRE_LOAD_POST', ABSPATH . __ . 'load-post.php' ); } else { error_die( "Please define ABSPATH or at least disable REQUIRE_LOAD_POST" ); } } if( REQUIRE_LOAD_POST ) { require REQUIRE_LOAD_POST; }