public function editar($id = null) { $producto = $this->Productos->get($id); if ($this->request->is('put')) { // or post <form> $producto = $this->Productos->patchEntity($producto, $this->request->data); if ($this->request->data['imagen']['error'] == 0) { // Eliminar el anterior $imagen_anterior = new File(WWW_ROOT . 'catalogo/' . $producto->imagen_nombre); $imagen_anterior->delete(); // Similar a unlink('catalogo/'.$producto->imagen_nombre); $producto->imagen_nombre = $this->request->data['imagen']['name']; $producto->imagen_tipo = $this->request->data['imagen']['type']; $producto->imagen_tamanio = $this->request->data['imagen']['size']; new Folder(WWW_ROOT . 'catalogo', true, 0755); $imagen = new File($this->request->data['imagen']['tmp_name']); $imagen->copy(WWW_ROOT . 'catalogo/' . $this->request->data['imagen']['name']); } if ($this->Productos->save($producto)) { $this->Flash->success('Registro guardado correctamente'); $this->redirect(['action' => 'index']); } else { $this->Flash->error('Error al momento de guardar el registro'); } } $this->set('producto', $producto); $query = $this->Categorias->find('list'); $this->set('categorias', $query); }
public function uploadToControllerFolderAndIdFolder($file, $controller, $model, $id) { $filefolder = '../webroot' . DS . 'files'; $tmppath = AMUploadBehavior::checkIfSubfolderExistsAndCreateIfFalseAndReturnPath($filefolder, $controller); $path = AMUploadBehavior::checkIfSubfolderExistsAndCreateIfFalseAndReturnPath($tmppath, $id); $filename = $file['name']; $tmpfile = new File($file['tmp_name']); $fullpath = $path . DS . $filename; $tmpfile->copy($fullpath); $tmpfile->close(); return $fullpath; }
/** * Faz uma instalação básica do plugin. * A instalação consiste em criar o arquivo de configurações do plugin no diretório apropriado. * Este método é chamado pelo método PluginStarter::load() quando necessário. * * @param string $pluginName O nome do plugin a ser instalado. * @return void */ public function install($pluginName) { $settingsFileFolder = $this->pluginInstallationFolder . $pluginName . DS; if (Plugin::loaded($pluginName)) { $defaultFile = Plugin::path($pluginName) . 'config' . DS . 'default_settings.php'; $folderHandler = new Folder(); if (!$folderHandler->cd($settingsFileFolder)) { $folderHandler->create($settingsFileFolder); } $fileHandler = new File($defaultFile); $fileHandler->copy($settingsFileFolder . 'settings.php'); $fileHandler->close(); } }
public function upload() { $evidence = $this->Evidences->newEntity(); require_once ROOT . DS . 'vendor' . DS . 'blueimp' . DS . 'jquery-file-upload' . DS . 'server' . DS . 'php' . DS . 'UploadHandler.php'; // for greater max_file_size, // sudo vim /etc/php5/cli/php.ini // change // upload_max_filesize = 1024M // post_max_size = 1024M $options = array('upload_dir' => WWW_ROOT . 'files' . DS, 'accept_file_types' => '/\\.(gif|jpe?g|png|txt|pdf|doc|docx|xls|xlsx|ppt|pptx|rar|zip|odt|tar|gz)$/i'); $upload_handler = new UploadHandler($options); $file = new File(WWW_ROOT . 'files' . DS . $upload_handler->get_file_name_param); $file->copy(WWW_ROOT . 'files' . DS . '1.pdf', true); exit; }
public function upload() { $response = []; foreach ($this->request->data('files') as $file) { $pluginsPhoto = $this->PluginsPhotos->newEntity(['name' => $file['name'], 'plugin_id' => 1]); $this->PluginsPhotos->save($pluginsPhoto); $folderDest = new Folder(WWW_ROOT . 'files/plugins/photos/d/'); $fileTemp = new File($file['tmp_name'], true, 0644); $fileTemp->copy($folderDest->path . $file['name']); $response[] = $folderDest->path . $file['name']; } $this->set(compact('response')); $this->set('_serialize', ['response']); echo json_encode($response); $this->autoRender = false; }
protected function _moveFile($data, $source = false, $destination = false, $field = false, array $options = []) { if ($source === false || $destination === false || $field === false) { return false; } if (isset($options['overwrite']) && is_bool($options['overwrite'])) { $this->_overwrite = $options['overwrite']; } if ($this->_overwrite) { $this->_deleteOldUpload($data, $field, $destination, $options); } $file = new File($source, false, 0755); if ($file->copy($this->_config['root'] . $destination, $this->_overwrite)) { return true; } return false; }
/** * Upload a file to the server * @param upload - file to upload * @param owner - contains model name and id associated with the file * @return array - uploaded file information or null for failure */ public function upload($upload, $owner = null) { // Filesize verification if ($upload['size'] == 0) { return null; } if ($upload['size'] > $this->maxFileSize) { return null; } $path = $this->storagePath; // Owner separated storage if ($this->storeOwner == true && $owner) { // Directory should be lower case $ownerTable = strtolower($owner->source()); // Owner specific directory must be unique (uuid) $ownerDirectory = Inflector::singularize($ownerTable) . $owner->id; $path .= DS . $ownerTable . DS . $ownerDirectory; } // If types do not match, default subdir is 'document' $subdir = 'document'; $types = ['image', 'audio', 'video']; // Check for filetype foreach ($types as $type) { if (strstr($upload['type'], $type)) { $subdir = $type; } } // Append the subdirectory (filtype directory) $path .= DS . $subdir; // Make directory if there is none $directory = new Folder(); if (!$directory->create(WWW_ROOT . DS . $path)) { return null; } // Find file in tmp $file = new File($upload['tmp_name']); // File's name must be unique, making the path unique as well $name = time() . '_' . Inflector::slug($upload['name']); $path .= DS . $name; // Copy from tmp to perm (create) if ($file->copy($path)) { return ['original_name' => $upload['name'], 'name' => $name, 'path' => $path, 'type' => $upload['type'], 'size' => $upload['size']]; } else { return null; } }
/** * Image manipulation view - Includes a small toolbox for basic * image editing before saving or discarding changes */ public function edit($id, $action = null, array $params = null) { $image = $this->Images->get($id, ['contain' => 'Uploads']); if ($this->request->is(['post', 'put'])) { $imgFile = new File($image->upload->full_path); // Backup original $backupFile = new File(TMP . DS . time() . 'bak'); $imgFile->copy($backupFile->path); if (!$image->hasTmp()) { return $this->Flash->error('Sorry, we lost your edit...'); } // Open tmp file $tmpFile = new File($image->tmp_path_full); // Copy tmp file to permanent location if (!$tmpFile->copy($imgFile->path)) { return $this->Flash->error('Could not save image'); } // Change recorded image dimentions and size $image->upload->size = $tmpFile->size(); $image->width = $this->Image->width($tmpFile->path); $image->height = $this->Image->height($tmpFile->path); // Delete tmp file $image->deleteTmp(); if (!$this->Images->save($image)) { // Restore file with matching, original size and dimentions $backupFile->copy($imgFile->path); $backupFile->delete(); $this->Flash->error('Could not save image.'); return $this->redirect(); } else { $this->Flash->success('Image edited successfully.'); return $this->redirect(); } } else { if (!$image->hasTmp()) { $image->makeTmp(); } } $this->set(['image' => $image, 'route' => $this->RedirectUrl->load()]); }
/** * Resize and cache image file. * * @param $file * @param $width * @param $height * @param null $folder * @return string */ public function resizeImage($file, $width, $height, $folder = null) { // init vars $width = (int) $width; $height = (int) $height; $fileInfo = pathinfo($file); $thumbName = $fileInfo['filename'] . '_' . md5($file . $width . $height) . '.' . $fileInfo['extension']; $cacheTime = 86400; if (!$folder) { $folder = $fileInfo['dirname']; } $thumbFile = $folder . $thumbName; if ($this->check() && (!is_file($thumbFile) || $cacheTime > 0 && time() > filemtime($thumbFile) + $cacheTime)) { $Thumbnail = new ImageThumbnail($file); if ($width > 0 && $height > 0) { $Thumbnail->setSize($width, $height); $Thumbnail->save($thumbFile); } else { if ($width > 0 && $height == 0) { $Thumbnail->sizeWidth($width); $Thumbnail->save($thumbFile); } else { if ($width == 0 && $height > 0) { $Thumbnail->sizeHeight($height); $Thumbnail->save($thumbFile); } else { $File = new File($file); if (file_exists($file)) { $File->copy($thumbFile); } } } } } if (is_file($thumbFile)) { return $thumbFile; } return $file; }
/** * Dump static files * * @param DOMDocument $domDocument * * @throws \Exception */ protected function dumpStaticFiles(DOMDocument $domDocument) { $xpath = new DOMXPath($domDocument); $assetsNodeList = $xpath->query('/assetic/static/files/file'); $validFlags = ['GLOB_MARK' => GLOB_MARK, 'GLOB_NOSORT' => GLOB_NOSORT, 'GLOB_NOCHECK' => GLOB_NOCHECK, 'GLOB_NOESCAPE' => GLOB_NOESCAPE, 'GLOB_BRACE' => GLOB_BRACE, 'GLOB_ONLYDIR' => GLOB_ONLYDIR, 'GLOB_ERR' => GLOB_ERR]; /** @var $assetNode DOMElement */ foreach ($assetsNodeList as $assetNode) { $source = strtr($assetNode->getElementsByTagName('source')->item(0)->nodeValue, $this->paths); $destination = strtr($assetNode->getElementsByTagName('destination')->item(0)->nodeValue, $this->paths); $flag = $assetNode->getElementsByTagName('source')->item(0)->getAttribute('flag'); if (empty($flag)) { $flag = null; } else { if (!array_key_exists($flag, $validFlags)) { throw new \Exception(sprintf('This flag "%s" not valid.', $flag)); } $flag = $validFlags[$flag]; } $des = new Folder(WWW_ROOT . $destination, true, 0777); $allFiles = glob($source, $flag); foreach ($allFiles as $src) { if (is_dir($src)) { $srcFolder = new Folder($src); $srcFolder->copy($des->pwd()); } else { $srcFile = new File($src); $srcFile->copy($des->path . DS . $srcFile->name); } $this->out($src . ' <info> >>> </info> ' . WWW_ROOT . $destination); } } }
/** * testReplaceText method * * @return void */ public function testReplaceText() { $TestFile = new File(TEST_APP . 'vendor/welcome.php'); $TmpFile = new File(TMP . 'tests' . DS . 'cakephp.file.test.tmp'); // Copy the test file to the temporary location $TestFile->copy($TmpFile->path, true); // Replace the contents of the temporary file $result = $TmpFile->replaceText('welcome.php', 'welcome.tmp'); $this->assertTrue($result); // Double check $expected = 'This is the welcome.tmp file in vendors directory'; $contents = $TmpFile->read(); $this->assertContains($expected, $contents); $search = ['This is the', 'welcome.php file', 'in tmp directory']; $replace = ['This should be a', 'welcome.tmp file', 'in the Lib directory']; // Replace the contents of the temporary file $result = $TmpFile->replaceText($search, $replace); $this->assertTrue($result); // Double check $expected = 'This should be a welcome.tmp file in vendors directory'; $contents = $TmpFile->read(); $this->assertContains($expected, $contents); $TmpFile->delete(); }
public function upload($system, $path) { // UPLOAD THE FILE TO THE RIGHT SYSTEM if ($system == 'production') { $other = 'development'; } else { $other = 'production'; } $path = str_replace('___', '/', $path); $file = new File('../../' . $other . $path); $file2 = new File('../../' . $system . $path); if (!$file2->exists()) { $dirs = explode('/', $path); $prod = new Folder('../../' . $system); for ($i = 0; $i < sizeof($dirs) - 1; $i++) { if (!$prod->cd($dirs[$i])) { $prod->create($dirs[$i]); $prod->cd($dirs[$i]); } } } if ($file->copy('../../' . $system . $path)) { if (touch('../../' . $system . $path, $file->lastChange())) { $this->Flash->success(__('File copied successfully.')); } else { $this->Flash->success(__('File copied successfully, but time not updated.')); } } else { $this->Flash->error(__('Unable copy file. ')); } return $this->redirect($this->referer()); }
/** * Move the temporary source file to the destination file. * * @param \Cake\ORM\Entity $entity The entity that is going to be saved. * @param string $source The temporary source file to copy. * @param string $destination The destination file to copy. * @param array $options The configuration options defined by the user. * @param string $field The current field to process. * * @return bool */ private function moveFile(Entity $entity, $source = '', $destination = '', array $options = [], $field) { if (empty($source) || empty($destination)) { return false; } /** * Check if the user has set an option for the overwrite. */ if (isset($options['overwrite']) && is_bool($options['overwrite'])) { $this->_overwrite = $options['overwrite']; } /** * Instance the File. */ $file = new File($source, false, 0755); /** * If you have set the overwrite to true, then we must delete the old upload file. */ if ($this->_overwrite) { $this->deleteOldUpload($entity, $field, $options, $destination); } /** * The copy function will overwrite the old file only if this file have the same * name as the old file. */ if ($file->copy($destination, $this->_overwrite)) { return true; } return false; }
private function saveAndRename($filename, $userId, $name) { $evidence = $this->newEntity(); // find extension $ext = strtolower(substr(strchr($filename, '.'), 1)); // data to save $evidence->user_id = $userId; $evidence->name = $name; $evidence->extension = $ext; if ($this->save($evidence)) { $evidenceId = $evidence->id; // rename filename $file = new File(WWW_ROOT . 'files' . DS . $filename); $file->copy(WWW_ROOT . 'files' . DS . $evidenceId . '.' . $ext); // delete original file $file->delete(); return $evidenceId; // @todo error handling if this process fail } }
/** * Make copy of the original file as a temporary file or working * file. This is used to prevent uncommitted changes affecting * the original file. * * @return boolean Success */ public function makeTmp() { // Create tmp folder if not found $tmpDir = new Folder($this->tmpDirFull, true, 0755); $tmpPath = $this->tmpDirPath . DS . $this->source() . '-' . $this->_properties['id']; $tmpPathFull = WWW_ROOT . $tmpPath; $tmpFile = new File($tmpPathFull); $tmpFile->create(); $original = new File($this->_getOriginalPath()); if ($original->copy($tmpPathFull)) { $this->tmpPath = $tmpPath; $this->tmpPathFull = $tmpPathFull; return true; } }
private function upload($id) { if (isset($this->request->data['foto']) and count($this->request->data['foto']) > 0 and $this->request->data['foto']['name'] != '') { $file = new File($this->request->data['foto']['tmp_name'], true, 0644); $ext = explode('/', $this->request->data['foto']['type']); $file->copy(ROOT . DS . 'webroot' . DS . 'ImagemProdutos' . DS . $id . '.' . strtolower($ext[1])); $file->close(); try { $img = new \abeautifulsite\SimpleImage(ROOT . DS . 'webroot' . DS . 'ImagemProdutos' . DS . $id . '.' . strtolower($ext[1])); $img->auto_orient()->best_fit(500, 500)->save(ROOT . DS . 'webroot' . DS . 'ImagemProdutos' . DS . $id . '.' . strtolower($ext[1])); } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } return $id . '.' . strtolower($ext[1]); } else { return null; } }
public function moveUploadedFile($file, $destFile) { $file = new File($file); if ($file->exists()) { return $file->copy($destFile); } return false; }
/** * beforeSave handle * @param \Cake\Event\Event $event The beforeSave event that was fired. * @param \Cake\ORM\Entity $entity The entity that is going to be saved. * @return void */ public function beforeSave(Event $event, Entity $entity) { // get config $config = $this->_config; // go through each field foreach ($config['fields'] as $field => $path) { // set virtual upload field $virtual = $field . $config['suffix']; // no field or field not array? skip if (!isset($entity[$virtual]) || !is_array($entity[$virtual])) { continue; } // get uploaded file information $file = $entity->get($virtual); // file not ok? skip if ((int) $file['error'] !== UPLOAD_ERR_OK) { continue; } // get the final name $final = $this->path($entity, $file, $path); // create the folder $folder = new Folder($config['root']); $folder->create($config['root'] . dirname($final)); // upload the file $file = new File($file['tmp_name'], false); if ($file->copy($config['root'] . $final)) { // get previous file and delete it $previous = $entity->get($field); if ($previous) { $old = new File($config['root'] . str_replace('/', DS, $previous), false); if ($old->exists()) { $old->delete(); } } // set new file $entity->set($field, str_replace(DS, '/', $final)); } // unset virtual $entity->unsetProperty($virtual); } }