public function run($class_name)
 {
     $path = realpath(Yii::app()->basePath . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . $class_name);
     $class_name = ucfirst($class_name);
     if ($path && is_dir($path) && is_writable($path)) {
         $dir = key($_GET);
         $filename = $_GET[$dir];
         $pk = pathinfo($filename, PATHINFO_FILENAME);
         $image = Images::model()->findByPk($pk);
         if ($image != null) {
             $image->resize($dir);
         }
     } elseif (class_exists($class_name)) {
         $dir = key($_GET);
         $filename = $_GET[$dir];
         $size = explode('x', $dir);
         $path = realpath(Yii::app()->basePath . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . $class_name);
         if (YII_DEBUG && !file_exists($path . DIRECTORY_SEPARATOR . $dir)) {
             mkdir($path . DIRECTORY_SEPARATOR . $dir, 0777);
         }
         if ($path !== FALSE && file_exists($path . DIRECTORY_SEPARATOR . $dir) && is_file($path . DIRECTORY_SEPARATOR . $filename) && $size[0] > 0 && $size[1] > 0) {
             Yii::import('ext.iwi.Iwi');
             $image = new Iwi($path . DIRECTORY_SEPARATOR . $filename);
             $image->adaptive($size[0], $size[1]);
             $image->save($path . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $filename, 0644, TRUE);
             $mime = CFileHelper::getMimeType($path . DIRECTORY_SEPARATOR . $filename);
             header('Content-Type: ' . $mime);
             $image->render();
             exit;
         }
     }
     return parent::run($class_name);
 }
 public function run($thumb)
 {
     $key = key($_GET);
     if (NULL == ($file = Files::model()->findByPk($key))) {
         throw new CException('Page not found', 404);
     }
     $path = Yii::getPathOfAlias('webroot') . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . 'photos';
     $src_file = $file->id . '.' . $file->extension;
     $in_file = $path . DIRECTORY_SEPARATOR . $src_file;
     $out_file = $path . DIRECTORY_SEPARATOR . $thumb . DIRECTORY_SEPARATOR . $src_file;
     if (is_file($out_file)) {
         $mime = CFileHelper::getMimeType($out_file);
         header('Content-Type: ' . $mime);
         readfile($out_file);
         exit;
     }
     if (is_file($in_file)) {
         $dir = $path . DIRECTORY_SEPARATOR . $thumb;
         if (YII_DEBUG && !file_exists($dir)) {
             mkdir($dir, 0777);
         }
         if (file_exists($dir)) {
             if (($out_file = $file->resize($thumb)) == 0) {
                 throw new CException('Page not found', 404);
             }
             $mime = CFileHelper::getMimeType($in_file);
             header('Content-Type: ' . $mime);
             readfile($out_file);
             exit;
         }
     }
     return parent::run($thumb);
 }
Пример #3
0
 /**
  * @static
  * @param $fullPath
  * @return bool|CsvImage
  */
 public static function create($fullPath)
 {
     if (!file_exists($fullPath)) {
         return false;
     }
     $name = explode(DS, $fullPath);
     return new C1ProductImage(end($name), $fullPath, CFileHelper::getMimeType($fullPath), filesize($fullPath), false);
 }
Пример #4
0
 /**
  * @param CUploadedFile $image
  * @return bool
  */
 public static function isAllowedType(CUploadedFile $image)
 {
     $type = CFileHelper::getMimeType($image->getTempName());
     if (!$type) {
         $type = CFileHelper::getMimeTypeByExtension($image->getName());
     }
     return in_array($type, array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png'));
 }
 /**
  * @param CUploadedFile $image
  * @return bool
  */
 public static function isAllowedType(CUploadedFile $image)
 {
     $type = CFileHelper::getMimeType($image->getTempName());
     if (!$type) {
         $type = CFileHelper::getMimeTypeByExtension($image->getName());
     }
     return in_array($type, EventsImagesConfig::get('types'));
 }
 /**
  * @param CUploadedFile $image
  * @return bool
  */
 public static function isAllowedType(CUploadedFile $image)
 {
     $type = CFileHelper::getMimeType($image->getTempName());
     if (!$type) {
         $type = CFileHelper::getMimeTypeByExtension($image->getName());
     }
     //return in_array($type, Yii::app()->params['storeImages']['types']);
     return in_array($type, StoreImagesConfig::get('types'));
 }
Пример #7
0
 /**
  * @param string $fileName
  * @return string
  */
 public static function getExtensionByMimeType($fileName)
 {
     $mimeTypes = (require Yii::getPathOfAlias('system.utils.mimeTypes') . '.php');
     $unsetArray = array('jpe', 'jpeg');
     foreach ($unsetArray as $key) {
         unset($mimeTypes[$key]);
     }
     $mimeType = CFileHelper::getMimeType($fileName);
     return (string) array_search($mimeType, $mimeTypes);
 }
 /**
  * Generates a thumbnail for the specified image path and size, then serves 
  * it to the browser. The next time the same thumbnail is rendered its URL 
  * will point to the generated image instead of this action.
  * @see Thumbnail
  * @param string $path the thumbnail path
  * @param int $size the thumbnail size
  * @throws PageNotFoundException if the image could not be generated
  */
 public function actionGenerate($path, $size)
 {
     $thumbnail = new Thumbnail($path, $size);
     $thumbnail->generate();
     $path = $thumbnail->getPath();
     if ($path === false) {
         throw new PageNotFoundException();
     }
     header('Content-Type: ' . CFileHelper::getMimeType($path));
     readfile($path);
     exit;
 }
Пример #9
0
 /**
  * Runs the action.
  */
 public function run()
 {
     foreach (Yii::app()->log->routes as $route) {
         if ($route instanceof CWebLogRoute || $route instanceof CFileLogRoute || $route instanceof YiiDebugToolbarRoute) {
             $route->enabled = false;
         }
     }
     $asset = $_GET['path'];
     #修改为action读取文件资料
     $SAECommon = new SAECommon();
     $path = $SAECommon->saedisk_decrypt($asset);
     if (!file_exists($path)) {
         throw new CHttpException(404, Yii::t('yii', 'The asset "{asset}" to be published does not exist.', array('{asset}' => $asset)));
     }
     // 浏览器根据etag来缓存,增加 date('H') 则为一小时更新
     $etag = md5($path + date('d'));
     header("ETag: {$etag}");
     $offset = 60 * 60 * 24;
     //css文件的距离现在的过期时间,这里设置为一天
     $expire = "expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
     header($expire);
     $type = CFileHelper::getMimeType($path);
     header("content-type: {$type}; charset: UTF-8");
     //注意修改到你的编码
     #header ("cache-control: max-age=$offset,must-revalidate");
     header("cache-control: max-age={$offset}");
     #header ("Pragma:");
     #print_r($_SERVER['HTTP_IF_NONE_MATCH']);die;
     if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) {
         #header('HTTP/1.1 304 Not Modified');
         header('Etag:' . $etag, true, 304);
     } else {
         if (extension_loaded('zlib')) {
             //检查服务器是否开启了zlib拓展
             ob_start('ob_gzhandler');
         }
         //加载文件
         //include($path);
         echo file_get_contents($path);
         if (extension_loaded('zlib')) {
             ob_end_flush();
             //输出buffer中的内容,即压缩后的css文件
         }
     }
     exit;
 }
Пример #10
0
 /**
  * 上传课时视频
  * Enter description here ...
  */
 public function actionUpload($lessonId)
 {
     $model = $this->loadModel($lessonId);
     if (isset($_FILES['file']['name'])) {
         $fileTypes = array('mp4', 'flv');
         // File extensions
         $fileParts = pathinfo($_FILES['file']['name']);
         if (in_array(strtolower($fileParts['extension']), $fileTypes)) {
             $tempFile = $_FILES['file']['tmp_name'];
             //向uploadfile表中插入记录
             $uploadFile = new UploadFile();
             $uploadFile->userId = Yii::app()->user->id;
             $uploadFile->addTime = time();
             $uploadFile->mime = CFileHelper::getMimeType($tempFile) ? CFileHelper::getMimeType($tempFile) : "video/mp4";
             $uploadFile->name = $_FILES['file']['name'];
             $uploadFile->size = $_FILES['file']['size'];
             $uploadFile->storage = 'local';
             $uploadFile->save();
             //得到id,并以此为文件名保存视频文件
             $id = $uploadFile->id;
             $path = 'uploads/uploadFile/Lesson/mediaId';
             if (!is_dir($path)) {
                 mkdir($path, 0777, true);
             }
             $path .= '/' . $id . "." . $fileParts['extension'];
             move_uploaded_file($tempFile, $path);
             $uploadFile->path = $path;
             $uploadFile->save();
             //清除旧数据
             $model->deleteMedia();
             $model->mediaType = "video";
             $model->mediaId = $uploadFile->getPrimaryKey();
             $model->save();
             //返回mediaId
             //	echo json_encode(array('id'=>$id,'status'=>'success'));
             //echo json_encode($uploadFile->name);
             echo true;
         } else {
             //echo json_encode(array('status'=>'fail'));
             //	echo json_encode(null);
             echo false;
         }
     }
     $this->layout = "/layouts/nonav_column1";
     $this->render('upload_fancy', array('model' => $model));
 }
Пример #11
0
public function actionFile($id){

        $id   = (int)$id;
        $model = City::model()->findByPk($id); 
        if(!$model)
            throw new CHttpException(404, Yii::t('site','Page not found'));

       // if(Yii::app()->user->isGuest && $model->issue->is_public !== true)
       //     Yii::app()->user->loginRequired();

        $available_mime = Yii::app()->params['mime_fileview'];

        $filename = $model->filename;
        $realname = $model->realname;

        $uploadPath = $model->getFileFolder();    

        if(file_exists($uploadPath.$filename )) {

            $type = CFileHelper::getMimeType($uploadPath.$filename); // get yii framework mime
            
            if(in_array($type, $available_mime)){

                //.. get the content of the requested file 
                $content=file_get_contents($uploadPath.$filename);
                //.. send appropriate headers
                header('Content-Type:' . $type);
                header("Content-Length: ". filesize($uploadPath.$filename));

                header('Content-Disposition: inline; filename="' . $realname . '"');
                header('Content-Transfer-Encoding: binary');
                header('Accept-Ranges: bytes');

                echo $content;
                exit; 
                
            } else {
                throw new CHttpException(404, Yii::t('site','Page not found'));
            }
        }
        else{
            throw new CHttpException(404, Yii::t('site','Page not found'));
        }   

    }
Пример #12
0
 public function actionGet()
 {
     $key = Yii::app()->request->getParam('key', null);
     if ($key != null) {
         $key = base64_decode($key);
         $key = str_replace('/', '', $key);
         $user_id = isset(Yii::app()->user->id) ? Yii::app()->user->id : 0;
         $dir = dirname(__FILE__) . '/../../shared/' . $user_id . '/';
         if (is_dir($dir)) {
             if (file_exists($dir . '/' . $key)) {
                 header("Pragma: public");
                 header("Expires: 0");
                 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                 header("Cache-Control: private", false);
                 header("Content-Disposition: attachment; filename=\"" . $key . "\";");
                 header('Content-type: ' . CFileHelper::getMimeType($dir . '/' . $key));
                 header("Content-Transfer-Encoding: binary");
                 readfile($dir . '/' . $key);
                 die;
             }
         }
         // list mentor directories
         $mentors = SchoolMentor::model()->findAll('user_id=:user_id', array(':user_id' => $user_id));
         $key = mb_substr($key, 1, mb_strlen($key, 'UTF-8') - 1, 'UTF-8');
         foreach ($mentors as $mentor) {
             $dir = dirname(__FILE__) . '/../../shared/M' . $mentor->id . '/';
             if (is_dir($dir)) {
                 if (file_exists($dir . '/' . $key)) {
                     header("Pragma: public");
                     header("Expires: 0");
                     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                     header("Cache-Control: private", false);
                     header("Content-Disposition: attachment; filename=\"" . $key . "\";");
                     header('Content-type: ' . CFileHelper::getMimeType($dir . '/' . $key));
                     header("Content-Transfer-Encoding: binary");
                     readfile($dir . '/' . $key);
                     die;
                 }
             }
         }
     }
 }
Пример #13
0
 /**
  * @param string $image name in ./uploads/importImages/ e.g. somename.jpg
  * @return CsvImage
  */
 public static function create($image)
 {
     $isDownloaded = substr($image, 0, 5) === 'http:';
     if ($isDownloaded) {
         $tmpName = Yii::getPathOfAlias('application.runtime') . DIRECTORY_SEPARATOR . sha1(pathinfo($image, PATHINFO_FILENAME)) . '.' . pathinfo($image, PATHINFO_EXTENSION);
         if ((bool) parse_url($image) && !file_exists($tmpName)) {
             $fileHeader = get_headers($image, 1);
             if ((int) substr($fileHeader[0], 9, 3) === 200) {
                 file_put_contents($tmpName, file_get_contents($image));
             }
         }
     } else {
         $tmpName = Yii::getPathOfAlias('webroot.uploads.importImages') . DIRECTORY_SEPARATOR . $image;
     }
     if (!file_exists($tmpName)) {
         return false;
     }
     $result = new CsvImage($image, $tmpName, CFileHelper::getMimeType($tmpName), filesize($tmpName), false);
     $result->isDownloaded = $isDownloaded;
     return $result;
 }
Пример #14
0
 /**
  * Runs the action.
  */
 public function run()
 {
     if (!Yii::app()->getRequest()->getIsPostRequest()) {
         throw new CHttpException(400, Yii::t('app', 'Invalid request. Please do not repeat this request again.'));
     }
     $folder = Yii::app()->params['uploadTargetPath'];
     $model = new $this->modelClass();
     $fk = $this->foreignKey;
     if (isset($_REQUEST[$fk]) && ($id = (int) $_REQUEST[$fk]) > 0) {
         $model->{$fk} = $id;
     }
     $result = $this->saveFile($folder);
     if (!isset($result['success'])) {
         throw new CHttpException(400, Yii::t('app', 'Error saving uploaded file.'));
     }
     $filePath = $folder . DIRECTORY_SEPARATOR . $result['filename'];
     $size = getimagesize($filePath);
     if (isset($_REQUEST['qqfile'])) {
         $model->filename = $_REQUEST['qqfile'];
     } elseif (isset($_FILES['qqfile']['name'])) {
         $model->filename = $_FILES['qqfile']['name'];
     }
     $model->content = file_get_contents($filePath);
     $model->size = filesize($filePath);
     $model->mimetype = CFileHelper::getMimeType($filePath);
     if ($size !== false) {
         list($width, $height, $type, $attr) = $size;
         $model->width = $width;
         $model->height = $height;
     }
     if ($model->save(false)) {
         echo json_encode(array_merge($result, array('id' => $model->primaryKey)));
     } else {
         echo json_encode(array('errors' => $model->getErrors()));
     }
     Yii::app()->end();
 }
Пример #15
0
 public function actionAnyFile($id, $model = 'Partner', $filename = 'image', $realname = false)
 {
     $id = (int) $id;
     $model = $model::model()->findByPk($id);
     if (!$model) {
         throw new CHttpException(404, Yii::t('site', 'Page not found'));
     }
     $available_mime = Yii::app()->params['mime_fileview'];
     $filename = $model->{$filename};
     $uploadPath = $model->getFileFolder();
     if (file_exists($uploadPath . $filename)) {
         $type = CFileHelper::getMimeType($uploadPath . $filename);
         // get yii framework mime
         if (in_array($type, $available_mime)) {
             //.. get the content of the requested file
             $content = file_get_contents($uploadPath . $filename);
             //.. send appropriate headers
             header('Content-Type:' . $type);
             header("Content-Length: " . filesize($uploadPath . $filename));
             if ($realname) {
                 $realname = $model->{$realname};
                 header('Content-Disposition: inline; filename="' . $realname . '"');
             } else {
                 header('Content-Disposition: inline; filename="' . $filename . '"');
             }
             header('Content-Transfer-Encoding: binary');
             header('Accept-Ranges: bytes');
             echo $content;
             exit;
         } else {
             throw new CHttpException(404, Yii::t('site', 'Page not found'));
         }
     } else {
         throw new CHttpException(404, Yii::t('site', 'Page not found'));
     }
 }
Пример #16
0
 private function writeHeader()
 {
     $this->checkResumeDownload();
     //Inicia checando se irá ou não resumir um download já iniciado
     $disposition = $this->force ? 'attachment' : 'inline';
     header('Content-Description: File Transfer');
     header('Content-Disposition: ' . $disposition . '; filename="' . $this->filename . '"');
     header('Content-Transfer-Encoding: binary');
     header('Cache-Control: public, must-revalidate, max-age=0');
     header('Pragma: no-cache');
     //header('Pragma: public');
     header('Accept-Ranges: bytes');
     header('Expires: 0');
     if ($this->_dummy) {
         header('Content-Type: ' . CFileHelper::getMimeTypeByExtension($this->_file));
     } else {
         header('Content-Type: ' . CFileHelper::getMimeType($this->_file));
         header("Content-Length: " . ($this->_size - $this->_begin));
         $contentRange = "Content-Range: bytes {$this->_begin}-" . ($this->_size - 1) . "/{$this->_size}";
         header($contentRange);
     }
     ob_clean();
     flush();
 }
Пример #17
0
 /**
  * If the path points to a real file, we call {@link \CFileHelper::getMimeType}, otherwise
  * {@link \CFileHelper::getMimeTypeByExtension}
  *
  * @param string $path The path to test.
  *
  * @return string The mime type.
  */
 public static function getMimeType($path)
 {
     if (@file_exists($path)) {
         return \CFileHelper::getMimeType($path);
     } else {
         return \CFileHelper::getMimeTypeByExtension($path);
     }
 }
Пример #18
0
 /**
  * 
  * Download a file with resume, stream and speed options
  * 
  * @param string $filename path to file including filename
  * @param integer $speed maximum download speed
  * @param boolean $doStream if stream or not
  */
 public static function download($filepath, $maxSpeed = 100, $doStream = false)
 {
     $seek_start = 0;
     $seek_end = -1;
     $data_section = false;
     $buffsize = 2048;
     // you can set by multiple of 1024
     if (!file_exists($filepath) && is_file($filepath)) {
         throw new CException(Yii::t('EDownloadHelper', 'Filepath does not exists on specified location or is not a regular file'));
     }
     $mimeType = CFileHelper::getMimeType($filepath);
     $filename = basename($filepath);
     if ($mimeType == null) {
         $mimeType = "application/octet-stream";
     }
     $extension = CFileHelper::getExtension($filepath);
     // resuming?
     if (isset($_SERVER['HTTP_RANGE'])) {
         $seek_range = substr($_SERVER['HTTP_RANGE'], strlen('bytes='));
         $range = explode('-', $seek_range);
         // do it the old way, no fancy stuff
         // to avoid problems
         if ($range[0] > 0) {
             $seek_start = intval($range[0]);
         }
         if ($range[1] > 0) {
             $seek_end = intval($range[1]);
         }
         $data_section = true;
     }
     // do some cleaning before we start
     ob_end_clean();
     $old_status = ignore_user_abort(true);
     set_time_limit(0);
     $size = filesize($filepath);
     if ($seek_start > $size - 1) {
         $seek_start = 0;
     }
     // open the file and move pointer
     // to started chunk
     $res = fopen($filepath, 'rb');
     if ($seek_start) {
         fseek($res, $seek_start);
     }
     if ($seek_end < $seek_start) {
         $seek_end = $size - 1;
     }
     header('Content-Type: ' . $mimeType);
     $contentDisposition = 'attachment';
     if ($doStream == true) {
         if (in_array($extension, self::$stream_types)) {
             $contentDisposition = 'inline';
         }
     }
     if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
         $fileName = preg_replace('/\\./', '%2e', $filename, substr_count($filename, '.') - 1);
     }
     header('Content-Disposition: ' . $contentDisposition . '; filename="' . $filename . '"');
     header('Last-Modified: ' . date('D, d M Y H:i:s \\G\\M\\T', filemtime($filepath)));
     // flushing a data section?
     if ($data_section) {
         header("HTTP/1.0 206 Partial Content");
         header("Status: 206 Partial Content");
         header('Accept-Ranges: bytes');
         header("Content-Range: bytes {$seek_start}-{$seek_end}/{$size}");
         header("Content-Length: " . ($seek_end - $seek_start + 1));
     } else {
         // nope, just
         header('Content-Length: ' . $size);
     }
     $size = $seek_end - $seek_start + 1;
     while (!(connection_aborted() || connection_status() == 1) && !feof($res)) {
         print fread($res, $buffsize * $maxSpeed);
         flush();
         @ob_flush();
         sleep(1);
     }
     // close file
     fclose($res);
     // restore defaults
     ignore_user_abort($old_status);
     set_time_limit(ini_get('max_execution_time'));
 }
Пример #19
0
	private function uploadImage($name, $slug, $model) {
		if ($model->image) {
			$model->image->saveAs(Yii::getPathOfAlias('webroot') . '/images/' . $model->filename);
			$type=CFileHelper::getMimeType(Yii::getPathOfAlias('webroot') . '/images/' . $model->filename);
			$type=explode('/',$type);
			if($type[0]=="image")
			{
				$img=Yii::app()->imagemod->load(Yii::getPathOfAlias('webroot') . '/images/' . $model->filename);
				if ($img->image_src_x > 200) {
					$img->image_resize=true;
					$img->image_ratio_y=true;
					$img->image_x=200;
					$img->file_new_name_body=$name;
					$img->process(Yii::getPathOfAlias('webroot') . '/thumb/' . $slug);
				}
			}
			else
			{
				unlink(Yii::getPathOfAlias('webroot') . '/images/' . $model->filename);
				$model->delete();
				$this->redirect(array('board', 'slug'=> $slug));
			}
		}
	}
Пример #20
0
 /**
  * Validate profile photo
  * 
  * @return boolean
  */
 public function validateProfilePhoto()
 {
     if (isset($this->account_profile_photo->size)) {
         // don't allow pic larger than 200 Kb
         if ($this->account_profile_photo->size > 1024 * 1024 * 1024) {
             $this->addError('account_profile_photo', 'Photo cannot be larger than 1Mb.');
             return false;
         }
     }
     // check MIME/Type (such as "image/gif")
     if (isset($this->account_profile_photo->type)) {
         if (!in_array(CFileHelper::getMimeType($this->account_profile_photo->getTempName()), array('image/png', 'image/jpg', 'image/jpeg'))) {
             $this->addError('account_profile_photo', 'Photo must be of type PNG, JPG, or JPEG.');
             return false;
         }
     }
     return true;
 }
Пример #21
0
 public function associate($user_id)
 {
     $userIdentityClass = $this->userIdentityClass;
     $identity = new $userIdentityClass(null, null);
     if (!$identity instanceof IHybridauthIdentity) {
         throw new CException(Yii::t('UsrModule.usr', 'The {class} class must implement the {interface} interface.', array('{class}' => get_class($identity), '{interface}' => 'IHybridauthIdentity')));
     }
     $identity->setId($user_id);
     $profile = $this->_hybridAuthAdapter->getUserProfile();
     if ($identity instanceof IPictureIdentity && !empty($profile->photoURL)) {
         $picture = $identity->getPictureUrl();
         if ($picture['url'] != $profile->photoURL) {
             $path = tempnam(sys_get_temp_dir(), 'external_profile_picture_');
             if (copy($profile->photoURL, $path)) {
                 $uploadedFile = new CUploadedFile(basename($path), $path, CFileHelper::getMimeType($path), filesize($path), UPLOAD_ERR_OK);
                 $identity->removePicture();
                 $identity->savePicture($uploadedFile);
             }
         }
     }
     return $identity->addRemoteIdentity(strtolower($this->provider), $profile->identifier);
 }
Пример #22
0
 /**
  * Return a image tag if fileUrl is an image, downloadlink otherwise
  * Used in renderElement as hint for a file attribute.
  *
  * If the model implements a method mmfGetFileInfo like below, this method will be used instead of default implementation.
  * public function mmfGetFileInfo($attribute,$value,$multiModelform)
  * {
  *    ... render the imagepreview/downloadlink ... for this attribute
  * }
  *
  * @param $value
  * @return string
  */
 public function getFileInfo($attribute, $value)
 {
     if (empty($value)) {
         return;
     }
     if (method_exists($this->model, 'mmfGetFileInfo')) {
         return call_user_func(array($this->model, 'mmfGetFileInfo'), $attribute, $value, $this);
     } else {
         $fileNamePath = $this->getFilePathFromUrl($value);
         if (!is_file($fileNamePath)) {
             return;
         }
         $mimeType = CFileHelper::getMimeType($fileNamePath);
         $value = self::getFileUrl($value);
         if (strpos($mimeType, 'image') === 0) {
             //image
             return CHtml::image($value, basename($value), $this->fileImagePreviewHtmlOptions);
         } else {
             return CHtml::link($value, $value, $this->fileLinkHtmlOptions);
         }
     }
 }
Пример #23
0
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate()
 {
     $this->model = $this->loadModel(Yii::app()->user->id);
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($this->model);
     if (isset($_POST['User'])) {
         $this->model->attributes = $_POST['User'];
         if ($this->model->Year) {
             if (!$this->model->Month) {
                 $this->model->Month = 01;
             }
             if (!$this->model->Day) {
                 $this->model->Day = 01;
             }
             $this->model->birthdate = strtotime($this->model->Year . "/" . $this->model->Month . "/" . $this->model->Day);
         }
         $this->model->addError('firstname', Yii::t('user', 'Please select an image smaller than 7MB.'));
         if ($this->model->validate()) {
             //Delete image reference if marked
             if ($this->model->deleteimage) {
                 $this->model->image_name = '';
             }
             //Save the image if any
             $image = CUploadedFile::getInstance($this->model, 'image');
             if (get_class($image) == 'CUploadedFile') {
                 if ($image->getSize() > 1024 * 1024 * Yii::app()->params['max_image_size']) {
                     $this->model->addError('image', Yii::t('user', 'Please select an image smaller than 7MB.'));
                     $error = true;
                 }
                 //MB
                 $types = array("image/jpg", "image/png", "image/gif", "image/jpeg");
                 if (!in_array($image->type, $types)) {
                     $this->model->addError('image', Yii::t('user', 'File type {filetype} not supported. Please select a valid image type.', array('{filetype}' => CFileHelper::getMimeType($image->getTempName()))));
                     $error = true;
                 }
             }
             if (!$error) {
                 Yii::import('ext.EUploadedImage');
                 if ($image) {
                     $img_extension = $image->getExtensionName() ? $image->getExtensionName() : '';
                     $img_name = $this->model->id . '.' . $img_extension;
                     $this->model->image_name = $img_name;
                     $this->model->image = EUploadedImage::getInstance($this->model, 'image');
                     $this->model->image->maxWidth = 980;
                     $this->model->image->maxHeight = 750;
                     $this->model->image->thumb = array('maxWidth' => 45, 'maxHeight' => 45, 'keepratio' => false, 'prefix' => 'small_');
                     if (!$this->model->image->saveAs(Yii::app()->params['webdir'] . DIRECTORY_SEPARATOR . Yii::app()->params['user_img_path'] . DIRECTORY_SEPARATOR . $img_name)) {
                         $this->model->addError('image', Yii::t('user', 'We could not save the image in the disk.'));
                         return false;
                     }
                 }
             }
         }
         $this->model->validate();
         if ($this->model->save()) {
             Yii::app()->user->setFlash('profile_success', Yii::t('user', 'Profile Settings updated successfully.'));
         }
         //$this->redirect(array('index'));
     }
     $this->render('update', array('model' => $this->model));
 }
Пример #24
0
 /**
  * @inheritdoc
  */
 public function savePicture($picture)
 {
     if (($record = $this->getActiveRecord()) === null) {
         return null;
     }
     $pictureRecord = $record->userProfilePictures(array('condition' => 'original_picture_id IS NULL'));
     if (!empty($pictureRecord)) {
         $pictureRecord = $pictureRecord[0];
     } else {
         $pictureRecord = new UserProfilePicture();
         $pictureRecord->user_id = $this->_id;
     }
     $picturePath = $picture->getTempName();
     $pictureRecord->filename = $picture;
     $pictureRecord->mimetype = CFileHelper::getMimeType($picturePath);
     $pictureRecord->contents = base64_encode(file_get_contents($picturePath));
     if (($size = @getimagesize($picturePath)) !== false) {
         list($width, $height, $type, $attr) = $size;
         $pictureRecord->width = $width;
         $pictureRecord->height = $height;
     } else {
         $pictureRecord->width = 0;
         $pictureRecord->height = 0;
     }
     return $pictureRecord->save() && $this->saveThumbnail($picture, $pictureRecord);
 }
Пример #25
0
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     //this parameter is the issueId!
     Result::model()->cleanRecords();
     //clean old remaining records
     $this->layout = "//layouts/column1";
     $issue = $this->loadIssue($id);
     $redirect = false;
     $issueId = $id;
     //checking if the document is already opened
     $opened = Opendocs::model()->find("issueId={$issueId}");
     //if there has been any
     if (isset($_POST['Result']) or isset($_POST['Checks']) or isset($_POST['Table']) or isset($_POST['File'])) {
         $redirect = true;
         //true means it is actually saving a document. False means is opening the update view
     }
     if (isset($opened)) {
         //the issue has a record in open docs
         $now = time();
         $morethanyesterday = strtotime($opened->createTime);
         $morethanyesterday = $morethanyesterday + 86400;
         if ($now < $morethanyesterday) {
             //less than 24h
             $user = User::model()->findByPk($opened->userId);
             if ($opened->userId == Yii::app()->user->id) {
                 //actual user is the issue's owner
                 if ($redirect) {
                     // the user is on the update view already and has clicked "save" button
                     //saving process:
                     if (isset($_POST['Result'])) {
                         //Result::model()->reset($id);//RESET
                         $redirect = true;
                         $post = $_POST['Result'];
                         if (isset($post['elementid'])) {
                             $elementId = $post['elementid'];
                             foreach ($elementId as $key => $value) {
                                 //if ($value != '') {
                                 if (is_array($value)) {
                                     foreach ($value as $option) {
                                         $model = new Result();
                                         $model->elementId = $key;
                                         $model->issueId = $issueId;
                                         if ($model->value != $option) {
                                             $model->value = $option;
                                             $model->save();
                                         }
                                     }
                                 } else {
                                     $model = Result::model()->find("elementId = {$key} and issueId = {$issueId}");
                                     if ($model === null) {
                                         $model = new Result();
                                         $model->elementId = $key;
                                         $model->issueId = $issueId;
                                     }
                                     if ($model->value != $value) {
                                         $model->value = $value;
                                         $model->save();
                                     }
                                 }
                                 //}
                             }
                         }
                     }
                     if (isset($_POST['Checks'])) {
                         //For Checkboxes: once one is selected there must be at least one checked option. It's impossible to uncheck all of them.
                         // that's the way is supposed to be. Keep track record.
                         $redirect = true;
                         $typeId = 6;
                         $post = $_POST['Checks'];
                         $values = array();
                         if (isset($post['elementid'])) {
                             $elementId = $post['elementid'];
                             foreach ($elementId as $key => $value) {
                                 if (is_array($value)) {
                                     foreach ($value as $option) {
                                         $values[] = $option;
                                         $model = new Result();
                                         $model->elementId = $key;
                                         $model->issueId = $issueId;
                                         if (in_array($option, $value)) {
                                             $what = Element::doesExist($key, $issueId, $option);
                                             if ($what < 1) {
                                                 $model->value = $option;
                                                 $model->save();
                                             }
                                         }
                                     }
                                 }
                                 $statement = " ";
                                 foreach ($values as $cond) {
                                     $statement .= " and t.value NOT like '{$cond}'";
                                 }
                                 $statement = "issueId= {$issueId} and elementId = {$key} " . $statement;
                                 $criteria = new CDbCriteria();
                                 $criteria->condition = $statement;
                                 //"issueId = $issueId and elementId = $key and value NOT LIKE ('$values')";
                                 $modelo = Result::model()->findAll($criteria);
                                 foreach ($modelo as $borrar) {
                                     $borrar->delete();
                                 }
                             }
                         }
                     }
                     if (isset($_POST['Table'])) {
                         //Result::model()->resetTable($id);
                         //Result::model()->setTableOFF($id);
                         $redirect = true;
                         $tables = $_POST['Table'];
                         foreach ($tables as $key => $value) {
                             $elementId = $key;
                             foreach ($value as $row => $array) {
                                 foreach ($array as $column => $response) {
                                     if ($elementId != "xxx") {
                                         $res = Result::model()->find("elementId = {$elementId} and issueId = {$issueId} and colonne = {$column} and ligne = {$row}");
                                         if ($res === null) {
                                             $res = new Result();
                                             $res->elementId = $elementId;
                                             $res->issueId = $issueId;
                                             $res->colonne = $column;
                                             $res->ligne = $row;
                                             //if($response!=null || $response!="" || !isset($response)){
                                         }
                                         if ($response != $res->value) {
                                             $res->value = $response;
                                             $res->save();
                                         }
                                     }
                                 }
                             }
                         }
                     }
                     if (isset($_FILES['File'])) {
                         //throw new CHttpException(403, "update de resultcontroller");
                         foreach ($_FILES['File']['name']['elementid'] as $key => $value) {
                             if (is_array($value)) {
                                 foreach ($value as $k => $v) {
                                     if ($v != '') {
                                         $rnd = rand(0, 99999);
                                         $tmpname = $_FILES['File']['tmp_name']['elementid'][$key][$k];
                                         $fichier = "{$rnd}-" . preg_replace("/[^a-zA-Z0-9\\/_|.-]/", "_", $v);
                                         $extensions = 'img';
                                         $fileType = CFileHelper::getMimeType($v);
                                         //this makes sure it is an image, getimagesize doesn't work
                                         if (move_uploaded_file($tmpname, Yii::app()->params['dfs'] . "/result/" . $fichier)) {
                                             $file = new File();
                                             if (strpos($fileType, 'image') !== false) {
                                                 $image = 1;
                                             } else {
                                                 $image = 0;
                                             }
                                             $file->image = $image;
                                             $file->userId = Yii::app()->user->id;
                                             $file->fileSelected = $v;
                                             $file->link = "result/" . $fichier;
                                             if ($file->save()) {
                                                 $fileId = $file->id;
                                                 $res = new Result();
                                                 $res->elementId = $key;
                                                 $res->issueId = $issueId;
                                                 $res->fileId = $fileId;
                                                 $res->value = $file->id;
                                                 $res->save();
                                             }
                                         }
                                     }
                                 }
                             } else {
                                 if ($value != '') {
                                     $tmp = $_FILES['File']['tmp_name']['elementid'][$key];
                                     $rnd = rand(0, 99999);
                                     $fichier = "{$rnd}-" . preg_replace("/[^a-zA-Z0-9\\/_|.-]/", "_", $value);
                                     if (@getimagesize($tmp)) {
                                         $image = 1;
                                     } else {
                                         $image = 0;
                                     }
                                     if (move_uploaded_file($tmp, Yii::app()->params['dfs'] . "result/" . $fichier)) {
                                         //Si la fonction renvoie TRUE, c'est que ça a fonctionné...
                                         $file = new File();
                                         $file->image = $image;
                                         $file->userId = Yii::app()->user->id;
                                         $file->fileSelected = $value;
                                         $file->link = "result/" . $fichier;
                                         if ($file->save()) {
                                             $fileId = $file->id;
                                             $res = new Result();
                                             $res->elementId = $key;
                                             $res->issueId = $issueId;
                                             $res->fileId = $fileId;
                                             $res->value = $file->id;
                                             $res->save();
                                         }
                                     }
                                 }
                             }
                         }
                     }
                     //delete record in opendocs and exit to view
                     $opened->delete();
                     //the document has been saved and exit. Then the opendoc item has to be deleted
                     $this->redirect(array('issue/view', 'id' => $issueId));
                 } else {
                     //user is accessing the update view of an issue. He's the owner of the issue therefore he can access it.
                     //creates a new opened doc item and access the update view
                     $opened->createTime = new CDbExpression('NOW()');
                     $opened->save();
                     $this->render('update', array('model' => $issue, 'traveler' => $issue->traveler, 'issueId' => $issueId));
                 }
             } else {
                 //less than 24h, not the owner. Then the user has to access the unlocking view if he still wants to access the update view
                 $this->render('open', array('user' => $user, 'opened' => $opened, 'issueId' => $issueId));
             }
         } else {
             //opendocs record is older than 24h.
             if ($redirect) {
                 //the user is on the update view already and has clicked "save" button
                 if (isset($_POST['Result'])) {
                     //Result::model()->reset($id);//RESET
                     $redirect = true;
                     $post = $_POST['Result'];
                     if (isset($post['elementid'])) {
                         $elementId = $post['elementid'];
                         foreach ($elementId as $key => $value) {
                             //if ($value != '') {
                             if (is_array($value)) {
                                 foreach ($value as $option) {
                                     $model = new Result();
                                     $model->elementId = $key;
                                     $model->issueId = $issueId;
                                     if ($model->value != $option) {
                                         $model->value = $option;
                                         $model->save();
                                     }
                                 }
                             } else {
                                 $model = Result::model()->find("elementId = {$key} and issueId = {$issueId}");
                                 if ($model === null) {
                                     $model = new Result();
                                     $model->elementId = $key;
                                     $model->issueId = $issueId;
                                 }
                                 if ($model->value != $value) {
                                     $model->value = $value;
                                     $model->save();
                                 }
                             }
                             //}
                         }
                     }
                 }
                 if (isset($_POST['Checks'])) {
                     //Result::model()->resetBox($id);//RESET
                     $redirect = true;
                     $typeId = 6;
                     $post = $_POST['Checks'];
                     $values = array();
                     if (isset($post['elementid'])) {
                         $elementId = $post['elementid'];
                         foreach ($elementId as $key => $value) {
                             if (is_array($value)) {
                                 foreach ($value as $option) {
                                     $values[] = $option;
                                     $model = new Result();
                                     $model->elementId = $key;
                                     $model->issueId = $issueId;
                                     if (in_array($option, $value)) {
                                         $what = Element::doesExist($key, $issueId, $option);
                                         if ($what < 1) {
                                             $model->value = $option;
                                             $model->save();
                                         }
                                     }
                                 }
                             }
                             $statement = " ";
                             foreach ($values as $cond) {
                                 $statement .= " and t.value NOT like '{$cond}'";
                             }
                             $statement = "issueId= {$issueId} and elementId = {$key} " . $statement;
                             $criteria = new CDbCriteria();
                             $criteria->condition = $statement;
                             //"issueId = $issueId and elementId = $key and value NOT LIKE ('$values')";
                             $modelo = Result::model()->findAll($criteria);
                             foreach ($modelo as $borrar) {
                                 $borrar->delete();
                             }
                         }
                     }
                 }
                 if (isset($_POST['Table'])) {
                     //Result::model()->resetTable($id);
                     //Result::model()->setTableOFF($id);
                     $redirect = true;
                     $tables = $_POST['Table'];
                     foreach ($tables as $key => $value) {
                         $elementId = $key;
                         foreach ($value as $row => $array) {
                             foreach ($array as $column => $response) {
                                 if ($elementId != "xxx") {
                                     $res = Result::model()->find("elementId = {$elementId} and issueId = {$issueId} and colonne = {$column} and ligne = {$row}");
                                     if ($res === null) {
                                         $res = new Result();
                                         $res->elementId = $elementId;
                                         $res->issueId = $issueId;
                                         $res->colonne = $column;
                                         $res->ligne = $row;
                                         //if($response!=null || $response!="" || !isset($response)){
                                     }
                                     if ($response != $res->value) {
                                         $res->value = $response;
                                         $res->save();
                                     }
                                 }
                             }
                         }
                     }
                 }
                 if (isset($_FILES['File'])) {
                     //throw new CHttpException(403, "update de resultcontroller");
                     foreach ($_FILES['File']['name']['elementid'] as $key => $value) {
                         if (is_array($value)) {
                             foreach ($value as $k => $v) {
                                 if ($v != '') {
                                     $rnd = rand(0, 99999);
                                     $tmpname = $_FILES['File']['tmp_name']['elementid'][$key][$k];
                                     $fichier = "{$rnd}-" . preg_replace("/[^a-zA-Z0-9\\/_|.-]/", "_", $v);
                                     if (move_uploaded_file($tmpname, Yii::app()->params['dfs'] . "/result/" . $fichier)) {
                                         $file = new File();
                                         if (@getimagesize($tmpname)) {
                                             $image = 1;
                                         } else {
                                             $image = 0;
                                         }
                                         $file->image = $image;
                                         $file->userId = Yii::app()->user->id;
                                         $file->fileSelected = $v;
                                         $file->link = "result/" . $fichier;
                                         if ($file->save()) {
                                             $fileId = $file->id;
                                             $res = new Result();
                                             $res->elementId = $key;
                                             $res->issueId = $issueId;
                                             $res->fileId = $fileId;
                                             $res->value = $file->id;
                                             $res->save();
                                         }
                                     }
                                 }
                             }
                         } else {
                             if ($value != '') {
                                 $tmp = $_FILES['File']['tmp_name']['elementid'][$key];
                                 $rnd = rand(0, 99999);
                                 $fichier = "{$rnd}-" . preg_replace("/[^a-zA-Z0-9\\/_|.-]/", "_", $value);
                                 if (@getimagesize($tmp)) {
                                     $image = 1;
                                 } else {
                                     $image = 0;
                                 }
                                 if (move_uploaded_file($tmp, Yii::app()->params['dfs'] . "/result/" . $fichier)) {
                                     //Si la fonction renvoie TRUE, c'est que ça a fonctionné...
                                     $file = new File();
                                     $file->image = $image;
                                     $file->userId = Yii::app()->user->id;
                                     $file->fileSelected = $value;
                                     $file->link = "result/" . $fichier;
                                     if ($file->save()) {
                                         $fileId = $file->id;
                                         $res = new Result();
                                         $res->elementId = $key;
                                         $res->issueId = $issueId;
                                         $res->fileId = $fileId;
                                         $res->value = $file->id;
                                         $res->save();
                                     }
                                 }
                             }
                         }
                     }
                 }
                 //delete record in opendocs and exit to view
                 $opened->delete();
                 $this->redirect(array('issue/view', 'id' => $issueId));
             } else {
                 //user is accessing the update view of an issue
                 //delete old opendocs record and create a new one
                 $opened->delete();
                 $model = new Opendocs();
                 $model->issueId = $issueId;
                 $model->userId = Yii::app()->user->id;
                 $model->createTime = new CDbExpression('GETDATE()');
                 $model->save();
                 $this->render('update', array('model' => $issue, 'traveler' => $issue->traveler, 'issueId' => $issueId));
             }
         }
     } else {
         //there is not previous opendocs record. Then no restrictions.
         if ($redirect) {
             //user is saving the issue
             if (isset($_POST['Result'])) {
                 //Result::model()->reset($id);//RESET
                 $redirect = true;
                 $post = $_POST['Result'];
                 if (isset($post['elementid'])) {
                     $elementId = $post['elementid'];
                     foreach ($elementId as $key => $value) {
                         //if ($value != '') {
                         if (is_array($value)) {
                             foreach ($value as $option) {
                                 $model = new Result();
                                 $model->elementId = $key;
                                 $model->issueId = $issueId;
                                 if ($model->value != $option) {
                                     $model->value = $option;
                                     $model->save();
                                 }
                             }
                         } else {
                             $model = Result::model()->find("elementId = {$key} and issueId = {$issueId}");
                             if ($model === null) {
                                 $model = new Result();
                                 $model->elementId = $key;
                                 $model->issueId = $issueId;
                             }
                             if ($model->value != $value) {
                                 $model->value = $value;
                                 $model->save();
                             }
                         }
                         //}
                     }
                 }
             }
             if (isset($_POST['Checks'])) {
                 //Result::model()->resetBox($id);//RESET
                 $redirect = true;
                 $typeId = 6;
                 $post = $_POST['Checks'];
                 $values = array();
                 if (isset($post['elementid'])) {
                     $elementId = $post['elementid'];
                     foreach ($elementId as $key => $value) {
                         if (is_array($value)) {
                             foreach ($value as $option) {
                                 $values[] = $option;
                                 $model = new Result();
                                 $model->elementId = $key;
                                 $model->issueId = $issueId;
                                 if (in_array($option, $value)) {
                                     $what = Element::doesExist($key, $issueId, $option);
                                     if ($what < 1) {
                                         $model->value = $option;
                                         $model->save();
                                     }
                                 }
                             }
                         }
                         $statement = " ";
                         foreach ($values as $cond) {
                             $statement .= " and t.value NOT like '{$cond}'";
                         }
                         $statement = "issueId= {$issueId} and elementId = {$key} " . $statement;
                         $criteria = new CDbCriteria();
                         $criteria->condition = $statement;
                         //"issueId = $issueId and elementId = $key and value NOT LIKE ('$values')";
                         $modelo = Result::model()->findAll($criteria);
                         foreach ($modelo as $borrar) {
                             $borrar->delete();
                         }
                     }
                 }
             }
             if (isset($_POST['Table'])) {
                 //Result::model()->resetTable($id);
                 //Result::model()->setTableOFF($id);
                 $redirect = true;
                 $tables = $_POST['Table'];
                 foreach ($tables as $key => $value) {
                     $elementId = $key;
                     foreach ($value as $row => $array) {
                         foreach ($array as $column => $response) {
                             if ($elementId != "xxx") {
                                 $res = Result::model()->find("elementId = {$elementId} and issueId = {$issueId} and colonne = {$column} and ligne = {$row}");
                                 if ($res === null) {
                                     $res = new Result();
                                     $res->elementId = $elementId;
                                     $res->issueId = $issueId;
                                     $res->colonne = $column;
                                     $res->ligne = $row;
                                     //if($response!=null || $response!="" || !isset($response)){
                                 }
                                 if ($response != $res->value) {
                                     $res->value = $response;
                                     $res->save();
                                 }
                             }
                         }
                     }
                 }
             }
             if (isset($_FILES['File'])) {
                 //throw new CHttpException(403, "update de resultcontroller");
                 foreach ($_FILES['File']['name']['elementid'] as $key => $value) {
                     if (is_array($value)) {
                         foreach ($value as $k => $v) {
                             if ($v != '') {
                                 $rnd = rand(0, 99999);
                                 $tmpname = $_FILES['File']['tmp_name']['elementid'][$key][$k];
                                 $fichier = "{$rnd}-" . preg_replace("/[^a-zA-Z0-9\\/_|.-]/", "_", $v);
                                 $fileType = CFileHelper::getMimeType($v);
                                 //this makes sure it is an image, getimagesize doesn't work
                                 $noexe = CFileHelper::getExtension($v);
                                 if (strpos($noexe, 'py') !== false or strpos($noexe, 'exe') !== false) {
                                     throw new CHttpException(403, "Forbidden type of file");
                                 }
                                 if (move_uploaded_file($tmpname, Yii::app()->params['dfs'] . "/result/" . $fichier)) {
                                     $file = new File();
                                     if (strpos($fileType, 'image') !== false) {
                                         $image = 1;
                                     } else {
                                         $image = 0;
                                     }
                                     $file->image = $image;
                                     $file->userId = Yii::app()->user->id;
                                     $file->fileSelected = $v;
                                     $file->link = "result/" . $fichier;
                                     if ($file->save()) {
                                         $fileId = $file->id;
                                         $res = new Result();
                                         $res->elementId = $key;
                                         $res->issueId = $issueId;
                                         $res->fileId = $fileId;
                                         $res->value = $file->id;
                                         $res->save();
                                     }
                                 }
                             }
                         }
                     } else {
                         if ($value != '') {
                             $tmp = $_FILES['File']['tmp_name']['elementid'][$key];
                             $rnd = rand(0, 99999);
                             $fichier = "{$rnd}-" . preg_replace("/[^a-zA-Z0-9\\/_|.-]/", "_", $value);
                             $fileType = CFileHelper::getMimeType($v);
                             //this makes sure it is an image, getimagesize doesn't work
                             $noexe = CFileHelper::getExtension($v);
                             if (strpos($noexe, 'py') !== false or strpos($noexe, 'exe') !== false) {
                                 throw new CHttpException(403, "Forbidden type of file");
                             }
                             if (move_uploaded_file($tmp, Yii::app()->params['dfs'] . "/result/" . $fichier)) {
                                 //Si la fonction renvoie TRUE, c'est que ça a fonctionné...
                                 $file = new File();
                                 if (strpos($fileType, 'image') !== false) {
                                     $image = 1;
                                 } else {
                                     $image = 0;
                                 }
                                 $file->image = $image;
                                 $file->userId = Yii::app()->user->id;
                                 $file->fileSelected = $value;
                                 $file->link = "result/" . $fichier;
                                 if ($file->save()) {
                                     $fileId = $file->id;
                                     $res = new Result();
                                     $res->elementId = $key;
                                     $res->issueId = $issueId;
                                     $res->fileId = $fileId;
                                     $res->value = $file->id;
                                     $res->save();
                                 }
                             }
                         }
                     }
                 }
             }
             $this->redirect(array('issue/view', 'id' => $issueId));
         } else {
             //user is trying to access the update view. Then create a new record in opendocs and access update view
             $model = new Opendocs();
             $model->issueId = $issueId;
             $model->userId = Yii::app()->user->id;
             $model->createTime = new CDbExpression('GETDATE()');
             $model->save();
             $this->render('update', array('model' => $issue, 'traveler' => $issue->traveler, 'issueId' => $issueId));
         }
     }
 }
Пример #26
0
 /**
  * Send any file as binary string with correct mime-type. If file not found it sends 404 error.
  * @param $fileName
  */
 public function sendAsset($fileName)
 {
     if (!is_file($fileName)) {
         $this->sendError(404);
         return;
     }
     $mime = CFileHelper::getMimeType($fileName);
     $status = $this->_statusCode;
     $contentType = $this->_contentType;
     // set the status
     $status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_statusText;
     header($status_header);
     // and the content type
     header('Content-type: ' . $mime);
     $file = fopen($fileName, 'r');
     $chunkSize = 1.5 * 1024 * 1024;
     while (!feof($file)) {
         $chunk = fread($file, $chunkSize);
         echo $chunk;
     }
     fclose($file);
 }
    function run($actionID)
    {
        $surveyid = Yii::app()->session['LEMsid'];
        $oSurvey = Survey::model()->findByPk($surveyid);
        if (!$oSurvey) {
            throw new CHttpException(400);
        }
        // See for debug > 1
        $sLanguage = isset(Yii::app()->session['survey_' . $surveyid]['s_lang']) ? Yii::app()->session['survey_' . $surveyid]['s_lang'] : "";
        $uploaddir = Yii::app()->getConfig("uploaddir");
        $tempdir = Yii::app()->getConfig("tempdir");
        Yii::app()->loadHelper("database");
        // Fill needed var
        $sFileGetContent = Yii::app()->request->getParam('filegetcontents', '');
        // The file to view fu_ or fu_tmp
        $bDelete = Yii::app()->request->getParam('delete');
        $sFieldName = Yii::app()->request->getParam('fieldname');
        $sFileName = Yii::app()->request->getParam('filename', '');
        // The file to delete fu_ or fu_tmp
        $sOriginalFileName = Yii::app()->request->getParam('name', '');
        // Used for javascript return only
        $sMode = Yii::app()->request->getParam('mode');
        $sPreview = Yii::app()->request->getParam('preview', 0);
        // Validate and filter and throw error if problems
        // Using 'futmp_'.randomChars(15).'_'.$pathinfo['extension'] for filename, then remove all other characters
        $sFileGetContentFiltered = preg_replace('/[^a-zA-Z0-9_]/', '', $sFileGetContent);
        $sFileNameFiltered = preg_replace('/[^a-zA-Z0-9_]/', '', $sFileName);
        $sFieldNameFiltered = preg_replace('/[^X0-9]/', '', $sFieldName);
        if ($sFileGetContent != $sFileGetContentFiltered || $sFileName != $sFileNameFiltered || $sFieldName != $sFieldNameFiltered) {
            // If one seems to be a hack: Bad request
            throw new CHttpException(400);
            // See for debug > 1
        }
        if ($sFileGetContent) {
            if (substr($sFileGetContent, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFileGetContent, 0, 3) == 'fu_') {
                // Need to validate $_SESSION['srid'], and this file is from this srid !
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            } else {
                throw new CHttpException(400);
                // See for debug > 1
            }
            if (is_file($sFileDir . $sFileGetContent)) {
                header('Content-Type: ' . CFileHelper::getMimeType($sFileDir . $sFileGetContent));
                readfile($sFileDir . $sFileGetContent);
                Yii::app()->end();
            } else {
                Yii::app()->end();
            }
        } elseif ($bDelete) {
            if (substr($sFileName, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFileName, 0, 3) == 'fu_') {
                // Need to validate $_SESSION['srid'], and this file is from this srid !
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            } else {
                throw new CHttpException(400);
                // See for debug > 1
            }
            if (isset($_SESSION[$sFieldName])) {
                // We already have $sFieldName ?
                $sJSON = $_SESSION[$sFieldName];
                $aFiles = json_decode(stripslashes($sJSON), true);
                if (substr($sFileName, 0, 3) == 'fu_') {
                    $iFileIndex = 0;
                    $found = false;
                    foreach ($aFiles as $aFile) {
                        if ($aFile['filename'] == $sFileName) {
                            $found = true;
                            break;
                        }
                        $iFileIndex++;
                    }
                    if ($found == true) {
                        unset($aFiles[$iFileIndex]);
                    }
                    $_SESSION[$sFieldName] = ls_json_encode($aFiles);
                }
            }
            //var_dump($sFileDir.$sFilename);
            // Return some json to do a beautiful text
            if (@unlink($sFileDir . $sFileName)) {
                echo sprintf(gT('File %s deleted'), $sOriginalFileName);
            } else {
                echo gT('Oops, There was an error deleting the file');
            }
            Yii::app()->end();
        }
        if ($sMode == "upload") {
            $sTempUploadDir = $tempdir . '/upload/';
            // Check if exists and is writable
            if (!file_exists($sTempUploadDir)) {
                // Try to create
                mkdir($sTempUploadDir);
            }
            $filename = $_FILES['uploadfile']['name'];
            // Do we filter file name ? It's used on displaying only , but not save like that.
            //$filename = sanitize_filename($_FILES['uploadfile']['name']);// This remove all non alpha numeric characters and replaced by _ . Leave only one dot .
            $size = 0.001 * $_FILES['uploadfile']['size'];
            $preview = Yii::app()->session['preview'];
            $aFieldMap = createFieldMap($surveyid, 'short', false, false, $sLanguage);
            if (!isset($aFieldMap[$sFieldName])) {
                throw new CHttpException(400);
                // See for debug > 1
            }
            $aAttributes = getQuestionAttributeValues($aFieldMap[$sFieldName]['qid']);
            $maxfilesize = (int) $aAttributes['max_filesize'];
            $valid_extensions_array = explode(",", $aAttributes['allowed_filetypes']);
            $valid_extensions_array = array_map('trim', $valid_extensions_array);
            $pathinfo = pathinfo($_FILES['uploadfile']['name']);
            $ext = strtolower($pathinfo['extension']);
            $randfilename = 'futmp_' . randomChars(15) . '_' . $pathinfo['extension'];
            $randfileloc = $sTempUploadDir . $randfilename;
            // check to see that this file type is allowed
            // it is also  checked at the client side, but jst double checking
            if (!in_array($ext, $valid_extensions_array)) {
                $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file extension (%s) is not allowed!"), $ext));
                //header('Content-Type: application/json');
                echo ls_json_encode($return);
                Yii::app()->end();
            }
            // If this is just a preview, don't save the file
            if ($preview) {
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } else {
                    if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                        $return = array("success" => true, "file_index" => $filecount, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => gT("The file has been successfuly uploaded."));
                        // TODO : unlink this file since this is just a preview. But we can do it only if it's not needed, and still needed to have the file content
                        // Maybe use a javascript 'onunload' on preview question/group
                        // unlink($randfileloc)
                        //header('Content-Type: application/json');
                        echo ls_json_encode($return);
                        Yii::app()->end();
                    }
                }
            } else {
                // if everything went fine and the file was uploaded successfuly,
                // send the file related info back to the client
                $iFileUploadTotalSpaceMB = Yii::app()->getConfig("iFileUploadTotalSpaceMB");
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files up to %s KB are allowed.", 'unescaped'), $maxfilesize));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } elseif ($iFileUploadTotalSpaceMB > 0 && calculateTotalFileUploadUsage() + $size / 1024 / 1024 > $iFileUploadTotalSpaceMB) {
                    $return = array("success" => false, "msg" => gT("We are sorry but there was a system error and your file was not saved. An email has been dispatched to notify the survey administrator.", 'unescaped'));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } elseif (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                    $return = array("success" => true, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => gT("The file has been successfuly uploaded."));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } else {
                    // check for upload error
                    if ($_FILES['uploadfile']['error'] > 2) {
                        $return = array("success" => false, "msg" => gT("Sorry, there was an error uploading your file"));
                        //header('Content-Type: application/json');
                        echo ls_json_encode($return);
                        Yii::app()->end();
                    } else {
                        if ($_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 || $size > $maxfilesize) {
                            $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                            //header('Content-Type: application/json');
                            echo ls_json_encode($return);
                            Yii::app()->end();
                        } else {
                            $return = array("success" => false, "msg" => gT("Unknown error"));
                            //header('Content-Type: application/json');
                            echo ls_json_encode($return);
                            Yii::app()->end();
                        }
                    }
                }
            }
            return;
        }
        $meta = '';
        App()->getClientScript()->registerPackage('jqueryui');
        App()->getClientScript()->registerPackage('jquery-superfish');
        $sNeededScriptVar = '
            var uploadurl = "' . $this->createUrl('/uploader/index/mode/upload/') . '";
            var imageurl = "' . Yii::app()->getConfig('imageurl') . '/";
            var surveyid = "' . $surveyid . '";
            var fieldname = "' . $sFieldName . '";
            var questgrppreview  = ' . $sPreview . ';
            csrfToken = ' . ls_json_encode(Yii::app()->request->csrfToken) . ';
            showpopups="' . Yii::app()->getConfig("showpopups") . '";
        ';
        $sLangScriptVar = "\n                uploadLang = {\n                     titleFld: '" . gT('Title', 'js') . "',\n                     commentFld: '" . gT('Comment', 'js') . "',\n                     errorNoMoreFiles: '" . gT('Sorry, no more files can be uploaded!', 'js') . "',\n                     errorOnlyAllowed: '" . gT('Sorry, only %s files can be uploaded for this question!', 'js') . "',\n                     uploading: '" . gT('Uploading', 'js') . "',\n                     selectfile: '" . gT('Select file', 'js') . "',\n                     errorNeedMore: '" . gT('Please upload %s more file(s).', 'js') . "',\n                     errorMoreAllowed: '" . gT('If you wish, you may upload %s more file(s); else you may return back to survey.', 'js') . "',\n                     errorMaxReached: '" . gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n                     errorTooMuch: '" . gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n                     errorNeedMoreConfirm: '" . gT("You need to upload %s more files for this question.\nAre you sure you want to exit?", 'js') . "',\n                     deleteFile : '" . gt('Delete', 'js') . "',\n                     editFile : '" . gt('Edit', 'js') . "',\n                    };\n        ";
        $aSurveyInfo = getSurveyInfo($surveyid, $sLanguage);
        $oEvent = new PluginEvent('beforeSurveyPage');
        $oEvent->set('surveyId', $surveyid);
        App()->getPluginManager()->dispatchEvent($oEvent);
        if (!is_null($oEvent->get('template'))) {
            $aSurveyInfo['templatedir'] = $event->get('template');
        }
        $sTemplateDir = getTemplatePath($aSurveyInfo['template']);
        $sTemplateUrl = getTemplateURL($aSurveyInfo['template']) . "/";
        App()->clientScript->registerScript('sNeededScriptVar', $sNeededScriptVar, CClientScript::POS_HEAD);
        App()->clientScript->registerScript('sLangScriptVar', $sLangScriptVar, CClientScript::POS_HEAD);
        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'ajaxupload.js');
        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'uploader.js');
        App()->getClientScript()->registerScriptFile("{$sTemplateUrl}template.js");
        App()->clientScript->registerCssFile(Yii::app()->getConfig("publicstyleurl") . "uploader.css");
        App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "uploader-files.css");
        if (file_exists($sTemplateDir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) {
            Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui-custom.css");
        } elseif (file_exists($sTemplateDir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) {
            Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui.css");
        } else {
            Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css");
        }
        App()->clientScript->registerCssFile("{$sTemplateUrl}template.css");
        $header = getHeader($meta);
        echo $header;
        $fn = $sFieldName;
        $qid = (int) Yii::app()->request->getParam('qid');
        $minfiles = (int) Yii::app()->request->getParam('minfiles');
        $maxfiles = (int) Yii::app()->request->getParam('maxfiles');
        $qidattributes = getQuestionAttributeValues($qid);
        $qidattributes['max_filesize'] = floor(min($qidattributes['max_filesize'] * 1024, getMaximumFileUploadSize()) / 1024);
        $body = '</head><body class="uploader">
                <div id="notice"></div>
                <input type="hidden" id="ia"                value="' . $fn . '" />
                <input type="hidden" id="' . $fn . '_minfiles"          value="' . $minfiles . '" />
                <input type="hidden" id="' . $fn . '_maxfiles"          value="' . $maxfiles . '" />
                <input type="hidden" id="' . $fn . '_maxfilesize"       value="' . $qidattributes['max_filesize'] . '" />
                <input type="hidden" id="' . $fn . '_allowed_filetypes" value="' . $qidattributes['allowed_filetypes'] . '" />
                <input type="hidden" id="preview"                   value="' . Yii::app()->session['preview'] . '" />
                <input type="hidden" id="' . $fn . '_show_comment"      value="' . $qidattributes['show_comment'] . '" />
                <input type="hidden" id="' . $fn . '_show_title"        value="' . $qidattributes['show_title'] . '" />
                <input type="hidden" id="' . $fn . '_licount"           value="0" />
                <input type="hidden" id="' . $fn . '_filecount"         value="0" />

                <!-- The upload button -->
                <div class="upload-div">
                    <button id="button1" class="button upload-button" type="button" >' . gT("Select file") . '</button>
                </div>

                <p class="uploadmsg">' . sprintf(gT("You can upload %s under %s KB each."), $qidattributes['allowed_filetypes'], $qidattributes['max_filesize']) . '</p>
                <div class="uploadstatus" id="uploadstatus"></div>

                <!-- The list of uploaded files -->

            </body>
        </html>';
        App()->getClientScript()->render($body);
        echo $body;
    }
Пример #28
0
 public function actionFile($id)
 {
     $model = $this->loadModel($id);
     if (file_exists($model->fileWithPath())) {
         header("Pragma: no-cache");
         header("Expires: 0");
         header('Content-Description: File Transfer');
         header('Content-Type: ' . CFileHelper::getMimeType($model->fileWithPath()));
         header('Content-Disposition: attachment; filename="' . $model->originalname . '"');
         header('Content-Transfer-Encoding: binary');
         header('Expires: 0');
         header('Cache-Control: must-revalidate');
         header('Pragma: public');
         header('Content-Length: ' . filesize($model->fileWithPath()));
         readfile($model->fileWithPath());
         Yii::app()->end();
     } else {
         throw new CHttpException(404, 'Not found');
     }
 }
Пример #29
0
 /**
  * Returns the file mime type.
  * @return string the file mime type.
  */
 public function getMimeType()
 {
     return CFileHelper::getMimeType($this->file->getTempName());
 }
Пример #30
0
 public function getMime($size = 'original')
 {
     return CFileHelper::getMimeType($_SERVER['DOCUMENT_ROOT'] . $this->{$size});
 }