/** * キャビネットファイルの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; }
/** * 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; }
/** * Returns a formatted-for-humans file size. * * @param int $size Size in bytes * @return string Human readable size * @see CakeNumber::toReadableSize() * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize */ public function toReadableSize($size) { return $this->_engine->toReadableSize($size); }
/** * 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); }
/** * 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; }
/** * 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; } }
/** * 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"); } } }
/** * edit method * * @return void */ public function add2() { if ($this->request->isPost()) { // $data = $this->data; // if (isset($data['File'][self::INPUT_NAME])) { // $data['File']['name'] = $data['File'][self::INPUT_NAME]['name']; // $data['File']['slug'] = Security::hash($data['File']['name'] . mt_rand() . microtime(), 'md5'); // $data['File']['extension'] = pathinfo($data['File']['name'], PATHINFO_EXTENSION); // $data['File']['original_name'] = $data['File']['slug']; // // if (preg_match('/^image/', $data['File'][self::INPUT_NAME]['type']) === 1 || // preg_match('/^video/', $data['File'][self::INPUT_NAME]['type']) === 1) { // $data['File']['alt'] = $data['File']['name']; // } // $this->FileModel->setUploadPath(self::INPUT_NAME, $data); // } // // if (! $result = $this->FileModel->saveFile($data)) { // //TODO: Error // return; // } // $result[$this->FileModel->alias]['readableSize'] = // CakeNumber::toReadableSize($result[$this->FileModel->alias]['size']); // // $this->renderJson($result); } else { $this->layout = null; $this->set('tabIndex', 0); $postMaxSize = CakeNumber::fromReadableSize(ini_get('post_max_size')); $uploadMaxFilesize = CakeNumber::fromReadableSize(ini_get('upload_max_filesize')); $this->set('maxUploadSize', CakeNumber::toReadableSize($postMaxSize > $uploadMaxFilesize ? $uploadMaxFilesize : $postMaxSize)); $this->set('maxDiskSize', CakeNumber::toReadableSize(1073741824)); $this->set('useDiskSize', CakeNumber::toReadableSize(50000000)); $this->set('data', ['File' => ['role_type' => $this->params->query['roleType'] ? $this->params->query['roleType'] : ''], 'FilesPlugin' => ['plugin_key' => $this->params->query['pluginKey'] ? $this->params->query['pluginKey'] : ''], 'FilesRoom' => ['room_id' => isset($this->params->query['roomId']) ? (int) $this->params->query['roomId'] : 0], 'FilesUser' => ['user_id' => isset($this->params->query['userId']) ? (int) $this->params->query['userId'] : (int) $this->Auth->user('id')]]); $this->set('accept', $this->params->query['accept']); } return; }