Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sat, Feb 22, 12:02 AM

in-portal

Index: branches/5.2.x/core/kernel/utility/formatters/upload_formatter.php
===================================================================
--- branches/5.2.x/core/kernel/utility/formatters/upload_formatter.php (revision 16028)
+++ branches/5.2.x/core/kernel/utility/formatters/upload_formatter.php (revision 16029)
@@ -1,627 +1,627 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2011 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class kUploadFormatter extends kFormatter
{
var $DestinationPath;
var $FullPath;
/**
* File helper reference
*
* @var FileHelper
*/
var $fileHelper = NULL;
/**
* Uploaded files, that are ordered as required (both live & temp images in one list)
*
* @var Array
* @access protected
*/
protected $sorting = Array ();
/**
* Creates formatter instance
*
* @access public
*/
public function __construct()
{
parent::__construct();
$this->fileHelper = $this->Application->recallObject('FileHelper');
if ( $this->DestinationPath ) {
$this->FullPath = FULL_PATH . $this->DestinationPath;
}
}
/**
* Processes file uploads from form
*
* @param mixed $value
* @param string $field_name
* @param kDBItem $object
* @return mixed
* @access public
*/
public function Parse($value, $field_name, &$object)
{
$value = $this->Application->HttpQuery->unescapeRequestVariable($value);
$options = $object->GetFieldOptions($field_name);
if ( getArrayValue($options, 'upload_dir') ) {
$this->DestinationPath = $options['upload_dir'];
$this->FullPath = FULL_PATH . $this->DestinationPath;
}
if ( is_array($value) && isset($value['tmp_ids']) ) {
// SWF Uploader
return $this->_processFlashUploader($value, $field_name, $object);
}
return $this->_processRegularUploader($value, $field_name, $object);
}
/**
* Handles uploaded files, provided by Flash uploader
*
* @param Array|string $value
* @param string $field_name
* @param kDBItem $object
* @return string
* @access protected
*/
protected function _processFlashUploader($value, $field_name, $object)
{
$options = $object->GetFieldOptions($field_name);
$this->sorting = isset($value['order']) ? explode('|', $value['order']) : Array ();
if ( $value['tmp_deleted'] ) {
$n_upload = Array ();
$deleted = explode('|', $value['tmp_deleted']);
$upload = explode('|', $value['upload']);
foreach ($upload as $name) {
if ( in_array($name, $deleted) ) {
continue;
}
$n_upload[] = $name;
}
$value['upload'] = implode('|', $n_upload);
}
if ( !$value['tmp_ids'] ) {
// no pending files -> return already uploaded files
return $this->_sortFiles($value['upload']);
}
$swf_uploaded_ids = explode('|', $value['tmp_ids']);
$swf_uploaded_names = explode('|', $value['tmp_names']);
$existing = $value['upload'] ? explode('|', $value['upload']) : Array ();
$fret = Array ();
$max_files = $this->_getMaxFiles($options);
$pending_actions = $object->getPendingActions();
$files_to_delete = $this->_getFilesToDelete($object);
for ($i = 0; $i < min($max_files, count($swf_uploaded_ids)); $i++) {
// don't delete uploaded file, when it's name matches delete file name
$real_name = $this->_getRealFilename($swf_uploaded_names[$i], $options, $object, $files_to_delete);
$file_name = $this->FullPath . $real_name;
$tmp_file = WRITEABLE . '/tmp/' . $swf_uploaded_ids[$i] . '_' . $swf_uploaded_names[$i];
rename($tmp_file, $file_name);
@chmod($file_name, 0666);
$fret[] = getArrayValue($options, 'upload_dir') ? $real_name : $this->DestinationPath . $real_name;
$pending_actions[] = Array (
'action' => 'make_live', 'id' => $object->GetID(), 'field' => $field_name, 'file' => $file_name
);
$this->_renameFileInSorting($swf_uploaded_names[$i], $real_name);
}
$object->setPendingActions($pending_actions);
return $this->_sortFiles(array_merge($existing, $fret));
}
/**
* Returns files, scheduled for deleting
*
* @param kDBItem $object
* @return Array
* @access protected
*/
protected function _getFilesToDelete($object)
{
$ret = Array ();
foreach ($object->getPendingActions() as $data) {
if ( $data['action'] == 'delete' ) {
$ret[] = $data['file'];
}
}
return $ret;
}
/**
* Handles regular file upload
*
* @param string|Array $value
* @param string $field_name
* @param kDBItem $object
* @return string
* @access protected
*/
protected function _processRegularUploader($value, $field_name, $object)
{
$ret = !is_array($value) ? $value : '';
$options = $object->GetFieldOptions($field_name);
if ( getArrayValue($value, 'upload') && getArrayValue($value, 'error') == UPLOAD_ERR_NO_FILE ) {
// file was not uploaded this time, but was uploaded before, then use previously uploaded file (from db)
return getArrayValue($value, 'upload');
}
if ( is_array($value) && count($value) > 1 && $value['size'] ) {
if ( is_array($value) && (int)$value['error'] === UPLOAD_ERR_OK ) {
$max_file_size = isset($options['max_size']) ? $options['max_size'] : MAX_UPLOAD_SIZE;
// we can get mime type based on file content and don't use one, provided by the client
// $value['type'] = kUtil::mimeContentType($value['tmp_name']);
if ( getArrayValue($options, 'file_types') && !$this->extensionMatch($value['name'], $options['file_types']) ) {
// match by file extensions
$error_params = Array (
'file_name' => $value['name'],
'file_types' => $options['file_types'],
);
$object->SetError($field_name, 'bad_file_format', 'la_error_InvalidFileFormat', $error_params);
}
elseif ( getArrayValue($options, 'allowed_types') && !in_array($value['type'], $options['allowed_types']) ) {
// match by mime type provided by web-browser
$error_params = Array (
'file_type' => $value['type'],
'allowed_types' => $options['allowed_types'],
);
$object->SetError($field_name, 'bad_file_format', 'la_error_InvalidFileFormat', $error_params);
}
elseif ( $value['size'] > $max_file_size ) {
$object->SetError($field_name, 'bad_file_size', 'la_error_FileTooLarge');
}
elseif ( !is_writable($this->FullPath) ) {
$object->SetError($field_name, 'cant_save_file', 'la_error_cant_save_file');
}
else {
$real_name = $this->_getRealFilename($value['name'], $options, $object);
$file_name = $this->FullPath . $real_name;
$storage_format = isset($options['storage_format']) ? $options['storage_format'] : false;
if ( $storage_format ) {
$image_helper = $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
move_uploaded_file($value['tmp_name'], $value['tmp_name'] . '.jpg'); // add extension, so ResizeImage can work
$url = $image_helper->ResizeImage($value['tmp_name'] . '.jpg', $storage_format);
$tmp_name = preg_replace('/^' . preg_quote($this->Application->BaseURL(), '/') . '/', '/', $url);
$moved = rename($tmp_name, $file_name);
}
else {
$moved = move_uploaded_file($value['tmp_name'], $file_name);
}
if ( !$moved ) {
$object->SetError($field_name, 'cant_save_file', 'la_error_cant_save_file');
}
else {
@chmod($file_name, 0666);
if ( getArrayValue($options, 'size_field') ) {
$object->SetDBField($options['size_field'], $value['size']);
}
if ( getArrayValue($options, 'orig_name_field') ) {
$object->SetDBField($options['orig_name_field'], $value['name']);
}
if ( getArrayValue($options, 'content_type_field') ) {
$object->SetDBField($options['content_type_field'], $value['type']);
}
$ret = getArrayValue($options, 'upload_dir') ? $real_name : $this->DestinationPath . $real_name;
// delete previous file, when new file is uploaded under same field
/*$previous_file = isset($value['upload']) ? $value['upload'] : false;
if ( $previous_file && file_exists($this->FullPath . $previous_file) ) {
unlink($this->FullPath . $previous_file);
}*/
}
}
}
else {
$object->SetError($field_name, 'cant_save_file', 'la_error_cant_save_file');
}
}
if ( (count($value) > 1) && $value['error'] && ($value['error'] != UPLOAD_ERR_NO_FILE) ) {
$object->SetError($field_name, 'cant_save_file', 'la_error_cant_save_file', $value);
}
return $ret;
}
/**
* Checks, that given file name has on of provided file extensions
*
* @param string $filename
* @param string $file_types
* @return bool
* @access protected
*/
protected function extensionMatch($filename, $file_types)
{
if ( preg_match_all('/\*\.(.*?)(;|$)/', $file_types, $regs) ) {
$file_extension = mb_strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$file_extensions = array_map('mb_strtolower', $regs[1]);
return in_array($file_extension, $file_extensions);
}
return true;
}
/**
* Resorts uploaded files according to given file order
*
* @param Array|string $files
* @return string
* @access protected
*/
protected function _sortFiles($files)
{
if ( !is_array($files) ) {
$files = explode('|', $files);
}
$sorted_files = array_intersect($this->sorting, $files); // removes deleted files from sorting
$new_files = array_diff($files, $sorted_files); // files, that weren't sorted - add to the end
return implode('|', array_merge($sorted_files, $new_files));
}
/**
* Returns maximal allowed file count per field
*
* @param Array $options
* @return int
* @access protected
*/
protected function _getMaxFiles($options)
{
if ( !isset($options['multiple']) ) {
return 1;
}
return $options['multiple'] == false ? 1 : $options['multiple'];
}
/**
* Returns final filename after applying storage-engine specific naming
*
* @param string $file_name
* @param Array $options
* @param kDBItem $object
* @param Array $files_to_delete
* @return string
* @access protected
*/
protected function _getRealFilename($file_name, $options, $object, $files_to_delete = Array ())
{
$real_name = $this->getStorageEngineFile($file_name, $options, $object->Prefix);
$real_name = $this->getStorageEngineFolder($real_name, $options) . $real_name;
return $this->fileHelper->ensureUniqueFilename($this->FullPath, $real_name, $files_to_delete);
}
/**
* Renames file in sorting list
*
* @param string $old_name
* @param string $new_name
* @return void
* @access protected
*/
protected function _renameFileInSorting($old_name, $new_name)
{
$index = array_search($old_name, $this->sorting);
if ( $index !== false ) {
$this->sorting[$index] = $new_name;
}
}
function getSingleFormat($format)
{
$single_mapping = Array (
'file_raw_urls' => 'raw_url',
'file_display_names' => 'display_name',
'file_urls' => 'full_url',
'file_paths' => 'full_path',
'file_sizes' => 'file_size',
'files_resized' => 'resize',
'img_sizes' => 'img_size',
'wms' => 'wm',
);
return $single_mapping[$format];
}
/**
* Return formatted file url,path or size (or same for multiple files)
*
* @param string $value
* @param string $field_name
* @param kDBItem|kDBList $object
* @param string $format
* @return string
*/
function Format($value, $field_name, &$object, $format = NULL)
{
if ( is_null($value) ) {
return '';
}
$options = $object->GetFieldOptions($field_name);
if ( !isset($format) ) {
$format = isset($options['format']) ? $options['format'] : false;
}
if ( $format && preg_match('/(file_raw_urls|file_display_names|file_urls|file_paths|file_names|file_sizes|img_sizes|files_resized|wms)(.*)/', $format, $regs) ) {
if ( !$value || $format == 'file_names' ) {
// storage format matches display format OR no value
return $value;
}
$ret = Array ();
$files = explode('|', $value);
$format = $this->getSingleFormat($regs[1]) . $regs[2];
foreach ($files as $a_file) {
$ret[] = $this->GetFormatted($a_file, $field_name, $object, $format);
}
return implode('|', $ret);
}
$tc_value = $this->TypeCast($value, $options);
if ( ($tc_value === false) || ($tc_value != $value) ) {
// for leaving badly formatted date on the form
return $value;
}
return $this->GetFormatted($tc_value, $field_name, $object, $format);
}
/**
* Return formatted file url,path or size
*
* @param string $value
* @param string $field_name
* @param kDBItem $object
* @param string $format
* @return string
*/
function GetFormatted($value, $field_name, &$object, $format = NULL)
{
if ( !$format ) {
return $value;
}
$options = $object->GetFieldOptions($field_name);
$upload_dir = isset($options['include_path']) && $options['include_path'] ? '' : $this->getUploadDir($options);
$file_path = strlen($value) ? FULL_PATH . str_replace('/', DIRECTORY_SEPARATOR, $upload_dir) . $value : '';
if ( preg_match('/resize:([\d]*)x([\d]*)/', $format, $regs) ) {
$image_helper = $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
try {
return $image_helper->ResizeImage($file_path, $format);
}
- catch ( \RuntimeException $e ) {
+ catch ( RuntimeException $e ) {
// error, during image resize -> return empty string
return '';
}
}
elseif ( !strlen($file_path) || !file_exists($file_path) ) {
// file doesn't exist OR not uploaded
return '';
}
switch ($format) {
case 'display_name':
return kUtil::removeTempExtension($value);
break;
case 'raw_url':
return $this->fileHelper->pathToUrl($file_path);
break;
case 'full_url':
$direct_links = isset($options['direct_links']) ? $options['direct_links'] : true;
if ( $direct_links ) {
return $this->fileHelper->pathToUrl($file_path);
}
else {
$url_params = Array (
'no_amp' => 1, 'pass' => 'm,'.$object->Prefix,
$object->Prefix . '_event' => 'OnViewFile',
'file' => kUtil::escape($value, kUtil::ESCAPE_URL), 'field' => $field_name
);
return $this->Application->HREF('', '', $url_params);
}
break;
case 'full_path':
return $file_path;
break;
case 'file_size':
return filesize($file_path);
break;
case 'img_size':
$image_helper = $this->Application->recallObject('ImageHelper');
/* @var $image_helper ImageHelper */
$image_info = $image_helper->getImageInfo($file_path);
return $image_info ? $image_info[3] : '';
break;
}
return sprintf($format, $value);
}
/**
* Creates & returns folder, based on storage engine specified in field options
*
* @param string $file_name
* @param array $options
* @return string
* @access protected
* @throws Exception
*/
protected function getStorageEngineFolder($file_name, $options)
{
$storage_engine = (string)getArrayValue($options, 'storage_engine');
if ( !$storage_engine ) {
return '';
}
switch ($storage_engine) {
case StorageEngine::HASH:
$folder_path = kUtil::getHashPathForLevel($file_name);
break;
case StorageEngine::TIMESTAMP:
$folder_path = adodb_date('Y-m/d/');
break;
default:
throw new Exception('Unknown storage engine "<strong>' . $storage_engine . '</strong>".');
break;
}
return $folder_path;
}
/**
* Applies prefix & suffix to uploaded filename, based on storage engine in field options
*
* @param string $name
* @param array $options
* @param string $unit_prefix
* @return string
* @access protected
*/
protected function getStorageEngineFile($name, $options, $unit_prefix)
{
$prefix = $this->getStorageEngineFilePart(getArrayValue($options, 'filename_prefix'), $unit_prefix);
$suffix = $this->getStorageEngineFilePart(getArrayValue($options, 'filename_suffix'), $unit_prefix);
$parts = pathinfo($name);
return ($prefix ? $prefix . '_' : '') . $parts['filename'] . ($suffix ? '_' . $suffix : '') . '.' . $parts['extension'];
}
/**
* Creates prefix/suffix to join with uploaded file
*
* Added "u" before user_id to keep this value after FileHelper::ensureUniqueFilename method call
*
* @param string $option
* @param string $unit_prefix
* @return string
* @access protected
*/
protected function getStorageEngineFilePart($option, $unit_prefix)
{
$replace_from = Array (
StorageEngine::PS_DATE_TIME, StorageEngine::PS_PREFIX, StorageEngine::PS_USER
);
$replace_to = Array (
adodb_date('Ymd-His'), $unit_prefix, 'u' . $this->Application->RecallVar('user_id')
);
return str_replace($replace_from, $replace_to, $option);
}
public function getUploadDir($options)
{
return isset($options['upload_dir']) ? $options['upload_dir'] : $this->DestinationPath;
}
}
class kPictureFormatter extends kUploadFormatter
{
public function __construct()
{
$this->NakeLookupPath = IMAGES_PATH; // used ?
$this->DestinationPath = kUtil::constOn('ADMIN') ? IMAGES_PENDING_PATH : IMAGES_PATH;
parent::__construct();
}
/**
* Return formatted file url,path or size
*
* @param string $value
* @param string $field_name
* @param kDBItem $object
* @param string $format
* @return string
*/
function GetFormatted($value, $field_name, &$object, $format = NULL)
{
if ( $format == 'img_size' ) {
$options = $object->GetFieldOptions($field_name);
$img_path = FULL_PATH . '/' . $this->getUploadDir($options) . $value;
$image_info = getimagesize($img_path);
return ' ' . $image_info[3];
}
return parent::GetFormatted($value, $field_name, $object, $format);
}
}
Index: branches/5.2.x/core/kernel/globals.php
===================================================================
--- branches/5.2.x/core/kernel/globals.php (revision 16028)
+++ branches/5.2.x/core/kernel/globals.php (revision 16029)
@@ -1,1107 +1,1107 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class kUtil {
// const KG_TO_POUND = 2.20462262;
const POUND_TO_KG = 0.45359237;
/**
* Escape text as HTML.
*
* @see escape
*/
const ESCAPE_HTML = 'html';
/**
* Escape text as JavaScript.
*
* @see escape
*/
const ESCAPE_JS = 'js';
/**
* Escape text as Url.
*/
const ESCAPE_URL = 'url';
/**
* Don't escape anything.
*/
const ESCAPE_RAW = 'raw';
/**
* Current escape strategy.
*
* @var string
* @see escape
*/
public static $escapeStrategy = self::ESCAPE_HTML;
/**
* Similar to array_merge_recursive but keyed-valued are always overwritten.
* Priority goes to the 2nd array.
*
* @param $paArray1 array
* @param $paArray2 array
* @return array
* @access public
*/
public static function array_merge_recursive($paArray1, $paArray2)
{
if (!is_array($paArray1) or !is_array($paArray2)) {
return $paArray2;
}
foreach ($paArray2 AS $sKey2 => $sValue2) {
$paArray1[$sKey2] = isset($paArray1[$sKey2]) ? self::array_merge_recursive($paArray1[$sKey2], $sValue2) : $sValue2;
}
return $paArray1;
}
/**
* Prepend a reference to an element to the beginning of an array.
* Renumbers numeric keys, so $value is always inserted to $array[0]
*
* @param $array array
* @param $value mixed
* @return int
* @access public
*/
public static function array_unshift_ref(&$array, &$value)
{
$return = array_unshift($array,'');
$array[0] =& $value;
return $return;
}
/**
* Rename key in associative array, maintaining keys order
*
* @param Array $array Associative Array
* @param mixed $old Old key name
* @param mixed $new New key name
* @access public
*/
public static function array_rename_key(&$array, $old, $new)
{
$new_array = Array ();
foreach ($array as $key => $val) {
$new_array[ $key == $old ? $new : $key] = $val;
}
$array = $new_array;
}
/**
* Same as print_r, but outputs result on screen or in debugger report (when in debug mode)
*
* @param Array $data
* @param string $label
* @param bool $on_screen
* @access public
*/
public static function print_r($data, $label = '', $on_screen = false)
{
$is_debug = false;
if ( class_exists('kApplication') && !$on_screen ) {
$application =& kApplication::Instance();
$is_debug = $application->isDebugMode();
}
if ( $is_debug && isset($application) ) {
if ( $label ) {
$application->Debugger->appendHTML('<strong>' . $label . '</strong>');
}
$application->Debugger->dumpVars($data);
}
else {
if ( $label ) {
echo '<strong>' . $label . '</strong><br/>';
}
echo '<pre>', print_r($data, true), '</pre>';
}
}
/**
* Define constant if it was not already defined before
*
* @param string $const_name
* @param string $const_value
* @access public
*/
public static function safeDefine($const_name, $const_value)
{
if ( !defined($const_name) ) {
define($const_name, $const_value);
}
}
/**
* Parses "/system/config.php" file and returns the result
*
* @param bool $parse_section
* @return Array
* @access public
*/
public static function parseConfig($parse_section = false)
{
$file = FULL_PATH . DIRECTORY_SEPARATOR . 'system' . DIRECTORY_SEPARATOR . 'config.php';
if ( !file_exists($file) ) {
return Array ();
}
if ( file_exists($file) && !is_readable($file) ) {
die('Could Not Open Ini File');
}
$contents = file($file);
if ( $contents && $contents[0] == '<' . '?' . 'php die() ?' . ">\n" ) {
// format of "config.php" file before 5.1.0 version
array_shift($contents);
return parse_ini_string(implode('', $contents), $parse_section);
}
$_CONFIG = Array ();
require($file);
if ( $parse_section ) {
if ( isset($_CONFIG['Database']['LoadBalancing']) && $_CONFIG['Database']['LoadBalancing'] ) {
require FULL_PATH . DIRECTORY_SEPARATOR . 'system' . DIRECTORY_SEPARATOR . 'db_servers.php';
}
return $_CONFIG;
}
$ret = Array ();
foreach ($_CONFIG as $section => $section_variables) {
$ret = array_merge($ret, $section_variables);
}
return $ret;
}
/**
* Returns parsed variables from "config.php" file
*
* @return Array
* @access public
*/
public static function getConfigVars()
{
static $vars = NULL;
if ( !isset($vars) ) {
$vars = self::parseConfig();
}
return $vars;
}
/**
* Same as "include_once", but also profiles file includes in debug mode and DBG_PROFILE_INCLUDES constant is set
*
* @param string $file
* @access public
*/
public static function includeOnce($file)
{
global $debugger;
if ( defined('DEBUG_MODE') && DEBUG_MODE && isset($debugger) && defined('DBG_PROFILE_INCLUDES') && DBG_PROFILE_INCLUDES ) {
if ( in_array($file, get_included_files()) ) {
return ;
}
global $debugger;
/*$debugger->IncludeLevel++;
$before_mem = memory_get_usage();*/
$debugger->ProfileStart('inc_'.crc32($file), $file);
include_once($file);
$debugger->ProfileFinish('inc_'.crc32($file));
$debugger->profilerAddTotal('includes', 'inc_'.crc32($file));
/*$used_mem = memory_get_usage() - $before_mem;
$debugger->IncludeLevel--;
$debugger->IncludesData['file'][] = str_replace(FULL_PATH, '', $file);
$debugger->IncludesData['mem'][] = $used_mem;
$debugger->IncludesData['time'][] = $used_time;
$debugger->IncludesData['level'][] = $debugger->IncludeLevel;*/
}
else {
include_once($file);
}
}
/**
* Checks if given string is a serialized array
*
* @param string $string
* @return bool
* @access public
*/
public static function IsSerialized($string)
{
if ( is_array($string) ) {
return false;
}
return preg_match('/a:([\d]+):{/', $string);
}
/**
* Generates password of given length
*
* @param int $length
* @return string
* @access public
*/
public static function generatePassword($length = 10)
{
$pass_length = $length;
$p1 = Array ('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
$p2 = Array ('a','e','i','o','u');
$p3 = Array ('1','2','3','4','5','6','7','8','9');
$p4 = Array ('(','&',')',';','%'); // if you need real strong stuff
// how much elements in the array
// can be done with a array count but counting once here is faster
$s1 = 21;// this is the count of $p1
$s2 = 5; // this is the count of $p2
$s3 = 9; // this is the count of $p3
$s4 = 5; // this is the count of $p4
// possible readable combinations
$c1 = '121'; // will be like 'bab'
$c2 = '212'; // will be like 'aba'
$c3 = '12'; // will be like 'ab'
$c4 = '3'; // will be just a number '1 to 9' if you dont like number delete the 3
//$c5 = '4'; // uncomment to active the strong stuff
$comb = '4'; // the amount of combinations you made above (and did not comment out)
for ($p = 0; $p < $pass_length;) {
mt_srand((double)microtime() * 1000000);
$strpart = mt_rand(1, $comb);
// checking if the stringpart is not the same as the previous one
if ($strpart != $previous) {
$pass_structure .= ${'c' . $strpart};
// shortcutting the loop a bit
$p = $p + mb_strlen(${'c' . $strpart});
}
$previous = $strpart;
}
// generating the password from the structure defined in $pass_structure
for ($g = 0; $g < mb_strlen($pass_structure); $g++) {
mt_srand((double)microtime() * 1000000);
$sel = mb_substr($pass_structure, $g, 1);
$pass .= ${'p' . $sel}[ mt_rand(0,-1+${'s'.$sel}) ];
}
return $pass;
}
/**
* submits $url with $post as POST
*
* @param string $url
* @param mixed $data
* @param Array $headers
* @param string $request_type
* @param Array $curl_options
* @return string
* @access public
* @deprecated
*/
public static function curl_post($url, $data, $headers = NULL, $request_type = 'POST', $curl_options = NULL)
{
$application =& kApplication::Instance();
$curl_helper = $application->recallObject('CurlHelper');
/* @var $curl_helper kCurlHelper */
if ($request_type == 'POST') {
$curl_helper->SetRequestMethod(kCurlHelper::REQUEST_METHOD_POST);
}
$curl_helper->SetRequestData($data);
if (!is_null($headers)) {
// not an associative array, so don't use kCurlHelper::SetHeaders method
$curl_helper->setOptions( Array (CURLOPT_HTTPHEADER => $headers) );
}
if (is_array($curl_options)) {
$curl_helper->setOptions($curl_options);
}
$curl_helper->followLocation = false;
$ret = $curl_helper->Send($url);
$GLOBALS['curl_errorno'] = $curl_helper->lastErrorCode;
$GLOBALS['curl_error'] = $curl_helper->lastErrorMsg;
return $ret;
}
/**
* Checks if constant is defined and has positive value
*
* @param string $const_name
* @return bool
* @access public
*/
public static function constOn($const_name)
{
return defined($const_name) && constant($const_name);
}
/**
* Converts KG to Pounds
*
* @param float $kg
* @param bool $pounds_only
* @return float
* @access public
*/
public static function Kg2Pounds($kg, $pounds_only = false)
{
$major = floor( round($kg / self::POUND_TO_KG, 3) );
$minor = abs(round(($kg - $major * self::POUND_TO_KG) / self::POUND_TO_KG * 16, 2));
if ($pounds_only) {
$major += round($minor * 0.0625, 2);
$minor = 0;
}
return array($major, $minor);
}
/**
* Converts Pounds to KG
*
* @param float $pounds
* @param float $ounces
* @return float
* @access public
*/
public static function Pounds2Kg($pounds, $ounces = 0.00)
{
return round(($pounds + ($ounces / 16)) * self::POUND_TO_KG, 5);
}
/**
* Formats file/memory size in nice way
*
* @param int $bytes
* @return string
* @access public
*/
public static function formatSize($bytes)
{
if ($bytes >= 1099511627776) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
} elseif ($bytes >= 1073741824) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
} elseif ($bytes >= 1048576) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
} elseif ($bytes >= 1024) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
$return .= ' '.$suffix;
return $return;
}
/**
* Enter description here...
*
* @param resource $filePointer the file resource to write to
* @param Array $data the data to write out
* @param string $delimiter the field separator
* @param string $enclosure symbol to enclose field data to
* @param string $recordSeparator symbols to separate records with
* @access public
*/
public static function fputcsv($filePointer, $data, $delimiter = ',', $enclosure = '"', $recordSeparator = "\r\n")
{
fwrite($filePointer, self::getcsvline($data, $delimiter, $enclosure, $recordSeparator));
}
/**
* Enter description here...
*
* @param Array $data the data to write out
* @param string $delimiter the field separator
* @param string $enclosure symbol to enclose field data to
* @param string $recordSeparator symbols to separate records with
* @return string
* @access public
*/
public static function getcsvline($data, $delimiter = ',', $enclosure = '"', $recordSeparator = "\r\n")
{
- $file = new SplFileObject('php://output', 'w');
-
ob_start();
- $file->fputcsv($data, $delimiter, $enclosure);
+ $fp = fopen('php://output', 'w');
+ fputcsv($fp, $data, $delimiter, $enclosure);
+ fclose($fp);
$ret = ob_get_clean();
if ( $recordSeparator != "\n" ) {
return substr($ret, 0, -1) . $recordSeparator;
}
return $ret;
}
/**
* Allows to replace #section# within any string with current section
*
* @param string $string
* @return string
* @access public
*/
public static function replaceModuleSection($string)
{
$application =& kApplication::Instance();
$module_section = $application->RecallVar('section');
if ($module_section) {
// substitute section instead of #section# parameter in title preset name
$module_section = explode(':', $module_section);
$section = preg_replace('/(configuration|configure)_(.*)/i', '\\2', $module_section[count($module_section) == 2 ? 1 : 0]);
$string = str_replace('#section#', mb_strtolower($section), $string);
}
return $string;
}
/**
* Checks, that user IP address is within allowed range
*
* @param string $ip_list semi-column (by default) separated ip address list
* @param string $separator ip address separator (default ";")
*
* @return bool
* @access public
*/
public static function ipMatch($ip_list, $separator = ';')
{
if ( php_sapi_name() == 'cli' ) {
return false;
}
$ip_match = false;
$ip_addresses = $ip_list ? explode($separator, $ip_list) : Array ();
$application =& kApplication::Instance();
$client_ip = $application->getClientIp();
foreach ($ip_addresses as $ip_address) {
if ( self::netMatch($ip_address, $client_ip) ) {
$ip_match = true;
break;
}
}
return $ip_match;
}
/**
* Checks, that given ip belongs to given subnet
*
* @param string $network
* @param string $ip
* @return bool
* @access public
*/
public static function netMatch($network, $ip)
{
$network = trim($network);
$ip = trim($ip);
if ( preg_replace('/[\d\.\/-]/', '', $network) != '' ) {
$network = gethostbyname($network);
}
if ($network == $ip) {
// comparing two ip addresses directly
return true;
}
$d = strpos($network, '-');
if ($d !== false) {
// ip address range specified
$from = ip2long(trim(substr($network, 0, $d)));
$to = ip2long(trim(substr($network, $d + 1)));
$ip = ip2long($ip);
return ($ip >= $from && $ip <= $to);
}
elseif (strpos($network, '/') !== false) {
// single subnet specified
$ip_arr = explode('/', $network);
if (!preg_match("@\d*\.\d*\.\d*\.\d*@", $ip_arr[0], $matches)) {
$ip_arr[0] .= '.0'; // Alternate form 194.1.4/24
}
$network_long = ip2long($ip_arr[0]);
$x = ip2long($ip_arr[1]);
$mask = long2ip($x) == $ip_arr[1] ? $x : (0xffffffff << (32 - $ip_arr[1]));
$ip_long = ip2long($ip);
return ($ip_long & $mask) == ($network_long & $mask);
}
return false;
}
/**
* Returns mime type corresponding to given file
* @param string $file
* @return string
* @access public
*/
public static function mimeContentType($file)
{
$ret = self::vendorMimeContentType($file);
if ( $ret ) {
// vendor-specific mime types override any automatic detection
return $ret;
}
if ( function_exists('finfo_open') && function_exists('finfo_file') ) {
$mime_magic_resource = finfo_open(FILEINFO_MIME_TYPE);
if ( $mime_magic_resource ) {
$ret = finfo_file($mime_magic_resource, $file);
finfo_close($mime_magic_resource);
}
}
elseif ( function_exists('mime_content_type') ) {
$ret = mime_content_type($file);
}
return $ret ? $ret : self::mimeContentTypeByExtension($file);
}
/**
* Determines vendor-specific mime type from a given file
*
* @param string $file
* @return bool
* @access public
* @static
*/
public static function vendorMimeContentType($file)
{
$file_extension = mb_strtolower(pathinfo(self::removeTempExtension($file), PATHINFO_EXTENSION));
$mapping = Array (
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12'
);
return isset($mapping[$file_extension]) ? $mapping[$file_extension] : false;
}
/**
* Detects mime type of the file purely based on it's extension
*
* @param string $file
* @return string
* @access public
*/
public static function mimeContentTypeByExtension($file)
{
$file_extension = mb_strtolower(pathinfo(self::removeTempExtension($file), PATHINFO_EXTENSION));
$mapping = '(xls:application/excel)(hqx:application/macbinhex40)(doc,dot,wrd:application/msword)(pdf:application/pdf)
(pgp:application/pgp)(ps,eps,ai:application/postscript)(ppt:application/powerpoint)(rtf:application/rtf)
(tgz,gtar:application/x-gtar)(gz:application/x-gzip)(php,php3:application/x-httpd-php)(js:application/x-javascript)
(ppd,psd:application/x-photoshop)(swf,swc,rf:application/x-shockwave-flash)(tar:application/x-tar)(zip:application/zip)
(mid,midi,kar:audio/midi)(mp2,mp3,mpga:audio/mpeg)(ra:audio/x-realaudio)(wav:audio/wav)(bmp:image/bitmap)(bmp:image/bitmap)
(gif:image/gif)(iff:image/iff)(jb2:image/jb2)(jpg,jpe,jpeg:image/jpeg)(jpx:image/jpx)(png:image/png)(tif,tiff:image/tiff)
(wbmp:image/vnd.wap.wbmp)(xbm:image/xbm)(css:text/css)(txt:text/plain)(htm,html:text/html)(xml:text/xml)
(mpg,mpe,mpeg:video/mpeg)(qt,mov:video/quicktime)(avi:video/x-ms-video)(eml:message/rfc822)
(sxw:application/vnd.sun.xml.writer)(sxc:application/vnd.sun.xml.calc)(sxi:application/vnd.sun.xml.impress)
(sxd:application/vnd.sun.xml.draw)(sxm:application/vnd.sun.xml.math)
(odt:application/vnd.oasis.opendocument.text)(oth:application/vnd.oasis.opendocument.text-web)
(odm:application/vnd.oasis.opendocument.text-master)(odg:application/vnd.oasis.opendocument.graphics)
(odp:application/vnd.oasis.opendocument.presentation)(ods:application/vnd.oasis.opendocument.spreadsheet)
(odc:application/vnd.oasis.opendocument.chart)(odf:application/vnd.oasis.opendocument.formula)
(odi:application/vnd.oasis.opendocument.image)';
if ( preg_match('/[\(,]' . $file_extension . '[,]{0,1}.*?:(.*?)\)/s', $mapping, $regs) ) {
return $regs[1];
}
return 'application/octet-stream';
}
/**
* Strips ".tmp" suffix (added by flash uploader) from a filename
*
* @param string $file
* @return string
* @access public
* @static
*/
public static function removeTempExtension($file)
{
return preg_replace('/(_[\d]+)?\.tmp$/', '', $file);
}
/**
* Return param value and removes it from params array
*
* @param string $name
* @param Array $params
* @param bool $default
* @return string
*/
public static function popParam($name, &$params, $default = false)
{
if ( isset($params[$name]) ) {
$value = $params[$name];
unset($params[$name]);
return $value;
}
return $default;
}
/**
* Generate subpath from hashed value
*
* @param string $name
* @param int $levels
* @return string
*/
public static function getHashPathForLevel($name, $levels = 2)
{
if ( $levels == 0 ) {
return '';
}
else {
$path = '';
$hash = md5($name);
for ($i = 0; $i < $levels; $i++) {
$path .= substr($hash, $i, 1) . '/';
}
return $path;
}
}
/**
* Calculates the crc32 polynomial of a string (always positive number)
*
* @param string $str
* @return int
*/
public static function crc32($str)
{
return sprintf('%u', crc32($str));
}
/**
* Returns instance of DateTime class with date set based on timestamp
*
* @static
* @param int $timestamp
* @return DateTime
* @access public
*/
public static function dateFromTimestamp($timestamp)
{
if ( version_compare(PHP_VERSION, '5.3.0', '<') ) {
$date = new DateTime('@' . $timestamp);
$date->setTimezone(new DateTimeZone(date_default_timezone_get()));
}
else {
$date = new DateTime();
$date->setTimestamp($timestamp);
}
return $date;
}
/**
* Returns timestamp from given DateTime class instance
*
* @static
* @param DateTime $date_time
* @return int|string
* @access public
*/
public static function timestampFromDate(DateTime $date_time)
{
if ( version_compare(PHP_VERSION, '5.3.0', '<') ) {
return $date_time->format('U');
}
return $date_time->getTimestamp();
}
/**
* Generates random numeric id
*
* @static
* @return string
* @access public
*/
public static function generateId()
{
list($usec, $sec) = explode(' ', microtime());
$id_part_1 = substr($usec, 4, 4);
$id_part_2 = mt_rand(1, 9);
$id_part_3 = substr($sec, 6, 4);
$digit_one = substr($id_part_1, 0, 1);
if ( $digit_one == 0 ) {
$digit_one = mt_rand(1, 9);
$id_part_1 = preg_replace('/^0/', '', $id_part_1);
$id_part_1 = $digit_one . $id_part_1;
}
return $id_part_1 . $id_part_2 . $id_part_3;
}
/**
* Changes script resource limits. Omitted argument results in limit removal.
*
* @static
* @param string|int $memory_limit
* @param int $time_limit
* @return void
* @access public
*/
public static function setResourceLimit($memory_limit = null, $time_limit = null)
{
set_time_limit(isset($time_limit) ? $time_limit : 0);
ini_set('memory_limit', isset($memory_limit) ? $memory_limit : -1);
}
/**
* Escapes a string.
*
* @param string $text Text to escape.
* @param string $strategy Escape strategy.
*
* @return string
* @throws InvalidArgumentException When unknown escape strategy is given.
*/
public static function escape($text, $strategy = null)
{
if ( !isset($strategy) ) {
$strategy = self::$escapeStrategy;
}
if ( strpos($strategy, '+') !== false ) {
$previous_strategy = '';
$strategies = explode('+', $strategy);
foreach ($strategies as $current_strategy) {
// apply default strategy
if ( $current_strategy == '' ) {
$current_strategy = self::$escapeStrategy;
}
// don't double-escape
if ( $current_strategy != $previous_strategy ) {
$text = self::escape($text, $current_strategy);
$previous_strategy = $current_strategy;
}
}
return $text;
}
if ( $strategy == self::ESCAPE_HTML ) {
return htmlspecialchars($text, ENT_QUOTES, CHARSET);
}
if ( $strategy == self::ESCAPE_JS ) {
// TODO: consider using "addcslashes", because "addslashes" isn't really for JavaScript escaping (according to docs)
$text = addslashes($text);
$text = str_replace(array("\r", "\n"), array('\r', '\n'), $text);
$text = str_replace('</script>', "</'+'script>", $text);
return $text;
}
if ( $strategy == self::ESCAPE_URL ) {
return rawurlencode($text);
}
if ( $strategy == self::ESCAPE_RAW ) {
return $text;
}
throw new InvalidArgumentException(sprintf('Unknown escape strategy "%s"', $strategy));
}
/**
* Unescapes a string.
*
* @param string $text Text to unescape.
* @param string $strategy Escape strategy.
*
* @return string
* @throws InvalidArgumentException When unknown escape strategy is given.
*/
public static function unescape($text, $strategy = null)
{
if ( !isset($strategy) ) {
$strategy = self::$escapeStrategy;
}
if ( strpos($strategy, '+') !== false ) {
$previous_strategy = '';
$strategies = explode('+', $strategy);
foreach ($strategies as $current_strategy) {
// apply default strategy
if ( $current_strategy == '' ) {
$current_strategy = self::$escapeStrategy;
}
// don't double-unescape
if ( $current_strategy != $previous_strategy ) {
$text = self::unescape($text, $current_strategy);
$previous_strategy = $current_strategy;
}
}
return $text;
}
if ( $strategy == self::ESCAPE_HTML ) {
return htmlspecialchars_decode($text, ENT_QUOTES);
}
if ( $strategy == self::ESCAPE_JS ) {
// TODO: consider using "stripcslashes", because "stripslashes" isn't really for JavaScript unescaping (according to docs)
$text = str_replace("</'+'script>", '</script>', $text);
$text = str_replace(array('\r', '\n'), array("\r", "\n"), $text);
$text = stripslashes($text);
return $text;
}
if ( $strategy == self::ESCAPE_URL ) {
return rawurldecode($text);
}
if ( $strategy == self::ESCAPE_RAW ) {
return $text;
}
throw new InvalidArgumentException(sprintf('Unknown escape strategy "%s"', $strategy));
}
}
/**
* Returns array value if key exists
* Accepts infinite number of parameters
*
* @param Array $array searchable array
* @param int $key array key
* @return string
*/
function getArrayValue(&$array, $key)
{
$ret = isset($array[$key]) ? $array[$key] : false;
if ( $ret && func_num_args() > 2 ) {
for ($i = 2; $i < func_num_args(); $i++) {
$cur_key = func_get_arg($i);
$ret = getArrayValue($ret, $cur_key);
if ( $ret === false ) {
break;
}
}
}
return $ret;
}
if ( !function_exists('parse_ini_string') ) {
/**
* Equivalent for "parse_ini_string" function available since PHP 5.3.0
*
* @param string $ini
* @param bool $process_sections
* @param int $scanner_mode
* @return Array
*/
function parse_ini_string($ini, $process_sections = false, $scanner_mode = NULL)
{
# Generate a temporary file.
$tempname = tempnam('/tmp', 'ini');
$fp = fopen($tempname, 'w');
fwrite($fp, $ini);
$ini = parse_ini_file($tempname, !empty($process_sections));
fclose($fp);
@unlink($tempname);
return $ini;
}
}
if ( !function_exists('memory_get_usage') ) {
// PHP 4.x and compiled without --enable-memory-limit option
function memory_get_usage() { return -1; }
}
if ( !function_exists('imagecreatefrombmp') ) {
// just in case if GD will add this function in future
function imagecreatefrombmp($filename)
{
//Ouverture du fichier en mode binaire
if (! $f1 = fopen($filename,"rb")) return FALSE;
//1 : Chargement des ent�tes FICHIER
$FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
if ($FILE['file_type'] != 19778) return FALSE;
//2 : Chargement des ent�tes BMP
$BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
'/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
'/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
$BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
$BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
$BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
$BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
$BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
$BMP['decal'] = 4-(4*$BMP['decal']);
if ($BMP['decal'] == 4) $BMP['decal'] = 0;
//3 : Chargement des couleurs de la palette
$PALETTE = array();
if ($BMP['colors'] < 16777216)
{
$PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
}
//4 : Cr�ation de l'image
$IMG = fread($f1,$BMP['size_bitmap']);
$VIDE = chr(0);
$res = imagecreatetruecolor($BMP['width'],$BMP['height']);
$P = 0;
$Y = $BMP['height']-1;
while ($Y >= 0)
{
$X=0;
while ($X < $BMP['width'])
{
if ($BMP['bits_per_pixel'] == 24)
$COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
elseif ($BMP['bits_per_pixel'] == 16)
{
$COLOR = unpack("n",substr($IMG,$P,2));
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
elseif ($BMP['bits_per_pixel'] == 8)
{
$COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
elseif ($BMP['bits_per_pixel'] == 4)
{
$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
elseif ($BMP['bits_per_pixel'] == 1)
{
$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
if (($P*8)%8 == 0) $COLOR[1] = $COLOR[1] >>7;
elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}
else
return FALSE;
imagesetpixel($res,$X,$Y,$COLOR[1]);
$X++;
$P += $BMP['bytes_per_pixel'];
}
$Y--;
$P+=$BMP['decal'];
}
//Fermeture du fichier
fclose($f1);
return $res;
}
}
Index: branches/5.2.x/core/units/helpers/image_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/image_helper.php (revision 16028)
+++ branches/5.2.x/core/units/helpers/image_helper.php (revision 16029)
@@ -1,714 +1,714 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class ImageHelper extends kHelper {
/**
* File helper reference
*
* @var FileHelper
*/
var $fileHelper = null;
public function __construct()
{
parent::__construct();
ini_set('gd.jpeg_ignore_warning', 1);
$this->fileHelper = $this->Application->recallObject('FileHelper');
}
/**
* Parses format string into array
*
* @param string $format sample format: "resize:300x500;wm:inc/wm.png|c|-20"
* @return Array sample result: Array('max_width' => 300, 'max_height' => 500, 'wm_filename' => 'inc/wm.png', 'h_margin' => 'c', 'v_margin' => -20)
*/
function parseFormat($format)
{
$res = Array ();
$format_parts = explode(';', $format);
foreach ($format_parts as $format_part) {
if (preg_match('/^resize:(\d*)x(\d*)$/', $format_part, $regs)) {
$res['max_width'] = $regs[1];
$res['max_height'] = $regs[2];
}
elseif (preg_match('/^wm:([^\|]*)\|([^\|]*)\|([^\|]*)$/', $format_part, $regs)) {
$res['wm_filename'] = FULL_PATH.THEMES_PATH.'/'.$regs[1];
$res['h_margin'] = strtolower($regs[2]);
$res['v_margin'] = strtolower($regs[3]);
}
elseif (preg_match('/^crop:([^\|]*)\|([^\|]*)$/', $format_part, $regs)) {
$res['crop_x'] = strtolower($regs[1]);
$res['crop_y'] = strtolower($regs[2]);
}
elseif ($format_part == 'img_size' || $format_part == 'img_sizes') {
$res['image_size'] = true;
}
elseif (preg_match('/^fill:(.*)$/', $format_part, $regs)) {
$res['fill'] = $regs[1];
} elseif (preg_match('/^default:(.*)$/', $format_part, $regs)) {
$res['default'] = FULL_PATH.THEMES_PATH.'/'.$regs[1];
}
}
return $res;
}
/**
* Resized given image to required dimensions & saves resized image to "resized" subfolder in source image folder
*
* @param string $src_image full path to image (on server)
* @param mixed $max_width maximal allowed resized image width or false if no limit
* @param mixed $max_height maximal allowed resized image height or false if no limit
*
* @return string direct url to resized image
- * @throws \RuntimeException When image doesn't exist.
+ * @throws RuntimeException When image doesn't exist.
*/
function ResizeImage($src_image, $max_width, $max_height = false)
{
$image_size = false;
if (is_numeric($max_width)) {
$params['max_width'] = $max_width;
$params['max_height'] = $max_height;
}
else {
$params = $this->parseFormat($max_width);
if (array_key_exists('image_size', $params)) {
// image_size param shouldn't affect resized file name (crc part)
$image_size = $params['image_size'];
unset($params['image_size']);
}
}
if ((!$src_image || !file_exists($src_image)) && array_key_exists('default', $params) && !(defined('DBG_IMAGE_RECOVERY') && DBG_IMAGE_RECOVERY)) {
$src_image = $params['default'];
}
if ( !strlen($src_image) || !file_exists($src_image) ) {
- throw new \RuntimeException(sprintf('Image "%s" doesn\'t exist', $src_image));
+ throw new RuntimeException(sprintf('Image "%s" doesn\'t exist', $src_image));
}
if ($params['max_width'] > 0 || $params['max_height'] > 0) {
list ($params['target_width'], $params['target_height'], $needs_resize) = $this->GetImageDimensions($src_image, $params['max_width'], $params['max_height'], $params);
if (!is_numeric($params['max_width'])) {
$params['max_width'] = $params['target_width'];
}
if (!is_numeric($params['max_height'])) {
$params['max_height'] = $params['target_height'];
}
$src_path = dirname($src_image);
$transform_keys = Array ('crop_x', 'crop_y', 'fill', 'wm_filename');
if ($needs_resize || array_intersect(array_keys($params), $transform_keys)) {
// resize required OR watermarking required -> change resulting image name !
$src_path_escaped = preg_replace('/(\\\[\d]+)/', '\\\\\1', $src_path); // escape replacement patterns, like "\<number>"
$dst_image = preg_replace('/^'.preg_quote($src_path, '/').'(.*)\.(.*)$/', $src_path_escaped . DIRECTORY_SEPARATOR . 'resized\\1_' . crc32(serialize($params)) . '.\\2', $src_image);
$this->fileHelper->CheckFolder( dirname($dst_image) );
if (!file_exists($dst_image) || filemtime($src_image) > filemtime($dst_image)) {
// resized image not available OR should be recreated due source image change
$params['dst_image'] = $dst_image;
$image_resized = $this->ScaleImage($src_image, $params);
if (!$image_resized) {
// resize failed, because of server error
$dst_image = $src_image;
}
}
// resize/watermarking ok
$src_image = $dst_image;
}
}
if ($image_size) {
// return only image size (resized or not)
$image_info = $this->getImageInfo($src_image);
return $image_info ? $image_info[3] : '';
}
return $this->fileHelper->pathToUrl($src_image);
}
/**
* Proportionally resizes given image to destination dimensions
*
* @param string $src_image full path to source image (already existing)
* @param Array $params
* @return bool
*/
function ScaleImage($src_image, $params)
{
$image_info = $this->getImageInfo($src_image);
if (!$image_info) {
return false;
}
/*list ($params['max_width'], $params['max_height'], $resized) = $this->GetImageDimensions($src_image, $params['max_width'], $params['max_height'], $params);
if (!$resized) {
// image dimensions are smaller or equals to required dimensions
return false;
}*/
if (!$this->Application->ConfigValue('ForceImageMagickResize') && function_exists('imagecreatefromjpeg')) {
// try to resize using GD
$resize_map = Array (
'image/jpeg' => 'imagecreatefromjpeg:imagejpeg:jpg',
'image/gif' => 'imagecreatefromgif:imagegif:gif',
'image/png' => 'imagecreatefrompng:imagepng:png',
'image/bmp' => 'imagecreatefrombmp:imagejpeg:bmp',
'image/x-ms-bmp' => 'imagecreatefrombmp:imagejpeg:bmp',
);
$mime_type = $image_info['mime'];
if (!isset($resize_map[$mime_type])) {
return false;
}
list ($read_function, $write_function, $file_extension) = explode(':', $resize_map[$mime_type]);
// when source image has large dimensions (over 1MB filesize), then 16M is not enough
kUtil::setResourceLimit();
$src_image_rs = @$read_function($src_image);
if ($src_image_rs) {
$dst_image_rs = imagecreatetruecolor($params['target_width'], $params['target_height']); // resize target size
$preserve_transparency = ($file_extension == 'gif') || ($file_extension == 'png');
if ($preserve_transparency) {
// preserve transparency of PNG and GIF images
$dst_image_rs = $this->_preserveTransparency($src_image_rs, $dst_image_rs, $image_info[2]);
}
// 1. resize
imagecopyresampled($dst_image_rs, $src_image_rs, 0, 0, 0, 0, $params['target_width'], $params['target_height'], $image_info[0], $image_info[1]);
$watermark_size = 'target';
if (array_key_exists('crop_x', $params) || array_key_exists('crop_y', $params)) {
// 2.1. crop image to given size
$dst_image_rs =& $this->_cropImage($dst_image_rs, $params, $preserve_transparency ? $image_info[2] : false);
$watermark_size = 'max';
} elseif (array_key_exists('fill', $params)) {
// 2.2. fill image margins from resize with given color
$dst_image_rs =& $this->_applyFill($dst_image_rs, $params, $preserve_transparency ? $image_info[2] : false);
$watermark_size = 'max';
}
// 3. apply watermark
$dst_image_rs =& $this->_applyWatermark($dst_image_rs, $params[$watermark_size . '_width'], $params[$watermark_size . '_height'], $params);
if ($write_function == 'imagegif') {
return @$write_function($dst_image_rs, $params['dst_image']);
}
return @$write_function($dst_image_rs, $params['dst_image'], $write_function == 'imagepng' ? 0 : 100);
}
}
else {
// try to resize using ImageMagick
// TODO: implement crop and watermarking using imagemagick
exec('/usr/bin/convert '.$src_image.' -resize '.$params['target_width'].'x'.$params['target_height'].' '.$params['dst_image'], $shell_output, $exec_status);
return $exec_status == 0;
}
return false;
}
/**
* Preserve transparency for GIF and PNG images
*
* @param resource $src_image_rs
* @param resource $dst_image_rs
* @param int $image_type
* @return resource
*/
function _preserveTransparency($src_image_rs, $dst_image_rs, $image_type)
{
$transparent_index = imagecolortransparent($src_image_rs);
// if we have a specific transparent color
if ( $transparent_index >= 0 && $transparent_index < imagecolorstotal($src_image_rs) ) {
// get the original image's transparent color's RGB values
$transparent_color = imagecolorsforindex($src_image_rs, $transparent_index);
// allocate the same color in the new image resource
$transparent_index = imagecolorallocate($dst_image_rs, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
// completely fill the background of the new image with allocated color
imagefill($dst_image_rs, 0, 0, $transparent_index);
// set the background color for new image to transparent
imagecolortransparent($dst_image_rs, $transparent_index);
return $dst_image_rs;
}
// always make a transparent background color for PNGs that don't have one allocated already
if ( $image_type == IMAGETYPE_PNG ) {
// turn off transparency blending (temporarily)
imagealphablending($dst_image_rs, false);
// create a new transparent color for image
$transparent_color = imagecolorallocatealpha($dst_image_rs, 0, 0, 0, 127);
// completely fill the background of the new image with allocated color
imagefill($dst_image_rs, 0, 0, $transparent_color);
// restore transparency blending
imagesavealpha($dst_image_rs, true);
}
return $dst_image_rs;
}
/**
* Fills margins (if any) of resized are with given color
*
* @param resource $src_image_rs resized image resource
* @param Array $params crop parameters
* @param int|bool $image_type
* @return resource
*/
function &_applyFill(&$src_image_rs, $params, $image_type = false)
{
$x_position = round(($params['max_width'] - $params['target_width']) / 2); // center
$y_position = round(($params['max_height'] - $params['target_height']) / 2); // center
// crop resized image
$fill_image_rs = imagecreatetruecolor($params['max_width'], $params['max_height']);
if ($image_type !== false) {
$fill_image_rs = $this->_preserveTransparency($src_image_rs, $fill_image_rs, $image_type);
}
$fill = $params['fill'];
if (substr($fill, 0, 1) == '#') {
// hexdecimal color
$color = imagecolorallocate($fill_image_rs, hexdec( substr($fill, 1, 2) ), hexdec( substr($fill, 3, 2) ), hexdec( substr($fill, 5, 2) ));
}
else {
// for now we don't support color names, but we will in future
return $src_image_rs;
}
imagefill($fill_image_rs, 0, 0, $color);
imagecopy($fill_image_rs, $src_image_rs, $x_position, $y_position, 0, 0, $params['target_width'], $params['target_height']);
return $fill_image_rs;
}
/**
* Crop given image resource using given params and return resulting image resource
*
* @param resource $src_image_rs resized image resource
* @param Array $params crop parameters
* @param int|bool $image_type
* @return resource
*/
function &_cropImage(&$src_image_rs, $params, $image_type = false)
{
if ($params['crop_x'] == 'c') {
$x_position = round(($params['max_width'] - $params['target_width']) / 2); // center
}
elseif ($params['crop_x'] >= 0) {
$x_position = $params['crop_x']; // margin from left
}
else {
$x_position = $params['target_width'] - ($params['max_width'] - $params['crop_x']); // margin from right
}
if ($params['crop_y'] == 'c') {
$y_position = round(($params['max_height'] - $params['target_height']) / 2); // center
}
elseif ($params['crop_y'] >= 0) {
$y_position = $params['crop_y']; // margin from top
}
else {
$y_position = $params['target_height'] - ($params['max_height'] - $params['crop_y']); // margin from bottom
}
// crop resized image
$crop_image_rs = imagecreatetruecolor($params['max_width'], $params['max_height']);
if ($image_type !== false) {
$crop_image_rs = $this->_preserveTransparency($src_image_rs, $crop_image_rs, $image_type);
}
if (array_key_exists('fill', $params)) {
// fill image margins from resize with given color
$crop_image_rs =& $this->_applyFill($crop_image_rs, $params, $image_type);
}
imagecopy($crop_image_rs, $src_image_rs, $x_position, $y_position, 0, 0, $params['target_width'], $params['target_height']);
return $crop_image_rs;
}
/**
* Apply watermark (transparent PNG image) to given resized image resource
*
* @param resource $src_image_rs
* @param int $max_width
* @param int $max_height
* @param Array $params
* @return resource
*/
function &_applyWatermark(&$src_image_rs, $max_width, $max_height, $params)
{
$watermark_file = array_key_exists('wm_filename', $params) ? $params['wm_filename'] : false;
if (!$watermark_file || !file_exists($watermark_file)) {
// no watermark required, or provided watermark image is missing
return $src_image_rs;
}
$watermark_img_rs = imagecreatefrompng($watermark_file);
list ($watermark_width, $watermark_height) = $this->getImageInfo($watermark_file);
imagealphablending($src_image_rs, true);
if ($params['h_margin'] == 'c') {
$x_position = round($max_width / 2 - $watermark_width / 2); // center
}
elseif ($params['h_margin'] >= 0) {
$x_position = $params['h_margin']; // margin from left
}
else {
$x_position = $max_width - ($watermark_width - $params['h_margin']); // margin from right
}
if ($params['v_margin'] == 'c') {
$y_position = round($max_height / 2 - $watermark_height / 2); // center
}
elseif ($params['v_margin'] >= 0) {
$y_position = $params['v_margin']; // margin from top
}
else {
$y_position = $max_height - ($watermark_height - $params['v_margin']); // margin from bottom
}
imagecopy($src_image_rs, $watermark_img_rs, $x_position, $y_position, 0, 0, $watermark_width, $watermark_height);
return $src_image_rs;
}
/**
* Returns destination image size without actual resizing (useful for <img .../> HTML tag)
*
* @param string $src_image full path to source image (already existing)
* @param int $dst_width destination image width (in pixels)
* @param int $dst_height destination image height (in pixels)
* @param Array $params
* @return Array resized image dimensions (0 - width, 1 - height)
*/
function GetImageDimensions($src_image, $dst_width, $dst_height, $params)
{
$image_info = $this->getImageInfo($src_image);
if (!$image_info) {
return false;
}
$orig_width = $image_info[0];
$orig_height = $image_info[1];
$too_large = is_numeric($dst_width) ? ($orig_width > $dst_width) : false;
$too_large = $too_large || (is_numeric($dst_height) ? ($orig_height > $dst_height) : false);
if ($too_large) {
$width_ratio = $dst_width ? $dst_width / $orig_width : 1;
$height_ratio = $dst_height ? $dst_height / $orig_height : 1;
if (array_key_exists('crop_x', $params) || array_key_exists('crop_y', $params)) {
// resize by smallest inverted radio
$resize_by = $this->_getCropImageMinRatio($image_info, $dst_width, $dst_height);
if ($resize_by === false) {
return Array ($orig_width, $orig_height, false);
}
$ratio = $resize_by == 'width' ? $width_ratio : $height_ratio;
}
else {
$ratio = min($width_ratio, $height_ratio);
}
$width = ceil($orig_width * $ratio);
$height = ceil($orig_height * $ratio);
}
else {
$width = $orig_width;
$height = $orig_height;
}
return Array ($width, $height, $too_large);
}
/**
* Returns ratio type with smaller relation of original size to target size
*
* @param Array $image_info image information from "ImageHelper::getImageInfo"
* @param int $dst_width destination image width (in pixels)
* @param int $dst_height destination image height (in pixels)
* @return Array
*/
function _getCropImageMinRatio($image_info, $dst_width, $dst_height)
{
$width_ratio = $dst_width ? $image_info[0] / $dst_width : 1;
$height_ratio = $dst_height ? $image_info[1] / $dst_height : 1;
$minimal_ratio = min($width_ratio, $height_ratio);
if ($minimal_ratio < 1) {
// ratio is less then 1, image will be enlarged -> don't allow that
return false;
}
return $width_ratio < $height_ratio ? 'width' : 'height';
}
/**
* Returns image dimensions + checks if given file is existing image
*
* @param string $src_image full path to source image (already existing)
* @return mixed
*/
function getImageInfo($src_image)
{
if (!file_exists($src_image)) {
return false;
}
$image_info = @getimagesize($src_image);
if (!$image_info) {
trigger_error('Image <b>'.$src_image.'</b> <span class="debug_error">missing or invalid</span>', E_USER_WARNING);
return false;
}
return $image_info;
}
/**
* Returns maximal image size (width & height) among fields specified
*
* @param kDBItem $object
* @param string $fields
* @param string $format any format, that returns full url (e.g. files_resized:WxH, resize:WxH, full_url, full_urls)
* @return string
*/
function MaxImageSize(&$object, $fields, $format = null)
{
static $cached_sizes = Array ();
$cache_key = $object->getPrefixSpecial().'_'.$object->GetID();
if (!isset($cached_sizes[$cache_key])) {
$images = Array ();
$fields = explode(',', $fields);
foreach ($fields as $field) {
$image_data = $object->GetField($field, $format);
if (!$image_data) {
continue;
}
$images = array_merge($images, explode('|', $image_data));
}
$max_width = 0;
$max_height = 0;
$base_url = rtrim($this->Application->BaseURL(), '/');
foreach ($images as $image_url) {
$image_path = preg_replace('/^'.preg_quote($base_url, '/').'(.*)/', FULL_PATH.'\\1', $image_url);
$image_info = $this->getImageInfo($image_path);
$max_width = max($max_width, $image_info[0]);
$max_height = max($max_height, $image_info[1]);
}
$cached_sizes[$cache_key] = Array ($max_width, $max_height);
}
return $cached_sizes[$cache_key];
}
/**
* Puts existing item images (from sub-item) to virtual fields (in main item)
*
* @param kCatDBItem|kDBItem $object
*/
function LoadItemImages(&$object)
{
if (!$this->_canUseImages($object)) {
return ;
}
$max_image_count = $this->Application->ConfigValue($object->Prefix.'_MaxImageCount');
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'CatalogImages
WHERE ResourceId = '.$object->GetDBField('ResourceId').'
ORDER BY Priority DESC
LIMIT 0, ' . (int)$max_image_count;
$item_images = $this->Conn->Query($sql);
$image_counter = 1;
foreach ($item_images as $item_image) {
$image_path = $item_image['ThumbPath'];
if ($item_image['DefaultImg'] == 1 || $item_image['Name'] == 'main') {
// process primary image separately
if ( $object->isField('PrimaryImage') ) {
$object->SetDBField('PrimaryImage', $image_path);
$object->SetOriginalField('PrimaryImage', $image_path);
$object->SetFieldOption('PrimaryImage', 'original_field', $item_image['Name']);
$this->_loadCustomFields($object, $item_image, 0);
}
continue;
}
if (abs($item_image['Priority'])) {
// use Priority as image counter, when specified
$image_counter = abs($item_image['Priority']);
}
if ( $object->isField('Image'.$image_counter) ) {
$object->SetDBField('Image'.$image_counter, $image_path);
$object->SetOriginalField('Image'.$image_counter, $image_path);
$object->SetFieldOption('Image'.$image_counter, 'original_field', $item_image['Name']);
$this->_loadCustomFields($object, $item_image, $image_counter);
}
$image_counter++;
}
}
/**
* Saves newly uploaded images to external image table
*
* @param kCatDBItem|kDBItem $object
*/
function SaveItemImages(&$object)
{
if (!$this->_canUseImages($object)) {
return ;
}
$table_name = $this->Application->getUnitOption('img', 'TableName');
$max_image_count = $this->Application->getUnitOption($object->Prefix, 'ImageCount'); // $this->Application->ConfigValue($object->Prefix.'_MaxImageCount');
$i = 0;
while ($i < $max_image_count) {
$field = $i ? 'Image'.$i : 'PrimaryImage';
$field_options = $object->GetFieldOptions($field);
$image_src = $object->GetDBField($field);
if ($image_src) {
if (isset($field_options['original_field'])) {
$key_clause = 'Name = '.$this->Conn->qstr($field_options['original_field']).' AND ResourceId = '.$object->GetDBField('ResourceId');
if ($object->GetDBField('Delete'.$field)) {
// if item was cloned, then new filename is in db (not in $image_src)
$sql = 'SELECT ThumbPath
FROM '.$table_name.'
WHERE '.$key_clause;
$image_src = $this->Conn->GetOne($sql);
if (@unlink(FULL_PATH.$image_src)) {
$sql = 'DELETE FROM '.$table_name.'
WHERE '.$key_clause;
$this->Conn->Query($sql);
}
}
else {
// image record found -> update
$fields_hash = Array (
'ThumbPath' => $image_src,
);
$this->_saveCustomFields($object, $fields_hash, $i);
$this->Conn->doUpdate($fields_hash, $table_name, $key_clause);
}
}
else {
// image record not found -> create
$fields_hash = Array (
'ResourceId' => $object->GetDBField('ResourceId'),
'Name' => $field,
'AltName' => $field,
'Enabled' => STATUS_ACTIVE,
'DefaultImg' => $i ? 0 : 1, // first image is primary, others not primary
'ThumbPath' => $image_src,
'Priority' => ($i == 0)? 0 : $i * (-1),
);
$this->_saveCustomFields($object, $fields_hash, $i);
$this->Conn->doInsert($fields_hash, $table_name);
$field_options['original_field'] = $field;
$object->SetFieldOptions($field, $field_options);
}
}
$i++;
}
}
/**
* Adds ability to load custom fields along with main image field
*
* @param kCatDBItem|kDBItem $object
* @param Array $fields_hash
* @param int $counter 0 - primary image, other number - additional image number
*/
function _loadCustomFields(&$object, $fields_hash, $counter)
{
$field_name = $counter ? 'Image' . $counter . 'Alt' : 'PrimaryImageAlt';
$object->SetDBField($field_name, (string)$fields_hash['AltName']);
}
/**
* Adds ability to save custom field along with main image save
*
* @param kCatDBItem|kDBItem $object
* @param Array $fields_hash
* @param int $counter 0 - primary image, other number - additional image number
*/
function _saveCustomFields(&$object, &$fields_hash, $counter)
{
$field_name = $counter ? 'Image' . $counter . 'Alt' : 'PrimaryImageAlt';
$fields_hash['AltName'] = (string)$object->GetDBField($field_name);
}
/**
* Checks, that item can use image upload capabilities
*
* @param kCatDBItem|kDBItem $object
* @return bool
*/
function _canUseImages(&$object)
{
$prefix = $object->Prefix == 'p' ? 'img' : $object->Prefix . '-img';
return $this->Application->prefixRegistred($prefix);
}
- }
\ No newline at end of file
+ }

Event Timeline