function updateProcess($id) { $send = Request::get('send'); $valid = Validator::make(array('send.title' => 'min:1|slashes', 'send.content' => 'min:1', 'send.keywords' => 'slashes')); if (!$valid) { throw new Exception("Error Processing Request: " . Validator::getMessage()); } $uploadMethod = Request::get('uploadMethod'); $loadData = Pages::get(array('where' => "where pageid='{$id}'")); if (!isset($loadData[0]['pageid'])) { throw new Exception("This page not exists."); } switch ($uploadMethod) { case 'frompc': if (Request::hasFile('imageFromPC')) { if (Request::isImage('imageFromPC')) { $send['image'] = File::upload('imageFromPC'); File::remove($loadData[0]['image']); } } break; case 'fromurl': if (Request::isImage('imageFromUrl')) { $url = Request::get('imageFromUrl'); $send['image'] = File::upload('uploadFromUrl'); File::remove($loadData[0]['image']); } break; } if (!Pages::update($id, $send)) { throw new Exception("Error. " . Database::$error); } }
public static function uploadFromUrl($imgUrl, $shortPath = 'uploads/images/') { $shortPath = File::uploadFromUrl($imgUrl, $shortPath); $result = self::isImage($shortPath); if (!$result) { File::remove($shortPath); return false; } return $shortPath; }
/** * Delete all image files that match $fileNameRegexp * @param string $imagesPath, * @param string $fileNameRegexp */ public static function deleteExistingFiles($imagesPath, $fileNameRegexp) { if (is_dir($imagesPath)) { $files = scandir($imagesPath); foreach ($files as $fileName) { if (preg_match($fileNameRegexp, $fileName)) { @File::remove(rtrim($imagesPath, '/\\') . DIRECTORY_SEPARATOR . $fileName); } } } }
public static function flush($group = null, $key = null) { if ($group === null) { File::removeAllFrom(self::$dir); } else { if ($key == null) { return File::removeAllFrom(self::$dir . '/' . String::replace('.', '/', $group)); } else { return File::remove(self::$dir . '/' . String::replace('.', '/', $group) . '/' . $key); } } }
function updateProcess($id) { $send = Request::get('send'); $valid = Validator::make(array('send.title' => 'min:1|slashes', 'send.keywords' => 'slashes', 'tags' => 'slashes', 'send.catid' => 'slashes', 'send.type' => 'slashes', 'send.allowcomment' => 'slashes')); if (!$valid) { throw new Exception("Error Processing Request. Error: " . Validator::getMessage()); } $uploadMethod = Request::get('uploadMethod'); $loadData = Post::get(array('where' => "where postid='{$id}'")); if (!isset($loadData[0]['postid'])) { throw new Exception("This post not exists."); } switch ($uploadMethod) { case 'frompc': if (Request::hasFile('imageFromPC')) { if (Request::isImage('imageFromPC')) { $send['image'] = File::upload('imageFromPC'); File::remove($loadData[0]['image']); } } break; case 'fromurl': if (Request::isImage('imageFromUrl')) { $url = Request::get('imageFromUrl'); $send['image'] = File::upload('uploadFromUrl'); File::remove($loadData[0]['image']); } break; } $send['userid'] = Users::getCookieUserId(); if (!Request::has('send.catid')) { $loadCat = Categories::get(array('limitShow' => 1)); if (isset($loadCat[0]['catid'])) { $send['catid'] = $loadCat[0]['catid']; } } if (!Post::update($id, $send)) { throw new Exception("Error. " . Database::$error); } PostTags::remove($id, " postid='{$id}' "); $tags = trim(Request::get('tags')); $parse = explode(',', $tags); $total = count($parse); $insertData = array(); for ($i = 0; $i < $total; $i++) { $insertData[$i]['title'] = trim($parse[$i]); $insertData[$i]['postid'] = $id; } PostTags::insert($insertData); }
public static function add($f) { $foo = new Upload($f); if ($foo->uploaded) { $foo->Process(TMPFILES); } if ($foo->processed) { $fname = $foo->file_src_name_body; $fpath = TMPFILES . DS . $fname; $zip = new ZipArchive(); $res = $zip->open(TMPFILES . DS . $foo->file_src_name); if ($res === TRUE) { $zip->extractTo($fpath . DS); $zip->close(); $pack = json_decode(file_get_contents($fpath . DS . 'package.json'), true); if (count($pack['controllers']) > 0) { foreach ($pack['controllers'] as $c) { File::copy($fpath . DS . 'controllers' . DS . $c, CONTROLLERS . DS . $c); } } if (count($pack['views']) > 0) { foreach ($pack['views'] as $c) { File::copy($fpath . DS . 'views' . DS . $c, VIEWS . DS . $c); } } if (count($pack['langs']) > 0) { foreach ($pack['langs'] as $c) { File::copy($fpath . DS . 'lang' . DS . $c, LANGS . DS . $c); } } if (count($pack['libs']) > 0) { foreach ($pack['libs'] as $c) { File::copy($fpath . DS . 'lib' . DS . $c, LIB . DS . $c); } } if (count($pack['filters']) > 0) { foreach ($pack['filters'] as $c) { File::copy($fpath . DS . 'filters' . DS . $c, FILTER . DS . $c); } } File::copy($fpath . DS . 'package.json', CONFPLUGINS . DS . $pack['name'] . '.json'); File::copy($fpath . DS . 'routes.php', ROOT . DS . "routes" . DS . $pack['name'] . '.routes.php'); File::removedir($fpath); File::remove(TMPFILES . DS . $foo->file_src_name); } else { return false; } } return true; }
/** * @covers mychaelstyle\storage\File::rollback * @covers mychaelstyle\storage\Storage::rollback * @covers mychaelstyle\storage\File::initialize * @covers mychaelstyle\storage\File::clean * @covers mychaelstyle\storage\File::remove * @covers mychaelstyle\storage\File::isOpened * @covers mychaelstyle\storage\File::checkOpen */ public function testRollback() { // remove first $this->object->remove(); // create new storage without transaction $this->storage = new \mychaelstyle\Storage($this->dsn, $this->options, false); $this->object = $this->storage->createFile($this->uri, $this->options, false); // none transaxtion $expected = $this->test_string; $this->object->open('w'); $this->object->write($expected); $this->object->close(); $localPath = $this->getLocalPathUsingUri($this->dsn, $this->uri); $this->assertFalse(file_exists($localPath)); $this->object->rollback(); $this->assertFalse(file_exists($localPath)); }
function updateProcess($id) { $update = Request::get('update'); $valid = Validator::make(array('update.title' => 'required|min:1|slashes', 'update.parentid' => 'slashes')); if (!$valid) { throw new Exception("Error Processing Request: " . Validator::getMessage()); } if (Request::hasFile('image')) { if (Request::isImage('image')) { $update['image'] = File::upload('image'); $loadData = Categories::get(array('where' => "where catid='{$id}'")); if (isset($loadData[0]['catid'])) { File::remove($loadData[0]['image']); } } } Categories::update($id, $update); }
/** * Move file. * * @param string $source * @param string $target * @param bool $mode (default = 0 = self::$DEFAULT_MODE) */ public static function move($source, $target, $mode = 0666) { $rp_target = realpath($target); if ($rp_target && realpath($source) == $rp_target) { throw new Exception('same source and target', "mv [{$source}] to [{$target}]"); } File::copy($source, $target, $mode); File::remove($source); }
/** * Remove directory. * * @param string $path * @param boolean $must_exist (default = true) */ public static function remove($path, $must_exist = true) { if ($path != trim($path)) { throw new Exception('no leading or trailing whitespace allowed in path', $path); } if (substr($path, -1) == '/') { throw new Exception('no trailing / allowed in path', $path); } if (!$must_exist && !FSEntry::isDir($path, false)) { return; } if (FSEntry::isLink($path, false)) { FSEntry::unlink($path); return; } $entries = Dir::entries($path); foreach ($entries as $entry) { if (FSEntry::isFile($entry, false)) { File::remove($entry); } else { Dir::remove($entry); } } if (!rmdir($path) || FSEntry::isDir($path, false)) { throw new Exception('remove directory failed', $path); } }
/** * Remove a directory contents but not the directory itself * * @param string $path * @param array $logs Logs registry passed by reference * @return bool */ public static function purge($path = null, array &$logs = array()) { if (is_null($path)) { return null; } if (file_exists($path) && is_dir($path)) { $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS); foreach ($iterator as $item) { if (in_array($item->getFilename(), array('.', '..'))) { continue; } $_path = $item->getRealpath(); if (array_key_exists($_path, $logs)) { return false; } if ($item->isDir()) { if (false === ($ok = self::remove($_path, $logs))) { $logs[$_path] = sprintf('Can not remove diretory "%s".', $_path); } } else { if (false === ($ok = File::remove($_path, $logs))) { $logs[$_path] = sprintf('Can not unlink file "%s".', $_path); } } } clearstatcache(); return $ok; } else { $logs[$path] = sprintf('Directory "%s" not found.', $path); } return false; }
function importAnnotationsAndDocuments() { $this->Round = $this->Project->Round; $this->Document = $this->Project->Document; $this->UsersRound = $this->Project->User->UsersRound; $this->AnnotatedDocument = $this->Round->AnnotatedDocument; $this->Type = $this->Project->Type; $this->Annotation = $this->Type->Annotation; $maxAnnotation = $this->Annotation->find('first', array('recursive' => -1, 'fields' => 'id', 'order' => 'id DESC')); if (isset($maxAnnotation['Annotation']['id'])) { $maxAnnotation = $maxAnnotation['Annotation']['id']; } else { $maxAnnotation = 0; } $maxType = $this->Project->Type->find('first', array('recursive' => -1, 'fields' => 'id', 'order' => 'id DESC')); if (isset($maxType['Type']['id'])) { $maxType = $maxType['Type']['id']; } else { $maxType = 0; } if ($this->request->is('post') || $this->request->is('put')) { $maxAnnotation++; App::uses('Folder', 'Utility'); App::uses('File', 'Utility'); App::uses('CakeTime', 'Utility'); $scriptTimeLimit = Configure::read('scriptTimeLimit'); set_time_limit($scriptTimeLimit); $users = $this->request->data['User']['User']; //App::import('Vendor', 'htmLawed', array('file' => 'htmLawed' . DS . 'htmLawed.php')); $zipFile = new File($this->request->data['Project']['File']['tmp_name'], false, 0777); $projectName = ucwords(pathinfo($this->request->data['Project']['File']['name'], PATHINFO_FILENAME)); if ($zipFile->exists() && !empty($users)) { $filesAllowed = Configure::read('filesAllowed'); $zip = new ZipArchive(); if (!$zip->open($zipFile->pwd(), ZipArchive::CREATE)) { $zipFile->remove(); throw new Exception("Failed to open Zip archive\n"); } $path = Configure::read('uploadFolder'); $path = $path . uniqid(); //creamos la carpeta de descarga para el usuario si no existe $extractFolder = new Folder($path, true, 0700); $zip->extractTo($extractFolder->pwd()); $zip->close(); $zipFile->delete(); // I am deleting this file $rounds = array(); $db = $this->Project->getDataSource(); $db->query("ALTER TABLE annotations AUTO_INCREMENT = {$maxAnnotation}"); $db->execute("LOCK TABLES " . $this->Annotation->table . " " . $this->Type->table . " WRITE"); $db->begin(); $db->useNestedTransactions = false; $this->Project->create(); if ($this->Project->save(array('Project' => array("title" => $projectName, "description" => ""), "User" => array('User' => $users)))) { //creamos round de anotacion automatica $this->Round->create(); if (!$this->Round->save(array('Round' => array("title" => "Round for job " . date("Y/m/d"), "project_id" => $this->Project->id, "description" => "-", 'ends_in_date' => date("Y-m-d", strtotime("+30 day")), 'trim_helper' => true, 'whole_word_helper' => true, 'punctuation_helper' => true, 'start_document' => 0, 'end_document' => 0, 'is_visible' => 0)))) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("Round work can not be saved"); } array_push($rounds, $this->Round->id); foreach ($users as $user) { foreach ($rounds as $round) { $this->UsersRound->create(); if (!$this->UsersRound->save(array('state' => 0, 'round_id' => $round, 'user_id' => $user))) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("This UsersRound can not be save:" . $fileName); } } } $typesText = new File($extractFolder->pwd() . DS . 'types.txt', false, 0644); if (!$typesText->exists()) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("types.txt not exist in zip file"); } $count = new File($extractFolder->pwd() . DS . 'count.txt', false, 0644); if (!$count->exists()) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("count.txt not exist in zip filer"); } $typesText = $typesText->read(); $count = $count->read(); $count = intval($count) + 1; //buscamos la anotacion final con dicho Id si ya existe no se puede crear el proyecto $existLastId = $this->Annotation->find('count', array('recursive' => -1, 'conditions' => array('id' => $count))); $existInitialId = $this->Annotation->find('count', array('recursive' => -1, 'conditions' => array('id' => $count - ($count - $maxAnnotation)))); if ($existInitialId > 0) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("the first id already exist in Marky"); } if ($existLastId > 0) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("the last id already exist in Marky"); } $types = preg_split("/[\r\n]+/", trim($typesText)); $typesMap = array(); $defaultColors = Configure::read('defaultColors'); $colorCont = 0; foreach ($types as $type) { //debug($types); $type = explode("\t", $type); if (sizeof($type) > 1) { $typeName = $type[0]; $typeId = $type[1]; $typeName = str_replace(' ', '_', $typeName); if (!empty($defaultColors[$colorCont])) { $color = $defaultColors[$colorCont]; $colorCont++; } else { $color = array(rand(50, 255), rand(50, 255), rand(50, 255)); } $this->Type->create(); if ($this->Type->save(array('Type' => array('id' => $typeId, 'name' => $typeName, 'project_id' => $this->Project->id, 'colour' => $color[0] . ',' . $color[1] . ',' . $color[2] . ',1'), 'Round' => array('Round' => $rounds)))) { $typesMap[$typeName] = $this->Type->id; } else { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); // debug($types); // debug($this->Project->Type->validationErrors); throw new Exception("This type can not be save" . $type); } } else { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); // debug($types); // debug($this->Project->Type->validationErrors); throw new Exception("This type can not be save" . $type); } } $files = $extractFolder->find('.*.html', true); if (empty($files)) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("The html documents can not be read"); } //$config = array('cdata' => 1, 'safe' => 1, 'keep_bad' => 6, 'no_depreca ted_attr' => 2, 'valid_xhtml' => 1, 'abs_url' => 1); $annotationsAcumulate = array(); foreach ($files as $file) { //sleep(5); $fileName = substr($file, 0, strrpos($file, '.')); $file = new File($extractFolder->pwd() . DS . $file); if ($file->readable()) { //$content = '<p>' . preg_replace("/\.\s*\n/", '.</p><p>', $file->read()) . '</p>'; $content = $file->read(); if (strlen($content) > 1) { $file->close(); $date = date("Y-m-d H:i:s"); $document = $this->Document->find('first', array('recursive' => -1, 'conditions' => array('external_id' => $fileName))); if (empty($document)) { $this->Document->create(); if (!$this->Document->save(array('Document' => array('external_id' => $fileName, 'title' => $fileName, 'html' => strip_tags($content), 'created' => $date), 'Project' => array('Project' => $this->Project->id)))) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("This Document can not be save:" . $fileName); } } else { $this->Document->id = $document['Document']['id']; if (!$this->Document->save(array('Document' => array('id' => $this->Document->id), 'Project' => array('Project' => $this->Project->id)))) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("This Document - Project can not be save"); } } $annotations = $this->getAnnotations($content, $typesMap, $this->Document->id); $tam = count($annotations); $modes = Configure::read('annotationsModes'); // $results = gzdeflate($content, 9); foreach ($users as $user) { foreach ($rounds as $round) { $this->AnnotatedDocument->create(); if (!$this->AnnotatedDocument->save(array('text_marked' => $content, 'document_id' => $this->Document->id, 'mode' => $modes["AUTOMATIC"], 'round_id' => $round, 'user_id' => $user))) { $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("This UsersRound can not be save:" . $fileName); } if (!empty($annotations)) { for ($index = 0; $index < $tam; $index++) { $annotations[$index]['user_id'] = $user; $annotations[$index]['round_id'] = $round; //// if ($round == $this->Round->id) { ////// $annotations[$index]['id'] = $maxAnnotation; ////// $maxAnnotation++; //// } } $annotationsAcumulate = array_merge($annotationsAcumulate, $annotations); } } } if (count($annotationsAcumulate) > 500) { if (!$this->Project->Type->Annotation->saveMany($annotationsAcumulate)) { //debug($annotations); debug($this->Project->Type->Annotation->validationErrors[0]); debug($fileName); $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("Annotations can not be save"); } $annotationsAcumulate = array(); } } } } if (count($annotationsAcumulate) > 0) { if (!$this->Annotation->saveMany($annotationsAcumulate)) { //debug($annotations); debug($this->Project->Type->Annotation->validationErrors[0]); debug($fileName); $extractFolder->delete(); $db->rollback(); $db->execute("UNLOCK TABLES"); throw new Exception("Annotations can not be save"); } } // throw new Exception; $extractFolder->delete(); $db->commit(); $db->execute("UNLOCK TABLES"); $this->Session->setFlash(__('Project has been created with documents imported'), 'success'); $this->redirect(array('action' => 'index')); } $extractFolder->delete(); } else { $this->Session->setFlash(__('Choose almost one user and one file')); } } $userConditions = array('group_id' => 2); $users = $this->Project->User->find('list', array('conditions' => $userConditions)); $this->set(compact('users', 'maxAnnotation', 'maxType')); }
public function remove($id) { try { $user = User::find(Session::uid()); if (!$user->getId()) { throw new Exception('Not enough rights'); } $file = new File(); $file->findFileById($id); if ($file->getWorkitem()) { $workitem = WorkItem::getById($file->getWorkitem()); $userInvolved = $user->getId() == $file->getUserid() || $user->getId() == $workitem->getCreatorId() || $user->getId() == $workitem->getMechanicId() || $user->getId() == $workitem->getRunnerId(); } else { $userInvolved = false; } if (!$user->isRunner() && !$user->isPayer() && !$userInvolved) { throw new Exception('Permission denied'); } $success = $file->remove(); return $this->setOutput(array('success' => true, 'message' => 'Attachment removed')); } catch (Exception $e) { return $this->setOutput(array('success' => false, 'message' => $e->getMessage())); } }
/** * @description Base method for remove * * @param bool $force * @param null | string $path * @throws \Exception */ private function removeBase($force = false, $path = null) { if (empty($path)) { $path = $this->path; } if (is_file($path)) { $file = new File($path); $file->remove(); } else { $folderContents = glob($path . "/*"); if ($force == false && count($folderContents) > 0) { throw new \Exception("Failed to remove. Folder is not empty. Use the method \"Folder::removeForce()\""); } foreach ($folderContents as $folderContent) { $this->removeBase($force, $folderContent); } if ($this->isset) { rmdir($path); } } }
/** * Remove directory * * @param boolean $recursive (empty directory contents and remove) * @return boolean */ public function remove($recursive = false) { if (!$this->__isDir()) { return false; } if (!$recursive) { if (!@rmdir($this->_path)) { $this->error = parent::_getLastError(); return false; } return true; } // recursive remove foreach ($this->read(false, true) as $asset) { if ($asset['type'] === 'dir') { $dir = new Directory($this->_path . $asset['name'], false); if (!$dir->remove(true)) { $this->error = 'Failed to remove subdirectory \'' . $dir->getPath() . '\' (' . $dir->error . '), try elevated chmod'; return false; } } else { $file = new File($this->_path . $asset['name'], false); if (!$file->remove()) { $this->error = 'Failed to remove file \'' . $file->getPath() . '\' (' . $file->error . '), try elevated chmod'; return false; } } } return $this->remove(); // finally remove base directory }
/** * Download $remote_path directory recursive as $local_path. * * @throws * @param string $remote_path * @param string $local_path * @return vector<string> */ public function getDir($remote_path, $local_path) { $entries = $this->ls($remote_path); Dir::create($local_path, 0, true); foreach ($entries as $path => $info) { if ($info['type'] === 'f') { $this->get($path, $local_path . '/' . $info['name']); } else { if ($info['type'] === 'l') { if (FSEntry::isLink($local_path . '/' . $info['name'], false)) { File::remove($local_path . '/' . $info['name']); } print "link: " . $info['link'] . " - " . $local_path . '/' . $info['name'] . "\n"; FSEntry::link($info['link'], $local_path . '/' . $info['name'], false); } else { if ($info['type'] === 'd') { $this->getDir($path, $local_path . '/' . $info['name']); } } } } }
/** * Recursively Remove directories if the system allows. * * @param string $path Path of directory to delete * @return boolean Success * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::delete */ public function delete($path = null) { if (!$path) { $path = $this->pwd(); } if (!$path) { return null; } $path = Folder::slashTerm($path); if (is_dir($path)) { try { $directory = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::CURRENT_AS_SELF); $iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::CHILD_FIRST); } catch (Exception $e) { return false; } /** @var RecursiveDirectoryIterator $item */ foreach ($iterator as $item) { $filePath = $item->getPathname(); if ($item->isFile() || $item->isLink()) { //@codingStandardsIgnoreStart if (@File::remove($filePath)) { //@codingStandardsIgnoreEnd $this->_messages[] = sprintf('%s removed', $filePath); } else { $this->_errors[] = sprintf('%s NOT removed', $filePath); } } elseif ($item->isDir() && !$item->isDot()) { //@codingStandardsIgnoreStart if (@rmdir($filePath)) { //@codingStandardsIgnoreEnd $this->_messages[] = sprintf('%s removed', $filePath); } else { $this->_errors[] = sprintf('%s NOT removed', $filePath); return false; } } } $path = rtrim($path, DIRECTORY_SEPARATOR); //@codingStandardsIgnoreStart if (@rmdir($path)) { //@codingStandardsIgnoreEnd $this->_messages[] = sprintf('%s removed', $path); } else { $this->_errors[] = sprintf('%s NOT removed', $path); return false; } } return true; }