示例#1
0
 /**
  * Transforms $number into a standard format.
  *
  * 	12345.67	=	12,346
  *
  * @param integer $number The number to format.
  * @param string $before The text to put in front of the number Default is ''.
  * @param integer $places The number to decimal places to show. Default is 0.
  * @return string The formated number.
  * @access public
  * @static
  */
 public static function standardFormat($number, $before = '', $places = 0)
 {
     if ($places === 0) {
         $number = round($number);
     }
     return CakeNumber::format($number, array('before' => $before, 'places' => $places));
 }
 /**
  * キャビネットファイルのUnzip
  *
  * @param Model $model CabinetFile
  * @param array $cabinetFile CabinetFileデータ
  * @return bool
  * @throws InternalErrorException
  */
 public function unzip(Model $model, $cabinetFile)
 {
     $model->begin();
     try {
         // テンポラリフォルダにunzip
         $zipPath = WWW_ROOT . $cabinetFile['UploadFile']['file']['path'] . $cabinetFile['UploadFile']['file']['id'] . DS . $cabinetFile['UploadFile']['file']['real_file_name'];
         //debug($zipPath);
         App::uses('UnZip', 'Files.Utility');
         $unzip = new UnZip($zipPath);
         $tmpFolder = $unzip->extract();
         if ($tmpFolder === false) {
             throw new InternalErrorException('UnZip Failed.');
         }
         $parentCabinetFolder = $model->find('first', ['conditions' => ['CabinetFileTree.id' => $cabinetFile['CabinetFileTree']['parent_id']]]);
         // unzipされたファイル拡張子のバリデーション
         // unzipされたファイルのファイルサイズバリデーション
         $files = $tmpFolder->findRecursive();
         $unzipTotalSize = 0;
         foreach ($files as $file) {
             //
             $unzipTotalSize += filesize($file);
             // ここでは拡張子だけチェックする
             $extension = pathinfo($file, PATHINFO_EXTENSION);
             if (!$model->isAllowUploadFileExtension($extension)) {
                 // NG
                 $model->validationErrors = [__d('cabinets', 'Unzip failed. Contains does not allow file format.')];
                 return false;
             }
         }
         // ルームファイルサイズ制限
         $maxRoomDiskSize = Current::read('Space.room_disk_size');
         if ($maxRoomDiskSize !== null) {
             // nullだったらディスクサイズ制限なし。null以外ならディスクサイズ制限あり
             // 解凍後の合計
             // 現在のルームファイルサイズ
             $roomId = Current::read('Room.id');
             $roomFileSize = $model->getTotalSizeByRoomId($roomId);
             if ($roomFileSize + $unzipTotalSize > $maxRoomDiskSize) {
                 $model->validationErrors[] = __d('cabinets', 'Failed to expand. The total size exceeds the limit.<br />' . 'The total size limit is %s (%s left).', CakeNumber::toReadableSize($roomFileSize + $unzipTotalSize), CakeNumber::toReadableSize($maxRoomDiskSize));
                 return false;
             }
         }
         // 再帰ループで登録処理
         list($folders, $files) = $tmpFolder->read(true, false, true);
         foreach ($files as $file) {
             $this->_addFileFromPath($model, $parentCabinetFolder, $file);
         }
         foreach ($folders as $folder) {
             $this->_addFolderFromPath($model, $parentCabinetFolder, $folder);
         }
     } catch (Exception $e) {
         return $model->rollback($e);
     }
     $model->commit();
     return true;
 }
示例#3
0
 /**
  * Called after the Controller::beforeFilter() and before the controller action
  *
  * @param Controller $controller Controller with components to startup
  * @return void
  */
 public function startup(Controller $controller)
 {
     // ファイルアップロード等で post_max_size を超えると $_POSTが空っぽになるため、このタイミングでエラー表示
     $contentLength = Hash::get($_SERVER, 'CONTENT_LENGTH');
     if ($contentLength > CakeNumber::fromReadableSize(ini_get('post_max_size'))) {
         $message = __d('files', 'FileUpload.post_max_size.over');
         $controller->NetCommons->setFlashNotification($message, array('class' => 'danger', 'interval' => NetCommonsComponent::ALERT_VALIDATE_ERROR_INTERVAL));
         $controller->redirect($controller->referer());
     }
 }
示例#4
0
 /**
  * Number format by market with currency code
  *
  * @param $market_id
  * @param $number
  * @param bool $no_symbol
  * @return string
  */
 public function numberCurrency($market_id, $number, $no_symbol = false)
 {
     if ($market_id == 5) {
         $currency = 'GBP';
     } elseif ($market_id == 7 || $market_id == 8 || $market_id == 9) {
         $currency = 'EUR';
     } else {
         $currency = 'USD';
     }
     if ($no_symbol) {
         $options = ['before' => false, 'after' => false, 'places' => 2];
     } else {
         $options = ['places' => 2];
     }
     return CakeNumber::currency($number, $currency, $options);
 }
示例#5
0
文件: Media.php 项目: hurad/hurad
 /**
  * Add media file
  *
  * @param array $requestData Array of POST data. Will contain form data as well as uploaded files.
  *
  * @return bool
  * @throws CakeException
  */
 public function addMedia(array $requestData)
 {
     if (CakeNumber::fromReadableSize(ini_get('post_max_size')) < env('CONTENT_LENGTH')) {
         throw new CakeException(__d('hurad', 'File could not be uploaded. please increase "post_max_size" in php.ini'));
     }
     $this->set($requestData);
     if ($this->validates()) {
         $prefix = uniqid() . '_';
         $uploadInfo = $requestData['Media']['media_file'];
         $path = date('Y') . DS . date('m');
         if ($uploadInfo['error']) {
             throw new CakeException($this->getUploadErrorMessages($uploadInfo['error']));
         }
         $folder = new Folder(WWW_ROOT . 'files' . DS . $path, true, 0755);
         if (!is_writable(WWW_ROOT . 'files')) {
             throw new CakeException(__d('hurad', '%s is not writable', WWW_ROOT . 'files'));
         }
         if (!move_uploaded_file($uploadInfo['tmp_name'], $folder->pwd() . DS . $prefix . $uploadInfo['name'])) {
             throw new CakeException(__d('hurad', 'File could not be uploaded. Please, try again.'));
         }
         $file = new File($folder->pwd() . DS . $prefix . $uploadInfo['name']);
         $requestData['Media']['user_id'] = CakeSession::read('Auth.User.id');
         $requestData['Media']['name'] = $prefix . $uploadInfo['name'];
         $requestData['Media']['original_name'] = $uploadInfo['name'];
         $requestData['Media']['mime_type'] = $file->mime();
         $requestData['Media']['size'] = $file->size();
         $requestData['Media']['extension'] = $file->ext();
         $requestData['Media']['path'] = $path;
         $requestData['Media']['web_path'] = Configure::read('General.site_url') . '/' . 'files' . '/' . $path . '/' . $prefix . $uploadInfo['name'];
         $this->create();
         if ($this->save($requestData)) {
             return true;
         } else {
             return false;
         }
     } else {
         return false;
     }
 }
示例#6
0
 /**
  * Sets protected properties based on config provided
  *
  * @param array $config Configuration array
  */
 public function __construct(array $config = [])
 {
     parent::__construct($config);
     if (!empty($this->_config['path'])) {
         $this->_path = $this->_config['path'];
     }
     if (Configure::read('debug') && !is_dir($this->_path)) {
         mkdir($this->_path, 0775, true);
     }
     if (!empty($this->_config['file'])) {
         $this->_file = $this->_config['file'];
         if (substr($this->_file, -4) !== '.log') {
             $this->_file .= '.log';
         }
     }
     if (!empty($this->_config['size'])) {
         if (is_numeric($this->_config['size'])) {
             $this->_size = (int) $this->_config['size'];
         } else {
             $this->_size = CakeNumber::fromReadableSize($this->_config['size']);
         }
     }
 }
示例#7
0
	function currency($number, $currency = null, $options = array()) {
		// App::uses('BakewellNumber', 'Utility');
		// return BakewellNumber::currency($number, $currency, $options);
		App::uses('CakeNumber', 'Utility');
		return CakeNumber::currency($number, $currency, $options);
	}
示例#8
0
 /**
  * Called during validation operations, before validation. Please note that custom
  * validation rules can be defined in $validate.
  *
  * @param array $options Options passed from Model::save().
  * @return bool True if validate operation should continue, false to abort
  * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate
  * @see Model::save()
  */
 public function beforeValidate($options = array())
 {
     $postMaxSize = CakeNumber::fromReadableSize(ini_get('post_max_size'));
     $uploadMaxFilesize = CakeNumber::fromReadableSize(ini_get('upload_max_filesize'));
     $maxUploadSize = CakeNumber::toReadableSize($postMaxSize > $uploadMaxFilesize ? $uploadMaxFilesize : $postMaxSize);
     $this->validate = Hash::merge($this->validate, array(self::INPUT_NAME => array('uploadError' => array('rule' => array('uploadError'), 'message' => array('Error uploading file'))), 'name' => array('notBlank' => array('rule' => array('notBlank'), 'message' => __d('net_commons', 'Invalid request.'), 'allowEmpty' => false, 'required' => true)), 'slug' => array('notBlank' => array('rule' => array('notBlank'), 'message' => __d('net_commons', 'Invalid request.'), 'allowEmpty' => false, 'required' => true)), 'path' => array('notBlank' => array('rule' => array('notBlank'), 'message' => __d('net_commons', 'Invalid request.'), 'allowEmpty' => false, 'on' => 'create')), 'extension' => array('notBlank' => array('rule' => array('notBlank'), 'message' => __d('net_commons', 'Invalid request.'), 'allowEmpty' => false, 'required' => true)), 'mimetype' => array('notBlank' => array('rule' => array('notBlank'), 'message' => __d('net_commons', 'Invalid request.'), 'allowEmpty' => false)), 'size' => array('numeric' => array('rule' => array('numeric'), 'message' => __d('net_commons', 'Invalid request.'), 'allowEmpty' => false)), 'role_type' => array('notBlank' => array('rule' => array('notBlank'), 'message' => __d('net_commons', 'Invalid request.'), 'allowEmpty' => false, 'required' => true)), 'number_of_downloads' => array('numeric' => array('rule' => array('numeric'), 'message' => __d('net_commons', 'Invalid request.'))), 'status' => array('numeric' => array('rule' => array('numeric'), 'message' => __d('net_commons', 'Invalid request.')))));
     return parent::beforeValidate($options);
 }
示例#9
0
 /**
  * @see: CakeNumber::addFormat()
  *
  * @param string $formatName The format name to be used in the future.
  * @param array $options The array of options for this format.
  * @return void
  * @see NumberHelper::currency()
  * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::addFormat
  */
 public function addFormat($formatName, $options)
 {
     return $this->_engine->addFormat($formatName, $options);
 }
示例#10
0
if (CakePlugin::loaded('I18n')) {
    App::uses('I18nRoute', 'I18n.Routing/Route');
    Router::defaultRouteClass('I18nRoute');
    Configure::write('Config.language', Configure::read('L10n.language'));
    Configure::write('Config.languages', Configure::read('L10n.languages'));
    if (!defined('DEFAULT_LANGUAGE')) {
        define('DEFAULT_LANGUAGE', Configure::read('L10n.language'));
    }
}
/**
 * Configure `CakeNumber` currencies.
 */
if (class_exists('CakeNumber')) {
    CakeNumber::defaultCurrency(Common::read('L10n.currency', 'USD'));
    foreach (Common::read('L10n.currencies', array()) as $currencyName => $currencyFormat) {
        CakeNumber::addFormat($currencyName, $currencyFormat);
    }
}
if (!function_exists('__t')) {
    /**
     * Translates different type of strings depending on the number of arguments it is passed and their types. Supports:
     *
     *  - all of `__()`, `__n()`, `__d()`, `__dn()`
     *  - placeholders for `String::insert()`
     *
     * Examples:
     *
     * 	- __t('Hello world!')
     * 	- __t('Hello :name!', array('name' => 'world'))
     * 	- __t('Hello mate!', 'Hello mates!', 2)
     * 	- __t(':salutation mate!', ':salutation mates!', 2, array('salutation' => 'Hello'))
<?php

Cache::config('default', array('engine' => 'File'));
// load all Plugins
CakePlugin::loadAll();
//Configuring Filters
Configure::write('Dispatcher.filters', array('AssetDispatcher', 'CacheDispatcher'));
// config the log
App::uses('CakeLog', 'Log');
CakeLog::config('debug', array('engine' => 'FileLog', 'types' => array('notice', 'info', 'debug'), 'file' => 'debug'));
CakeLog::config('error', array('engine' => 'FileLog', 'types' => array('warning', 'error', 'critical', 'alert', 'emergency'), 'file' => 'error'));
// Configure currency for BRAZIL
App::uses('CakeNumber', 'Utility');
CakeNumber::addFormat('BRR', array('before' => 'R$ ', 'thousands' => '.', 'decimals' => ',', 'zero' => 'R$ 0,00', 'after' => false));
CakeNumber::addFormat('BR', array('before' => null, 'thousands' => '.', 'decimals' => ',', 'after' => false));
/* function check route 
 ex:  if (checkRoute('pages#home')) {}  */
function checkRoute($route = null)
{
    list($controller, $action) = explode('#', $route);
    $params = Router::getParams();
    return $params['controller'] == $controller && $params['action'] == $action;
}
function mostraMes($m)
{
    switch ($m) {
        case 01:
        case 1:
            $mes = "Janeiro";
            break;
        case 02:
 /**
  * Alternative number_format() to accommodate multibyte decimals and thousands < PHP 5.4
  *
  * @param float $value
  * @param integer $places
  * @param string $decimals
  * @param string $thousands
  * @return string
  */
 protected static function _numberFormat($value, $places = 0, $decimals = '.', $thousands = ',')
 {
     if (!isset(self::$_numberFormatSupport)) {
         self::$_numberFormatSupport = version_compare(PHP_VERSION, '5.4.0', '>=');
     }
     if (self::$_numberFormatSupport) {
         return number_format($value, $places, $decimals, $thousands);
     }
     $value = number_format($value, $places, '.', '');
     $after = '';
     $foundDecimal = strpos($value, '.');
     if ($foundDecimal !== false) {
         $after = substr($value, $foundDecimal);
         $value = substr($value, 0, $foundDecimal);
     }
     while (($foundThousand = preg_replace('/(\\d+)(\\d\\d\\d)/', '\\1 \\2', $value)) != $value) {
         $value = $foundThousand;
     }
     $value .= $after;
     return strtr($value, array(' ' => $thousands, '.' => $decimals));
 }
示例#13
0
 /**
  * Returns a formatted-for-humans file size.
  *
  * @param int $size Size in bytes
  * @return string Human readable size
  * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize
  */
 public static function toReadableSize($size, $decimals = '.')
 {
     $size = parent::toReadableSize($size);
     if ($decimals !== '.') {
         $size = str_replace('.', $decimals, $size);
     }
     return $size;
 }
示例#14
0
 * 		array('callable' => $aFunction, 'on' => 'before', 'priority' => 9), // A valid PHP callback type to be called on beforeDispatch
 *		array('callable' => $anotherMethod, 'on' => 'after'), // A valid PHP callback type to be called on afterDispatch
 *
 * ));
 */
Configure::write('Dispatcher.filters', array('AssetDispatcher', 'CacheDispatcher'));
/**
 * Configures default file logging options
 */
App::uses('CakeLog', 'Log');
CakeLog::config('debug', array('engine' => 'File', 'types' => array('notice', 'info', 'debug'), 'file' => 'debug'));
CakeLog::config('error', array('engine' => 'File', 'types' => array('warning', 'error', 'critical', 'alert', 'emergency'), 'file' => 'error'));
App::uses('CakeTime', 'Utility');
App::uses('CakeNumber', 'Utility');
CakeNumber::addFormat('EUR', array('wholeSymbol' => ' &#8364;', 'wholePosition' => 'after', 'fractionSymbol' => false, 'fractionPosition' => 'after', 'zero' => 0, 'places' => 0, 'thousands' => ' ', 'decimals' => ',', 'negative' => '-', 'escape' => false));
CakeNumber::defaultCurrency('USD');
/**
 * All available languages in format (except the default which is defined in constants.php):
 * ISO-639-1 => ISO-639-2
 * napriklad 'sk' => 'slo'
 *
 * @see ISO link: http://www.loc.gov/standards/iso639-2/php/code_list.php
 */
function availableLocals()
{
    return array();
}
/**
 * Return local in format ISO-639-2.
 *
 * @param string $lang locale ISO-639-1
示例#15
0
 /**
  * testMultibyteFormat
  *
  * @return void
  */
 public function testMultibyteFormat()
 {
     $value = '5199100.0006';
     $result = $this->Number->format($value, array('thousands' => '&nbsp;', 'decimals' => '&amp;', 'places' => 3, 'escape' => false, 'before' => ''));
     $expected = '5&nbsp;199&nbsp;100&amp;001';
     $this->assertEquals($expected, $result);
     $value = 1000.45;
     $result = $this->Number->format($value, array('thousands' => ',,', 'decimals' => '.a', 'escape' => false));
     $expected = '$1,,000.a45';
     $this->assertEquals($expected, $result);
     $value = 519919827593784.0;
     $this->Number->addFormat('RUR', array('thousands' => 'ø€ƒ‡™', 'decimals' => '(§.§)', 'escape' => false, 'wholeSymbol' => '€', 'wholePosition' => 'after'));
     $result = $this->Number->currency($value, 'RUR');
     $expected = '519ø€ƒ‡™919ø€ƒ‡™827ø€ƒ‡™593ø€ƒ‡™784(§.§)00€';
     $this->assertEquals($expected, $result);
     $value = '13371337.1337';
     $result = CakeNumber::format($value, array('thousands' => '- |-| /-\\ >< () |2 -', 'decimals' => '- £€€† -', 'before' => ''));
     $expected = '13- |-| /-\\ &gt;&lt; () |2 -371- |-| /-\\ &gt;&lt; () |2 -337- £€€† -13';
     $this->assertEquals($expected, $result);
 }
 /**
  * Override main() for help message hook
  *
  * @access public
  */
 public function main()
 {
     $path = $this->path;
     $Folder = new Folder($path, true);
     $fileSufix = date('Ymd\\_His') . '.sql';
     $file = $path . $fileSufix;
     if (!is_writable($path)) {
         trigger_error('The path "' . $path . '" isn\'t writable!', E_USER_ERROR);
     }
     $this->out("Backing up...\n");
     $File = new File($file);
     $db = ConnectionManager::getDataSource($this->dataSourceName);
     $config = $db->config;
     $this->connection = "default";
     foreach ($db->listSources() as $table) {
         $table = str_replace($config['prefix'], '', $table);
         // $table = str_replace($config['prefix'], '', 'dinings');
         $ModelName = Inflector::classify($table);
         if (in_array($ModelName, $this->excluidos)) {
             continue;
         }
         $Model = ClassRegistry::init($ModelName);
         $Model->virtualFields = array();
         $DataSource = $Model->getDataSource();
         $this->Schema = new CakeSchema(array('connection' => $this->connection));
         $cakeSchema = $db->describe($table);
         // $CakeSchema = new CakeSchema();
         $this->Schema->tables = array($table => $cakeSchema);
         $File->write("\n/* Drop statement for {$table} */\n");
         $File->write("\nSET foreign_key_checks = 0;\n\n");
         #$File->write($DataSource->dropSchema($this->Schema, $table) . "\n");
         $File->write($DataSource->dropSchema($this->Schema, $table));
         $File->write("SET foreign_key_checks = 1;\n");
         $File->write("\n/* Backuping table schema {$table} */\n");
         $File->write($DataSource->createSchema($this->Schema, $table) . "\n");
         $File->write("/* Backuping table data {$table} */\n");
         unset($valueInsert, $fieldInsert);
         $rows = $Model->find('all', array('recursive' => -1));
         $quantity = 0;
         $File->write($this->separador . "\n");
         if (count($rows) > 0) {
             $fields = array_keys($rows[0][$ModelName]);
             $values = array_values($rows);
             $count = count($fields);
             for ($i = 0; $i < $count; $i++) {
                 $fieldInsert[] = $DataSource->name($fields[$i]);
             }
             $fieldsInsertComma = implode(', ', $fieldInsert);
             foreach ($rows as $k => $row) {
                 unset($valueInsert);
                 for ($i = 0; $i < $count; $i++) {
                     $valueInsert[] = $DataSource->value(utf8_encode($row[$ModelName][$fields[$i]]), $Model->getColumnType($fields[$i]), false);
                 }
                 $query = array('table' => $DataSource->fullTableName($table), 'fields' => $fieldsInsertComma, 'values' => implode(', ', $valueInsert));
                 $File->write($DataSource->renderStatement('create', $query) . ";\n");
                 $quantity++;
             }
         }
         $this->out('Model "' . $ModelName . '" (' . $quantity . ')');
     }
     $this->out("Backup: " . $file);
     $this->out("Peso:: " . CakeNumber::toReadableSize(filesize($file)));
     $File->close();
     if (class_exists('ZipArchive') && filesize($file) > 100) {
         $zipear = $this->in('Deseas zipear este backup', null, 's');
         $zipear = strtolower($zipear);
         if ($zipear === 's') {
             $this->hr();
             $this->out('Zipping...');
             $zip = new ZipArchive();
             $zip->open($file . '.zip', ZIPARCHIVE::CREATE);
             $zip->addFile($file, $fileSufix);
             $zip->close();
             $this->out("Peso comprimido: " . CakeNumber::toReadableSize(filesize($file . '.zip')));
             $this->out("Listo!");
             if (file_exists($file . '.zip') && filesize($file) > 10) {
                 unlink($file);
             }
             $this->out("Database Backup Successful.\n");
         }
     }
 }
 /**
  * NetCommons3のシステム管理→一般設定で許可されているルーム容量内かをチェックするバリデータ
  *
  * @param Model $model Model
  * @param array $check バリデートする値
  * @return bool|string 容量内: true, 容量オーバー: string エラーメッセージ
  */
 public function validateRoomFileSizeLimit(Model $model, $check)
 {
     $field = $this->_getField($check);
     $roomId = Current::read('Room.id');
     $maxRoomDiskSize = Current::read('Space.room_disk_size');
     if ($maxRoomDiskSize === null) {
         return true;
     }
     $size = $check[$field]['size'];
     $roomTotalSize = $this->getTotalSizeByRoomId($model, $roomId);
     if ($roomTotalSize + $size < $maxRoomDiskSize) {
         return true;
     } else {
         $roomsLanguage = ClassRegistry::init('Room.RoomsLanguage');
         $data = $roomsLanguage->find('first', ['conditions' => ['room_id' => $roomId, 'language_id' => Current::read('Language.id')]]);
         $roomName = $data['RoomsLanguage']['name'];
         // ファイルサイズをMBとかkb表示に
         $message = __d('files', 'Total file size uploaded to the %s, exceeded the limit. The limit is %s(%s left).', $roomName, CakeNumber::toReadableSize($maxRoomDiskSize), CakeNumber::toReadableSize($maxRoomDiskSize - $roomTotalSize));
         return $message;
     }
 }
示例#18
0
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
App::uses('Controller', 'Controller');
App::uses('CakeNumber', 'Utility');
App::uses('CakeTime', 'Utility');
$options = array('before' => false, 'fractionPosition' => 'after', 'zero' => 0, 'places' => 2, 'thousands' => '.', 'decimals' => ',', 'negative' => '-', 'escape' => true);
CakeNumber::addFormat('BR', $options);
/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller
{
    public $components = array('RequestHandler', 'Session', 'Acl', 'Auth' => array('authorize' => array('Actions' => array('actionPath' => 'controllers'))));
    public $helpers = array('Html', 'Form', 'Session', 'Js');
    public function beforeRender()
    {
示例#19
0
 /**
  * Replace by formatted currency string.
  *
  * Examples:
  *  - [currency]50[/currency]
  *  - [currency zero="$0.00"]0[/currency]
  *
  * @param string $str String to check and modify.
  * @return string Modified string.
  */
 protected function _replaceCurrency($str)
 {
     if (!preg_match_all('/\\[currency(.*?)\\](.*)\\[\\/currency\\]/i', $str, $matches)) {
         // Fallback regex for when no options are passed.
         if (!preg_match_all('/\\[currency(.*?)\\](.[^\\[]*)\\[\\/currency\\]/i', $str, $matches)) {
             return $str;
         }
     }
     foreach ($matches[0] as $i => $find) {
         $opts = $this->_extractAttributes(trim($matches[1][$i]));
         $currency = CakeNumber::defaultCurrency();
         if (isset($opts['currency'])) {
             $currency = $opts['currency'];
             unset($opts['currency']);
         }
         $replace = empty($matches[2][$i]) || !is_numeric($matches[2][$i]) ? '' : CakeNumber::currency($matches[2][$i], $currency, $opts);
         $str = str_replace($find, $replace, $str);
     }
     return $str;
 }
 public function exportToExcel($data = array(), $filename = null)
 {
     /*
      * Export to excel - php
      */
     //http://w3lessons.info/2015/07/13/export-html-table-to-excel-csv-json-pdf-png-using-jquery/
     //html contain export in excel(upper link)
     // http://www.codexworld.com/export-data-to-excel-in-php/
     $preparedArray = array();
     if (!empty($data)) {
         $payment_total = 0;
         $receipt_total = 0;
         foreach ($data as $signleTransaction) {
             $recordArray = array();
             if ($signleTransaction["Transaction"]["transaction_type"] == "Payment") {
                 $amount = $signleTransaction["Transaction"]["amount"];
                 $recordArray["Payment Amount"] = CakeNumber::currency($amount, "");
                 $recordArray["Payment Particulars"] = $this->getParticulars($signleTransaction);
                 $payment_total += $amount;
             } else {
                 $recordArray["Payment Amount"] = null;
                 $recordArray["Payment Particulars"] = null;
             }
             if ($signleTransaction["Transaction"]["transaction_type"] == "Receipt") {
                 $amount = $signleTransaction["Transaction"]["amount"];
                 $recordArray["Receipt Amount"] = CakeNumber::currency($amount, "");
                 $recordArray["Receipt Particulars"] = $this->getParticulars($signleTransaction);
                 $receipt_total += $amount;
             } else {
                 $recordArray["Receipt Amount"] = null;
                 $recordArray["Receipt Particulars"] = null;
             }
             $preparedArray[] = $recordArray;
         }
         $recordArray = array();
         $recordArray["Payment Amount"] = null;
         $recordArray["Payment Particulars"] = null;
         $recordArray["Receipt Amount"] = null;
         $recordArray["Receipt Particulars"] = null;
         $preparedArray[] = $recordArray;
         $recordArray = array();
         $recordArray["Payment Amount"] = "Total Payment";
         $recordArray["Payment Particulars"] = null;
         $recordArray["Receipt Amount"] = "Total Receipt";
         $recordArray["Receipt Particulars"] = null;
         $preparedArray[] = $recordArray;
         $recordArray["Payment Amount"] = CakeNumber::currency($payment_total, "");
         $recordArray["Payment Particulars"] = null;
         $recordArray["Receipt Amount"] = CakeNumber::currency($receipt_total, "");
         $recordArray["Receipt Particulars"] = null;
         $preparedArray[] = $recordArray;
     }
     //        $preparedArray = array();
     //        if (!empty($data)) {
     //            foreach ($data as $signleTransaction) {
     //                $recordArray = array();
     //                $recordArray["Amount"] = $signleTransaction["Transaction"]["amount"];
     //                $recordArray["Transaction Type"] = $signleTransaction["Transaction"]["transaction_type"];
     //                $recordArray["Is Interest Entry"] = $signleTransaction["Transaction"]["is_interest"];
     //                $recordArray["Remarks"] = $signleTransaction["Transaction"]["remarks"];
     //                $recordArray["Transaction Date"] = $signleTransaction["Transaction"]["transaction_date"];
     //                $recordArray["Created Date"] = $signleTransaction["Transaction"]["created"];
     //                $recordArray["Modified Date"] = $signleTransaction["Transaction"]["modified"];
     //                $preparedArray[] = $recordArray;
     //            }
     //        }
     if (empty($filename)) {
         // file name for download
         $filename = "export_data" . date('Ymd') . ".xls";
     }
     $columnHeadings = array("Amount", "Particulars(Payment)", "Amount", "Particulars(Receipt)");
     // headers for download
     header("Content-Disposition: attachment; filename=\"{$filename}\"");
     header("Content-Type: application/vnd.ms-excel");
     $flag = false;
     foreach ($preparedArray as $row) {
         if (!$flag) {
             // display column names as first row
             //echo implode("\t", array_keys($row)) . "\n";
             echo implode("\t", $columnHeadings) . "\n";
             $flag = true;
         }
         // filter data
         array_walk($row, array($this, 'filterData'));
         echo implode("\t", array_values($row)) . "\n";
     }
     exit;
 }
示例#21
0
 /**
  * Getter/setter for default currency
  *
  * @param string $currency Default currency string  used by currency() if $currency argument is not provided
  * @return string Currency
  */
 public static function defaultCurrency($currency = null)
 {
     if ($currency) {
         self::$_defaultCurrency = $currency;
     }
     return self::$_defaultCurrency;
 }
/**
 * Configures default file logging options
 */
App::uses('CakeLog', 'Log');
CakeLog::config('debug', array('engine' => 'File', 'types' => array('notice', 'info', 'debug'), 'file' => 'debug'));
CakeLog::config('error', array('engine' => 'File', 'types' => array('warning', 'error', 'critical', 'alert', 'emergency'), 'file' => 'error'));
/*  ==  */
// Definindo idioma da aplicação
Configure::write('Config.language', 'pt-br');
// Adicionando o caminho do locale
App::build(array('locales' => dirname(dirname(__FILE__)) . DS . 'locale' . DS));
// Alteração do inflector
$_uninflected = array('atlas', 'lapis', 'onibus', 'pires', 'virus', '.*x');
$_pluralIrregular = array('abdomens' => 'abdomen', 'alemao' => 'alemaes', 'artesa' => 'artesaos', 'as' => 'ases', 'bencao' => 'bencaos', 'cao' => 'caes', 'capelao' => 'capelaes', 'capitao' => 'capitaes', 'chao' => 'chaos', 'charlatao' => 'charlataes', 'cidadao' => 'cidadaos', 'consul' => 'consules', 'cristao' => 'cristaos', 'dificil' => 'dificeis', 'email' => 'emails', 'escrivao' => 'escrivaes', 'fossel' => 'fosseis', 'germens' => 'germen', 'grao' => 'graos', 'hifens' => 'hifen', 'irmao' => 'irmaos', 'liquens' => 'liquen', 'mal' => 'males', 'mao' => 'maos', 'orfao' => 'orfaos', 'pais' => 'paises', 'pai' => 'pais', 'pao' => 'paes', 'perfil' => 'perfis', 'projetil' => 'projeteis', 'reptil' => 'repteis', 'sacristao' => 'sacristaes', 'sotao' => 'sotaos', 'tabeliao' => 'tabeliaes', 'banner' => 'banners', 'newsletter' => 'newsletters', 'status' => 'status');
Inflector::rules('singular', array('rules' => array('/^(.*)(oes|aes|aos)$/i' => '\\1ao', '/^(.*)(a|e|o|u)is$/i' => '\\1\\2l', '/^(.*)e?is$/i' => '\\1il', '/^(.*)(r|s|z)es$/i' => '\\1\\2', '/^(.*)ns$/i' => '\\1m', '/^(.*)s$/i' => '\\1'), 'uninflected' => $_uninflected, 'irregular' => array_flip($_pluralIrregular)), true);
Inflector::rules('plural', array('rules' => array('/^(.*)ao$/i' => '\\1oes', '/^(.*)(r|s|z)$/i' => '\\1\\2es', '/^(.*)(a|e|o|u)l$/i' => '\\1\\2is', '/^(.*)il$/i' => '\\1is', '/^(.*)(m|n)$/i' => '\\1ns', '/^(.*)$/i' => '\\1s'), 'uninflected' => $_uninflected, 'irregular' => $_pluralIrregular), true);
Inflector::rules('transliteration', array('/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A', '/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E', '/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I', '/Ò|Ó|Ô|Õ|Ö|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O', '/Ù|Ú|Û|Ü|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U', '/Ç|Ć|Ĉ|Ċ|Č/' => 'C', '/Ð|Ď|Đ/' => 'D', '/Ĝ|Ğ|Ġ|Ģ/' => 'G', '/Ĥ|Ħ/' => 'H', '/Ĵ/' => 'J', '/Ķ/' => 'K', '/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L', '/Ñ|Ń|Ņ|Ň/' => 'N', '/Ŕ|Ŗ|Ř/' => 'R', '/Ś|Ŝ|Ş|Š/' => 'S', '/Ţ|Ť|Ŧ/' => 'T', '/Ý|Ÿ|Ŷ/' => 'Y', '/Ź|Ż|Ž/' => 'Z', '/Ŵ/' => 'W', '/Æ|Ǽ/' => 'AE', '/ß/' => 'ss', '/IJ/' => 'IJ', '/Œ/' => 'OE', '/à|á|â|ã|ä|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a', '/è|é|ê|ë|ē|ĕ|ė|ę|ě|&/' => 'e', '/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i', '/ò|ó|ô|õ|ö|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o', '/ù|ú|û|ü|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u', '/ç|ć|ĉ|ċ|č/' => 'c', '/ð|ď|đ/' => 'd', '/ĝ|ğ|ġ|ģ/' => 'g', '/ĥ|ħ/' => 'h', '/ĵ/' => 'j', '/ķ/' => 'k', '/ĺ|ļ|ľ|ŀ|ł/' => 'l', '/ñ|ń|ņ|ň|ʼn/' => 'n', '/ŕ|ŗ|ř/' => 'r', '/ś|ŝ|ş|š|ſ/' => 's', '/ţ|ť|ŧ/' => 't', '/ý|ÿ|ŷ/' => 'y', '/ŵ/' => 'w', '/ź|ż|ž/' => 'z', '/æ|ǽ/' => 'ae', '/ij/' => 'ij', '/œ/' => 'oe', '/ƒ/' => 'f'));
unset($_uninflected, $_pluralIrregular);
Cache::config('appCache', array('engine' => 'File', 'duration' => '+10 years', 'path' => CACHE . DS . 'app'));
Cache::config('pdfCache', array('engine' => 'File', 'duration' => '+10 years', 'path' => CACHE . DS . 'pdf'));
App::uses('IniReader', 'Configure');
// Read config files from app/Config
Configure::config('CONFIG', new IniReader());
Configure::load('CONFIG', 'CONFIG');
App::uses('CakeNumber', 'Utility');
CakeNumber::addFormat('BRL', array('before' => 'R$', 'thousands' => '.', 'decimals' => ','));
define('APP_BASE_PATH', ROOT . DS . APP_DIR);
define('APP_WEBROOT_BASE_PATH', ROOT . DS . APP_DIR . DS . WEBROOT_DIR);
CakePlugin::load('Mapbiomas');
CakePlugin::load('Export');
CakePlugin::load('Dashboard');
示例#23
0
 /**
  * Sets protected properties based on config provided
  *
  * @param array $config Engine configuration
  *
  * @return array
  */
 public function config($config = array())
 {
     parent::config($config);
     if (!empty($config['path'])) {
         $this->_path = $config['path'];
     }
     if (Configure::read('debug') && !is_dir($this->_path)) {
         mkdir($this->_path, 0775, TRUE);
     }
     if (!empty($config['file'])) {
         $this->_file = $config['file'];
         if (substr($this->_file, -4) !== '.log') {
             $this->_file .= '.log';
         }
     }
     if (!empty($config['size'])) {
         if (is_numeric($config['size'])) {
             $this->_size = (int) $config['size'];
         } else {
             $this->_size = CakeNumber::fromReadableSize($config['size']);
         }
     }
     return $this->_config;
 }
示例#24
0
 public function convert_price($number)
 {
     return CakeNumber::format($number, array('places' => 0, 'before' => ' ', 'escape' => false, 'decimals' => '.', 'thousands' => ','));
 }
示例#25
0
 /**
  * Getter/setter for default currency
  *
  * @param string $currency The currency to be used in the future.
  * @return string Currency
  * @see CakeNumber::defaultCurrency()
  */
 public function defaultCurrency($currency)
 {
     return $this->_engine->defaultCurrency($currency);
 }
 /**
  * Valdates the error value that comes with the file input file
  *
  * @param Model $Model
  * @param integer Error value from the form input [file_field][error]
  * @return boolean True on success, if false the error message is set to the models field and also set in $this->uploadError
  */
 public function validateUploadError(Model $Model, $error = null)
 {
     if (!is_null($error)) {
         switch ($error) {
             case UPLOAD_ERR_OK:
                 return true;
                 break;
             case UPLOAD_ERR_INI_SIZE:
                 $this->uploadError = __d('file_storage', 'The uploaded file exceeds limit of %s.', CakeNumber::toReadableSize(ini_get('upload_max_filesize')));
                 break;
             case UPLOAD_ERR_FORM_SIZE:
                 $this->uploadError = __d('file_storage', 'The uploaded file is to big, please choose a smaller file or try to compress it.');
                 break;
             case UPLOAD_ERR_PARTIAL:
                 $this->uploadError = __d('file_storage', 'The uploaded file was only partially uploaded.');
                 break;
             case UPLOAD_ERR_NO_FILE:
                 if ($this->settings[$Model->alias]['allowNoFileError'] === false) {
                     $this->uploadError = __d('file_storage', 'No file was uploaded.');
                     return false;
                 }
                 return true;
                 break;
             case UPLOAD_ERR_NO_TMP_DIR:
                 $this->uploadError = __d('file_storage', 'The remote server has no temporary folder for file uploads. Please contact the site admin.');
                 break;
             case UPLOAD_ERR_CANT_WRITE:
                 $this->uploadError = __d('file_storage', 'Failed to write file to disk. Please contact the site admin.');
                 break;
             case UPLOAD_ERR_EXTENSION:
                 $this->uploadError = __d('file_storage', 'File upload stopped by extension. Please contact the site admin.');
                 break;
             default:
                 $this->uploadError = __d('file_storage', 'Unknown File Error. Please contact the site admin.');
                 break;
         }
         return false;
     }
     return true;
 }
示例#27
0
    function word($id = NULL)
    {
        $this->autoRender = false;
        $delivery_data = $this->Proforma->find('all', array('order' => array('Proforma.id' => 'DESC'), 'recursive' => 5));
        //pr($delivery_data);exit;
        //$this->set('proforma', $delivery_data);
        $file_type = 'doc';
        $filename = $id;
        $html = '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>PDF</title>
<style>
body { background-color:#fff; font-family:"Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; color:#394263; font-size:14px; }
* { text-decoration: none; font-size: 1em; outline: none; padding: 0; margin: 0; }
.group:before, .group:after { content: ""; display: table; }
.group:after { clear: both; }
.group { zoom: 1; /* For IE 6/7 (trigger hasLayout) */ }
.pdf_container { margin: 0 auto; min-height: 800px; padding: 10px; width: 900px; }
.header_id { padding:10px 0; width:100%; display:block; }
.logo { margin-top:10px;display:inline-block;width:50%; }
.address_details { width:46%; line-height:20px; text-align:right;display:inline-block; }
.address_details p { float:left; width:100%; }
.address_details a { color: #1bbae1; float:left; width:100%; }
.cmpny_reg { background:#FF8E00; padding:5px; color:#fff; text-transform:uppercase; width:100%; float:left; margin:10px 0 0 -8px; }
.address_box { border: 1px solid #ccc; margin-top: 20px; padding: 10px; width: 47%; min-height: 185px;display:inline-block; }
.address_box h2 { width:100%; padding:5px 0; font-size:23px; font-weight:bold; text-align:center; display:inline-block;}
.address_box p { display:inline-block;}
.invoice_address_blog { margin-top:20px; display:inline-block;width:100%;}
.invoice_add {  margin:3px 0; display:inline-block;width:100%;}
.invoice_add h5 { display:inline-block; width:30%; }
.invoice_add span { margin-right:15px;display:inline-block; }
.invoice_add abbr { font-style: italic;display:inline-block; }
.services_details { margin-top:20px; width:100%; }
.services_details h4 { width:100%; margin-top:20px; font-size:15px; font-weight:bold; }
.services_details h4 abbr { width: 22%; display:inline-block;}
.services_details h4 span { color:#fff; background-color:#1BBAE1; padding: 0 10px; }
.invoice_table { width:100%; margin-top:20px;margin-bottom:30px; }
.invoice_table table { width:100%; border:1px  solid #ccc; border-bottom:none; border-left:none; }
.invoice_table table th, td { padding: 10px; text-align: center; text-transform:uppercase; border:1px solid #ccc; border-top:none; border-right:none; }
.invoice_table table thead { background-color: #f1f1f1; }
.instrument h4 { font-weight:normal; }
.instrument span { font-size: 13px; color: #2980b9; font-style: italic; margin: 0 10px; }
    
</style>
</head>';
        foreach ($delivery_data as $delivery_data_list) {
            $customername = $delivery_data_list['Customer']['customername'];
            $billing_address = $delivery_data_list['Customer']['Address'][1]['address'];
            $phone = $delivery_data_list['Salesorder']['phone'];
            $fax = $delivery_data_list['Salesorder']['fax'];
            $email = $delivery_data_list['Salesorder']['email'];
            $our_ref_no = $delivery_data_list['Salesorder']['our_ref_no'];
            $ref_no = $delivery_data_list['Salesorder']['ref_no'];
            $reg_date = $delivery_data_list['Proforma']['reg_date'];
            $contact = $delivery_data_list['Quotation']['Customer']['Contactpersoninfo'][0]['name'];
            $payment_term = $delivery_data_list['Customer']['Paymentterm']['paymentterm'] . ' ' . $delivery_data_list['Customer']['Paymentterm']['paymenttype'];
            $salesorderno = $delivery_data_list['Proforma']['salesorderno'];
            foreach ($delivery_data_list['Salesorder']['Description'] as $device) {
                $device_name[] = $device;
                //$device_price[]= $device;
            }
        }
        //pr($device_name);exit;
        $html .= '<body>
<div class="pdf_container group"> 
     <!-- header part-->
     <div class="header_id">
          <div class="f_left logo"><img src="img/logoBs.png" width="273" height="50" alt="" /></div>
          <div class="address_details f_right">
               <p>41 SENOKO DRIVE</p>
               <p>SINGAPORE</p>
               <p>758249</p>
               <p> 6458 4411</p>
               <a href="#" title="">invoice@bestandards.com</a>
               <div class="cmpny_reg">GST REG NO. M200510697 / COMPANY REG NO. 200510697M</div>
          </div>
     </div>
     <div class="address_box">
          <p> ' . $customername . ' </p>
          <p> ' . $billing_address . ' </p>
          <p> Singapore 758301 </p>
          <div class="invoice_address_blog">
               <div class="invoice_add">
                    <h5>ATTN </h5>
                    <span>:</span><abbr>' . $contact . '</abbr></div>
               <div class="invoice_add">
                    <h5>TEL </h5>
                    <span>:</span><abbr> ' . $phone . ' </abbr></div>
               <div class="invoice_add">
                    <h5>FAX </h5>
                    <span>:</span><abbr>' . $fax . '</abbr></div>
               <div class="invoice_add">
                    <h5>EMAIL </h5>
                    <span>:</span><abbr>' . $email . '</abbr></div>
          </div>
     </div>
     <div class="address_box">
          <h2 class=""> ' . $id . ' </h2>
          <div class="invoice_address_blog f_left">
               <div class="invoice_add f_left">
                    <h5> TRACK ID </h5>
                    <span>:</span><abbr>' . $our_ref_no . '</abbr></div>
               <div class="invoice_add f_left">
                    <h5>PURCHASE ORDER NUMBER </h5>
                    <span>:</span><abbr>' . $ref_no . '</abbr></div>
               <div class="invoice_add f_left">
                    <h5>DATE </h5>
                    <span>:</span><abbr>' . $reg_date . '</abbr></div>
               <div class="invoice_add f_left">
                    <h5> PAYMENT TERMS </h5>
                    <span>:</span><abbr>' . $payment_term . '</abbr></div>
          </div>
     </div>
     <div class="services_details f_left">
          <p>Being provided calibration service of the following(s) :</p>
          <h4 class="f_left"><abbr>SALES ORDER NO</abbr><span> ' . $salesorderno . '</span></h4>
     </div>
     <div class="invoice_table f_left">
          <table cellpadding="0" cellspacing="0">
               <thead>
                    <tr>
                         <th>Instrument</th>
                         <th>Brand</th>
                         <th>Model</th>
                         <th>Serial No</th>
                         <th>Quantity</th>
                         <th>Unit Price $(SGD)</th>
                         <th>Total Price $(SGD)</th>
                    </tr>
               </thead>
               <tbody>';
        $subtotal = 0;
        foreach ($device_name as $device) {
            $html .= '
                    <tr>
                         <td class="instrument"><h4>' . $device['Instrument']['name'] . '</h4>
                              <span>Faulty</span> <span>(9~10)/mm</span></td>
                         <td>' . $device['Instrument']['InstrumentBrand']['Brand']['brandname'] . '</td>
                         <td>' . $device['model_no'] . '</td>
                         <td>53254324</td>
                         <td>1</td>
                         <td> $' . $device['sales_unitprice'] . '</td>
                         <td> $' . $device['sales_unitprice'] . '</td>
                    </tr>';
            $subtotal = $subtotal + $device['sales_unitprice'];
        }
        $gst = $subtotal * 0.07000000000000001;
        //setlocale(LC_MONETARY, 'en_SG');
        //$subtotal = money_format('%i', $subtotal);
        //$gst = money_format('%i', $gst);
        $total_due = $gst + $subtotal;
        App::uses('CakeNumber', 'Utility');
        $currency = 'USD';
        $total_due = CakeNumber::currency($total_due, $currency);
        $gst = CakeNumber::currency($gst, $currency);
        $subtotal = CakeNumber::currency($subtotal, $currency);
        //$total_due = $this->Number->currency($total_due, $currency);
        //$total_due = money_format('%i', $total_due);
        //echo $a;
        //exit;
        $html .= '<tr>
                         <td colspan="6">SUBTOTAL</td>
                         <td>' . $subtotal . '</td>
                    </tr>
                    <tr>
                         <td colspan="6">GST ( 7.00% )</td>
                         <td>' . $gst . '</td>
                    </tr>
                    <tr>
                         <td colspan="6"><h4>TOTAL DUE</h4></td>
                         <td><h4>' . $total_due . '</h4></td>
                    </tr>
               </tbody>
          </table>
     </div>
</div>
</body>
</html>';
        $this->export_report_all_format($file_type, $filename, $html);
    }
示例#28
0
 /**
  * @param totalCodes The total number of codes the user is purchasing
  */
 public function getItemName($totalCodes)
 {
     // called as CakeNumber
     App::uses('CakeNumber', 'Utility');
     $itemName = CakeNumber::format($totalCodes, array('places' => 0, 'before' => '', 'escape' => false, 'thousands' => ','));
     return $itemName . " download codes";
 }
 /**
  * Checks the filesize
  *
  * @param string|array $check
  * @param integer|string $size Size in bytes or human readable string like '5MB'
  * @param string $operator See `Validation::comparison()`
  * @return boolean Success
  */
 public static function fileSize($check, $operator = null, $size = null)
 {
     if (is_array($check) && isset($check['tmp_name'])) {
         $check = $check['tmp_name'];
     }
     if (is_string($size)) {
         $size = CakeNumber::fromReadableSize($size);
     }
     $filesize = filesize($check);
     return self::comparison($filesize, $operator, $size);
 }
 /**
  * Add product names from drupal for items
  *
  * @param $items
  * @param $market_id
  * @return array
  */
 private function processItems($items, $market_id)
 {
     $ret = [];
     $parents = [];
     $children = [];
     foreach ($items as $i) {
         $name = '';
         /**
          * Optionally add variant master name
          */
         if (!empty($i['Item']['ParentItems']) && $i['Item']['ParentItems'][0]['item_type_id'] == 2) {
             $name = $this->drupalName($i['Item']['ParentItems'][0]) . ' - ';
             $variant = true;
         } else {
             $variant = false;
         }
         $name .= $this->drupalName($i);
         $child = !empty($i['parent_id']);
         $cur = $this->currencyByMarket($market_id);
         $dec = ['places' => 2];
         if ($child) {
             $price = CakeNumber::currency($i['price'], $cur, $dec);
             $suppl = CakeNumber::currency($i['price'], $cur, $dec);
         } else {
             if ($variant == true) {
                 $price = CakeNumber::currency($i['Item']['ParentItems'][0]['ItemPrice']['price'], $cur, $dec);
                 $suppl = CakeNumber::currency($i['Item']['ParentItems'][0]['ItemPrice']['price_supplement'], $cur, $dec);
             } else {
                 $price = CakeNumber::currency($i['Item']['ItemPrice']['price'], $cur, $dec);
                 $suppl = CakeNumber::currency($i['Item']['ItemPrice']['price_supplement'], $cur, $dec);
             }
         }
         $sub = CakeNumber::currency($i['price'] * $i['quantity'], $cur, $dec);
         $total = CakeNumber::currency($i['extended_price'], $cur, $dec);
         $status = $i['order_item_hold_code_id'];
         if (!$child) {
             $class = 'success';
         } else {
             $class = 'warning';
         }
         if ($status == 1) {
             $class = 'danger';
         }
         $object = ['id' => $i['id'], 'item_id' => $i['Item']['id'], 'shipment_id' => $i['order_shipment_id'], 'hold_code' => $i['order_item_hold_code_id'], 'ns_warehouse_id' => $i['ns_warehouse_id'], 'parent_id' => $i['parent_id'], 'sku' => $i['Item']['sku'], 'display_name' => $name, 'quantity' => $i['quantity'], 'price' => $price, 'price_supplement' => $suppl, 'total' => $total, 'subtotal' => $sub, 'backorder' => $status == 1, 'class' => $class];
         if (!empty($i['OrderItemRestock'])) {
             $object['restock_date'] = $i['OrderItemRestock'][0]['restock_date'];
         }
         if ($child) {
             $children[$i['parent_id']][] = $object;
         } else {
             $parents[] = $object;
         }
     }
     foreach ($parents as $obj) {
         $ret[] = $obj;
         $child_items = $children[$obj['id']];
         if (!empty($child_items)) {
             foreach ($child_items as $c) {
                 $ret[] = $c;
             }
         }
     }
     return $ret;
 }