Example #1
0
 /**
  * @param  string                 $destination where to save file
  * @param  string|ConfigInterface $config
  * @param  RequestInterface       $request     optional
  * @return bool
  */
 public static function save($destination, $config, RequestInterface $request = null)
 {
     if (!$config instanceof ConfigInterface) {
         $config = new Config(array('tempDir' => $config));
     }
     $file = new File($config, $request);
     if ($_SERVER['REQUEST_METHOD'] === 'GET') {
         if ($file->checkChunk()) {
             header("HTTP/1.1 200 Ok");
         } else {
             header("HTTP/1.1 404 Not Found");
             return false;
         }
     } else {
         if ($file->validateChunk()) {
             $file->saveChunk();
         } else {
             // error, invalid chunk upload request, retry
             header("HTTP/1.1 400 Bad Request");
             return false;
         }
     }
     if ($file->validateFile() && $file->save($destination)) {
         return true;
     } else {
         return false;
     }
 }
Example #2
0
 public function storeFileForIndexing($file_path)
 {
     $FileInstance = new File(array('init' => false));
     if ($this->db) {
         $FileInstance->setConnection($this->db);
     }
     $FileInstance->init();
     $file_details = array('path' => $file_path, 'body' => file_get_contents($this->base_dir . DS . $file_path), 'hash' => md5_file($this->base_dir . DS . $file_path), 'has_been_analyzed' => false);
     if ($SourceFile = $FileInstance->findFirstBy('path', $file_path)) {
         if (!$file_details['has_been_analyzed']) {
             $this->log('File ' . $file_details['path'] . ' is stored but not indexed.');
         }
         $file_details['has_been_analyzed'] = $SourceFile->hash == $file_details['hash'] && $SourceFile->get('has_been_analyzed');
         if (!$file_details['has_been_analyzed']) {
             $this->log('File ' . $file_details['path'] . ' marked for reanalizing');
             $SourceFile->setAttributes($file_details);
             $SourceFile->save();
         } else {
             $this->log('File ' . $file_details['path'] . ' is up to date');
         }
     } else {
         $this->log('Storing file ' . $file_details['path']);
         $SourceFile = new File(array('init' => false));
         if ($this->db) {
             $SourceFile->setConnection($this->db);
         }
         $SourceFile->init();
         $SourceFile->setAttributes($file_details);
         $SourceFile->save();
     }
 }
Example #3
0
 public function indexAction()
 {
     $request = $this->getRequest();
     if (!$request->isPost()) {
         $this->getHelper('Redirector')->goto('index', 'index');
         // action, controller
     }
     $c = Zend_Registry::get('config');
     $apiKey = Zend_Filter::get($request->getPost('apikey'), 'Alnum');
     try {
         $user = User::findByApiKey($apiKey);
         if ($user === null) {
             $this->view->assign('response', 'Invalid API key.');
         } else {
             $user->setIp($request->getServer('REMOTE_ADDR'));
         }
     } catch (Zend_Db_Adapter_Exception $e) {
         $this->view->assign('response', $e->getMessage());
     }
     if (isset($user)) {
         if ($_FILES['file']['error'] === 0) {
             $file = new File();
             $file->setFileName($_FILES['file']['name']);
             $file->setFileSize($_FILES['file']['size']);
             $file->setTmpName($_FILES['file']['tmp_name']);
             $file->setUploadedBy($user);
             try {
                 $url = $file->save();
                 $this->view->assign('response', $url . "\n");
             } catch (Exception $e) {
                 $this->view->assign('response', $e->getMessage());
             }
         } else {
             switch ($_FILES['file']['error']) {
                 case UPLOAD_ERR_OK:
                     break;
                 case UPLOAD_ERR_INI_SIZE:
                     throw new Exception('The uploaded file exceeds the upload_max_filesize directive (' . ini_get('upload_max_filesize') . ') in php.ini.');
                     break;
                 case UPLOAD_ERR_FORM_SIZE:
                     throw new Exception('The uploaded file exceeds the MAX_FILE_SIZE directive' . 'that was specified in the HTML form.');
                     break;
                 case UPLOAD_ERR_PARTIAL:
                     throw new Exception('The uploaded file was only partially uploaded.');
                     break;
                 case UPLOAD_ERR_NO_FILE:
                     throw new Exception('No file was uploaded.');
                     break;
                 case UPLOAD_ERR_NO_TMP_DIR:
                     throw new Exception('Missing a temporary folder.');
                     break;
                 case UPLOAD_ERR_CANT_WRITE:
                     throw new Exception('Failed to write file to disk.');
                     break;
                 default:
                     throw new Exception('Unknown File Error.');
             }
         }
     }
 }
Example #4
0
 public function executePost(sfWebRequest $request)
 {
     $this->forward400If('' === (string) $request['body'], 'body parameter is not specified.');
     $this->forward400If('' === (string) $request['toMember'], 'toMember parameter is not specified.');
     $body = $request['body'];
     $this->myMember = $this->member;
     $toMember = Doctrine::getTable('Member')->find($request['toMember']);
     $this->forward400Unless($toMember, 'invalid member');
     $relation = Doctrine_Core::getTable('MemberRelationship')->retrieveByFromAndTo($toMember->getId(), $this->member->getId());
     $this->forward400If($relation && $relation->getIsAccessBlock(), 'Cannot send the message.');
     $message = Doctrine::getTable('SendMessageData')->sendMessage($toMember, SendMessageData::SMARTPHONE_SUBJECT, $body, array());
     $file = $request->getFiles('message_image');
     try {
         $validator = new opValidatorImageFile(array('required' => false));
         $clean = $validator->clean($file);
         if (is_null($clean)) {
             // if empty.
             return sfView::SUCCESS;
         }
     } catch (Exception $e) {
         $this->logMessage($e->getMessage());
         $this->forward400('This image file is invalid.');
     }
     $file = new File();
     $file->setFromValidatedFile($clean);
     $file->save();
     $messageFile = new MessageFile();
     $messageFile->setMessageId($message->getId());
     $messageFile->setFile($file);
     $messageFile->save();
 }
 public function __construct()
 {
     $title = getInput("title");
     $description = getInput("description");
     // Create filestore object to store file information
     $file = new File();
     $file->title = $title;
     $file->description = $description;
     $file->owner_guid = getLoggedInUserGuid();
     $file->access_id = "public";
     $file->container_guid = getInput("container_guid");
     $guid = $file->save();
     uploadFile("file", $guid, getLoggedInUserGuid());
     $file = getEntity($guid);
     Image::createThumbnail($file->guid, TINY);
     Image::createThumbnail($file->guid, SMALL);
     Image::createThumbnail($file->guid, MEDIUM);
     Image::createThumbnail($file->guid, LARGE);
     Image::createThumbnail($file->guid, EXTRALARGE);
     Image::createThumbnail($file->guid, HUGE);
     new Activity(getLoggedInUserGuid(), "action:upload:file", $guid);
     runHook("upload_file:redirect");
     new SystemMessage("Your file has been uploaded.");
     forward();
 }
Example #6
0
 function datos($campo_id, $etapa_id)
 {
     $etapa = Doctrine::getTable('Etapa')->find($etapa_id);
     if (UsuarioSesion::usuario()->id != $etapa->usuario_id) {
         echo 'Usuario no tiene permisos para subir archivos en esta etapa';
         exit;
     }
     $campo = Doctrine_Query::create()->from('Campo c, c.Formulario.Pasos.Tarea.Etapas e')->where('c.id = ? AND e.id = ?', array($campo_id, $etapa_id))->fetchOne();
     if (!$campo) {
         echo 'Campo no existe';
         exit;
     }
     // list of valid extensions, ex. array("jpeg", "xml", "bmp")
     $allowedExtensions = array('gif', 'jpg', 'png', 'pdf', 'doc', 'docx', 'zip', 'rar', 'ppt', 'pptx', 'xls', 'xlsx', 'mpp', 'vsd');
     if (isset($campo->extra->filetypes)) {
         $allowedExtensions = $campo->extra->filetypes;
     }
     // max file size in bytes
     $sizeLimit = 20 * 1024 * 1024;
     $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
     $result = $uploader->handleUpload('uploads/datos/');
     if (isset($result['success'])) {
         $file = new File();
         $file->tramite_id = $etapa->Tramite->id;
         $file->filename = $result['file_name'];
         $file->tipo = 'dato';
         $file->llave = strtolower(random_string('alnum', 12));
         $file->save();
         $result['id'] = $file->id;
         $result['llave'] = $file->llave;
     }
     // to pass data through iframe you will need to encode all html tags
     echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
 }
Example #7
0
 /**
  * Feltölt egy fájlt a megadott tantárgyhoz.
  * @param int $id A tantárgy azonosítója
  */
 public function actionUpload($id)
 {
     if (!Yii::app()->user->getId()) {
         throw new CHttpException(403, 'A funkció használatához be kell jelentkeznie');
     }
     $id = (int) $id;
     $file = CUploadedFile::getInstanceByName("to_upload");
     if ($file == null) {
         throw new CHttpException(404, 'Nem lett fájl kiválasztva a feltöltéshez');
     }
     $filename = $file->getName();
     $localFileName = sha1($filename . microtime()) . "." . CFileHelper::getExtension($filename);
     if (in_array(strtolower(CFileHelper::getExtension($filename)), Yii::app()->params["deniedexts"])) {
         throw new CHttpException(403, ucfirst(CFileHelper::getExtension($filename)) . ' kiterjesztésű fájl nem tölthető fel a szerverre');
     }
     $model = new File();
     $model->subject_id = $id;
     $model->filename_real = $filename;
     $model->filename_local = $localFileName;
     $model->description = htmlspecialchars($_POST["description"]);
     $model->user_id = Yii::app()->user->getId();
     $model->date_created = new CDbExpression('NOW()');
     $model->date_updated = new CDbExpression('NOW()');
     $model->downloads = 0;
     $model->save();
     if ($file->saveAs("upload/" . $localFileName)) {
         $this->redirect(Yii::App()->createUrl("file/list", array("id" => $id)));
     }
 }
Example #8
0
 /**
  * @param  string                 $destination where to save file
  * @param  string|ConfigInterface $config
  * @param  RequestInterface       $request     optional
  * @return bool
  */
 public static function save($destination, $config, RequestInterface $request = null)
 {
     if (!$config instanceof ConfigInterface) {
         $config = new Config(array('tempDir' => $config));
     }
     $file = new File($config, $request);
     if ($_SERVER['REQUEST_METHOD'] === 'GET') {
         if ($file->checkChunk()) {
             header("HTTP/1.1 200 Ok");
         } else {
             // The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.
             header("HTTP/1.1 204 No Content");
             return false;
         }
     } else {
         if ($file->validateChunk()) {
             $file->saveChunk();
         } else {
             // error, invalid chunk upload request, retry
             header("HTTP/1.1 400 Bad Request");
             return false;
         }
     }
     if ($file->validateFile() && $file->save($destination)) {
         return true;
     } else {
         return false;
     }
 }
Example #9
0
 public static function export(\Rebond\Core\ModelInterface $module)
 {
     $exportPath = \Rebond\Config::path('export');
     $tempPath = \Rebond\Config::path('temp');
     // TODO add XML model node
     // generate data script
     $dataScriptPath = $tempPath . 'data.sql';
     $table = 'app_' . strtolower($module->getTitle());
     $db = new Util\Data();
     $result = $db->select('SELECT * FROM ' . $table);
     $script = $db->backupData($table, $result);
     $result = $db->select('SELECT * FROM cms_content WHERE module_id = ?', [$module->getId()]);
     $script .= $db->backupData('cms_content', $result);
     File::save($dataScriptPath, 'w', $script);
     // create zip
     $zipFile = $module->getTitle() . '.zip';
     $zip = new \ZipArchive();
     $res = $zip->open($exportPath . $zipFile, \ZIPARCHIVE::OVERWRITE);
     if (!$res) {
         return $res;
     }
     $modulePath = FULL_PATH . 'Rebond/App/' . $module->getTitle() . '/';
     $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($modulePath));
     foreach ($iterator as $file) {
         $filename = str_replace($modulePath, '', str_replace('\\', '/', $file));
         if (file_exists($file) && substr($filename, -1) != '.') {
             $zip->addFile($file, $filename);
         }
     }
     $zip->addFile($dataScriptPath, 'data.sql');
     $zip->close();
     return $zipFile;
 }
Example #10
0
 /**
  * Handles a single upload by given CUploadedFile and returns an array
  * of informations.
  *
  * The 'error' attribute of the array, indicates there was an error.
  *
  * Informations on error:
  *       - error: true
  *       - errorMessage: some message
  *       - name: name of the file
  *       - size: file size
  *
  * Informations on success:
  *      - error: false
  *      - name: name of the uploaded file
  *      - size: file size
  *      - guid: of the file
  *      - url: url to the file
  *      - thumbnailUrl: url to the thumbnail if exists
  *
  * @param type $cFile
  * @return Array Informations about the uploaded file
  */
 protected function handleFileUpload($cFile, $object = null)
 {
     $output = array();
     $file = new File();
     $file->setUploadedFile($cFile);
     if ($object != null) {
         $file->object_id = $object->getPrimaryKey();
         $file->object_model = get_class($object);
     }
     if ($file->validate() && $file->save()) {
         $output['error'] = false;
         $output['guid'] = $file->guid;
         $output['name'] = $file->file_name;
         $output['title'] = $file->title;
         $output['size'] = $file->size;
         $output['mimeIcon'] = HHtml::getMimeIconClassByExtension($file->getExtension());
         $output['mimeBaseType'] = $file->getMimeBaseType();
         $output['mimeSubType'] = $file->getMimeSubType();
         $output['url'] = $file->getUrl("", false);
         $output['thumbnailUrl'] = $file->getPreviewImageUrl(200, 200);
     } else {
         $output['error'] = true;
         $output['errors'] = $file->getErrors();
     }
     $output['name'] = $file->file_name;
     $output['size'] = $file->size;
     $output['deleteUrl'] = "";
     $output['deleteType'] = "";
     $output['thumbnailUrl'] = "";
     return $output;
 }
Example #11
0
 public function afterSave($event)
 {
     if (!empty($_FILES)) {
         $model = $this->getOwner();
         $file = new File();
         $file->filename = UploadUtils::createUniquefilename($_FILES[self::NAME]['name'], UploadUtils::getPath(self::$fileDir));
         if (move_uploaded_file($_FILES[self::NAME]['tmp_name'], UploadUtils::getPath(self::$fileDir) . DIRECTORY_SEPARATOR . $file->filename)) {
             $file->entity = get_class($model);
             $file->EXid = $model->getPrimaryKey();
             $file->uid = Yii::app()->user->id;
             $file->tag = $this->tag;
             $file->weight = 0;
             $file->timestamp = time();
             $file->filemime = CFileHelper::getMimeTypeByExtension($_FILES[self::NAME]['name']);
             $file->filesize = $_FILES[self::NAME]['size'];
             $file->status = File::STATUS_SAVED;
             // Ensure all other files of the entity are deleted
             //UploadUtils::deleteAllFiles(get_class($this->getOwner()), self::$fileDir);
             if ($file->save()) {
                 Yii::trace("File saved " . $file . "!!!!");
             } else {
                 Yii::log("Could not save File " . print_r($file->getErrors(), true), CLogger::LEVEL_ERROR);
             }
         } else {
             Yii::log("Couldnt move the file", CLogger::LEVEL_ERROR);
         }
     } else {
         Yii::log("Files empty!!!", CLogger::LEVEL_ERROR);
     }
 }
Example #12
0
    public function generar($etapa_id) {
        $etapa = Doctrine::getTable('Etapa')->find($etapa_id);

        $filename_uniqid = uniqid();
        
        //Generamos el file
        $file = new File();
        $file->tramite_id = $etapa->tramite_id;
        $file->tipo = 'documento';
        $file->llave = strtolower(random_string('alnum', 12));
        $file->llave_copia = $this->tipo == 'certificado' ? strtolower(random_string('alnum', 12)) : null;
        $file->llave_firma = strtolower(random_string('alnum', 12));
        if($this->tipo=='certificado'){
            $file->validez = $this->validez;
            $file->validez_habiles= $this->validez_habiles;
        }
        $file->filename = $filename_uniqid . '.pdf';
        $file->save();

        //Renderizamos     
        $this->render($file->id, $file->llave_copia, $etapa->id, $file->filename, false);
        $filename_copia = $filename_uniqid . '.copia.pdf';
        $this->render($file->id, $file->llave_copia, $etapa->id,$filename_copia, true);

        return $file;
    }
 public function share_validation()
 {
     $this->load->library('form_validation');
     $this->load->helper('form');
     $this->form_validation->set_error_delimiters('<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">×</button>', '</div>');
     //mise en place des regles
     $this->form_validation->set_rules('keywords', 'Mots-clés', 'required|encode_php_tags|htmlspecialchars|trim|xss_clean|max_length[200]');
     $this->form_validation->set_rules('description', 'Description', 'required|encode_php_tags|htmlspecialchars|trim|xss_clean|max_length[300]');
     if ($this->form_validation->run() == FALSE) {
         //on affiche le formulaire
         $this->share();
     } else {
         // upload du fichier
         $file_up = new Upload();
         $user = unserialize($this->session->userdata('user_obj'));
         if ($file_up->upload_file($user->id, array('userfile'))) {
             // Création fichier
             $file = new File();
             $file->id_user = $user->id;
             $file->desc = $this->input->post('description');
             $file->keywords = $this->input->post('keywords');
             $file->url = $file_up->files_uploaded[0][0];
             $file->type = $file_up->files_uploaded[0][1];
             //sauvegarde du fichier
             $file->save();
             //notification
             $this->session->set_userdata('notif_ok', '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">×</button><strong>Bravo! </strong> Votre partage a été réussi.</div>');
             //redirection sur l'actualité
             redirect('flux', 'refresh');
         } else {
             //on affiche le formulaire
             $this->share();
         }
     }
 }
Example #14
0
 public function save()
 {
     $file = new File();
     $file->setFromValidatedFile($this->getValue('file'));
     $file->setName(sprintf('admin_%s_%d', $this->getValue('imageName'), time()));
     return $file->save();
 }
Example #15
0
 /**
  * Ajoute un log au fichier correspondant
  *
  * @param string $type -> Type de log : access, action, etc
  * @param string $str  -> Ligne de log à écrire
  * @return bool
  */
 public static function add($type, $str)
 {
     $out = false;
     $type = strtolower($type);
     if (defined('USER_PAGE')) {
         $userPage = USER_PAGE;
     } else {
         $userPage = 'index';
     }
     if (defined('SERVER_NAME')) {
         $serverName = '[' . utf8_decode(SERVER_NAME) . '] ';
     } else {
         $serverName = null;
     }
     $str = '[' . date('d/m/Y H:i:s') . '] [' . $_SERVER['REMOTE_ADDR'] . '] : ' . $serverName . '[' . $userPage . '] ' . utf8_decode($str) . "\n";
     $path = self::$LOGS_PATH . $type . '.log';
     if (file_exists($path)) {
         if (File::save($path, utf8_encode($str)) !== true) {
             $error = Utils::t('Unable to add log in file:') . ' ' . $type . '.';
             if ($_SESSION['error'] != null) {
                 $_SESSION['error'] .= '<br />' . $error;
             } else {
                 $_SESSION['error'] = $error;
             }
         } else {
             $out = true;
         }
     }
     return $out;
 }
 function __construct()
 {
     adminGateKeeper();
     $guid = getInput("guid");
     $title = getInput("title");
     $description = getInput('description');
     $price = getInput("price");
     $hidden = getInput("hidden") == 0 ? false : true;
     $product = getEntity($guid);
     $product->title = $title;
     $product->description = $description;
     $product->price = $price;
     $product->hidden = $hidden;
     $product->save();
     $product->createAvatar();
     if (isset($_FILES["download"]) && $_FILES["download"]["name"]) {
         $file = new File();
         $file->access_id = "product";
         $file->container_guid = $product->guid;
         $guid = $file->save();
         uploadFile("download", $guid, array("zip"));
         $product->download = $guid;
     }
     new SystemMessage("Your product has been updated.");
     forward("store");
 }
 /**
  * @param string $filename
  * @param Video $container
  */
 static function processUploadedVideo($filename, $container)
 {
     $file = new File();
     $file->access_id = $container->access_id;
     $file->container_guid = $container->guid;
     $file_guid = $file->save();
     FileSystem::uploadFile($filename, $file_guid, array("mov", "mpeg4", "mp4", "avi", "wmv", "mpegps", "flv", "3gpp", "webm", "3gp", "3g2", "m4v", "m2v", "mkv"));
     return $file_guid;
 }
Example #18
0
 /**
  * 库数据导出
  * 导出及备份系统数据
  * { "v" : 1, "key" : { "code" : 1 }, "unique" : true, "ns" : "gamedb_test.game", "name" : "code_" }
  * { "_id" : { "$oid" : "51adb8139b2a950402000008" }, "code" : "bns11", "name" : "剑灵11", "addtime" : "2013-06-04 17:49:07", "status" : 1 }
  */
 public function actionExport()
 {
     $selectedTables = isset($_POST['checked']) ? $_POST['checked'] : array();
     //获取数据库对象和所有文档列表
     $db = CardItem::model()->getDb();
     $tables = $this->_listCollections($db);
     //获取文档列表
     //获取需要导出的文档列表,并导出
     if (!empty($_POST)) {
         //循环处理勾选文档
         foreach ($selectedTables as $collection) {
             $contents = "";
             //内容
             //indexes 获取文档索引
             $collObj = $db->selectCollection($collection);
             //文档对象
             $infos = $collObj->getIndexInfo();
             //索引信息
             foreach ($infos as $info) {
                 if (!isset($info['key']['_id'])) {
                     //非“_id”索引才保留
                     $contents .= 'index' . $this->json_unicode_utf8(json_encode($info)) . "\n";
                     //标准json格式的index语句
                 }
             }
             //data	获取文档数据
             $cursor = DBModel::model()->getfind($collection);
             //查询所有文档数据
             foreach ($cursor as $one) {
                 $contents .= str_replace('"_id":{"$id":"', '"_id":{"$oid":"', $this->json_unicode_utf8(json_encode($one))) . "\n";
                 //将$id变为$oid键
             }
             unset($cursor);
             //生成文件
             $addtime = time();
             $fie_name = yiiBase::getPathOfAlias($this->dirpath) . '/' . date("YmdHis", $addtime) . '-' . $collection . '.js';
             file_put_contents($fie_name, $contents);
             //保存入库
             $image = new File();
             $image->filename = $fie_name;
             $image->metadata = array('name' => $collection . '.js', 'addTime' => $addtime);
             $res = $image->save();
             unlink($fie_name);
             //删除临时文件
             //多文件无法循环下载,暂时在服务器上生成文件
             //$this->_output_json();
         }
         //清理过期备份文件
         $this->cleanFile($this->expire);
     }
     //扫描导出文件并获取列表
     $exportTables = $this->findDir($this->dirpath, 'js');
     $exe_msg = $this->_exe_message();
     $this->render('export', array('tables' => $tables, 'selectedTables' => $selectedTables, 'exportTables' => $exportTables, 'exe_msg' => $exe_msg));
 }
Example #19
0
 public function executePost(sfWebRequest $request)
 {
     $this->forward400If('' === (string) $request['title'], 'title parameter is not specified.');
     $this->forward400If('' === (string) $request['body'], 'body parameter is not specified.');
     $this->forward400If(!isset($request['public_flag']) || '' === (string) $request['public_flag'], 'public flag is not specified');
     if (isset($request['id']) && '' !== $request['id']) {
         $diary = Doctrine::getTable('Diary')->findOneById($request['id']);
         $this->forward400If(false === $diary, 'the specified diary does not exit.');
         $this->forward400If(false === $diary->isAuthor($this->member->getId()), 'this diary is not yours.');
     } else {
         $diary = new Diary();
         $diary->setMemberId($this->member->getId());
     }
     $diary->setTitle($request['title']);
     $diary->setBody($request['body']);
     $diary->setPublicFlag($request['public_flag']);
     $diary->save();
     $this->diary = $diary;
     for ($i = 1; $i <= 3; $i++) {
         $diaryImage = Doctrine::getTable('DiaryImage')->retrieveByDiaryIdAndNumber($diary->getId(), $i);
         $filename = basename($_FILES['diary_photo_' . $i]['name']);
         if (!is_null($filename) && '' !== $filename) {
             try {
                 $validator = new opValidatorImageFile(array('required' => false));
                 $validFile = $validator->clean($_FILES['diary_photo_' . $i]);
             } catch (Exception $e) {
                 $this->forward400($e->getMessage());
             }
             $f = new File();
             $f->setFromValidatedFile($validFile);
             $f->setName(hash('md5', uniqid((string) $i) . $filename));
             if ($stream = fopen($_FILES['diary_photo_' . $i]['tmp_name'], 'r')) {
                 if (!is_null($diaryImage)) {
                     $diaryImage->delete();
                 }
                 $bin = new FileBin();
                 $bin->setBin(stream_get_contents($stream));
                 $f->setFileBin($bin);
                 $f->save();
                 $di = new DiaryImage();
                 $di->setDiaryId($diary->getId());
                 $di->setFileId($f->getId());
                 $di->setNumber($i);
                 $di->save();
                 $diary->updateHasImages();
             } else {
                 $this->forward400(__('Failed to write file to disk.'));
             }
         }
         $deleteCheck = $request['diary_photo_' . $i . '_photo_delete'];
         if ('on' === $deleteCheck && !is_null($diaryImage)) {
             $diaryImage->delete();
         }
     }
 }
Example #20
0
 /**
  * Saves PHP file and invalidates opcache.
  *
  * @param  mixed  $data  Optional data to be saved, usually array.
  * @throws \RuntimeException
  */
 public function save($data = null)
 {
     parent::save($data);
     // Invalidate configuration file from the opcache.
     if (function_exists('opcache_invalidate')) {
         // PHP 5.5.5+
         @opcache_invalidate($this->filename, true);
     } elseif (function_exists('apc_invalidate')) {
         // APC
         @apc_invalidate($this->filename);
     }
 }
Example #21
0
 public function changeLogo(CUploadedFile $uploadedFile)
 {
     $basePath = Yii::app()->getModule('cabinet')->getUploadPath();
     //создаем каталог для аватарок, если не существует
     if (!is_dir($basePath) && !@mkdir($basePath, 0755, true)) {
         throw new CException(Yii::t('default', 'It is not possible to create directory for logos!'));
     }
     $filename = $this->id . '_' . time() . '.' . $uploadedFile->extensionName;
     // обновить файл
     //$this->removeOldLogo();
     if (!$uploadedFile->saveAs($basePath . $filename)) {
         throw new CException(Yii::t('default', 'It is not possible to save logos!'));
     }
     // получить запись лого
     $photo = $this->with('photo')->find('photo.id=:id', [':id' => $this->logo_id]);
     $webroot = Yii::getpathOfAlias('webroot');
     $trimPath = str_replace($webroot, '', $basePath);
     $logoFileOld = null;
     $File = new File();
     $File->model = 'Company';
     $File->type = 'image';
     $File->size = filesize($basePath . $filename);
     $File->name = $filename;
     $File->path = $trimPath . $filename;
     $File->record_id = 0;
     if (!is_null($photo['photo'])) {
         $File->id = $photo['photo']['id'];
         $File->isNewRecord = false;
         $logoFileOld = $photo['photo']['path'];
     }
     if ($File->save()) {
         if (0 != strcmp($logoFileOld, $File->path)) {
             @unlink($webroot . $logoFileOld);
         }
     } else {
         yii::log("changeLogo save FAILED id=[" . $File->id . "]", "info");
     }
     if ($this->logo_id != $File->id) {
         // поменять logo_id
         $this->logo_id = $File->id;
         if ($this->validate(['logo_id'])) {
             if (true === $this->update(['logo_id'])) {
             } else {
                 Yii::log("changeLogo update logo_id FAILED", 'info');
             }
         } else {
             Yii::log("changeLogo validate logo_id FAILED", 'info');
         }
     }
     //$this->logo = $filename;
     return true;
 }
Example #22
0
 public function actionBlogEdit($id)
 {
     $model = BlogModel::model()->where("`id`='" . (int) $id . "'")->findRow();
     if (isset($_POST['yt0'])) {
         $model->setAttrs($_POST['Blog']);
         if ($_FILES['mainImage']['name']) {
             $model->mainImage = File::save($_FILES['mainImage'], "assets/images/gifts");
         }
         $model->save();
         $this->redirect("/admin/blog");
     }
     $this->view("admin/blog/edit", array("model" => $model), false);
 }
Example #23
0
 public function actionpresentsCardsEdit($id)
 {
     $model = UserCardsModel::model()->where("`id`='" . (int) $id . "'")->findRow();
     if (isset($_POST['UserCards'])) {
         $model->setAttrs($_POST['UserCards']);
         if ($_FILES['cardImage']['name']) {
             $model->cardImage = File::save($_FILES['cardImage'], "assets/images/cards");
         }
         $model->save();
         $this->redirect("/admin/presents");
     }
     $this->view("admin/presents/card/edit", array("model" => $model), false);
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new File();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['File'])) {
         $model->attributes = $_POST['File'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id_file));
         }
     }
     $this->render('create', array('model' => $model));
 }
 private function generateTempFile()
 {
     $tempfile = new TempFile($this->getStorage());
     $file = new File($this->getStorage());
     $file->setExportFilename("vpanel-chart-" . date("Y-m-d"));
     $file->save();
     $tempfile->setFile($file);
     $tempfile->setTimestamp(time());
     $tempfile->setUserID($this->getUserID());
     $tempfile->save();
     $this->tempfileids[] = $tempfile->getTempFileID();
     return $tempfile;
 }
Example #26
0
 public function actionCreate()
 {
     $project = $this->loadModel('Project', User::getLastProjectId());
     $model = new File();
     $this->pageTitle = 'Добавить файл в ' . $project->title . ' - ' . Yii::app()->name;
     if (isset($_POST['File'])) {
         $model->attributes = $_POST['File'];
         if ($model->save()) {
             user()->setFlash('success', "Файл добавлен");
             $this->redirect(array('index'));
         }
     }
     $this->render('create', array('model' => $model, 'project' => $project));
 }
Example #27
0
 public function getTempFile()
 {
     if ($this->tempfile == null) {
         $this->tempfile = new TempFile($this->getStorage());
         $file = new File($this->getStorage());
         $file->setExportFilename("export-" . time());
         $file->save();
         $this->tempfile->setUserID($this->getProcess()->getUserID());
         $this->tempfile->setFile($file);
         $this->tempfile->setTimestamp(time());
         $this->tempfile->save();
     }
     return $this->tempfile;
 }
Example #28
0
 public function actionEdit($id)
 {
     $model = SliderModel::model()->where("`id`='{$id}'")->findRow();
     if (isset($_POST['Slide'])) {
         $model->setAttrs($_POST['Slide']);
         if ($_FILES['poster']['name']) {
             $model->poster = File::save($_FILES['poster'], "assets/images/posters");
             File::resizeImage($model->poster, 500, 500);
         }
         $model->save();
         $this->redirect($this->url);
     }
     $this->view("admin/slider/edit", array("model" => $model), false);
 }
 public function getTempFile()
 {
     if ($this->tempfile == null) {
         $this->tempfile = new TempFile($this->getStorage());
         $file = new File($this->getStorage());
         $file->setMimeType("application/zip");
         $file->setExportFilename("download.zip");
         $file->save();
         $this->tempfile->setUserID($this->getUserID());
         $this->tempfile->setFile($file);
         $this->tempfile->setTimestamp(time());
         $this->tempfile->save();
     }
     return $this->tempfile;
 }
Example #30
0
 /**
  * Performs the work of inserting or updating the row in the database.
  *
  * If the object is new, it inserts it; otherwise an update is performed.
  * All related objects are also updated in this method.
  *
  * @param      PropelPDO $con
  * @return     int The number of rows affected by this insert/update and any referring fk objects' save() operations.
  * @throws     PropelException
  * @see        save()
  */
 protected function doSave(PropelPDO $con)
 {
     $affectedRows = 0;
     // initialize var to track total num of affected rows
     if (!$this->alreadyInSave) {
         $this->alreadyInSave = true;
         // We call the save method on the following object(s) if they
         // were passed to this object by their coresponding set
         // method.  This object relates to these object(s) by a
         // foreign key reference.
         if ($this->asfGuardUser !== null) {
             if ($this->asfGuardUser->isModified() || $this->asfGuardUser->isNew()) {
                 $affectedRows += $this->asfGuardUser->save($con);
             }
             $this->setsfGuardUser($this->asfGuardUser);
         }
         if ($this->aRepository !== null) {
             if ($this->aRepository->isModified() || $this->aRepository->isNew()) {
                 $affectedRows += $this->aRepository->save($con);
             }
             $this->setRepository($this->aRepository);
         }
         if ($this->aBranch !== null) {
             if ($this->aBranch->isModified() || $this->aBranch->isNew()) {
                 $affectedRows += $this->aBranch->save($con);
             }
             $this->setBranch($this->aBranch);
         }
         if ($this->aFile !== null) {
             if ($this->aFile->isModified() || $this->aFile->isNew()) {
                 $affectedRows += $this->aFile->save($con);
             }
             $this->setFile($this->aFile);
         }
         if ($this->isNew() || $this->isModified()) {
             // persist changes
             if ($this->isNew()) {
                 $this->doInsert($con);
             } else {
                 $this->doUpdate($con);
             }
             $affectedRows += 1;
             $this->resetModified();
         }
         $this->alreadyInSave = false;
     }
     return $affectedRows;
 }